1096ba7ae2112b5801e4c9810287d6d25a76d5c8
[oweals/busybox.git] / modutils / modprobe-small.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * simplified modprobe
4  *
5  * Copyright (c) 2008 Vladimir Dronnikov
6  * Copyright (c) 2008 Bernhard Fischer (initial depmod code)
7  *
8  * Licensed under GPLv2, see file LICENSE in this tarball for details.
9  */
10
11 #include "libbb.h"
12 #include "unarchive.h"
13
14 #include <sys/utsname.h> /* uname() */
15 #include <fnmatch.h>
16
17 #define dbg1_error_msg(...) ((void)0)
18 #define dbg2_error_msg(...) ((void)0)
19 //#define dbg1_error_msg(...) bb_error_msg(__VA_ARGS__)
20 //#define dbg2_error_msg(...) bb_error_msg(__VA_ARGS__)
21
22 extern int init_module(void *module, unsigned long len, const char *options);
23 extern int delete_module(const char *module, unsigned flags);
24 extern int query_module(const char *name, int which, void *buf, size_t bufsize, size_t *ret);
25
26 enum {
27         OPT_q = (1 << 0), /* be quiet */
28         OPT_r = (1 << 1), /* module removal instead of loading */
29 };
30
31 typedef struct module_info {
32         char *pathname;
33         char *desc;
34 } module_info;
35
36 /*
37  * GLOBALS
38  */
39 struct globals {
40         module_info *modinfo;
41         char *module_load_options;
42         int module_count;
43         int module_found_idx;
44         int stringbuf_idx;
45         char stringbuf[32 * 1024]; /* some modules have lots of stuff */
46         /* for example, drivers/media/video/saa7134/saa7134.ko */
47 };
48 #define G (*ptr_to_globals)
49 #define modinfo             (G.modinfo            )
50 #define module_count        (G.module_count       )
51 #define module_found_idx    (G.module_found_idx   )
52 #define module_load_options (G.module_load_options)
53 #define stringbuf_idx       (G.stringbuf_idx      )
54 #define stringbuf           (G.stringbuf          )
55 #define INIT_G() do { \
56         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
57 } while (0)
58
59
60 static void appendc(char c)
61 {
62         if (stringbuf_idx < sizeof(stringbuf))
63                 stringbuf[stringbuf_idx++] = c;
64 }
65
66 static void append(const char *s)
67 {
68         size_t len = strlen(s);
69         if (stringbuf_idx + len < sizeof(stringbuf)) {
70                 memcpy(stringbuf + stringbuf_idx, s, len);
71                 stringbuf_idx += len;
72         }
73 }
74
75 static void reset_stringbuf(void)
76 {
77         stringbuf_idx = 0;
78 }
79
80 static char* copy_stringbuf(void)
81 {
82         char *copy = xmalloc(stringbuf_idx);
83         return memcpy(copy, stringbuf, stringbuf_idx);
84 }
85
86 static char* find_keyword(char *ptr, size_t len, const char *word)
87 {
88         int wlen;
89
90         if (!ptr) /* happens if read_module cannot read it */
91                 return NULL;
92
93         wlen = strlen(word);
94         len -= wlen - 1;
95         while ((ssize_t)len > 0) {
96                 char *old = ptr;
97                 /* search for the first char in word */
98                 ptr = memchr(ptr, *word, len);
99                 if (ptr == NULL) /* no occurance left, done */
100                         break;
101                 if (strncmp(ptr, word, wlen) == 0)
102                         return ptr + wlen; /* found, return ptr past it */
103                 ++ptr;
104                 len -= (ptr - old);
105         }
106         return NULL;
107 }
108
109 static void replace(char *s, char what, char with)
110 {
111         while (*s) {
112                 if (what == *s)
113                         *s = with;
114                 ++s;
115         }
116 }
117
118 #if ENABLE_FEATURE_MODPROBE_SMALL_ZIPPED
119 static char *xmalloc_open_zipped_read_close(const char *fname, size_t *sizep)
120 {
121         size_t len;
122         char *image;
123         char *suffix;
124
125         int fd = open_or_warn(fname, O_RDONLY);
126         if (fd < 0)
127                 return NULL;
128
129         suffix = strrchr(fname, '.');
130         if (suffix) {
131                 if (strcmp(suffix, ".gz") == 0)
132                         fd = open_transformer(fd, unpack_gz_stream, "gunzip");
133                 else if (strcmp(suffix, ".bz2") == 0)
134                         fd = open_transformer(fd, unpack_bz2_stream, "bunzip2");
135         }
136
137         len = (sizep) ? *sizep : 64 * 1024 * 1024;
138         image = xmalloc_read(fd, &len);
139         if (!image)
140                 bb_perror_msg("read error from '%s'", fname);
141         close(fd);
142
143         if (sizep)
144                 *sizep = len;
145         return image;
146 }
147 # define read_module xmalloc_open_zipped_read_close
148 #else
149 # define read_module xmalloc_open_read_close
150 #endif
151
152 /* We use error numbers in a loose translation... */
153 static const char *moderror(int err)
154 {
155         switch (err) {
156         case ENOEXEC:
157                 return "invalid module format";
158         case ENOENT:
159                 return "unknown symbol in module or invalid parameter";
160         case ESRCH:
161                 return "module has wrong symbol version";
162         case EINVAL: /* "invalid parameter" */
163                 return "unknown symbol in module or invalid parameter"
164                 + sizeof("unknown symbol in module or");
165         default:
166                 return strerror(err);
167         }
168 }
169
170 static int load_module(const char *fname, const char *options)
171 {
172 #if 1
173         int r;
174         size_t len = MAXINT(ssize_t);
175         char *module_image;
176         dbg1_error_msg("load_module('%s','%s')", fname, options);
177
178         module_image = read_module(fname, &len);
179         r = (!module_image || init_module(module_image, len, options ? options : "") != 0);
180         free(module_image);
181         dbg1_error_msg("load_module:%d", r);
182         return r; /* 0 = success */
183 #else
184         /* For testing */
185         dbg1_error_msg("load_module('%s','%s')", fname, options);
186         return 1;
187 #endif
188 }
189
190 static char* parse_module(const char *pathname, const char *name)
191 {
192         char *module_image;
193         char *ptr;
194         size_t len;
195         size_t pos;
196         dbg1_error_msg("parse_module('%s','%s')", pathname, name);
197
198         /* Read (possibly compressed) module */
199         len = 64 * 1024 * 1024; /* 64 Mb at most */
200         module_image = read_module(pathname, &len);
201
202         reset_stringbuf();
203
204         /* First desc line's format is
205          * "modname alias1 symbol:sym1 alias2 symbol:sym2 " (note trailing ' ')
206          */
207         append(name);
208         appendc(' ');
209         /* Aliases */
210         pos = 0;
211         while (1) {
212                 ptr = find_keyword(module_image + pos, len - pos, "alias=");
213                 if (!ptr) {
214                         ptr = find_keyword(module_image + pos, len - pos, "__ksymtab_");
215                         if (!ptr)
216                                 break;
217                         /* DOCME: __ksymtab_gpl and __ksymtab_strings occur
218                          * in many modules. What do they mean? */
219                         if (strcmp(ptr, "gpl") != 0 && strcmp(ptr, "strings") != 0) {
220                                 dbg2_error_msg("alias: 'symbol:%s'", ptr);
221                                 append("symbol:");
222                         }
223                 } else {
224                         dbg2_error_msg("alias: '%s'", ptr);
225                 }
226                 append(ptr);
227                 appendc(' ');
228                 pos = (ptr - module_image);
229         }
230         appendc('\0');
231
232         /* Second line: "dependency1 depandency2 " (note trailing ' ') */
233         ptr = find_keyword(module_image, len, "depends=");
234         if (ptr && *ptr) {
235                 replace(ptr, ',', ' ');
236                 replace(ptr, '-', '_');
237                 dbg2_error_msg("dep:'%s'", ptr);
238                 append(ptr);
239         }
240         appendc(' '); appendc('\0');
241
242         free(module_image);
243         return copy_stringbuf();
244 }
245
246 static char* pathname_2_modname(const char *pathname)
247 {
248         const char *fname = bb_get_last_path_component_nostrip(pathname);
249         const char *suffix = strrstr(fname, ".ko");
250         char *name = xstrndup(fname, suffix - fname);
251         replace(name, '-', '_');
252         return name;
253 }
254
255 static FAST_FUNC int fileAction(const char *pathname,
256                 struct stat *sb UNUSED_PARAM,
257                 void *data,
258                 int depth UNUSED_PARAM)
259 {
260         int cur;
261         char *name;
262         const char *fname;
263
264         pathname += 2; /* skip "./" */
265         fname = bb_get_last_path_component_nostrip(pathname);
266         if (!strrstr(fname, ".ko")) {
267                 dbg1_error_msg("'%s' is not a module", pathname);
268                 return TRUE; /* not a module, continue search */
269         }
270
271         cur = module_count++;
272         modinfo = xrealloc_vector(modinfo, 12, cur);
273         modinfo[cur].pathname = xstrdup(pathname);
274         modinfo[cur].desc = NULL;
275         modinfo[cur+1].pathname = NULL;
276         modinfo[cur+1].desc = NULL;
277
278         name = pathname_2_modname(fname);
279         if (strcmp(name, data) != 0) {
280                 free(name);
281                 dbg1_error_msg("'%s' module name doesn't match", pathname);
282                 return TRUE; /* module name doesn't match, continue search */
283         }
284
285         dbg1_error_msg("'%s' module name matches", pathname);
286         module_found_idx = cur;
287         modinfo[cur].desc = parse_module(pathname, name);
288
289         if (!(option_mask32 & OPT_r)) {
290                 if (load_module(pathname, module_load_options) == 0) {
291                         /* Load was successful, there is nothing else to do.
292                          * This can happen ONLY for "top-level" module load,
293                          * not a dep, because deps dont do dirscan. */
294                         exit(EXIT_SUCCESS);
295                         /*free(name);return RECURSE_RESULT_ABORT;*/
296                 }
297         }
298
299         free(name);
300         return TRUE;
301 }
302
303 static module_info* find_alias(const char *alias)
304 {
305         int i;
306         dbg1_error_msg("find_alias('%s')", alias);
307
308         /* First try to find by name (cheaper) */
309         i = 0;
310         while (modinfo[i].pathname) {
311                 char *name = pathname_2_modname(modinfo[i].pathname);
312                 if (strcmp(name, alias) == 0) {
313                         dbg1_error_msg("found '%s' in module '%s'",
314                                         alias, modinfo[i].pathname);
315                         if (!modinfo[i].desc)
316                                 modinfo[i].desc = parse_module(modinfo[i].pathname, name);
317                         free(name);
318                         return &modinfo[i];
319                 }
320                 free(name);
321                 i++;
322         }
323
324         /* Scan all module bodies, extract modinfo (it contains aliases) */
325         i = 0;
326         while (modinfo[i].pathname) {
327                 char *desc, *s;
328                 if (!modinfo[i].desc) {
329                         char *name = pathname_2_modname(modinfo[i].pathname);
330                         modinfo[i].desc = parse_module(modinfo[i].pathname, name);
331                         free(name);
332                 }
333                 /* "modname alias1 symbol:sym1 alias2 symbol:sym2 " */
334                 desc = xstrdup(modinfo[i].desc);
335                 /* Does matching substring exist? */
336                 replace(desc, ' ', '\0');
337                 for (s = desc; *s; s += strlen(s) + 1) {
338                         /* aliases in module bodies can be defined with
339                          * shell patterns. Example:
340                          * "pci:v000010DEd000000D9sv*sd*bc*sc*i*".
341                          * Plain strcmp() won't catch that */
342                         if (fnmatch(s, alias, 0) == 0) {
343                                 free(desc);
344                                 dbg1_error_msg("found alias '%s' in module '%s'",
345                                                 alias, modinfo[i].pathname);
346                                 return &modinfo[i];
347                         }
348                 }
349                 free(desc);
350                 i++;
351         }
352         dbg1_error_msg("find_alias '%s' returns NULL", alias);
353         return NULL;
354 }
355
356 #if ENABLE_FEATURE_MODPROBE_SMALL_CHECK_ALREADY_LOADED
357 static int already_loaded(const char *name)
358 {
359         int ret = 0;
360         int len = strlen(name);
361         char *line;
362         FILE* modules;
363
364         modules = xfopen("/proc/modules", "r");
365         while ((line = xmalloc_fgets(modules)) != NULL) {
366                 if (strncmp(line, name, len) == 0 && line[len] == ' ') {
367                         free(line);
368                         ret = 1;
369                         break;
370                 }
371                 free(line);
372         }
373         fclose(modules);
374         return ret;
375 }
376 #else
377 #define already_loaded(name) is_rmmod
378 #endif
379
380 /*
381  Given modules definition and module name (or alias, or symbol)
382  load/remove the module respecting dependencies
383 */
384 #if !ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
385 #define process_module(a,b) process_module(a)
386 #define cmdline_options ""
387 #endif
388 static void process_module(char *name, const char *cmdline_options)
389 {
390         char *s, *deps, *options;
391         module_info *info;
392         int is_rmmod = (option_mask32 & OPT_r) != 0;
393         dbg1_error_msg("process_module('%s','%s')", name, cmdline_options);
394
395         replace(name, '-', '_');
396
397         dbg1_error_msg("already_loaded:%d is_rmmod:%d", already_loaded(name), is_rmmod);
398         if (already_loaded(name) != is_rmmod) {
399                 dbg1_error_msg("nothing to do for '%s'", name);
400                 return;
401         }
402
403         options = NULL;
404         if (!is_rmmod) {
405                 char *opt_filename = xasprintf("/etc/modules/%s", name);
406                 options = xmalloc_open_read_close(opt_filename, NULL);
407                 if (options)
408                         replace(options, '\n', ' ');
409 #if ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
410                 if (cmdline_options) {
411                         /* NB: cmdline_options always have one leading ' '
412                          * (see main()), we remove it here */
413                         char *op = xasprintf(options ? "%s %s" : "%s %s" + 3,
414                                                 cmdline_options + 1, options);
415                         free(options);
416                         options = op;
417                 }
418 #endif
419                 free(opt_filename);
420                 module_load_options = options;
421                 dbg1_error_msg("process_module('%s'): options:'%s'", name, options);
422         }
423
424         if (!module_count) {
425                 /* Scan module directory. This is done only once.
426                  * It will attempt module load, and will exit(EXIT_SUCCESS)
427                  * on success. */
428                 module_found_idx = -1;
429                 recursive_action(".",
430                         ACTION_RECURSE, /* flags */
431                         fileAction, /* file action */
432                         NULL, /* dir action */
433                         name, /* user data */
434                         0); /* depth */
435                 dbg1_error_msg("dirscan complete");
436                 /* Module was not found, or load failed, or is_rmmod */
437                 if (module_found_idx >= 0) { /* module was found */
438                         info = &modinfo[module_found_idx];
439                 } else { /* search for alias, not a plain module name */
440                         info = find_alias(name);
441                 }
442         } else {
443                 info = find_alias(name);
444         }
445
446         /* rmmod? unload it by name */
447         if (is_rmmod) {
448                 if (delete_module(name, O_NONBLOCK|O_EXCL) != 0
449                  && !(option_mask32 & OPT_q)
450                 ) {
451                         bb_perror_msg("remove '%s'", name);
452                         goto ret;
453                 }
454                 /* N.B. we do not stop here -
455                  * continue to unload modules on which the module depends:
456                  * "-r --remove: option causes modprobe to remove a module.
457                  * If the modules it depends on are also unused, modprobe
458                  * will try to remove them, too." */
459         }
460
461         if (!info) { /* both dirscan and find_alias found nothing */
462                 goto ret;
463         }
464
465         /* Second line of desc contains dependencies */
466         deps = xstrdup(info->desc + strlen(info->desc) + 1);
467
468         /* Transform deps to string list */
469         replace(deps, ' ', '\0');
470         /* Iterate thru dependencies, trying to (un)load them */
471         for (s = deps; *s; s += strlen(s) + 1) {
472                 //if (strcmp(name, s) != 0) // N.B. do loops exist?
473                 dbg1_error_msg("recurse on dep '%s'", s);
474                 process_module(s, NULL);
475                 dbg1_error_msg("recurse on dep '%s' done", s);
476         }
477         free(deps);
478
479         /* insmod -> load it */
480         if (!is_rmmod) {
481                 errno = 0;
482                 if (load_module(info->pathname, options) != 0) {
483                         if (EEXIST != errno) {
484                                 bb_error_msg("insert '%s' %s: %s",
485                                                 info->pathname, options,
486                                                 moderror(errno));
487                         } else {
488                                 dbg1_error_msg("insert '%s' %s: %s",
489                                                 info->pathname, options,
490                                                 moderror(errno));
491                         }
492                 }
493         }
494  ret:
495         free(options);
496 //TODO: return load attempt result from process_module.
497 //If dep didn't load ok, continuing makes little sense.
498 }
499 #undef cmdline_options
500
501
502 /* For reference, module-init-tools-0.9.15-pre2 options:
503
504 # insmod
505 Usage: insmod filename [args]
506
507 # rmmod --help
508 Usage: rmmod [-fhswvV] modulename ...
509  -f (or --force) forces a module unload, and may crash your machine.
510  -s (or --syslog) says use syslog, not stderr
511  -v (or --verbose) enables more messages
512  -w (or --wait) begins a module removal even if it is used
513     and will stop new users from accessing the module (so it
514     should eventually fall to zero).
515
516 # modprobe
517 Usage: modprobe [--verbose|--version|--config|--remove] filename [options]
518
519 # depmod --help
520 depmod 0.9.15-pre2 -- part of module-init-tools
521 depmod -[aA] [-n -e -v -q -V -r -u] [-b basedirectory] [forced_version]
522 depmod [-n -e -v -q -r -u] [-F kernelsyms] module1.o module2.o ...
523 If no arguments (except options) are given, "depmod -a" is assumed
524
525 depmod will output a dependancy list suitable for the modprobe utility.
526
527 Options:
528         -a, --all               Probe all modules
529         -n, --show              Write the dependency file on stdout only
530         -b basedirectory
531         --basedir basedirectory Use an image of a module tree.
532         -F kernelsyms
533         --filesyms kernelsyms   Use the file instead of the
534                                 current kernel symbols.
535 */
536
537 int modprobe_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
538 int modprobe_main(int argc UNUSED_PARAM, char **argv)
539 {
540         struct utsname uts;
541         char applet0 = applet_name[0];
542         USE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(char *options;)
543
544         /* depmod is a stub */
545         if ('d' == applet0)
546                 return EXIT_SUCCESS;
547
548         /* are we lsmod? -> just dump /proc/modules */
549         if ('l' == applet0) {
550                 xprint_and_close_file(xfopen("/proc/modules", "r"));
551                 return EXIT_SUCCESS;
552         }
553
554         INIT_G();
555
556         /* insmod, modprobe, rmmod require at least one argument */
557         opt_complementary = "-1";
558         /* only -q (quiet) and -r (rmmod),
559          * the rest are accepted and ignored (compat) */
560         getopt32(argv, "qrfsvw");
561         argv += optind;
562
563         /* are we rmmod? -> simulate modprobe -r */
564         if ('r' == applet0) {
565                 option_mask32 |= OPT_r;
566         }
567
568         /* goto modules directory */
569         xchdir(CONFIG_DEFAULT_MODULES_DIR);
570         uname(&uts); /* never fails */
571         xchdir(uts.release);
572
573 #if ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
574         /* If not rmmod, parse possible module options given on command line.
575          * insmod/modprobe takes one module name, the rest are parameters. */
576         options = NULL;
577         if ('r' != applet0) {
578                 char **arg = argv;
579                 while (*++arg) {
580                         /* Enclose options in quotes */
581                         char *s = options;
582                         options = xasprintf("%s \"%s\"", s ? s : "", *arg);
583                         free(s);
584                         *arg = NULL;
585                 }
586         }
587 #else
588         if ('r' != applet0)
589                 argv[1] = NULL;
590 #endif
591
592         /* Load/remove modules.
593          * Only rmmod loops here, insmod/modprobe has only argv[0] */
594         do {
595                 process_module(*argv++, options);
596         } while (*argv);
597
598         if (ENABLE_FEATURE_CLEAN_UP) {
599                 USE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(free(options);)
600         }
601         return EXIT_SUCCESS;
602 }