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