modprobe-small: match aliases with fnmatch(), making
[platform/upstream/busybox.git] / modutils / modprobe-small.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * simplified modprobe
4  *
5  * Copyright (c) 2008 Vladimir Dronnikov
6  * Copyright (c) 2008 Bernhard Fischer (initial depmod code)
7  *
8  * Licensed under GPLv2, see file LICENSE in this tarball for details.
9  */
10
11 #include "libbb.h"
12 #include "unarchive.h"
13
14 #include <sys/utsname.h> /* uname() */
15 #include <fnmatch.h>
16
17 /* libbb candidate */
18 static void *xmalloc_read(int fd, size_t *sizep)
19 {
20         char *buf;
21         size_t size, rd_size, total;
22         off_t to_read;
23         struct stat st;
24
25         to_read = sizep ? *sizep : INT_MAX; /* max to read */
26
27         /* Estimate file size */
28         st.st_size = 0; /* in case fstat fails, assume 0 */
29         fstat(fd, &st);
30         /* /proc/N/stat files report st_size 0 */
31         /* In order to make such files readable, we add small const */
32         size = (st.st_size | 0x3ff) + 1;
33
34         total = 0;
35         buf = NULL;
36         while (1) {
37                 if (to_read < size)
38                         size = to_read;
39                 buf = xrealloc(buf, total + size + 1);
40                 rd_size = full_read(fd, buf + total, size);
41                 if ((ssize_t)rd_size < 0) { /* error */
42                         free(buf);
43                         return NULL;
44                 }
45                 total += rd_size;
46                 if (rd_size < size) /* EOF */
47                         break;
48                 to_read -= rd_size;
49                 if (to_read <= 0)
50                         break;
51                 /* grow by 1/8, but in [1k..64k] bounds */
52                 size = ((total / 8) | 0x3ff) + 1;
53                 if (size > 64*1024)
54                         size = 64*1024;
55         }
56         xrealloc(buf, total + 1);
57         buf[total] = '\0';
58
59         if (sizep)
60                 *sizep = total;
61         return buf;
62 }
63
64
65 #define dbg1_error_msg(...) ((void)0)
66 #define dbg2_error_msg(...) ((void)0)
67 //#define dbg1_error_msg(...) bb_error_msg(__VA_ARGS__)
68 //#define dbg2_error_msg(...) bb_error_msg(__VA_ARGS__)
69
70 extern int init_module(void *module, unsigned long len, const char *options);
71 extern int delete_module(const char *module, unsigned flags);
72 extern int query_module(const char *name, int which, void *buf, size_t bufsize, size_t *ret);
73
74 enum {
75         OPT_q = (1 << 0), /* be quiet */
76         OPT_r = (1 << 1), /* module removal instead of loading */
77 };
78
79 typedef struct module_info {
80         char *pathname;
81         char *desc;
82 } module_info;
83
84 /*
85  * GLOBALS
86  */
87 struct globals {
88         module_info *modinfo;
89         char *module_load_options;
90         int module_count;
91         int module_found_idx;
92         int stringbuf_idx;
93         char stringbuf[32 * 1024]; /* some modules have lots of stuff */
94         /* for example, drivers/media/video/saa7134/saa7134.ko */
95 };
96 #define G (*ptr_to_globals)
97 #define modinfo             (G.modinfo            )
98 #define module_count        (G.module_count       )
99 #define module_found_idx    (G.module_found_idx   )
100 #define module_load_options (G.module_load_options)
101 #define stringbuf_idx       (G.stringbuf_idx      )
102 #define stringbuf           (G.stringbuf          )
103 #define INIT_G() do { \
104         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
105 } while (0)
106
107
108 static void appendc(char c)
109 {
110         if (stringbuf_idx < sizeof(stringbuf))
111                 stringbuf[stringbuf_idx++] = c;
112 }
113
114 static void append(const char *s)
115 {
116         size_t len = strlen(s);
117         if (stringbuf_idx + len < sizeof(stringbuf)) {
118                 memcpy(stringbuf + stringbuf_idx, s, len);
119                 stringbuf_idx += len;
120         }
121 }
122
123 static void reset_stringbuf(void)
124 {
125         stringbuf_idx = 0;
126 }
127
128 static char* copy_stringbuf(void)
129 {
130         char *copy = xmalloc(stringbuf_idx);
131         return memcpy(copy, stringbuf, stringbuf_idx);
132 }
133
134 static char* find_keyword(char *ptr, size_t len, const char *word)
135 {
136         int wlen;
137
138         if (!ptr) /* happens if read_module cannot read it */
139                 return NULL;
140
141         wlen = strlen(word);
142         len -= wlen - 1;
143         while ((ssize_t)len > 0) {
144                 char *old = ptr;
145                 /* search for the first char in word */
146                 ptr = memchr(ptr, *word, len);
147                 if (ptr == NULL) /* no occurance left, done */
148                         break;
149                 if (strncmp(ptr, word, wlen) == 0)
150                         return ptr + wlen; /* found, return ptr past it */
151                 ++ptr;
152                 len -= (ptr - old);
153         }
154         return NULL;
155 }
156
157 static void replace(char *s, char what, char with)
158 {
159         while (*s) {
160                 if (what == *s)
161                         *s = with;
162                 ++s;
163         }
164 }
165
166 #if ENABLE_FEATURE_MODPROBE_SMALL_ZIPPED
167 static char *xmalloc_open_zipped_read_close(const char *fname, size_t *sizep)
168 {
169         size_t len;
170         char *image;
171         char *suffix;
172
173         int fd = open_or_warn(fname, O_RDONLY);
174         if (fd < 0)
175                 return NULL;
176
177         suffix = strrchr(fname, '.');
178         if (suffix) {
179                 if (strcmp(suffix, ".gz") == 0)
180                         fd = open_transformer(fd, unpack_gz_stream, "gunzip");
181                 else if (strcmp(suffix, ".bz2") == 0)
182                         fd = open_transformer(fd, unpack_bz2_stream, "bunzip2");
183         }
184
185         len = (sizep) ? *sizep : 64 * 1024 * 1024;
186         image = xmalloc_read(fd, &len);
187         if (!image)
188                 bb_perror_msg("read error from '%s'", fname);
189         close(fd);
190
191         if (sizep)
192                 *sizep = len;
193         return image;
194 }
195 # define read_module xmalloc_open_zipped_read_close
196 #else
197 # define read_module xmalloc_open_read_close
198 #endif
199
200 /* We use error numbers in a loose translation... */
201 static const char *moderror(int err)
202 {
203         switch (err) {
204         case ENOEXEC:
205                 return "invalid module format";
206         case ENOENT:
207                 return "unknown symbol in module or invalid parameter";
208         case ESRCH:
209                 return "module has wrong symbol version";
210         case EINVAL: /* "invalid parameter" */
211                 return "unknown symbol in module or invalid parameter"
212                 + sizeof("unknown symbol in module or");
213         default:
214                 return strerror(err);
215         }
216 }
217
218 static int load_module(const char *fname, const char *options)
219 {
220 #if 1
221         int r;
222         size_t len = MAXINT(ssize_t);
223         char *module_image;
224         dbg1_error_msg("load_module('%s','%s')", fname, options);
225
226         module_image = read_module(fname, &len);
227         r = (!module_image || init_module(module_image, len, options ? options : "") != 0);
228         free(module_image);
229         dbg1_error_msg("load_module:%d", r);
230         return r; /* 0 = success */
231 #else
232         /* For testing */
233         dbg1_error_msg("load_module('%s','%s')", fname, options);
234         return 1;
235 #endif
236 }
237
238 static char* parse_module(const char *pathname, const char *name)
239 {
240         char *module_image;
241         char *ptr;
242         size_t len;
243         size_t pos;
244         dbg1_error_msg("parse_module('%s','%s')", pathname, name);
245
246         /* Read (possibly compressed) module */
247         len = 64 * 1024 * 1024; /* 64 Mb at most */
248         module_image = read_module(pathname, &len);
249
250         reset_stringbuf();
251
252         /* First desc line's format is
253          * "modname alias1 symbol:sym1 alias2 symbol:sym2 " (note trailing ' ')
254          */
255         append(name);
256         appendc(' ');
257         /* Aliases */
258         pos = 0;
259         while (1) {
260                 ptr = find_keyword(module_image + pos, len - pos, "alias=");
261                 if (!ptr) {
262                         ptr = find_keyword(module_image + pos, len - pos, "__ksymtab_");
263                         if (!ptr)
264                                 break;
265                         /* DOCME: __ksymtab_gpl and __ksymtab_strings occur
266                          * in many modules. What do they mean? */
267                         if (strcmp(ptr, "gpl") != 0 && strcmp(ptr, "strings") != 0) {
268                                 dbg2_error_msg("alias: 'symbol:%s'", ptr);
269                                 append("symbol:");
270                         }
271                 } else {
272                         dbg2_error_msg("alias: '%s'", ptr);
273                 }
274                 append(ptr);
275                 appendc(' ');
276                 pos = (ptr - module_image);
277         }
278         appendc('\0');
279
280         /* Second line: "dependency1 depandency2 " (note trailing ' ') */
281         ptr = find_keyword(module_image, len, "depends=");
282         if (ptr && *ptr) {
283                 replace(ptr, ',', ' ');
284                 replace(ptr, '-', '_');
285                 dbg2_error_msg("dep:'%s'", ptr);
286                 append(ptr);
287         }
288         appendc(' '); appendc('\0');
289
290         free(module_image);
291         return copy_stringbuf();
292 }
293
294 static char* pathname_2_modname(const char *pathname)
295 {
296         const char *fname = bb_get_last_path_component_nostrip(pathname);
297         const char *suffix = strrstr(fname, ".ko");
298         char *name = xstrndup(fname, suffix - fname);
299         replace(name, '-', '_');
300         return name;
301 }
302
303 static FAST_FUNC int fileAction(const char *pathname,
304                 struct stat *sb UNUSED_PARAM,
305                 void *data,
306                 int depth UNUSED_PARAM)
307 {
308         int cur;
309         char *name;
310         const char *fname;
311
312         pathname += 2; /* skip "./" */
313         fname = bb_get_last_path_component_nostrip(pathname);
314         if (!strrstr(fname, ".ko")) {
315                 dbg1_error_msg("'%s' is not a module", pathname);
316                 return TRUE; /* not a module, continue search */
317         }
318
319         cur = module_count++;
320         if (!(cur & 0xfff)) {
321                 modinfo = xrealloc(modinfo, sizeof(modinfo[0]) * (cur + 0x1001));
322         }
323         modinfo[cur].pathname = xstrdup(pathname);
324         modinfo[cur].desc = NULL;
325         modinfo[cur+1].pathname = NULL;
326         modinfo[cur+1].desc = NULL;
327
328         name = pathname_2_modname(fname);
329         if (strcmp(name, data) != 0) {
330                 free(name);
331                 dbg1_error_msg("'%s' module name doesn't match", pathname);
332                 return TRUE; /* module name doesn't match, continue search */
333         }
334
335         dbg1_error_msg("'%s' module name matches", pathname);
336         module_found_idx = cur;
337         modinfo[cur].desc = parse_module(pathname, name);
338
339         if (!(option_mask32 & OPT_r)) {
340                 if (load_module(pathname, module_load_options) == 0) {
341                         /* Load was successful, there is nothing else to do.
342                          * This can happen ONLY for "top-level" module load,
343                          * not a dep, because deps dont do dirscan. */
344                         exit(EXIT_SUCCESS);
345                         /*free(name);return RECURSE_RESULT_ABORT;*/
346                 }
347         }
348
349         free(name);
350         return TRUE;
351 }
352
353 static module_info* find_alias(const char *alias)
354 {
355         int i;
356         dbg1_error_msg("find_alias('%s')", alias);
357
358         /* First try to find by name (cheaper) */
359         i = 0;
360         while (modinfo[i].pathname) {
361                 char *name = pathname_2_modname(modinfo[i].pathname);
362                 if (strcmp(name, alias) == 0) {
363                         dbg1_error_msg("found '%s' in module '%s'",
364                                         alias, modinfo[i].pathname);
365                         if (!modinfo[i].desc)
366                                 modinfo[i].desc = parse_module(modinfo[i].pathname, name);
367                         free(name);
368                         return &modinfo[i];
369                 }
370                 free(name);
371                 i++;
372         }
373
374         /* Scan all module bodies, extract modinfo (it contains aliases) */
375         i = 0;
376         while (modinfo[i].pathname) {
377                 char *desc, *s;
378                 if (!modinfo[i].desc) {
379                         char *name = pathname_2_modname(modinfo[i].pathname);
380                         modinfo[i].desc = parse_module(modinfo[i].pathname, name);
381                         free(name);
382                 }
383                 /* "modname alias1 symbol:sym1 alias2 symbol:sym2 " */
384                 desc = xstrdup(modinfo[i].desc);
385                 /* Does matching substring exist? */
386                 replace(desc, ' ', '\0');
387                 for (s = desc; *s; s += strlen(s) + 1) {
388                         /* aliases in module bodies can be defined with
389                          * shell patterns. Example:
390                          * "pci:v000010DEd000000D9sv*sd*bc*sc*i*".
391                          * Plain strcmp() won't catch that */
392                         if (fnmatch(s, alias, 0) == 0) {
393                                 free(desc);
394                                 dbg1_error_msg("found alias '%s' in module '%s'",
395                                                 alias, modinfo[i].pathname);
396                                 return &modinfo[i];
397                         }
398                 }
399                 free(desc);
400                 i++;
401         }
402         dbg1_error_msg("find_alias '%s' returns NULL", alias);
403         return NULL;
404 }
405
406 #if ENABLE_FEATURE_MODPROBE_SMALL_CHECK_ALREADY_LOADED
407 static int already_loaded(const char *name)
408 {
409         int ret = 0;
410         int len = strlen(name);
411         char *line;
412         FILE* modules;
413
414         modules = xfopen("/proc/modules", "r");
415         while ((line = xmalloc_fgets(modules)) != NULL) {
416                 if (strncmp(line, name, len) == 0 && line[len] == ' ') {
417                         free(line);
418                         ret = 1;
419                         break;
420                 }
421                 free(line);
422         }
423         fclose(modules);
424         return ret;
425 }
426 #else
427 #define already_loaded(name) is_rmmod
428 #endif
429
430 /*
431  Given modules definition and module name (or alias, or symbol)
432  load/remove the module respecting dependencies
433 */
434 #if !ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
435 #define process_module(a,b) process_module(a)
436 #define cmdline_options ""
437 #endif
438 static void process_module(char *name, const char *cmdline_options)
439 {
440         char *s, *deps, *options;
441         module_info *info;
442         int is_rmmod = (option_mask32 & OPT_r) != 0;
443         dbg1_error_msg("process_module('%s','%s')", name, cmdline_options);
444
445         replace(name, '-', '_');
446
447         dbg1_error_msg("already_loaded:%d is_rmmod:%d", already_loaded(name), is_rmmod);
448         if (already_loaded(name) != is_rmmod) {
449                 dbg1_error_msg("nothing to do for '%s'", name);
450                 return;
451         }
452
453         options = NULL;
454         if (!is_rmmod) {
455                 char *opt_filename = xasprintf("/etc/modules/%s", name);
456                 options = xmalloc_open_read_close(opt_filename, NULL);
457                 if (options)
458                         replace(options, '\n', ' ');
459 #if ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
460                 if (cmdline_options) {
461                         /* NB: cmdline_options always have one leading ' '
462                          * (see main()), we remove it here */
463                         char *op = xasprintf(options ? "%s %s" : "%s %s" + 3,
464                                                 cmdline_options + 1, options);
465                         free(options);
466                         options = op;
467                 }
468 #endif
469                 free(opt_filename);
470                 module_load_options = options;
471                 dbg1_error_msg("process_module('%s'): options:'%s'", name, options);
472         }
473
474         if (!module_count) {
475                 /* Scan module directory. This is done only once.
476                  * It will attempt module load, and will exit(EXIT_SUCCESS)
477                  * on success. */
478                 module_found_idx = -1;
479                 recursive_action(".",
480                         ACTION_RECURSE, /* flags */
481                         fileAction, /* file action */
482                         NULL, /* dir action */
483                         name, /* user data */
484                         0); /* depth */
485                 dbg1_error_msg("dirscan complete");
486                 /* Module was not found, or load failed, or is_rmmod */
487                 if (module_found_idx >= 0) { /* module was found */
488                         info = &modinfo[module_found_idx];
489                 } else { /* search for alias, not a plain module name */
490                         info = find_alias(name);
491                 }
492         } else {
493                 info = find_alias(name);
494         }
495
496         /* rmmod? unload it by name */
497         if (is_rmmod) {
498                 if (delete_module(name, O_NONBLOCK|O_EXCL) != 0
499                  && !(option_mask32 & OPT_q)
500                 ) {
501                         bb_perror_msg("remove '%s'", name);
502                         goto ret;
503                 }
504                 /* N.B. we do not stop here -
505                  * continue to unload modules on which the module depends:
506                  * "-r --remove: option causes modprobe to remove a module.
507                  * If the modules it depends on are also unused, modprobe
508                  * will try to remove them, too." */
509         }
510
511         if (!info) { /* both dirscan and find_alias found nothing */
512                 goto ret;
513         }
514
515         /* Second line of desc contains dependencies */
516         deps = xstrdup(info->desc + strlen(info->desc) + 1);
517
518         /* Transform deps to string list */
519         replace(deps, ' ', '\0');
520         /* Iterate thru dependencies, trying to (un)load them */
521         for (s = deps; *s; s += strlen(s) + 1) {
522                 //if (strcmp(name, s) != 0) // N.B. do loops exist?
523                 dbg1_error_msg("recurse on dep '%s'", s);
524                 process_module(s, NULL);
525                 dbg1_error_msg("recurse on dep '%s' done", s);
526         }
527         free(deps);
528
529         /* insmod -> load it */
530         if (!is_rmmod) {
531                 errno = 0;
532                 if (load_module(info->pathname, options) != 0) {
533                         if (EEXIST != errno) {
534                                 bb_error_msg("insert '%s' %s: %s",
535                                                 info->pathname, options,
536                                                 moderror(errno));
537                         } else {
538                                 dbg1_error_msg("insert '%s' %s: %s",
539                                                 info->pathname, options,
540                                                 moderror(errno));
541                         }
542                 }
543         }
544  ret:
545         free(options);
546 //TODO: return load attempt result from process_module.
547 //If dep didn't load ok, continuing makes little sense.
548 }
549 #undef cmdline_options
550
551
552 /* For reference, module-init-tools-0.9.15-pre2 options:
553
554 # insmod
555 Usage: insmod filename [args]
556
557 # rmmod --help
558 Usage: rmmod [-fhswvV] modulename ...
559  -f (or --force) forces a module unload, and may crash your machine.
560  -s (or --syslog) says use syslog, not stderr
561  -v (or --verbose) enables more messages
562  -w (or --wait) begins a module removal even if it is used
563     and will stop new users from accessing the module (so it
564     should eventually fall to zero).
565
566 # modprobe
567 Usage: modprobe [--verbose|--version|--config|--remove] filename [options]
568
569 # depmod --help
570 depmod 0.9.15-pre2 -- part of module-init-tools
571 depmod -[aA] [-n -e -v -q -V -r -u] [-b basedirectory] [forced_version]
572 depmod [-n -e -v -q -r -u] [-F kernelsyms] module1.o module2.o ...
573 If no arguments (except options) are given, "depmod -a" is assumed
574
575 depmod will output a dependancy list suitable for the modprobe utility.
576
577 Options:
578         -a, --all               Probe all modules
579         -n, --show              Write the dependency file on stdout only
580         -b basedirectory
581         --basedir basedirectory Use an image of a module tree.
582         -F kernelsyms
583         --filesyms kernelsyms   Use the file instead of the
584                                 current kernel symbols.
585 */
586
587 int modprobe_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
588 int modprobe_main(int argc UNUSED_PARAM, char **argv)
589 {
590         struct utsname uts;
591         char applet0 = applet_name[0];
592         USE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(char *options;)
593
594         /* depmod is a stub */
595         if ('d' == applet0)
596                 return EXIT_SUCCESS;
597
598         /* are we lsmod? -> just dump /proc/modules */
599         if ('l' == applet0) {
600                 xprint_and_close_file(xfopen("/proc/modules", "r"));
601                 return EXIT_SUCCESS;
602         }
603
604         INIT_G();
605
606         /* insmod, modprobe, rmmod require at least one argument */
607         opt_complementary = "-1";
608         /* only -q (quiet) and -r (rmmod),
609          * the rest are accepted and ignored (compat) */
610         getopt32(argv, "qrfsvw");
611         argv += optind;
612
613         /* are we rmmod? -> simulate modprobe -r */
614         if ('r' == applet0) {
615                 option_mask32 |= OPT_r;
616         }
617
618         /* goto modules directory */
619         xchdir(CONFIG_DEFAULT_MODULES_DIR);
620         uname(&uts); /* never fails */
621         xchdir(uts.release);
622
623 #if ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
624         /* If not rmmod, parse possible module options given on command line.
625          * insmod/modprobe takes one module name, the rest are parameters. */
626         options = NULL;
627         if ('r' != applet0) {
628                 char **arg = argv;
629                 while (*++arg) {
630                         /* Enclose options in quotes */
631                         char *s = options;
632                         options = xasprintf("%s \"%s\"", s ? s : "", *arg);
633                         free(s);
634                         *arg = NULL;
635                 }
636         }
637 #else
638         if ('r' != applet0)
639                 argv[1] = NULL;
640 #endif
641
642         /* Load/remove modules.
643          * Only rmmod loops here, insmod/modprobe has only argv[0] */
644         do {
645                 process_module(*argv++, options);
646         } while (*argv);
647
648         if (ENABLE_FEATURE_CLEAN_UP) {
649                 USE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(free(options);)
650         }
651         return EXIT_SUCCESS;
652 }