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