hush: add #defines to switch off break/continue if loops are not supported
[oweals/busybox.git] / modutils / modprobe.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Modprobe written from scratch for BusyBox
4  *
5  * Copyright (c) 2002 by Robert Griebl, griebl@gmx.de
6  * Copyright (c) 2003 by Andrew Dennison, andrew.dennison@motec.com.au
7  * Copyright (c) 2005 by Jim Bauer, jfbauer@nfr.com
8  *
9  * Portions Copyright (c) 2005 by Yann E. MORIN, yann.morin.1998@anciens.enib.fr
10  *
11  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
12 */
13
14 #include "libbb.h"
15 #include <sys/utsname.h>
16 #include <fnmatch.h>
17
18 #define line_buffer bb_common_bufsiz1
19
20 struct mod_opt_t {      /* one-way list of options to pass to a module */
21         char *  m_opt_val;
22         struct mod_opt_t * m_next;
23 };
24
25 struct dep_t {  /* one-way list of dependency rules */
26         /* a dependency rule */
27         char *  m_name;                     /* the module name*/
28         char *  m_path;                     /* the module file path */
29         struct mod_opt_t *  m_options;      /* the module options */
30
31         unsigned int m_isalias      :1;     /* the module is an alias */
32         unsigned int m_isblacklisted:1;     /* the module is blacklisted */
33         unsigned int m_reserved     :14;    /* stuffin' */
34
35         unsigned int m_depcnt       :16;    /* the number of dependable module(s) */
36         char ** m_deparr;                   /* the list of dependable module(s) */
37
38         struct dep_t * m_next;              /* the next dependency rule */
39 };
40
41 struct mod_list_t {     /* two-way list of modules to process */
42         /* a module description */
43         const char * m_name;
44         char * m_path;
45         struct mod_opt_t * m_options;
46
47         struct mod_list_t * m_prev;
48         struct mod_list_t * m_next;
49 };
50
51 struct include_conf_t {
52         struct dep_t *first;
53         struct dep_t *current;
54 };
55
56 static struct dep_t *depend;
57
58 #define MAIN_OPT_STR "acdklnqrst:vVC:"
59 #define INSERT_ALL     1        /* a */
60 #define DUMP_CONF_EXIT 2        /* c */
61 #define D_OPT_IGNORED  4        /* d */
62 #define AUTOCLEAN_FLG  8        /* k */
63 #define LIST_ALL       16       /* l */
64 #define SHOW_ONLY      32       /* n */
65 #define QUIET          64       /* q */
66 #define REMOVE_OPT     128      /* r */
67 #define DO_SYSLOG      256      /* s */
68 #define RESTRICT_DIR   512      /* t */
69 #define VERBOSE        1024     /* v */
70 #define VERSION_ONLY   2048     /* V */
71 #define CONFIG_FILE    4096     /* C */
72
73 #define autoclean       (option_mask32 & AUTOCLEAN_FLG)
74 #define show_only       (option_mask32 & SHOW_ONLY)
75 #define quiet           (option_mask32 & QUIET)
76 #define remove_opt      (option_mask32 & REMOVE_OPT)
77 #define do_syslog       (option_mask32 & DO_SYSLOG)
78 #define verbose         (option_mask32 & VERBOSE)
79
80 static int parse_tag_value(char *buffer, char **ptag, char **pvalue)
81 {
82         char *tag, *value;
83
84         buffer = skip_whitespace(buffer);
85         tag = value = buffer;
86         while (!isspace(*value)) {
87                 if (!*value)
88                         return 0;
89                 value++;
90         }
91         *value++ = '\0';
92         value = skip_whitespace(value);
93         if (!*value)
94                 return 0;
95
96         *ptag = tag;
97         *pvalue = value;
98
99         return 1;
100 }
101
102 /*
103  * This function appends an option to a list
104  */
105 static struct mod_opt_t *append_option(struct mod_opt_t *opt_list, char *opt)
106 {
107         struct mod_opt_t *ol = opt_list;
108
109         if (ol) {
110                 while (ol->m_next) {
111                         ol = ol->m_next;
112                 }
113                 ol->m_next = xzalloc(sizeof(struct mod_opt_t));
114                 ol = ol->m_next;
115         } else {
116                 ol = opt_list = xzalloc(sizeof(struct mod_opt_t));
117         }
118
119         ol->m_opt_val = xstrdup(opt);
120         /*ol->m_next = NULL; - done by xzalloc*/
121
122         return opt_list;
123 }
124
125 #if ENABLE_FEATURE_MODPROBE_MULTIPLE_OPTIONS
126 /* static char* parse_command_string(char* src, char **dst);
127  *   src: pointer to string containing argument
128  *   dst: pointer to where to store the parsed argument
129  *   return value: the pointer to the first char after the parsed argument,
130  *                 NULL if there was no argument parsed (only trailing spaces).
131  *   Note that memory is allocated with xstrdup when a new argument was
132  *   parsed. Don't forget to free it!
133  */
134 #define ARG_EMPTY      0x00
135 #define ARG_IN_DQUOTES 0x01
136 #define ARG_IN_SQUOTES 0x02
137 static char *parse_command_string(char *src, char **dst)
138 {
139         int opt_status = ARG_EMPTY;
140         char* tmp_str;
141
142         /* Dumb you, I have nothing to do... */
143         if (src == NULL) return src;
144
145         /* Skip leading spaces */
146         while (*src == ' ') {
147                 src++;
148         }
149         /* Is the end of string reached? */
150         if (*src == '\0') {
151                 return NULL;
152         }
153         /* Reached the start of an argument
154          * By the way, we duplicate a little too much
155          * here but what is too much is freed later. */
156         *dst = tmp_str = xstrdup(src);
157         /* Get to the end of that argument */
158         while (*tmp_str != '\0'
159          && (*tmp_str != ' ' || (opt_status & (ARG_IN_DQUOTES | ARG_IN_SQUOTES)))
160         ) {
161                 switch (*tmp_str) {
162                 case '\'':
163                         if (opt_status & ARG_IN_DQUOTES) {
164                                 /* Already in double quotes, keep current char as is */
165                         } else {
166                                 /* shift left 1 char, until end of string: get rid of the opening/closing quotes */
167                                 memmove(tmp_str, tmp_str + 1, strlen(tmp_str));
168                                 /* mark me: we enter or leave single quotes */
169                                 opt_status ^= ARG_IN_SQUOTES;
170                                 /* Back one char, as we need to re-scan the new char there. */
171                                 tmp_str--;
172                         }
173                         break;
174                 case '"':
175                         if (opt_status & ARG_IN_SQUOTES) {
176                                 /* Already in single quotes, keep current char as is */
177                         } else {
178                                 /* shift left 1 char, until end of string: get rid of the opening/closing quotes */
179                                 memmove(tmp_str, tmp_str + 1, strlen(tmp_str));
180                                 /* mark me: we enter or leave double quotes */
181                                 opt_status ^= ARG_IN_DQUOTES;
182                                 /* Back one char, as we need to re-scan the new char there. */
183                                 tmp_str--;
184                         }
185                         break;
186                 case '\\':
187                         if (opt_status & ARG_IN_SQUOTES) {
188                                 /* Between single quotes: keep as is. */
189                         } else {
190                                 switch (*(tmp_str+1)) {
191                                 case 'a':
192                                 case 'b':
193                                 case 't':
194                                 case 'n':
195                                 case 'v':
196                                 case 'f':
197                                 case 'r':
198                                 case '0':
199                                         /* We escaped a special character. For now, keep
200                                          * both the back-slash and the following char. */
201                                         tmp_str++;
202                                         src++;
203                                         break;
204                                 default:
205                                         /* We escaped a space or a single or double quote,
206                                          * or a back-slash, or a non-escapable char. Remove
207                                          * the '\' and keep the new current char as is. */
208                                         memmove(tmp_str, tmp_str + 1, strlen(tmp_str));
209                                         break;
210                                 }
211                         }
212                         break;
213                 /* Any other char that is special shall appear here.
214                  * Example: $ starts a variable
215                 case '$':
216                         do_variable_expansion();
217                         break;
218                  * */
219                 default:
220                         /* any other char is kept as is. */
221                         break;
222                 }
223                 tmp_str++; /* Go to next char */
224                 src++; /* Go to next char to find the end of the argument. */
225         }
226         /* End of string, but still no ending quote */
227         if (opt_status & (ARG_IN_DQUOTES | ARG_IN_SQUOTES)) {
228                 bb_error_msg_and_die("unterminated (single or double) quote in options list: %s", src);
229         }
230         *tmp_str++ = '\0';
231         *dst = xrealloc(*dst, (tmp_str - *dst));
232         return src;
233 }
234 #else
235 #define parse_command_string(src, dst)  (0)
236 #endif /* ENABLE_FEATURE_MODPROBE_MULTIPLE_OPTIONS */
237
238 static int is_conf_command(char *buffer, const char *command)
239 {
240         int len = strlen(command);
241         return ((strstr(buffer, command) == buffer) &&
242                         isspace(buffer[len]));
243 }
244
245 /*
246  * This function reads aliases and default module options from a configuration file
247  * (/etc/modprobe.conf syntax). It supports includes (only files, no directories).
248  */
249
250 static int FAST_FUNC include_conf_file_act(const char *filename,
251                                            struct stat *statbuf UNUSED_PARAM,
252                                            void *userdata,
253                                            int depth UNUSED_PARAM);
254
255 static int FAST_FUNC include_conf_dir_act(const char *filename UNUSED_PARAM,
256                                           struct stat *statbuf UNUSED_PARAM,
257                                           void *userdata UNUSED_PARAM,
258                                           int depth)
259 {
260         if (depth > 1)
261                 return SKIP;
262
263         return TRUE;
264 }
265
266 static int include_conf_recursive(struct include_conf_t *conf, const char *filename)
267 {
268         return recursive_action(filename, ACTION_RECURSE,
269                                 include_conf_file_act,
270                                 include_conf_dir_act,
271                                 conf, 1);
272 }
273
274 static int FAST_FUNC include_conf_file_act(const char *filename,
275                                            struct stat *statbuf UNUSED_PARAM,
276                                            void *userdata,
277                                            int depth UNUSED_PARAM)
278 {
279         struct include_conf_t *conf = (struct include_conf_t *) userdata;
280         struct dep_t **first = &conf->first;
281         struct dep_t **current = &conf->current;
282         int continuation_line = 0;
283         int fd;
284
285         if (bb_basename(filename)[0] == '.')
286                 return TRUE;
287
288         fd = open(filename, O_RDONLY);
289         if (fd < 0)
290                 return FALSE;
291
292         // alias parsing is not 100% correct (no correct handling of continuation lines within an alias)!
293
294         while (reads(fd, line_buffer, sizeof(line_buffer))) {
295                 int l;
296
297                 *strchrnul(line_buffer, '#') = '\0';
298
299                 l = strlen(line_buffer);
300
301                 while (l && isspace(line_buffer[l-1])) {
302                         line_buffer[l-1] = '\0';
303                         l--;
304                 }
305
306                 if (l == 0) {
307                         continuation_line = 0;
308                         continue;
309                 }
310
311                 if (continuation_line)
312                         continue;
313
314                 if (is_conf_command(line_buffer, "alias")) {
315                         char *alias, *mod;
316
317                         if (parse_tag_value(line_buffer + 6, &alias, &mod)) {
318                                 /* handle alias as a module dependent on the aliased module */
319                                 if (!*current) {
320                                         (*first) = (*current) = xzalloc(sizeof(struct dep_t));
321                                 } else {
322                                         (*current)->m_next = xzalloc(sizeof(struct dep_t));
323                                         (*current) = (*current)->m_next;
324                                 }
325                                 (*current)->m_name = xstrdup(alias);
326                                 (*current)->m_isalias = 1;
327
328                                 if ((strcmp(mod, "off") == 0) || (strcmp(mod, "null") == 0)) {
329                                         /*(*current)->m_depcnt = 0; - done by xzalloc */
330                                         /*(*current)->m_deparr = 0;*/
331                                 } else {
332                                         (*current)->m_depcnt = 1;
333                                         (*current)->m_deparr = xmalloc(sizeof(char *));
334                                         (*current)->m_deparr[0] = xstrdup(mod);
335                                 }
336                                 /*(*current)->m_next = NULL; - done by xzalloc */
337                         }
338                 } else if (is_conf_command(line_buffer, "options")) {
339                         char *mod, *opt;
340
341                         /* split the line in the module/alias name, and options */
342                         if (parse_tag_value(line_buffer + 8, &mod, &opt)) {
343                                 struct dep_t *dt;
344
345                                 /* find the corresponding module */
346                                 for (dt = *first; dt; dt = dt->m_next) {
347                                         if (strcmp(dt->m_name, mod) == 0)
348                                                 break;
349                                 }
350                                 if (dt) {
351                                         if (ENABLE_FEATURE_MODPROBE_MULTIPLE_OPTIONS) {
352                                                 char* new_opt = NULL;
353                                                 while ((opt = parse_command_string(opt, &new_opt))) {
354                                                         dt->m_options = append_option(dt->m_options, new_opt);
355                                                 }
356                                         } else {
357                                                 dt->m_options = append_option(dt->m_options, opt);
358                                         }
359                                 }
360                         }
361                 } else if (is_conf_command(line_buffer, "include")) {
362                         char *includefile;
363
364                         includefile = skip_whitespace(line_buffer + 8);
365                         include_conf_recursive(conf, includefile);
366                 } else if (ENABLE_FEATURE_MODPROBE_BLACKLIST &&
367                                 (is_conf_command(line_buffer, "blacklist"))) {
368                         char *mod;
369                         struct dep_t *dt;
370
371                         mod = skip_whitespace(line_buffer + 10);
372                         for (dt = *first; dt; dt = dt->m_next) {
373                                 if (strcmp(dt->m_name, mod) == 0)
374                                         break;
375                         }
376                         if (dt)
377                                 dt->m_isblacklisted = 1;
378                 }
379         } /* while (reads(...)) */
380
381         close(fd);
382         return TRUE;
383 }
384
385 static int include_conf_file(struct include_conf_t *conf,
386                              const char *filename)
387 {
388         return include_conf_file_act(filename, NULL, conf, 0);
389 }
390
391 static int include_conf_file2(struct include_conf_t *conf,
392                               const char *filename, const char *oldname)
393 {
394         if (include_conf_file(conf, filename) == TRUE)
395                 return TRUE;
396         return include_conf_file(conf, oldname);
397 }
398
399 /*
400  * This function builds a list of dependency rules from /lib/modules/`uname -r`/modules.dep.
401  * It then fills every modules and aliases with their default options, found by parsing
402  * modprobe.conf (or modules.conf, or conf.modules).
403  */
404 static struct dep_t *build_dep(void)
405 {
406         int fd;
407         struct utsname un;
408         struct include_conf_t conf = { NULL, NULL };
409         char *filename;
410         int continuation_line = 0;
411         int k_version;
412
413         if (uname(&un))
414                 bb_error_msg_and_die("can't determine kernel version");
415
416         k_version = 0;
417         if (un.release[0] == '2') {
418                 k_version = un.release[2] - '0';
419         }
420
421         filename = xasprintf(CONFIG_DEFAULT_MODULES_DIR"/%s/"CONFIG_DEFAULT_DEPMOD_FILE, un.release);
422         fd = open(filename, O_RDONLY);
423         if (ENABLE_FEATURE_CLEAN_UP)
424                 free(filename);
425         if (fd < 0) {
426                 /* Ok, that didn't work.  Fall back to looking in /lib/modules */
427                 fd = open(CONFIG_DEFAULT_MODULES_DIR"/"CONFIG_DEFAULT_DEPMOD_FILE, O_RDONLY);
428                 if (fd < 0) {
429                         bb_error_msg_and_die("cannot parse " CONFIG_DEFAULT_DEPMOD_FILE);
430                 }
431         }
432
433         while (reads(fd, line_buffer, sizeof(line_buffer))) {
434                 int l = strlen(line_buffer);
435                 char *p = 0;
436
437                 while (l > 0 && isspace(line_buffer[l-1])) {
438                         line_buffer[l-1] = '\0';
439                         l--;
440                 }
441
442                 if (l == 0) {
443                         continuation_line = 0;
444                         continue;
445                 }
446
447                 /* Is this a new module dep description? */
448                 if (!continuation_line) {
449                         /* find the dep beginning */
450                         char *col = strchr(line_buffer, ':');
451                         char *dot = col;
452
453                         if (col) {
454                                 /* This line is a dep description */
455                                 const char *mods;
456                                 char *modpath;
457                                 char *mod;
458
459                                 /* Find the beginning of the module file name */
460                                 *col = '\0';
461                                 mods = bb_basename(line_buffer);
462
463                                 /* find the path of the module */
464                                 modpath = strchr(line_buffer, '/'); /* ... and this is the path */
465                                 if (!modpath)
466                                         modpath = line_buffer; /* module with no path */
467                                 /* find the end of the module name in the file name */
468                                 if (ENABLE_FEATURE_2_6_MODULES &&
469                                     (k_version > 4) && (col[-3] == '.') &&
470                                     (col[-2] == 'k') && (col[-1] == 'o'))
471                                         dot = col - 3;
472                                 else if ((col[-2] == '.') && (col[-1] == 'o'))
473                                         dot = col - 2;
474
475                                 mod = xstrndup(mods, dot - mods);
476
477                                 /* enqueue new module */
478                                 if (!conf.current) {
479                                         conf.first = conf.current = xzalloc(sizeof(struct dep_t));
480                                 } else {
481                                         conf.current->m_next = xzalloc(sizeof(struct dep_t));
482                                         conf.current = conf.current->m_next;
483                                 }
484                                 conf.current->m_name = mod;
485                                 conf.current->m_path = xstrdup(modpath);
486                                 /*current->m_options = NULL; - xzalloc did it*/
487                                 /*current->m_isalias = 0;*/
488                                 /*current->m_depcnt = 0;*/
489                                 /*current->m_deparr = 0;*/
490                                 /*current->m_next = 0;*/
491
492                                 p = col + 1;
493                         } else
494                                 /* this line is not a dep description */
495                                 p = NULL;
496                 } else
497                         /* It's a dep description continuation */
498                         p = line_buffer;
499
500                 /* p points to the first dependable module; if NULL, no dependable module */
501                 if (p && (p = skip_whitespace(p))[0] != '\0') {
502                         char *end = &line_buffer[l-1];
503                         const char *deps;
504                         char *dep;
505                         char *next;
506                         int ext = 0;
507
508                         while (isblank(*end) || (*end == '\\'))
509                                 end--;
510
511                         do {
512                                 /* search the end of the dependency */
513                                 next = strchr(p, ' ');
514                                 if (next) {
515                                         *next = '\0';
516                                         next--;
517                                 } else
518                                         next = end;
519
520                                 /* find the beginning of the module file name */
521                                 deps = bb_basename(p);
522                                 if (deps == p)
523                                         deps = skip_whitespace(deps);
524
525                                 /* find the end of the module name in the file name */
526                                 if (ENABLE_FEATURE_2_6_MODULES
527                                  && (k_version > 4) && (next[-2] == '.')
528                                  && (next[-1] == 'k') && (next[0] == 'o'))
529                                         ext = 3;
530                                 else if ((next[-1] == '.') && (next[0] == 'o'))
531                                         ext = 2;
532
533                                 /* Cope with blank lines */
534                                 if ((next-deps-ext+1) <= 0)
535                                         continue;
536                                 dep = xstrndup(deps, next - deps - ext + 1);
537
538                                 /* Add the new dependable module name */
539                                 conf.current->m_deparr = xrealloc_vector(conf.current->m_deparr, 2, conf.current->m_depcnt);
540                                 conf.current->m_deparr[conf.current->m_depcnt++] = dep;
541
542                                 p = next + 2;
543                         } while (next < end);
544                 }
545
546                 /* is there other dependable module(s) ? */
547                 continuation_line = (line_buffer[l-1] == '\\');
548         } /* while (reads(...)) */
549         close(fd);
550
551         /*
552          * First parse system-specific options and aliases
553          * as they take precedence over the kernel ones.
554          * >=2.6: we only care about modprobe.conf
555          * <=2.4: we care about modules.conf and conf.modules
556          */
557         {
558                 int r = FALSE;
559
560                 if (ENABLE_FEATURE_2_6_MODULES) {
561                         if (include_conf_file(&conf, "/etc/modprobe.conf"))
562                                 r = TRUE;
563                         if (include_conf_recursive(&conf, "/etc/modprobe.d"))
564                                 r = TRUE;
565                 }
566                 if (ENABLE_FEATURE_2_4_MODULES && !r)
567                         include_conf_file2(&conf,
568                                            "/etc/modules.conf",
569                                            "/etc/conf.modules");
570         }
571
572         /* Only 2.6 has a modules.alias file */
573         if (ENABLE_FEATURE_2_6_MODULES) {
574                 /* Parse kernel-declared module aliases */
575                 filename = xasprintf(CONFIG_DEFAULT_MODULES_DIR"/%s/modules.alias", un.release);
576                 include_conf_file2(&conf,
577                                    filename,
578                                    CONFIG_DEFAULT_MODULES_DIR"/modules.alias");
579                 if (ENABLE_FEATURE_CLEAN_UP)
580                         free(filename);
581
582                 /* Parse kernel-declared symbol aliases */
583                 filename = xasprintf(CONFIG_DEFAULT_MODULES_DIR"/%s/modules.symbols", un.release);
584                 include_conf_file2(&conf,
585                                    filename,
586                                    CONFIG_DEFAULT_MODULES_DIR"/modules.symbols");
587                 if (ENABLE_FEATURE_CLEAN_UP)
588                         free(filename);
589         }
590
591         return conf.first;
592 }
593
594 /* return 1 = loaded, 0 = not loaded, -1 = can't tell */
595 static int already_loaded(const char *name)
596 {
597         int fd, ret = 0;
598
599         fd = open("/proc/modules", O_RDONLY);
600         if (fd < 0)
601                 return -1;
602
603         while (reads(fd, line_buffer, sizeof(line_buffer))) {
604                 char *p;
605
606                 p = strchr(line_buffer, ' ');
607                 if (p) {
608                         const char *n;
609
610                         // Truncate buffer at first space and check for matches, with
611                         // the idiosyncrasy that _ and - are interchangeable because the
612                         // 2.6 kernel does weird things.
613
614                         *p = '\0';
615                         for (p = line_buffer, n = name; ; p++, n++) {
616                                 if (*p != *n) {
617                                         if ((*p == '_' || *p == '-') && (*n == '_' || *n == '-'))
618                                                 continue;
619                                         break;
620                                 }
621                                 // If we made it to the end, that's a match.
622                                 if (!*p) {
623                                         ret = 1;
624                                         goto done;
625                                 }
626                         }
627                 }
628         }
629  done:
630         close(fd);
631         return ret;
632 }
633
634 static int mod_process(const struct mod_list_t *list, int do_insert)
635 {
636         int rc = 0;
637         char **argv = NULL;
638         struct mod_opt_t *opts;
639         int argc_malloc; /* never used when CONFIG_FEATURE_CLEAN_UP not defined */
640         int argc;
641
642         while (list) {
643                 argc = 0;
644                 if (ENABLE_FEATURE_CLEAN_UP)
645                         argc_malloc = 0;
646                 /* If CONFIG_FEATURE_CLEAN_UP is not defined, then we leak memory
647                  * each time we allocate memory for argv.
648                  * But it is (quite) small amounts of memory that leak each
649                  * time a module is loaded,  and it is reclaimed when modprobe
650                  * exits anyway (even when standalone shell?).
651                  * This could become a problem when loading a module with LOTS of
652                  * dependencies, with LOTS of options for each dependencies, with
653                  * very little memory on the target... But in that case, the module
654                  * would not load because there is no more memory, so there's no
655                  * problem. */
656                 /* enough for minimal insmod (5 args + NULL) or rmmod (3 args + NULL) */
657                 argv = xmalloc(6 * sizeof(char*));
658                 if (do_insert) {
659                         if (already_loaded(list->m_name) != 1) {
660                                 argv[argc++] = (char*)"insmod";
661                                 if (ENABLE_FEATURE_2_4_MODULES) {
662                                         if (do_syslog)
663                                                 argv[argc++] = (char*)"-s";
664                                         if (autoclean)
665                                                 argv[argc++] = (char*)"-k";
666                                         if (quiet)
667                                                 argv[argc++] = (char*)"-q";
668                                         else if (verbose) /* verbose and quiet are mutually exclusive */
669                                                 argv[argc++] = (char*)"-v";
670                                 }
671                                 argv[argc++] = list->m_path;
672                                 if (ENABLE_FEATURE_CLEAN_UP)
673                                         argc_malloc = argc;
674                                 opts = list->m_options;
675                                 while (opts) {
676                                         /* Add one more option */
677                                         argc++;
678                                         argv = xrealloc(argv, (argc + 1) * sizeof(char*));
679                                         argv[argc-1] = opts->m_opt_val;
680                                         opts = opts->m_next;
681                                 }
682                         }
683                 } else {
684                         /* modutils uses short name for removal */
685                         if (already_loaded(list->m_name) != 0) {
686                                 argv[argc++] = (char*)"rmmod";
687                                 if (do_syslog)
688                                         argv[argc++] = (char*)"-s";
689                                 argv[argc++] = (char*)list->m_name;
690                                 if (ENABLE_FEATURE_CLEAN_UP)
691                                         argc_malloc = argc;
692                         }
693                 }
694                 argv[argc] = NULL;
695
696                 if (argc) {
697                         if (verbose) {
698                                 printf("%s module %s\n", do_insert?"Loading":"Unloading", list->m_name);
699                         }
700                         if (!show_only) {
701                                 int rc2 = wait4pid(spawn(argv));
702
703                                 if (do_insert) {
704                                         rc = rc2; /* only last module matters */
705                                 } else if (!rc2) {
706                                         rc = 0; /* success if remove any mod */
707                                 }
708                         }
709                         if (ENABLE_FEATURE_CLEAN_UP) {
710                                 /* the last value in the array has index == argc, but
711                                  * it is the terminating NULL, so we must not free it. */
712                                 while (argc_malloc < argc) {
713                                         free(argv[argc_malloc++]);
714                                 }
715                         }
716                 }
717                 if (ENABLE_FEATURE_CLEAN_UP) {
718                         free(argv);
719                         argv = NULL;
720                 }
721                 list = do_insert ? list->m_prev : list->m_next;
722         }
723         return (show_only) ? 0 : rc;
724 }
725
726 /*
727  * Check the matching between a pattern and a module name.
728  * We need this as *_* is equivalent to *-*, even in pattern matching.
729  */
730 static int check_pattern(const char* pat_src, const char* mod_src)
731 {
732         int ret;
733
734         if (ENABLE_FEATURE_MODPROBE_FANCY_ALIAS) {
735                 char* pat;
736                 char* mod;
737                 char* p;
738
739                 pat = xstrdup(pat_src);
740                 mod = xstrdup(mod_src);
741
742                 for (p = pat; (p = strchr(p, '-')); *p++ = '_');
743                 for (p = mod; (p = strchr(p, '-')); *p++ = '_');
744
745                 ret = fnmatch(pat, mod, 0);
746
747                 if (ENABLE_FEATURE_CLEAN_UP) {
748                         free(pat);
749                         free(mod);
750                 }
751
752                 return ret;
753         }
754         return fnmatch(pat_src, mod_src, 0);
755 }
756
757 /*
758  * Builds the dependency list (aka stack) of a module.
759  * head: the highest module in the stack (last to insmod, first to rmmod)
760  * tail: the lowest module in the stack (first to insmod, last to rmmod)
761  */
762 static void check_dep(char *mod, struct mod_list_t **head, struct mod_list_t **tail)
763 {
764         struct mod_list_t *find;
765         struct dep_t *dt;
766         struct mod_opt_t *opt = NULL;
767         char *path = NULL;
768
769         /* Search for the given module name amongst all dependency rules.
770          * The module name in a dependency rule can be a shell pattern,
771          * so try to match the given module name against such a pattern.
772          * Of course if the name in the dependency rule is a plain string,
773          * then we consider it a pattern, and matching will still work. */
774         for (dt = depend; dt; dt = dt->m_next) {
775                 if (check_pattern(dt->m_name, mod) == 0) {
776                         break;
777                 }
778         }
779
780         if (!dt) {
781                 bb_error_msg("module %s not found", mod);
782                 return;
783         }
784
785         // resolve alias names
786         while (dt->m_isalias) {
787                 if (dt->m_depcnt == 1) {
788                         struct dep_t *adt;
789
790                         for (adt = depend; adt; adt = adt->m_next) {
791                                 if (check_pattern(adt->m_name, dt->m_deparr[0]) == 0 &&
792                                                 !(ENABLE_FEATURE_MODPROBE_BLACKLIST &&
793                                                         adt->m_isblacklisted))
794                                         break;
795                         }
796                         if (adt) {
797                                 /* This is the module we are aliased to */
798                                 struct mod_opt_t *opts = dt->m_options;
799                                 /* Option of the alias are appended to the options of the module */
800                                 while (opts) {
801                                         adt->m_options = append_option(adt->m_options, opts->m_opt_val);
802                                         opts = opts->m_next;
803                                 }
804                                 dt = adt;
805                         } else {
806                                 bb_error_msg("module %s not found", mod);
807                                 return;
808                         }
809                 } else {
810                         bb_error_msg("bad alias %s", dt->m_name);
811                         return;
812                 }
813         }
814
815         mod = dt->m_name;
816         path = dt->m_path;
817         opt = dt->m_options;
818
819         // search for duplicates
820         for (find = *head; find; find = find->m_next) {
821                 if (strcmp(mod, find->m_name) == 0) {
822                         // found -> dequeue it
823
824                         if (find->m_prev)
825                                 find->m_prev->m_next = find->m_next;
826                         else
827                                 *head = find->m_next;
828
829                         if (find->m_next)
830                                 find->m_next->m_prev = find->m_prev;
831                         else
832                                 *tail = find->m_prev;
833
834                         break; // there can be only one duplicate
835                 }
836         }
837
838         if (!find) { // did not find a duplicate
839                 find = xzalloc(sizeof(struct mod_list_t));
840                 find->m_name = mod;
841                 find->m_path = path;
842                 find->m_options = opt;
843         }
844
845         // enqueue at tail
846         if (*tail)
847                 (*tail)->m_next = find;
848         find->m_prev = *tail;
849         find->m_next = NULL; /* possibly NOT done by xzalloc! */
850
851         if (!*head)
852                 *head = find;
853         *tail = find;
854
855         if (dt) {
856                 int i;
857
858                 /* Add all dependable module for that new module */
859                 for (i = 0; i < dt->m_depcnt; i++)
860                         check_dep(dt->m_deparr[i], head, tail);
861         }
862 }
863
864 static int mod_insert(char *mod, int argc, char **argv)
865 {
866         struct mod_list_t *tail = NULL;
867         struct mod_list_t *head = NULL;
868         int rc;
869
870         // get dep list for module mod
871         check_dep(mod, &head, &tail);
872
873         rc = 1;
874         if (head && tail) {
875                 if (argc) {
876                         int i;
877                         // append module args
878                         for (i = 0; i < argc; i++)
879                                 head->m_options = append_option(head->m_options, argv[i]);
880                 }
881
882                 // process tail ---> head
883                 rc = mod_process(tail, 1);
884                 if (rc) {
885                         /*
886                          * In case of using udev, multiple instances of modprobe can be
887                          * spawned to load the same module (think of two same usb devices,
888                          * for example; or cold-plugging at boot time). Thus we shouldn't
889                          * fail if the module was loaded, and not by us.
890                          */
891                         if (already_loaded(mod))
892                                 rc = 0;
893                 }
894         }
895         return rc;
896 }
897
898 static int mod_remove(char *mod)
899 {
900         int rc;
901         static const struct mod_list_t rm_a_dummy = { "-a", NULL, NULL, NULL, NULL };
902
903         struct mod_list_t *head = NULL;
904         struct mod_list_t *tail = NULL;
905
906         if (mod)
907                 check_dep(mod, &head, &tail);
908         else  // autoclean
909                 head = tail = (struct mod_list_t*) &rm_a_dummy;
910
911         rc = 1;
912         if (head && tail)
913                 rc = mod_process(head, 0);  // process head ---> tail
914         return rc;
915 }
916
917 int modprobe_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
918 int modprobe_main(int argc, char **argv)
919 {
920         int rc = EXIT_SUCCESS;
921         char *unused;
922
923         opt_complementary = "q-v:v-q";
924         getopt32(argv, MAIN_OPT_STR, &unused, &unused);
925
926         if (option_mask32 & (DUMP_CONF_EXIT | LIST_ALL))
927                 return EXIT_SUCCESS;
928         if (option_mask32 & (RESTRICT_DIR | CONFIG_FILE))
929                 bb_error_msg_and_die("-t and -C not supported");
930
931         depend = build_dep();
932
933         if (!depend)
934                 bb_error_msg_and_die("cannot parse "CONFIG_DEFAULT_DEPMOD_FILE);
935
936         if (remove_opt) {
937                 do {
938                         /* argv[optind] can be NULL here */
939                         if (mod_remove(argv[optind])) {
940                                 bb_error_msg("failed to %s module %s", "remove",
941                                                 argv[optind]);
942                                 rc = EXIT_FAILURE;
943                         }
944                 } while (++optind < argc);
945         } else {
946                 if (optind >= argc)
947                         bb_error_msg_and_die("no module or pattern provided");
948
949                 if (mod_insert(argv[optind], argc - optind - 1, argv + optind + 1))
950                         bb_error_msg_and_die("failed to %s module %s", "load", argv[optind]);
951         }
952
953         /* Here would be a good place to free up memory allocated during the dependencies build. */
954
955         return rc;
956 }