ash: [EVAL] Fix use-after-free in dotrap/evalstring
[oweals/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 Reutner-Fischer (initial depmod code)
7  *
8  * Licensed under GPLv2, see file LICENSE in this source tree.
9  */
10
11 //applet:IF_MODPROBE_SMALL(APPLET(modprobe, BB_DIR_SBIN, BB_SUID_DROP))
12 //applet:IF_MODPROBE_SMALL(APPLET_ODDNAME(depmod, modprobe, BB_DIR_SBIN, BB_SUID_DROP, depmod))
13 //applet:IF_MODPROBE_SMALL(APPLET_ODDNAME(insmod, modprobe, BB_DIR_SBIN, BB_SUID_DROP, insmod))
14 //applet:IF_MODPROBE_SMALL(APPLET_ODDNAME(lsmod, modprobe, BB_DIR_SBIN, BB_SUID_DROP, lsmod))
15 //applet:IF_MODPROBE_SMALL(APPLET_ODDNAME(rmmod, modprobe, BB_DIR_SBIN, BB_SUID_DROP, rmmod))
16
17 #include "libbb.h"
18 /* After libbb.h, since it needs sys/types.h on some systems */
19 #include <sys/utsname.h> /* uname() */
20 #include <fnmatch.h>
21 #include <sys/syscall.h>
22
23 extern int init_module(void *module, unsigned long len, const char *options);
24 extern int delete_module(const char *module, unsigned flags);
25 #ifdef __NR_finit_module
26 # define finit_module(fd, uargs, flags) syscall(__NR_finit_module, fd, uargs, flags)
27 #endif
28 /* linux/include/linux/module.h has limit of 64 chars on module names */
29 #undef MODULE_NAME_LEN
30 #define MODULE_NAME_LEN 64
31
32
33 #if 1
34 # define dbg1_error_msg(...) ((void)0)
35 # define dbg2_error_msg(...) ((void)0)
36 #else
37 # define dbg1_error_msg(...) bb_error_msg(__VA_ARGS__)
38 # define dbg2_error_msg(...) bb_error_msg(__VA_ARGS__)
39 #endif
40
41 #define DEPFILE_BB CONFIG_DEFAULT_DEPMOD_FILE".bb"
42
43 enum {
44         OPT_q = (1 << 0), /* be quiet */
45         OPT_r = (1 << 1), /* module removal instead of loading */
46 };
47
48 typedef struct module_info {
49         char *pathname;
50         char *aliases;
51         char *deps;
52         smallint open_read_failed;
53 } module_info;
54
55 /*
56  * GLOBALS
57  */
58 struct globals {
59         module_info *modinfo;
60         char *module_load_options;
61         smallint dep_bb_seen;
62         smallint wrote_dep_bb_ok;
63         unsigned module_count;
64         int module_found_idx;
65         unsigned stringbuf_idx;
66         unsigned stringbuf_size;
67         char *stringbuf; /* some modules have lots of stuff */
68         /* for example, drivers/media/video/saa7134/saa7134.ko */
69         /* therefore having a fixed biggish buffer is not wise */
70 };
71 #define G (*ptr_to_globals)
72 #define modinfo             (G.modinfo            )
73 #define dep_bb_seen         (G.dep_bb_seen        )
74 #define wrote_dep_bb_ok     (G.wrote_dep_bb_ok    )
75 #define module_count        (G.module_count       )
76 #define module_found_idx    (G.module_found_idx   )
77 #define module_load_options (G.module_load_options)
78 #define stringbuf_idx       (G.stringbuf_idx      )
79 #define stringbuf_size      (G.stringbuf_size     )
80 #define stringbuf           (G.stringbuf          )
81 #define INIT_G() do { \
82         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
83 } while (0)
84
85 static void append(const char *s)
86 {
87         unsigned len = strlen(s);
88         if (stringbuf_idx + len + 15 > stringbuf_size) {
89                 stringbuf_size = stringbuf_idx + len + 127;
90                 dbg2_error_msg("grow stringbuf to %u", stringbuf_size);
91                 stringbuf = xrealloc(stringbuf, stringbuf_size);
92         }
93         memcpy(stringbuf + stringbuf_idx, s, len);
94         stringbuf_idx += len;
95 }
96
97 static void appendc(char c)
98 {
99         /* We appendc() only after append(), + 15 trick in append()
100          * makes it unnecessary to check for overflow here */
101         stringbuf[stringbuf_idx++] = c;
102 }
103
104 static void bksp(void)
105 {
106         if (stringbuf_idx)
107                 stringbuf_idx--;
108 }
109
110 static void reset_stringbuf(void)
111 {
112         stringbuf_idx = 0;
113 }
114
115 static char* copy_stringbuf(void)
116 {
117         char *copy = xzalloc(stringbuf_idx + 1); /* terminating NUL */
118         return memcpy(copy, stringbuf, stringbuf_idx);
119 }
120
121 static char* find_keyword(char *ptr, size_t len, const char *word)
122 {
123         if (!ptr) /* happens if xmalloc_open_zipped_read_close cannot read it */
124                 return NULL;
125
126         len -= strlen(word) - 1;
127         while ((ssize_t)len > 0) {
128                 char *old = ptr;
129                 char *after_word;
130
131                 /* search for the first char in word */
132                 ptr = memchr(ptr, word[0], len);
133                 if (ptr == NULL) /* no occurance left, done */
134                         break;
135                 after_word = is_prefixed_with(ptr, word);
136                 if (after_word)
137                         return after_word; /* found, return ptr past it */
138                 ++ptr;
139                 len -= (ptr - old);
140         }
141         return NULL;
142 }
143
144 static void replace(char *s, char what, char with)
145 {
146         while (*s) {
147                 if (what == *s)
148                         *s = with;
149                 ++s;
150         }
151 }
152
153 static char *filename2modname(const char *filename, char *modname)
154 {
155         int i;
156         const char *from;
157
158         // Disabled since otherwise "modprobe dir/name" would work
159         // as if it is "modprobe name". It is unclear why
160         // 'basenamization' was here in the first place.
161         //from = bb_get_last_path_component_nostrip(filename);
162         from = filename;
163         for (i = 0; i < (MODULE_NAME_LEN-1) && from[i] != '\0' && from[i] != '.'; i++)
164                 modname[i] = (from[i] == '-') ? '_' : from[i];
165         modname[i] = '\0';
166
167         return modname;
168 }
169
170 static int pathname_matches_modname(const char *pathname, const char *modname)
171 {
172         int r;
173         char name[MODULE_NAME_LEN];
174         filename2modname(bb_get_last_path_component_nostrip(pathname), name);
175         r = (strcmp(name, modname) == 0);
176         return r;
177 }
178
179 /* Take "word word", return malloced "word",NUL,"word",NUL,NUL */
180 static char* str_2_list(const char *str)
181 {
182         int len = strlen(str) + 1;
183         char *dst = xmalloc(len + 1);
184
185         dst[len] = '\0';
186         memcpy(dst, str, len);
187 //TODO: protect against 2+ spaces: "word  word"
188         replace(dst, ' ', '\0');
189         return dst;
190 }
191
192 /* We use error numbers in a loose translation... */
193 static const char *moderror(int err)
194 {
195         switch (err) {
196         case ENOEXEC:
197                 return "invalid module format";
198         case ENOENT:
199                 return "unknown symbol in module or invalid parameter";
200         case ESRCH:
201                 return "module has wrong symbol version";
202         case EINVAL: /* "invalid parameter" */
203                 return "unknown symbol in module or invalid parameter"
204                 + sizeof("unknown symbol in module or");
205         default:
206                 return strerror(err);
207         }
208 }
209
210 static int load_module(const char *fname, const char *options)
211 {
212 #if 1
213         int r;
214         size_t len = MAXINT(ssize_t);
215         char *module_image;
216
217         if (!options)
218                 options = "";
219
220         dbg1_error_msg("load_module('%s','%s')", fname, options);
221
222         /*
223          * First we try finit_module if available.  Some kernels are configured
224          * to only allow loading of modules off of secure storage (like a read-
225          * only rootfs) which needs the finit_module call.  If it fails, we fall
226          * back to normal module loading to support compressed modules.
227          */
228         r = 1;
229 # ifdef __NR_finit_module
230         {
231                 int fd = open(fname, O_RDONLY | O_CLOEXEC);
232                 if (fd >= 0) {
233                         r = finit_module(fd, options, 0) != 0;
234                         close(fd);
235                 }
236         }
237 # endif
238         if (r != 0) {
239                 module_image = xmalloc_open_zipped_read_close(fname, &len);
240                 r = (!module_image || init_module(module_image, len, options) != 0);
241                 free(module_image);
242         }
243
244         dbg1_error_msg("load_module:%d", r);
245         return r; /* 0 = success */
246 #else
247         /* For testing */
248         dbg1_error_msg("load_module('%s','%s')", fname, options);
249         return 1;
250 #endif
251 }
252
253 /* Returns !0 if open/read was unsuccessful */
254 static int parse_module(module_info *info, const char *pathname)
255 {
256         char *module_image;
257         char *ptr;
258         size_t len;
259         size_t pos;
260         dbg1_error_msg("parse_module('%s')", pathname);
261
262         /* Read (possibly compressed) module */
263         errno = 0;
264         len = 64 * 1024 * 1024; /* 64 Mb at most */
265         module_image = xmalloc_open_zipped_read_close(pathname, &len);
266         /* module_image == NULL is ok here, find_keyword handles it */
267 //TODO: optimize redundant module body reads
268
269         /* "alias1 symbol:sym1 alias2 symbol:sym2" */
270         reset_stringbuf();
271         pos = 0;
272         while (1) {
273                 unsigned start = stringbuf_idx;
274                 ptr = find_keyword(module_image + pos, len - pos, "alias=");
275                 if (!ptr) {
276                         ptr = find_keyword(module_image + pos, len - pos, "__ksymtab_");
277                         if (!ptr)
278                                 break;
279                         /* DOCME: __ksymtab_gpl and __ksymtab_strings occur
280                          * in many modules. What do they mean? */
281                         if (strcmp(ptr, "gpl") == 0 || strcmp(ptr, "strings") == 0)
282                                 goto skip;
283                         dbg2_error_msg("alias:'symbol:%s'", ptr);
284                         append("symbol:");
285                 } else {
286                         dbg2_error_msg("alias:'%s'", ptr);
287                 }
288                 append(ptr);
289                 appendc(' ');
290                 /*
291                  * Don't add redundant aliases, such as:
292                  * libcrc32c.ko symbol:crc32c symbol:crc32c
293                  */
294                 if (start) { /* "if we aren't the first alias" */
295                         char *found, *last;
296                         stringbuf[stringbuf_idx] = '\0';
297                         last = stringbuf + start;
298                         /*
299                          * String at last-1 is " symbol:crc32c "
300                          * (with both leading and trailing spaces).
301                          */
302                         if (strncmp(stringbuf, last, stringbuf_idx - start) == 0)
303                                 /* First alias matches us */
304                                 found = stringbuf;
305                         else
306                                 /* Does any other alias match? */
307                                 found = strstr(stringbuf, last-1);
308                         if (found < last-1) {
309                                 /* There is absolutely the same string before us */
310                                 dbg2_error_msg("redundant:'%s'", last);
311                                 stringbuf_idx = start;
312                                 goto skip;
313                         }
314                 }
315  skip:
316                 pos = (ptr - module_image);
317         }
318         bksp(); /* remove last ' ' */
319         info->aliases = copy_stringbuf();
320         replace(info->aliases, '-', '_');
321
322         /* "dependency1 depandency2" */
323         reset_stringbuf();
324         ptr = find_keyword(module_image, len, "depends=");
325         if (ptr && *ptr) {
326                 replace(ptr, ',', ' ');
327                 replace(ptr, '-', '_');
328                 dbg2_error_msg("dep:'%s'", ptr);
329                 append(ptr);
330         }
331         free(module_image);
332         info->deps = copy_stringbuf();
333
334         info->open_read_failed = (module_image == NULL);
335         return info->open_read_failed;
336 }
337
338 static FAST_FUNC int fileAction(const char *pathname,
339                 struct stat *sb UNUSED_PARAM,
340                 void *modname_to_match,
341                 int depth UNUSED_PARAM)
342 {
343         int cur;
344         const char *fname;
345
346         pathname += 2; /* skip "./" */
347         fname = bb_get_last_path_component_nostrip(pathname);
348         if (!strrstr(fname, ".ko")) {
349                 dbg1_error_msg("'%s' is not a module", pathname);
350                 return TRUE; /* not a module, continue search */
351         }
352
353         cur = module_count++;
354         modinfo = xrealloc_vector(modinfo, 12, cur);
355         modinfo[cur].pathname = xstrdup(pathname);
356         /*modinfo[cur].aliases = NULL; - xrealloc_vector did it */
357         /*modinfo[cur+1].pathname = NULL;*/
358
359         if (!pathname_matches_modname(fname, modname_to_match)) {
360                 dbg1_error_msg("'%s' module name doesn't match", pathname);
361                 return TRUE; /* module name doesn't match, continue search */
362         }
363
364         dbg1_error_msg("'%s' module name matches", pathname);
365         module_found_idx = cur;
366         if (parse_module(&modinfo[cur], pathname) != 0)
367                 return TRUE; /* failed to open/read it, no point in trying loading */
368
369         if (!(option_mask32 & OPT_r)) {
370                 if (load_module(pathname, module_load_options) == 0) {
371                         /* Load was successful, there is nothing else to do.
372                          * This can happen ONLY for "top-level" module load,
373                          * not a dep, because deps dont do dirscan. */
374                         exit(EXIT_SUCCESS);
375                 }
376         }
377
378         return TRUE;
379 }
380
381 static int load_dep_bb(void)
382 {
383         char *line;
384         FILE *fp = fopen_for_read(DEPFILE_BB);
385
386         if (!fp)
387                 return 0;
388
389         dep_bb_seen = 1;
390         dbg1_error_msg("loading "DEPFILE_BB);
391
392         /* Why? There is a rare scenario: we did not find modprobe.dep.bb,
393          * we scanned the dir and found no module by name, then we search
394          * for alias (full scan), and we decided to generate modprobe.dep.bb.
395          * But we see modprobe.dep.bb.new! Other modprobe is at work!
396          * We wait and other modprobe renames it to modprobe.dep.bb.
397          * Now we can use it.
398          * But we already have modinfo[] filled, and "module_count = 0"
399          * makes us start anew. Yes, we leak modinfo[].xxx pointers -
400          * there is not much of data there anyway. */
401         module_count = 0;
402         memset(&modinfo[0], 0, sizeof(modinfo[0]));
403
404         while ((line = xmalloc_fgetline(fp)) != NULL) {
405                 char* space;
406                 char* linebuf;
407                 int cur;
408
409                 if (!line[0]) {
410                         free(line);
411                         continue;
412                 }
413                 space = strchrnul(line, ' ');
414                 cur = module_count++;
415                 modinfo = xrealloc_vector(modinfo, 12, cur);
416                 /*modinfo[cur+1].pathname = NULL; - xrealloc_vector did it */
417                 modinfo[cur].pathname = line; /* we take ownership of malloced block here */
418                 if (*space)
419                         *space++ = '\0';
420                 modinfo[cur].aliases = space;
421                 linebuf = xmalloc_fgetline(fp);
422                 modinfo[cur].deps = linebuf ? linebuf : xzalloc(1);
423                 if (modinfo[cur].deps[0]) {
424                         /* deps are not "", so next line must be empty */
425                         line = xmalloc_fgetline(fp);
426                         /* Refuse to work with damaged config file */
427                         if (line && line[0])
428                                 bb_error_msg_and_die("error in %s at '%s'", DEPFILE_BB, line);
429                         free(line);
430                 }
431         }
432         return 1;
433 }
434
435 static int start_dep_bb_writeout(void)
436 {
437         int fd;
438
439         /* depmod -n: write result to stdout */
440         if (applet_name[0] == 'd' && (option_mask32 & 1))
441                 return STDOUT_FILENO;
442
443         fd = open(DEPFILE_BB".new", O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
444         if (fd < 0) {
445                 if (errno == EEXIST) {
446                         int count = 5 * 20;
447                         dbg1_error_msg(DEPFILE_BB".new exists, waiting for "DEPFILE_BB);
448                         while (1) {
449                                 usleep(1000*1000 / 20);
450                                 if (load_dep_bb()) {
451                                         dbg1_error_msg(DEPFILE_BB" appeared");
452                                         return -2; /* magic number */
453                                 }
454                                 if (!--count)
455                                         break;
456                         }
457                         bb_error_msg("deleting stale %s", DEPFILE_BB".new");
458                         fd = open_or_warn(DEPFILE_BB".new", O_WRONLY | O_CREAT | O_TRUNC);
459                 }
460         }
461         dbg1_error_msg("opened "DEPFILE_BB".new:%d", fd);
462         return fd;
463 }
464
465 static void write_out_dep_bb(int fd)
466 {
467         int i;
468         FILE *fp;
469
470         /* We want good error reporting. fdprintf is not good enough. */
471         fp = xfdopen_for_write(fd);
472         i = 0;
473         while (modinfo[i].pathname) {
474                 fprintf(fp, "%s%s%s\n" "%s%s\n",
475                         modinfo[i].pathname, modinfo[i].aliases[0] ? " " : "", modinfo[i].aliases,
476                         modinfo[i].deps, modinfo[i].deps[0] ? "\n" : "");
477                 i++;
478         }
479         /* Badly formatted depfile is a no-no. Be paranoid. */
480         errno = 0;
481         if (ferror(fp) | fclose(fp)) /* | instead of || is intended */
482                 goto err;
483
484         if (fd == STDOUT_FILENO) /* it was depmod -n */
485                 goto ok;
486
487         if (rename(DEPFILE_BB".new", DEPFILE_BB) != 0) {
488  err:
489                 bb_perror_msg("can't create '%s'", DEPFILE_BB);
490                 unlink(DEPFILE_BB".new");
491         } else {
492  ok:
493                 wrote_dep_bb_ok = 1;
494                 dbg1_error_msg("created "DEPFILE_BB);
495         }
496 }
497
498 static module_info** find_alias(const char *alias)
499 {
500         int i;
501         int dep_bb_fd;
502         int infoidx;
503         module_info **infovec;
504         dbg1_error_msg("find_alias('%s')", alias);
505
506  try_again:
507         /* First try to find by name (cheaper) */
508         i = 0;
509         while (modinfo[i].pathname) {
510                 if (pathname_matches_modname(modinfo[i].pathname, alias)) {
511                         dbg1_error_msg("found '%s' in module '%s'",
512                                         alias, modinfo[i].pathname);
513                         if (!modinfo[i].aliases) {
514                                 parse_module(&modinfo[i], modinfo[i].pathname);
515                         }
516                         infovec = xzalloc(2 * sizeof(infovec[0]));
517                         infovec[0] = &modinfo[i];
518                         return infovec;
519                 }
520                 i++;
521         }
522
523         /* Ok, we definitely have to scan module bodies. This is a good
524          * moment to generate modprobe.dep.bb, if it does not exist yet */
525         dep_bb_fd = dep_bb_seen ? -1 : start_dep_bb_writeout();
526         if (dep_bb_fd == -2) /* modprobe.dep.bb appeared? */
527                 goto try_again;
528
529         /* Scan all module bodies, extract modinfo (it contains aliases) */
530         i = 0;
531         infoidx = 0;
532         infovec = NULL;
533         while (modinfo[i].pathname) {
534                 char *desc, *s;
535                 if (!modinfo[i].aliases) {
536                         parse_module(&modinfo[i], modinfo[i].pathname);
537                 }
538                 /* "alias1 symbol:sym1 alias2 symbol:sym2" */
539                 desc = str_2_list(modinfo[i].aliases);
540                 /* Does matching substring exist? */
541                 for (s = desc; *s; s += strlen(s) + 1) {
542                         /* Aliases in module bodies can be defined with
543                          * shell patterns. Example:
544                          * "pci:v000010DEd000000D9sv*sd*bc*sc*i*".
545                          * Plain strcmp() won't catch that */
546                         if (fnmatch(s, alias, 0) == 0) {
547                                 dbg1_error_msg("found alias '%s' in module '%s'",
548                                                 alias, modinfo[i].pathname);
549                                 infovec = xrealloc_vector(infovec, 1, infoidx);
550                                 infovec[infoidx++] = &modinfo[i];
551                                 break;
552                         }
553                 }
554                 free(desc);
555                 i++;
556         }
557
558         /* Create module.dep.bb if needed */
559         if (dep_bb_fd >= 0) {
560                 write_out_dep_bb(dep_bb_fd);
561         }
562
563         dbg1_error_msg("find_alias '%s' returns %d results", alias, infoidx);
564         return infovec;
565 }
566
567 #if ENABLE_FEATURE_MODPROBE_SMALL_CHECK_ALREADY_LOADED
568 // TODO: open only once, invent config_rewind()
569 static int already_loaded(const char *name)
570 {
571         int ret;
572         char *line;
573         FILE *fp;
574
575         ret = 5 * 2;
576  again:
577         fp = fopen_for_read("/proc/modules");
578         if (!fp)
579                 return 0;
580         while ((line = xmalloc_fgetline(fp)) != NULL) {
581                 char *live;
582                 char *after_name;
583
584                 // Examples from kernel 3.14.6:
585                 //pcspkr 12718 0 - Live 0xffffffffa017e000
586                 //snd_timer 28690 2 snd_seq,snd_pcm, Live 0xffffffffa025e000
587                 //i915 801405 2 - Live 0xffffffffa0096000
588                 after_name = is_prefixed_with(line, name);
589                 if (!after_name || *after_name != ' ') {
590                         free(line);
591                         continue;
592                 }
593                 live = strstr(line, " Live");
594                 free(line);
595                 if (!live) {
596                         /* State can be Unloading, Loading, or Live.
597                          * modprobe must not return prematurely if we see "Loading":
598                          * it can cause further programs to assume load completed,
599                          * but it did not (yet)!
600                          * Wait up to 5*20 ms for it to resolve.
601                          */
602                         ret -= 2;
603                         if (ret == 0)
604                                 break;  /* huh? report as "not loaded" */
605                         fclose(fp);
606                         usleep(20*1000);
607                         goto again;
608                 }
609                 ret = 1;
610                 break;
611         }
612         fclose(fp);
613
614         return ret & 1;
615 }
616 #else
617 #define already_loaded(name) 0
618 #endif
619
620 static int rmmod(const char *filename)
621 {
622         int r;
623         char modname[MODULE_NAME_LEN];
624
625         filename2modname(filename, modname);
626         r = delete_module(modname, O_NONBLOCK | O_EXCL);
627         dbg1_error_msg("delete_module('%s', O_NONBLOCK | O_EXCL):%d", modname, r);
628         if (r != 0 && !(option_mask32 & OPT_q)) {
629                 bb_perror_msg("remove '%s'", modname);
630         }
631         return r;
632 }
633
634 /*
635  * Given modules definition and module name (or alias, or symbol)
636  * load/remove the module respecting dependencies.
637  * NB: also called by depmod with bogus name "/",
638  * just in order to force modprobe.dep.bb creation.
639 */
640 #if !ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
641 #define process_module(a,b) process_module(a)
642 #define cmdline_options ""
643 #endif
644 static int process_module(char *name, const char *cmdline_options)
645 {
646         char *s, *deps, *options;
647         module_info **infovec;
648         module_info *info;
649         int infoidx;
650         int is_remove = (option_mask32 & OPT_r) != 0;
651         int exitcode = EXIT_SUCCESS;
652
653         dbg1_error_msg("process_module('%s','%s')", name, cmdline_options);
654
655         replace(name, '-', '_');
656
657         dbg1_error_msg("already_loaded:%d is_remove:%d", already_loaded(name), is_remove);
658
659         if (applet_name[0] == 'r') {
660                 /* rmmod.
661                  * Does not remove dependencies, no need to scan, just remove.
662                  * (compat note: this allows and strips .ko suffix)
663                  */
664                 rmmod(name);
665                 return EXIT_SUCCESS;
666         }
667
668         /*
669          * We used to have "is_remove != already_loaded(name)" check here, but
670          *  modprobe -r pci:v00008086d00007010sv00000000sd00000000bc01sc01i80
671          * won't unload modules (there are more than one)
672          * which have this alias.
673          */
674         if (!is_remove && already_loaded(name)) {
675                 dbg1_error_msg("nothing to do for '%s'", name);
676                 return EXIT_SUCCESS;
677         }
678
679         options = NULL;
680         if (!is_remove) {
681                 char *opt_filename = xasprintf("/etc/modules/%s", name);
682                 options = xmalloc_open_read_close(opt_filename, NULL);
683                 if (options)
684                         replace(options, '\n', ' ');
685 #if ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
686                 if (cmdline_options) {
687                         /* NB: cmdline_options always have one leading ' '
688                          * (see main()), we remove it here */
689                         char *op = xasprintf(options ? "%s %s" : "%s %s" + 3,
690                                                 cmdline_options + 1, options);
691                         free(options);
692                         options = op;
693                 }
694 #endif
695                 free(opt_filename);
696                 module_load_options = options;
697                 dbg1_error_msg("process_module('%s'): options:'%s'", name, options);
698         }
699
700         if (!module_count) {
701                 /* Scan module directory. This is done only once.
702                  * It will attempt module load, and will exit(EXIT_SUCCESS)
703                  * on success.
704                  */
705                 module_found_idx = -1;
706                 recursive_action(".",
707                         ACTION_RECURSE, /* flags */
708                         fileAction, /* file action */
709                         NULL, /* dir action */
710                         name, /* user data */
711                         0 /* depth */
712                 );
713                 dbg1_error_msg("dirscan complete");
714                 /* Module was not found, or load failed, or is_remove */
715                 if (module_found_idx >= 0) { /* module was found */
716                         infovec = xzalloc(2 * sizeof(infovec[0]));
717                         infovec[0] = &modinfo[module_found_idx];
718                 } else { /* search for alias, not a plain module name */
719                         infovec = find_alias(name);
720                 }
721         } else {
722                 infovec = find_alias(name);
723         }
724
725         if (!infovec) {
726                 /* both dirscan and find_alias found nothing */
727                 if (!is_remove && applet_name[0] != 'd') /* it wasn't rmmod or depmod */
728                         bb_error_msg("module '%s' not found", name);
729 //TODO: _and_die()? or should we continue (un)loading modules listed on cmdline?
730                 goto ret;
731         }
732
733         /* There can be more than one module for the given alias. For example,
734          * "pci:v00008086d00007010sv00000000sd00000000bc01sc01i80" matches
735          * ata_piix because it has alias "pci:v00008086d00007010sv*sd*bc*sc*i*"
736          * and ata_generic, it has alias "pci:v*d*sv*sd*bc01sc01i*"
737          * Standard modprobe loads them both. We achieve it by returning
738          * a *list* of modinfo pointers from find_alias().
739          */
740
741         /* modprobe -r? unload module(s) */
742         if (is_remove) {
743                 infoidx = 0;
744                 while ((info = infovec[infoidx++]) != NULL) {
745                         int r = rmmod(bb_get_last_path_component_nostrip(info->pathname));
746                         if (r != 0) {
747                                 goto ret; /* error */
748                         }
749                 }
750                 /* modprobe -r: we do not stop here -
751                  * continue to unload modules on which the module depends:
752                  * "-r --remove: option causes modprobe to remove a module.
753                  * If the modules it depends on are also unused, modprobe
754                  * will try to remove them, too."
755                  */
756         }
757
758         infoidx = 0;
759         while ((info = infovec[infoidx++]) != NULL) {
760                 /* Iterate thru dependencies, trying to (un)load them */
761                 deps = str_2_list(info->deps);
762                 for (s = deps; *s; s += strlen(s) + 1) {
763                         //if (strcmp(name, s) != 0) // N.B. do loops exist?
764                         dbg1_error_msg("recurse on dep '%s'", s);
765                         process_module(s, NULL);
766                         dbg1_error_msg("recurse on dep '%s' done", s);
767                 }
768                 free(deps);
769
770                 if (is_remove)
771                         continue;
772
773                 /* We are modprobe: load it */
774                 if (options && strstr(options, "blacklist")) {
775                         dbg1_error_msg("'%s': blacklisted", info->pathname);
776                         continue;
777                 }
778                 if (info->open_read_failed) {
779                         /* We already tried it, didn't work. Don't try load again */
780                         exitcode = EXIT_FAILURE;
781                         continue;
782                 }
783                 errno = 0;
784                 if (load_module(info->pathname, options) != 0) {
785                         if (EEXIST != errno) {
786                                 bb_error_msg("'%s': %s",
787                                         info->pathname,
788                                         moderror(errno));
789                         } else {
790                                 dbg1_error_msg("'%s': %s",
791                                         info->pathname,
792                                         moderror(errno));
793                         }
794                         exitcode = EXIT_FAILURE;
795                 }
796         }
797  ret:
798         free(infovec);
799         free(options);
800
801         return exitcode;
802 }
803 #undef cmdline_options
804
805
806 /* For reference, module-init-tools v3.4 options:
807
808 # insmod
809 Usage: insmod filename [args]
810
811 # rmmod --help
812 Usage: rmmod [-fhswvV] modulename ...
813  -f (or --force) forces a module unload, and may crash your
814     machine. This requires the Forced Module Removal option
815     when the kernel was compiled.
816  -h (or --help) prints this help text
817  -s (or --syslog) says use syslog, not stderr
818  -v (or --verbose) enables more messages
819  -V (or --version) prints the version code
820  -w (or --wait) begins module removal even if it is used
821     and will stop new users from accessing the module (so it
822     should eventually fall to zero).
823
824 # modprobe
825 Usage: modprobe [-v] [-V] [-C config-file] [-n] [-i] [-q] [-b]
826     [-o <modname>] [ --dump-modversions ] <modname> [parameters...]
827 modprobe -r [-n] [-i] [-v] <modulename> ...
828 modprobe -l -t <dirname> [ -a <modulename> ...]
829
830 # depmod --help
831 depmod 3.4 -- part of module-init-tools
832 depmod -[aA] [-n -e -v -q -V -r -u]
833       [-b basedirectory] [forced_version]
834 depmod [-n -e -v -q -r -u] [-F kernelsyms] module1.ko module2.ko ...
835 If no arguments (except options) are given, "depmod -a" is assumed.
836 depmod will output a dependency list suitable for the modprobe utility.
837 Options:
838     -a, --all           Probe all modules
839     -A, --quick         Only does the work if there's a new module
840     -n, --show          Write the dependency file on stdout only
841     -e, --errsyms       Report not supplied symbols
842     -V, --version       Print the release version
843     -v, --verbose       Enable verbose mode
844     -h, --help          Print this usage message
845 The following options are useful for people managing distributions:
846     -b basedirectory
847     --basedir basedirectory
848                         Use an image of a module tree
849     -F kernelsyms
850     --filesyms kernelsyms
851                         Use the file instead of the current kernel symbols
852 */
853
854 //usage:#if ENABLE_MODPROBE_SMALL
855
856 //usage:#define depmod_trivial_usage NOUSAGE_STR
857 //usage:#define depmod_full_usage ""
858
859 //usage:#define lsmod_trivial_usage
860 //usage:       ""
861 //usage:#define lsmod_full_usage "\n\n"
862 //usage:       "List the currently loaded kernel modules"
863
864 //usage:#define insmod_trivial_usage
865 //usage:        IF_FEATURE_2_4_MODULES("[OPTIONS] MODULE ")
866 //usage:        IF_NOT_FEATURE_2_4_MODULES("FILE ")
867 //usage:        "[SYMBOL=VALUE]..."
868 //usage:#define insmod_full_usage "\n\n"
869 //usage:       "Load kernel module"
870 //usage:        IF_FEATURE_2_4_MODULES( "\n"
871 //usage:     "\n        -f      Force module to load into the wrong kernel version"
872 //usage:     "\n        -k      Make module autoclean-able"
873 //usage:     "\n        -v      Verbose"
874 //usage:     "\n        -q      Quiet"
875 //usage:     "\n        -L      Lock: prevent simultaneous loads"
876 //usage:        IF_FEATURE_INSMOD_LOAD_MAP(
877 //usage:     "\n        -m      Output load map to stdout"
878 //usage:        )
879 //usage:     "\n        -x      Don't export externs"
880 //usage:        )
881
882 //usage:#define rmmod_trivial_usage
883 //usage:       "[-wfa] [MODULE]..."
884 //usage:#define rmmod_full_usage "\n\n"
885 //usage:       "Unload kernel modules\n"
886 //usage:     "\n        -w      Wait until the module is no longer used"
887 //usage:     "\n        -f      Force unload"
888 //usage:     "\n        -a      Remove all unused modules (recursively)"
889 //usage:
890 //usage:#define rmmod_example_usage
891 //usage:       "$ rmmod tulip\n"
892
893 //usage:#define modprobe_trivial_usage
894 //usage:        "[-qfwrsv] MODULE [SYMBOL=VALUE]..."
895 //usage:#define modprobe_full_usage "\n\n"
896 //usage:       "        -r      Remove MODULE (stacks) or do autoclean"
897 //usage:     "\n        -q      Quiet"
898 //usage:     "\n        -v      Verbose"
899 //usage:     "\n        -f      Force"
900 //usage:     "\n        -w      Wait for unload"
901 //usage:     "\n        -s      Report via syslog instead of stderr"
902
903 //usage:#endif
904
905 int modprobe_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
906 int modprobe_main(int argc UNUSED_PARAM, char **argv)
907 {
908         int exitcode;
909         struct utsname uts;
910         char applet0 = applet_name[0];
911         IF_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(char *options;)
912
913         /* are we lsmod? -> just dump /proc/modules */
914         if ('l' == applet0) {
915                 xprint_and_close_file(xfopen_for_read("/proc/modules"));
916                 return EXIT_SUCCESS;
917         }
918
919         INIT_G();
920
921         /* Prevent ugly corner cases with no modules at all */
922         modinfo = xzalloc(sizeof(modinfo[0]));
923
924         if ('i' != applet0) { /* not insmod */
925                 /* Goto modules directory */
926                 xchdir(CONFIG_DEFAULT_MODULES_DIR);
927         }
928         uname(&uts); /* never fails */
929
930         /* depmod? */
931         if ('d' == applet0) {
932                 /* Supported:
933                  * -n: print result to stdout
934                  * -a: process all modules (default)
935                  * optional VERSION parameter
936                  * Ignored:
937                  * -A: do work only if a module is newer than depfile
938                  * -e: report any symbols which a module needs
939                  *  which are not supplied by other modules or the kernel
940                  * -F FILE: System.map (symbols for -e)
941                  * -q, -r, -u: noop?
942                  * Not supported:
943                  * -b BASEDIR: (TODO!) modules are in
944                  *  $BASEDIR/lib/modules/$VERSION
945                  * -v: human readable deps to stdout
946                  * -V: version (don't want to support it - people may depend
947                  *  on it as an indicator of "standard" depmod)
948                  * -h: help (well duh)
949                  * module1.o module2.o parameters (just ignored for now)
950                  */
951                 getopt32(argv, "na" "AeF:qru" /* "b:vV", NULL */, NULL);
952                 argv += optind;
953                 /* if (argv[0] && argv[1]) bb_show_usage(); */
954                 /* Goto $VERSION directory */
955                 xchdir(argv[0] ? argv[0] : uts.release);
956                 /* Force full module scan by asking to find a bogus module.
957                  * This will generate modules.dep.bb as a side effect. */
958                 process_module((char*)"/", NULL);
959                 return !wrote_dep_bb_ok;
960         }
961
962         /* insmod, modprobe, rmmod require at least one argument */
963         opt_complementary = "-1";
964         /* only -q (quiet) and -r (rmmod),
965          * the rest are accepted and ignored (compat) */
966         getopt32(argv, "qrfsvwb");
967         argv += optind;
968
969         /* are we rmmod? -> simulate modprobe -r */
970         if ('r' == applet0) {
971                 option_mask32 |= OPT_r;
972         }
973
974         if ('i' != applet0) { /* not insmod */
975                 /* Goto $VERSION directory */
976                 xchdir(uts.release);
977         }
978
979 #if ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
980         /* If not rmmod/-r, parse possible module options given on command line.
981          * insmod/modprobe takes one module name, the rest are parameters. */
982         options = NULL;
983         if (!(option_mask32 & OPT_r)) {
984                 char **arg = argv;
985                 while (*++arg) {
986                         /* Enclose options in quotes */
987                         char *s = options;
988                         options = xasprintf("%s \"%s\"", s ? s : "", *arg);
989                         free(s);
990                         *arg = NULL;
991                 }
992         }
993 #else
994         if (!(option_mask32 & OPT_r))
995                 argv[1] = NULL;
996 #endif
997
998         if ('i' == applet0) { /* insmod */
999                 size_t len;
1000                 void *map;
1001
1002                 len = MAXINT(ssize_t);
1003                 map = xmalloc_open_zipped_read_close(*argv, &len);
1004                 if (!map)
1005                         bb_perror_msg_and_die("can't read '%s'", *argv);
1006                 if (init_module(map, len,
1007                         IF_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(options ? options : "")
1008                         IF_NOT_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE("")
1009                         ) != 0
1010                 ) {
1011                         bb_error_msg_and_die("can't insert '%s': %s",
1012                                         *argv, moderror(errno));
1013                 }
1014                 return EXIT_SUCCESS;
1015         }
1016
1017         /* Try to load modprobe.dep.bb */
1018         if ('r' != applet0) { /* not rmmod */
1019                 load_dep_bb();
1020         }
1021
1022         /* Load/remove modules.
1023          * Only rmmod/modprobe -r loops here, insmod/modprobe has only argv[0] */
1024         exitcode = EXIT_SUCCESS;
1025         do {
1026                 exitcode |= process_module(*argv, options);
1027         } while (*++argv);
1028
1029         if (ENABLE_FEATURE_CLEAN_UP) {
1030                 IF_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(free(options);)
1031         }
1032         return exitcode;
1033 }