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