]> git.ipfire.org Git - thirdparty/kmod.git/blob - libkmod/libkmod.c
tools: add modprobe
[thirdparty/kmod.git] / libkmod / libkmod.c
1 /*
2 * libkmod - interface to kernel module operations
3 *
4 * Copyright (C) 2011 ProFUSION embedded systems
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation version 2.1.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18 */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <stddef.h>
23 #include <stdarg.h>
24 #include <limits.h>
25 #include <unistd.h>
26 #include <errno.h>
27 #include <fnmatch.h>
28 #include <string.h>
29 #include <ctype.h>
30 #include <sys/utsname.h>
31
32 #include "libkmod.h"
33 #include "libkmod-private.h"
34 #include "libkmod-index.h"
35
36 #define KMOD_HASH_SIZE (256)
37 #define KMOD_LRU_MAX (128)
38
39 /**
40 * SECTION:libkmod
41 * @short_description: libkmod context
42 *
43 * The context contains the default values for the library user,
44 * and is passed to all library operations.
45 */
46
47 enum kmod_index {
48 KMOD_INDEX_DEP = 0,
49 KMOD_INDEX_ALIAS,
50 KMOD_INDEX_SYMBOL,
51 _KMOD_INDEX_LAST,
52 };
53
54 static const char* index_files[] = {
55 [KMOD_INDEX_DEP] = "modules.dep",
56 [KMOD_INDEX_ALIAS] = "modules.alias",
57 [KMOD_INDEX_SYMBOL] = "modules.symbols",
58 };
59
60 /**
61 * kmod_ctx:
62 *
63 * Opaque object representing the library context.
64 */
65 struct kmod_ctx {
66 int refcount;
67 int log_priority;
68 void (*log_fn)(void *data,
69 int priority, const char *file, int line,
70 const char *fn, const char *format, va_list args);
71 void *log_data;
72 const void *userdata;
73 char *dirname;
74 struct kmod_config *config;
75 struct kmod_hash *modules_by_name;
76 struct index_mm *indexes[_KMOD_INDEX_LAST];
77 };
78
79 void kmod_log(const struct kmod_ctx *ctx,
80 int priority, const char *file, int line, const char *fn,
81 const char *format, ...)
82 {
83 va_list args;
84
85 if (ctx->log_fn == NULL)
86 return;
87
88 va_start(args, format);
89 ctx->log_fn(ctx->log_data, priority, file, line, fn, format, args);
90 va_end(args);
91 }
92
93 static void log_filep(void *data,
94 int priority, const char *file, int line,
95 const char *fn, const char *format, va_list args)
96 {
97 FILE *fp = data;
98 fprintf(fp, "libkmod: %s: ", fn);
99 vfprintf(fp, format, args);
100 }
101
102 const char *kmod_get_dirname(const struct kmod_ctx *ctx)
103 {
104 return ctx->dirname;
105 }
106
107 /**
108 * kmod_get_userdata:
109 * @ctx: kmod library context
110 *
111 * Retrieve stored data pointer from library context. This might be useful
112 * to access from callbacks like a custom logging function.
113 *
114 * Returns: stored userdata
115 */
116 KMOD_EXPORT void *kmod_get_userdata(const struct kmod_ctx *ctx)
117 {
118 if (ctx == NULL)
119 return NULL;
120 return (void *)ctx->userdata;
121 }
122
123 /**
124 * kmod_set_userdata:
125 * @ctx: kmod library context
126 * @userdata: data pointer
127 *
128 * Store custom @userdata in the library context.
129 */
130 KMOD_EXPORT void kmod_set_userdata(struct kmod_ctx *ctx, const void *userdata)
131 {
132 if (ctx == NULL)
133 return;
134 ctx->userdata = userdata;
135 }
136
137 static int log_priority(const char *priority)
138 {
139 char *endptr;
140 int prio;
141
142 prio = strtol(priority, &endptr, 10);
143 if (endptr[0] == '\0' || isspace(endptr[0]))
144 return prio;
145 if (strncmp(priority, "err", 3) == 0)
146 return LOG_ERR;
147 if (strncmp(priority, "info", 4) == 0)
148 return LOG_INFO;
149 if (strncmp(priority, "debug", 5) == 0)
150 return LOG_DEBUG;
151 return 0;
152 }
153
154 static const char *dirname_default_prefix = "/lib/modules";
155
156 static char *get_kernel_release(const char *dirname)
157 {
158 struct utsname u;
159 char *p;
160
161 if (dirname != NULL)
162 return strdup(dirname);
163
164 if (uname(&u) < 0)
165 return NULL;
166
167 if (asprintf(&p, "%s/%s", dirname_default_prefix, u.release) < 0)
168 return NULL;
169
170 return p;
171 }
172
173 /**
174 * kmod_new:
175 *
176 * Create kmod library context. This reads the kmod configuration
177 * and fills in the default values.
178 *
179 * The initial refcount is 1, and needs to be decremented to
180 * release the resources of the kmod library context.
181 *
182 * Returns: a new kmod library context
183 */
184 KMOD_EXPORT struct kmod_ctx *kmod_new(const char *dirname)
185 {
186 const char *env;
187 struct kmod_ctx *ctx;
188 int err;
189
190 ctx = calloc(1, sizeof(struct kmod_ctx));
191 if (!ctx)
192 return NULL;
193
194 ctx->refcount = 1;
195 ctx->log_fn = log_filep;
196 ctx->log_data = stderr;
197 ctx->log_priority = LOG_ERR;
198
199 ctx->dirname = get_kernel_release(dirname);
200
201 /* environment overwrites config */
202 env = getenv("KMOD_LOG");
203 if (env != NULL)
204 kmod_set_log_priority(ctx, log_priority(env));
205
206 err = kmod_config_new(ctx, &ctx->config);
207 if (err < 0) {
208 ERR(ctx, "could not create config\n");
209 goto fail;
210 }
211
212 ctx->modules_by_name = kmod_hash_new(KMOD_HASH_SIZE, NULL);
213 if (ctx->modules_by_name == NULL) {
214 ERR(ctx, "could not create by-name hash\n");
215 goto fail;
216 }
217
218 INFO(ctx, "ctx %p created\n", ctx);
219 DBG(ctx, "log_priority=%d\n", ctx->log_priority);
220
221 return ctx;
222
223 fail:
224 free(ctx->modules_by_name);
225 free(ctx->dirname);
226 free(ctx);
227 return NULL;
228 }
229
230 /**
231 * kmod_ref:
232 * @ctx: kmod library context
233 *
234 * Take a reference of the kmod library context.
235 *
236 * Returns: the passed kmod library context
237 */
238 KMOD_EXPORT struct kmod_ctx *kmod_ref(struct kmod_ctx *ctx)
239 {
240 if (ctx == NULL)
241 return NULL;
242 ctx->refcount++;
243 return ctx;
244 }
245
246 /**
247 * kmod_unref:
248 * @ctx: kmod library context
249 *
250 * Drop a reference of the kmod library context. If the refcount
251 * reaches zero, the resources of the context will be released.
252 *
253 */
254 KMOD_EXPORT struct kmod_ctx *kmod_unref(struct kmod_ctx *ctx)
255 {
256 if (ctx == NULL)
257 return NULL;
258
259 if (--ctx->refcount > 0)
260 return ctx;
261
262 INFO(ctx, "context %p released\n", ctx);
263
264 kmod_unload_resources(ctx);
265 kmod_hash_free(ctx->modules_by_name);
266 free(ctx->dirname);
267 if (ctx->config)
268 kmod_config_free(ctx->config);
269
270 free(ctx);
271 return NULL;
272 }
273
274 /**
275 * kmod_set_log_fn:
276 * @ctx: kmod library context
277 * @log_fn: function to be called for logging messages
278 *
279 * The built-in logging writes to stderr. It can be
280 * overridden by a custom function, to plug log messages
281 * into the user's logging functionality.
282 *
283 */
284 KMOD_EXPORT void kmod_set_log_fn(struct kmod_ctx *ctx,
285 void (*log_fn)(void *data,
286 int priority, const char *file,
287 int line, const char *fn,
288 const char *format, va_list args),
289 const void *data)
290 {
291 if (ctx == NULL)
292 return;
293 ctx->log_fn = log_fn;
294 ctx->log_data = (void *)data;
295 INFO(ctx, "custom logging function %p registered\n", log_fn);
296 }
297
298 /**
299 * kmod_get_log_priority:
300 * @ctx: kmod library context
301 *
302 * Returns: the current logging priority
303 */
304 KMOD_EXPORT int kmod_get_log_priority(const struct kmod_ctx *ctx)
305 {
306 if (ctx == NULL)
307 return -1;
308 return ctx->log_priority;
309 }
310
311 /**
312 * kmod_set_log_priority:
313 * @ctx: kmod library context
314 * @priority: the new logging priority
315 *
316 * Set the current logging priority. The value controls which messages
317 * are logged.
318 */
319 KMOD_EXPORT void kmod_set_log_priority(struct kmod_ctx *ctx, int priority)
320 {
321 if (ctx == NULL)
322 return;
323 ctx->log_priority = priority;
324 }
325
326 struct kmod_module *kmod_pool_get_module(struct kmod_ctx *ctx,
327 const char *name)
328 {
329 struct kmod_module *mod;
330
331 mod = kmod_hash_find(ctx->modules_by_name, name);
332
333 DBG(ctx, "get module name='%s' found=%p\n", name, mod);
334
335 return mod;
336 }
337
338 void kmod_pool_add_module(struct kmod_ctx *ctx, struct kmod_module *mod)
339 {
340 const char *name = kmod_module_get_name(mod);
341
342 DBG(ctx, "add %p name='%s'\n", mod, name);
343
344 kmod_hash_add(ctx->modules_by_name, name, mod);
345 }
346
347 void kmod_pool_del_module(struct kmod_ctx *ctx, struct kmod_module *mod)
348 {
349 const char *name = kmod_module_get_name(mod);
350
351 DBG(ctx, "del %p name='%s'\n", mod, name);
352
353 kmod_hash_del(ctx->modules_by_name, name);
354 }
355
356 static int kmod_lookup_alias_from_alias_bin(struct kmod_ctx *ctx,
357 enum kmod_index index_number,
358 const char *name,
359 struct kmod_list **list)
360 {
361 int err, nmatch = 0;
362 struct index_file *idx;
363 struct index_value *realnames, *realname;
364
365 if (ctx->indexes[index_number] != NULL) {
366 DBG(ctx, "use mmaped index '%s' for name=%s\n",
367 index_files[index_number], name);
368 realnames = index_mm_searchwild(ctx->indexes[index_number],
369 name);
370 } else{
371 char fn[PATH_MAX];
372
373 snprintf(fn, sizeof(fn), "%s/%s.bin", ctx->dirname,
374 index_files[index_number]);
375
376 DBG(ctx, "file=%s name=%s\n", fn, name);
377
378 idx = index_file_open(fn);
379 if (idx == NULL)
380 return -ENOSYS;
381
382 realnames = index_searchwild(idx, name);
383 index_file_close(idx);
384 }
385
386 for (realname = realnames; realname; realname = realnames->next) {
387 struct kmod_module *mod;
388
389 err = kmod_module_new_from_name(ctx, realname->value, &mod);
390 if (err < 0) {
391 ERR(ctx, "%s\n", strerror(-err));
392 goto fail;
393 }
394
395 *list = kmod_list_append(*list, mod);
396 nmatch++;
397 }
398
399 index_values_free(realnames);
400 return nmatch;
401
402 fail:
403 *list = kmod_list_remove_n_latest(*list, nmatch);
404 return err;
405
406 }
407
408 int kmod_lookup_alias_from_symbols_file(struct kmod_ctx *ctx, const char *name,
409 struct kmod_list **list)
410 {
411 if (!startswith(name, "symbol:"))
412 return 0;
413
414 return kmod_lookup_alias_from_alias_bin(ctx, KMOD_INDEX_SYMBOL, name,
415 list);
416 }
417
418 int kmod_lookup_alias_from_aliases_file(struct kmod_ctx *ctx, const char *name,
419 struct kmod_list **list)
420 {
421 return kmod_lookup_alias_from_alias_bin(ctx, KMOD_INDEX_ALIAS, name,
422 list);
423 }
424
425 char *kmod_search_moddep(struct kmod_ctx *ctx, const char *name)
426 {
427 struct index_file *idx;
428 char fn[PATH_MAX];
429 char *line;
430
431 if (ctx->indexes[KMOD_INDEX_DEP]) {
432 DBG(ctx, "use mmaped index '%s' modname=%s\n",
433 index_files[KMOD_INDEX_DEP], name);
434 return index_mm_search(ctx->indexes[KMOD_INDEX_DEP], name);
435 }
436
437 snprintf(fn, sizeof(fn), "%s/%s.bin", ctx->dirname,
438 index_files[KMOD_INDEX_DEP]);
439
440 DBG(ctx, "file=%s modname=%s\n", fn, name);
441
442 idx = index_file_open(fn);
443 if (idx == NULL) {
444 ERR(ctx, "Could not open moddep file '%s'\n", fn);
445 return NULL;
446 }
447
448 line = index_search(idx, name);
449 index_file_close(idx);
450
451 return line;
452 }
453
454 int kmod_lookup_alias_from_moddep_file(struct kmod_ctx *ctx, const char *name,
455 struct kmod_list **list)
456 {
457 char *line;
458 int n = 0;
459
460 /*
461 * Module names do not contain ':'. Return early if we know it will
462 * not be found.
463 */
464 if (strchr(name, ':'))
465 return 0;
466
467 line = kmod_search_moddep(ctx, name);
468 if (line != NULL) {
469 struct kmod_module *mod;
470
471 n = kmod_module_new_from_name(ctx, name, &mod);
472 if (n < 0) {
473 ERR(ctx, "%s\n", strerror(-n));
474 goto finish;
475 }
476
477 *list = kmod_list_append(*list, mod);
478 kmod_module_parse_depline(mod, line);
479 }
480
481 finish:
482 free(line);
483
484 return n;
485 }
486
487 int kmod_lookup_alias_from_config(struct kmod_ctx *ctx, const char *name,
488 struct kmod_list **list)
489 {
490 struct kmod_config *config = ctx->config;
491 struct kmod_list *l;
492 int err, nmatch = 0;
493
494 kmod_list_foreach(l, config->aliases) {
495 const char *aliasname = kmod_alias_get_name(l);
496 const char *modname = kmod_alias_get_modname(l);
497
498 if (fnmatch(aliasname, name, 0) == 0) {
499 struct kmod_module *mod;
500
501 err = kmod_module_new_from_name(ctx, modname, &mod);
502 if (err < 0) {
503 ERR(ctx, "%s\n", strerror(-err));
504 goto fail;
505 }
506
507 *list = kmod_list_append(*list, mod);
508 nmatch++;
509 }
510 }
511
512 return nmatch;
513
514 fail:
515 *list = kmod_list_remove_n_latest(*list, nmatch);
516 return err;
517 }
518
519 /**
520 * kmod_module_get_filtered_blacklist:
521 * @ctx: kmod library context
522 * @input: list to be filtered with blacklist
523 * @output: where to save the new list
524 *
525 * Given a list @input, this function filter it out with config's blacklist
526 * ans save it in @output.
527 *
528 * Returns: 0 on success or < 0 otherwise. @output is saved with the updated
529 * list.
530 */
531 KMOD_EXPORT int kmod_module_get_filtered_blacklist(const struct kmod_ctx *ctx, const struct kmod_list *input, struct kmod_list **output)
532 {
533 const struct kmod_config *config;
534 const struct kmod_list *li;
535
536 if (ctx == NULL || output == NULL)
537 return -ENOENT;
538
539 *output = NULL;
540 if (input == NULL)
541 return 0;
542
543 config = ctx->config;
544 kmod_list_foreach(li, input) {
545 struct kmod_module *mod = li->data;
546 const struct kmod_list *lb;
547 struct kmod_list *node;
548 bool filtered = false;
549 kmod_list_foreach(lb, config->blacklists) {
550 const char *name = lb->data;
551 if (streq(name, kmod_module_get_name(mod))) {
552 filtered = true;
553 break;
554 }
555 }
556 if (filtered)
557 continue;
558
559 node = kmod_list_append(*output, mod);
560 if (node == NULL)
561 goto fail;
562 *output = node;
563 kmod_module_ref(mod);
564 }
565 return 0;
566
567 fail:
568 kmod_module_unref_list(*output);
569 *output = NULL;
570 return -ENOMEM;
571 }
572
573 KMOD_EXPORT int kmod_load_resources(struct kmod_ctx *ctx)
574 {
575 char path[PATH_MAX];
576 size_t i;
577
578 if (ctx == NULL)
579 return -ENOENT;
580
581 for (i = 0; i < ARRAY_SIZE(index_files); i++) {
582 if (ctx->indexes[i] == NULL) {
583 const char *fn = index_files[i];
584 size_t fnlen = strlen(fn);
585 const char *prefix = "";
586 const char *suffix = "";
587
588 if (fn[0] != '/')
589 prefix = ctx->dirname;
590
591 if (fnlen < 4 || !streq(fn + fnlen - 4, ".bin"))
592 suffix = ".bin";
593
594 snprintf(path, sizeof(path), "%s/%s%s",
595 prefix, fn, suffix);
596 fn = path;
597
598 ctx->indexes[i] = index_mm_open(ctx, fn, true);
599 if (ctx->indexes[i] == NULL)
600 goto fail;
601 }
602 }
603
604 return 0;
605
606 fail:
607 kmod_unload_resources(ctx);
608 return -ENOMEM;
609 }
610
611 KMOD_EXPORT void kmod_unload_resources(struct kmod_ctx *ctx)
612 {
613 size_t i;
614
615 if (ctx == NULL)
616 return;
617
618 for (i = 0; i < ARRAY_SIZE(index_files); i++) {
619 if (ctx->indexes[i] != NULL) {
620 index_mm_close(ctx->indexes[i]);
621 ctx->indexes[i] = NULL;
622 }
623 }
624 }
625
626 KMOD_EXPORT int kmod_resolve_alias_options(struct kmod_ctx *ctx, const char *given_alias, char **options)
627 {
628 struct kmod_list *modules = NULL, *l;
629 char alias[NAME_MAX];
630 char *opts = NULL;
631 size_t optslen = 0;
632 int err;
633
634 if (ctx == NULL || options == NULL)
635 return -ENOENT;
636
637 modname_normalize(given_alias, alias, NULL);
638
639 err = kmod_module_new_from_lookup(ctx, alias, &modules);
640 if (err >= 0) {
641 kmod_list_foreach(l, modules) {
642 const char *str = kmod_module_get_options(l->data);
643 size_t len;
644 void *tmp;
645
646 if (str == NULL)
647 continue;
648 len = strlen(str);
649
650 tmp = realloc(opts, optslen + len + 2);
651 if (tmp == NULL)
652 goto failed;
653 opts = tmp;
654 if (optslen > 0) {
655 opts[optslen] = ' ';
656 optslen++;
657 }
658 memcpy(opts + optslen, str, len);
659 optslen += len;
660 opts[optslen] = '\0';
661 }
662 }
663
664 kmod_list_foreach(l, ctx->config->options) {
665 const struct kmod_list *ml;
666 const char *modname = kmod_option_get_modname(l);
667 const char *str;
668 bool already_done = false;
669 size_t len;
670 void *tmp;
671
672 if (fnmatch(modname, alias, 0) != 0)
673 continue;
674
675 kmod_list_foreach(ml, modules) {
676 const char *mln = kmod_module_get_name(ml->data);
677 if (fnmatch(modname, mln, 0) == 0) {
678 already_done = true;
679 break;
680 }
681 }
682 if (already_done)
683 continue;
684
685 str = kmod_option_get_options(l);
686 len = strlen(str);
687 tmp = realloc(opts, optslen + len + 2);
688 if (tmp == NULL)
689 goto failed;
690 opts = tmp;
691 if (optslen > 0) {
692 opts[optslen] = ' ';
693 optslen++;
694 }
695 memcpy(opts + optslen, str, len);
696 optslen += len;
697 opts[optslen] = '\0';
698 }
699
700 DBG(ctx, "alias=%s options='%s'\n", alias, opts);
701 kmod_module_unref_list(modules);
702 *options = opts;
703 return 0;
704
705 failed:
706 kmod_module_unref_list(modules);
707 free(opts);
708 ERR(ctx, "out of memory\n");
709 *options = NULL;
710 return -ENOMEM;
711 }
712
713 const struct kmod_list *kmod_get_options(const struct kmod_ctx *ctx)
714 {
715 return ctx->config->options;
716 }
717
718 const struct kmod_list *kmod_get_install_commands(const struct kmod_ctx *ctx)
719 {
720 return ctx->config->install_commands;
721 }
722
723 const struct kmod_list *kmod_get_remove_commands(const struct kmod_ctx *ctx)
724 {
725 return ctx->config->remove_commands;
726 }