98bda48b506357b66e3d0fef4aa06f52edfb0c20
[project/ubox.git] / kmodloader.c
1 /*
2  * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3  * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU Lesser General Public License version 2.1
7  * as published by the Free Software Foundation
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #define _GNU_SOURCE
16 #include <sys/syscall.h>
17 #include <sys/mman.h>
18 #include <sys/utsname.h>
19
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <sys/syscall.h>
23 #include <sys/types.h>
24 #include <values.h>
25 #include <errno.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <sys/stat.h>
29 #include <fcntl.h>
30 #include <syslog.h>
31 #include <libgen.h>
32 #include <glob.h>
33 #include <elf.h>
34
35 #include <libubox/avl.h>
36 #include <libubox/avl-cmp.h>
37 #include <libubox/utils.h>
38
39 #define DEF_MOD_PATH "/lib/modules/%s/"
40
41 #define LOG(fmt, ...) do { \
42         syslog(LOG_INFO, fmt, ## __VA_ARGS__); \
43         printf("kmod: "fmt, ## __VA_ARGS__); \
44         } while (0)
45
46
47 enum {
48         SCANNED,
49         PROBE,
50         LOADED,
51 };
52
53 struct module {
54         struct avl_node avl;
55
56         char *name;
57         char *depends;
58
59         int size;
60         int usage;
61         int state;
62         int error;
63 };
64
65 static struct avl_tree modules;
66 static char *prefix = "";
67
68 static struct module *find_module(const char *name)
69 {
70         struct module *m;
71         return avl_find_element(&modules, name, m, avl);
72 }
73
74 static void free_modules(void)
75 {
76         struct module *m, *tmp;
77
78         avl_remove_all_elements(&modules, m, avl, tmp)
79                 free(m);
80 }
81
82 static char* get_module_path(char *name)
83 {
84         static char path[256];
85         struct utsname ver;
86         struct stat s;
87         char *t;
88
89         if (!stat(name, &s))
90                 return name;
91
92         uname(&ver);
93         snprintf(path, 256, "%s" DEF_MOD_PATH "%s.ko", prefix, ver.release, name);
94
95         if (!stat(path, &s))
96                 return path;
97
98         t = name;
99         while (t && *t) {
100                 if (*t == '_')
101                         *t = '-';
102                 t++;
103         }
104
105         snprintf(path, 256, "%s" DEF_MOD_PATH "%s.ko", prefix, ver.release, name);
106
107         if (!stat(path, &s))
108                 return path;
109
110         return NULL;
111 }
112
113 static char* get_module_name(char *path)
114 {
115         static char name[32];
116         char *t;
117
118         strncpy(name, basename(path), sizeof(name));
119
120         t = strstr(name, ".ko");
121         if (t)
122                 *t = '\0';
123         t = name;
124         while (t && *t) {
125                 if (*t == '-')
126                         *t = '_';
127                 t++;
128         }
129
130         return name;
131 }
132
133 #if __WORDSIZE == 64
134 static int elf_find_section(char *map, const char *section, unsigned int *offset, unsigned int *size)
135 {
136         const char *secnames;
137         Elf64_Ehdr *e;
138         Elf64_Shdr *sh;
139         int i;
140
141         e = (Elf64_Ehdr *) map;
142         sh = (Elf64_Shdr *) (map + e->e_shoff);
143
144         secnames = map + sh[e->e_shstrndx].sh_offset;
145         for (i = 0; i < e->e_shnum; i++) {
146                 if (!strcmp(section, secnames + sh[i].sh_name)) {
147                         *size = sh[i].sh_size;
148                         *offset = sh[i].sh_offset;
149                         return 0;
150                 }
151         }
152
153         return -1;
154 }
155 #else
156 static int elf_find_section(char *map, const char *section, unsigned int *offset, unsigned int *size)
157 {
158         const char *secnames;
159         Elf32_Ehdr *e;
160         Elf32_Shdr *sh;
161         int i;
162
163         e = (Elf32_Ehdr *) map;
164         sh = (Elf32_Shdr *) (map + e->e_shoff);
165
166         secnames = map + sh[e->e_shstrndx].sh_offset;
167         for (i = 0; i < e->e_shnum; i++) {
168                 if (!strcmp(section, secnames + sh[i].sh_name)) {
169                         *size = sh[i].sh_size;
170                         *offset = sh[i].sh_offset;
171                         return 0;
172                 }
173         }
174
175         return -1;
176 }
177 #endif
178
179 static struct module *
180 alloc_module(const char *name, const char *depends, int size)
181 {
182         struct module *m;
183         char *_name, *_dep;
184
185         m = calloc_a(sizeof(*m),
186                 &_name, strlen(name) + 1,
187                 &_dep, depends ? strlen(depends) + 1 : 0);
188         if (!m)
189                 return NULL;
190
191         m->avl.key = m->name = strcpy(_name, name);
192
193         if (depends)
194                 m->depends = strcpy(_dep, depends);
195
196         m->size = size;
197         avl_insert(&modules, &m->avl);
198         return m;
199 }
200
201 static int scan_loaded_modules(void)
202 {
203         size_t buf_len = 0;
204         char *buf = NULL;
205         FILE *fp;
206
207         fp = fopen("/proc/modules", "r");
208         if (!fp) {
209                 LOG("failed to open /proc/modules\n");
210                 return -1;
211         }
212
213         while (getline(&buf, &buf_len, fp) > 0) {
214                 struct module m;
215                 struct module *n;
216
217                 m.name = strtok(buf, " ");
218                 m.size = atoi(strtok(NULL, " "));
219                 m.usage = atoi(strtok(NULL, " "));
220                 m.depends = strtok(NULL, " ");
221
222                 if (!m.name || !m.depends)
223                         continue;
224
225                 n = alloc_module(m.name, m.depends, m.size);
226                 n->usage = m.usage;
227                 n->state = LOADED;
228         }
229         free(buf);
230         fclose(fp);
231
232         return 0;
233 }
234
235 static struct module* get_module_info(const char *module, const char *name)
236 {
237         int fd = open(module, O_RDONLY);
238         unsigned int offset, size;
239         char *map, *strings, *dep = NULL;
240         struct module *m;
241         struct stat s;
242
243         if (!fd) {
244                 LOG("failed to open %s\n", module);
245                 return NULL;
246         }
247
248         if (fstat(fd, &s) == -1) {
249                 LOG("failed to stat %s\n", module);
250                 return NULL;
251         }
252
253         map = mmap(NULL, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
254         if (map == MAP_FAILED) {
255                 LOG("failed to mmap %s\n", module);
256                 return NULL;
257         }
258
259         if (elf_find_section(map, ".modinfo", &offset, &size)) {
260                 LOG("failed to load the .modinfo section from %s\n", module);
261                 return NULL;
262         }
263
264         strings = map + offset;
265         while (strings && (strings < map + offset + size)) {
266                 char *sep;
267                 int len;
268
269                 while (!strings[0])
270                         strings++;
271                 sep = strstr(strings, "=");
272                 if (!sep)
273                         break;
274                 len = sep - strings;
275                 sep++;
276                 if (!strncmp(strings, "depends=", len + 1))
277                         dep = sep;
278                 strings = &sep[strlen(sep)];
279         }
280
281         m = alloc_module(name, dep, s.st_size);
282         if (!m)
283                 return NULL;
284
285         m->state = SCANNED;
286
287         return m;
288 }
289
290 static int scan_module_folder(void)
291 {
292         int gl_flags = GLOB_NOESCAPE | GLOB_MARK;
293         struct utsname ver;
294         char *path;
295         glob_t gl;
296         int j;
297
298         uname(&ver);
299         path = alloca(sizeof(DEF_MOD_PATH "*.ko") + strlen(ver.release) + 1);
300         sprintf(path, DEF_MOD_PATH "*.ko", ver.release);
301
302         if (glob(path, gl_flags, NULL, &gl) < 0)
303                 return -1;
304
305         for (j = 0; j < gl.gl_pathc; j++) {
306                 char *name = get_module_name(gl.gl_pathv[j]);
307                 struct module *m;
308
309                 if (!name)
310                         continue;
311
312                 m = find_module(name);
313                 if (!m)
314                         get_module_info(gl.gl_pathv[j], name);
315         }
316
317         globfree(&gl);
318
319         return 0;
320 }
321
322 static int print_modinfo(char *module)
323 {
324         int fd = open(module, O_RDONLY);
325         unsigned int offset, size;
326         struct stat s;
327         char *map, *strings;
328
329         if (!fd) {
330                 LOG("failed to open %s\n", module);
331                 return -1;
332         }
333
334         if (fstat(fd, &s) == -1) {
335                 LOG("failed to stat %s\n", module);
336                 return -1;
337         }
338
339         map = mmap(NULL, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
340         if (map == MAP_FAILED) {
341                 LOG("failed to mmap %s\n", module);
342                 return -1;
343         }
344
345         if (elf_find_section(map, ".modinfo", &offset, &size)) {
346                 LOG("failed to load the .modinfo section from %s\n", module);
347                 return -1;
348         }
349
350         strings = map + offset;
351         printf("module:\t\t%s\n", module);
352         while (strings && (strings < map + offset + size)) {
353                 char *dup = NULL;
354                 char *sep;
355
356                 while (!strings[0])
357                         strings++;
358                 sep = strstr(strings, "=");
359                 if (!sep)
360                         break;
361                 dup = strndup(strings, sep - strings);
362                 sep++;
363                 if (strncmp(strings, "parm", 4)) {
364                         if (strlen(dup) < 7)
365                                 printf("%s:\t\t%s\n",  dup, sep);
366                         else
367                                 printf("%s:\t%s\n",  dup, sep);
368                 }
369                 strings = &sep[strlen(sep)];
370                 if (dup)
371                         free(dup);
372         }
373
374         return 0;
375 }
376
377 static int deps_available(struct module *m, int verbose)
378 {
379         char *deps, *_deps;
380         char *comma;
381         int err = 0;
382
383         if (!strcmp(m->depends, "-") || !strcmp(m->depends, ""))
384                 return 0;
385
386         _deps = deps = strdup(m->depends);
387
388         do {
389                 comma = strstr(deps, ",");
390                 if (comma)
391                         *comma = '\0';
392
393                 m = find_module(deps);
394
395                 if (verbose && !m)
396                         LOG("missing dependency %s\n", deps);
397                 if (verbose && m && (m->state != LOADED))
398                         LOG("dependency not loaded %s\n", deps);
399                 if (!m || (m->state != LOADED))
400                         err++;
401                 if (comma)
402                         deps = ++comma;
403         } while (comma);
404
405         free(_deps);
406
407         return err;
408 }
409
410 static int insert_module(char *path, const char *options)
411 {
412         void *data = 0;
413         struct stat s;
414         int fd, ret = -1;
415
416         if (stat(path, &s)) {
417                 LOG("missing module %s\n", path);
418                 return ret;
419         }
420
421         fd = open(path, O_RDONLY);
422         if (!fd) {
423                 LOG("cannot open %s\n", path);
424                 return ret;
425         }
426
427         data = malloc(s.st_size);
428         if (read(fd, data, s.st_size) == s.st_size)
429                 ret = syscall(__NR_init_module, data, s.st_size, options);
430         else
431                 LOG("failed to read full module %s\n", path);
432
433         close(fd);
434         free(data);
435
436         return ret;
437 }
438
439 static void load_moddeps(struct module *_m)
440 {
441         char *deps, *_deps;
442         struct module *m;
443         char *comma;
444
445         if (!strcmp(_m->depends, "-") || !strcmp(_m->depends, ""))
446                 return;
447
448         _deps = deps = strdup(_m->depends);
449
450         do {
451                 char *t = deps;
452
453                 comma = strstr(deps, ",");
454                 if (comma)
455                         *comma = '\0';
456
457                 m = find_module(deps);
458
459                 if (!m) {
460                         while (t && *t) {
461                                 if (*t == '-')
462                                         *t = '_';
463                                 t++;
464                         }
465                         m = find_module(deps);
466                 }
467
468                 if (!m)
469                         LOG("failed to find dependency %s\n", deps);
470                 if (m && (m->state != LOADED)) {
471                         m->state = PROBE;
472                         load_moddeps(m);
473                 }
474
475                 if (comma)
476                         deps = ++comma;
477         } while (comma);
478
479         free(_deps);
480 }
481
482 static int load_modprobe(void)
483 {
484         int loaded, todo;
485         struct module *m;
486
487         avl_for_each_element(&modules, m, avl)
488                 if (m->state == PROBE)
489                         load_moddeps(m);
490
491         do {
492                 loaded = 0;
493                 todo = 0;
494                 avl_for_each_element(&modules, m, avl) {
495                         if ((m->state == PROBE) && (!deps_available(m, 0))) {
496                                 if (!insert_module(get_module_path(m->name), "")) {
497                                         m->state = LOADED;
498                                         m->error = 0;
499                                         loaded++;
500                                         continue;
501                                 }
502                                 m->error = 1;
503                         }
504
505                         if ((m->state == PROBE) || m->error)
506                                 todo++;
507                 }
508         } while (loaded);
509
510         return todo;
511 }
512
513 static int print_insmod_usage(void)
514 {
515         LOG("Usage:\n\tinsmod filename [args]\n");
516
517         return -1;
518 }
519
520 static int print_usage(char *arg)
521 {
522         LOG("Usage:\n\t%s module\n", arg);
523
524         return -1;
525 }
526
527 static int main_insmod(int argc, char **argv)
528 {
529         char *name, *cur, *options;
530         int i, ret, len;
531
532         if (argc < 2)
533                 return print_insmod_usage();
534
535         name = get_module_name(argv[1]);
536         if (!name) {
537                 LOG("cannot find module - %s\n", argv[1]);
538                 return -1;
539         }
540
541         if (scan_loaded_modules())
542                 return -1;
543
544         if (find_module(name)) {
545                 LOG("module is already loaded - %s\n", name);
546                 return -1;
547
548         }
549
550         free_modules();
551
552         for (len = 0, i = 2; i < argc; i++)
553                 len += strlen(argv[i]) + 1;
554
555         options = malloc(len);
556         options[0] = 0;
557         cur = options;
558         for (i = 2; i < argc; i++) {
559                 if (options[0]) {
560                         *cur = ' ';
561                         cur++;
562                 }
563                 cur += sprintf(cur, "%s", argv[i]);
564         }
565
566         ret = insert_module(get_module_path(name), options);
567         free(options);
568
569         if (ret)
570                 LOG("failed to insert %s\n", get_module_path(name));
571
572         return ret;
573 }
574
575 static int main_rmmod(int argc, char **argv)
576 {
577         struct module *m;
578         char *name;
579         int ret;
580
581         if (argc != 2)
582                 return print_usage("rmmod");
583
584         if (scan_loaded_modules())
585                 return -1;
586
587         name = get_module_name(argv[1]);
588         m = find_module(name);
589         if (!m) {
590                 LOG("module is not loaded\n");
591                 return -1;
592         }
593         free_modules();
594
595         ret = syscall(__NR_delete_module, name, 0);
596
597         if (ret)
598                 LOG("unloading the module failed\n");
599
600         return ret;
601 }
602
603 static int main_lsmod(int argc, char **argv)
604 {
605         struct module *m;
606
607         if (scan_loaded_modules())
608                 return -1;
609
610         avl_for_each_element(&modules, m, avl)
611                 if (m->state == LOADED)
612                         printf("%-20s%8d%3d %s\n",
613                                 m->name, m->size, m->usage,
614                                 (*m->depends == '-') ? ("") : (m->depends));
615
616         free_modules();
617
618         return 0;
619 }
620
621 static int main_modinfo(int argc, char **argv)
622 {
623         char *module;
624
625         if (argc != 2)
626                 return print_usage("modinfo");
627
628         module = get_module_path(argv[1]);
629         if (!module) {
630                 LOG("cannot find module - %s\n", argv[1]);
631                 return -1;
632         }
633
634         print_modinfo(module);
635
636         return 0;
637 }
638
639 static int main_modprobe(int argc, char **argv)
640 {
641         struct module *m;
642         char *name;
643
644         if (argc != 2)
645                 return print_usage("modprobe");
646
647         if (scan_loaded_modules())
648                 return -1;
649
650         if (scan_module_folder())
651                 return -1;
652
653         name = get_module_name(argv[1]);
654         m = find_module(name);
655         if (m && m->state == LOADED) {
656                 LOG("%s is already loaded\n", name);
657                 return -1;
658         } else if (!m) {
659                 LOG("failed to find a module named %s\n", name);
660         } else {
661                 int fail;
662
663                 m->state = PROBE;
664
665                 fail = load_modprobe();
666
667                 if (fail) {
668                         LOG("%d module%s could not be probed\n",
669                                         fail, (fail == 1) ? ("") : ("s"));
670
671                         avl_for_each_element(&modules, m, avl)
672                                 if ((m->state == PROBE) || m->error)
673                                         LOG("- %s\n", m->name);
674                 }
675         }
676
677         free_modules();
678
679         return 0;
680 }
681
682 static int main_loader(int argc, char **argv)
683 {
684         int gl_flags = GLOB_NOESCAPE | GLOB_MARK;
685         char *dir = "/etc/modules.d/*";
686         struct module *m;
687         glob_t gl;
688         char *path;
689         int fail, j;
690
691         if (argc > 1)
692                 dir = argv[1];
693
694         if (argc > 2)
695                 prefix = argv[2];
696
697         path = malloc(strlen(dir) + 2);
698         strcpy(path, dir);
699         strcat(path, "*");
700
701         if (scan_loaded_modules())
702                 return -1;
703
704         if (scan_module_folder())
705                 return -1;
706
707         syslog(0, "kmodloader: loading kernel modules from %s\n", path);
708
709         if (glob(path, gl_flags, NULL, &gl) < 0)
710                 goto out;
711
712         for (j = 0; j < gl.gl_pathc; j++) {
713                 FILE *fp = fopen(gl.gl_pathv[j], "r");
714                 size_t mod_len = 0;
715                 char *mod = NULL;
716
717                 if (!fp) {
718                         LOG("failed to open %s\n", gl.gl_pathv[j]);
719                         continue;
720                 }
721
722                 while (getline(&mod, &mod_len, fp) > 0) {
723                         char *nl = strchr(mod, '\n');
724                         struct module *m;
725                         char *opts;
726
727                         if (nl)
728                                 *nl = '\0';
729
730                         opts = strchr(mod, ' ');
731                         if (opts)
732                                 *opts++ = '\0';
733
734                         m = find_module(get_module_name(mod));
735                         if (!m || (m->state == LOADED))
736                                 continue;
737
738                         m->state = PROBE;
739                         if (basename(gl.gl_pathv[j])[0] - '0' <= 9)
740                                 load_modprobe();
741
742                 }
743                 free(mod);
744                 fclose(fp);
745         }
746
747         fail = load_modprobe();
748
749         if (fail) {
750                 LOG("%d module%s could not be probed\n",
751                                 fail, (fail == 1) ? ("") : ("s"));
752
753                 avl_for_each_element(&modules, m, avl)
754                         if ((m->state == PROBE) || (m->error))
755                                 LOG("- %s - %d\n", m->name, deps_available(m, 1));
756         }
757
758 out:
759         globfree(&gl);
760         free(path);
761
762         return 0;
763 }
764
765 int main(int argc, char **argv)
766 {
767         char *exec = basename(*argv);
768
769         avl_init(&modules, avl_strcmp, false, NULL);
770         if (!strcmp(exec, "insmod"))
771                 return main_insmod(argc, argv);
772
773         if (!strcmp(exec, "rmmod"))
774                 return main_rmmod(argc, argv);
775
776         if (!strcmp(exec, "lsmod"))
777                 return main_lsmod(argc, argv);
778
779         if (!strcmp(exec, "modinfo"))
780                 return main_modinfo(argc, argv);
781
782         if (!strcmp(exec, "modprobe"))
783                 return main_modprobe(argc, argv);
784
785         return main_loader(argc, argv);
786 }