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