xref: /aosp_15_r20/external/kmod/libkmod/libkmod.c (revision cc4ad7da8cefe208cb129ac2aa9a357c7c72deb2)
1 /*
2  * libkmod - interface to kernel module operations
3  *
4  * Copyright (C) 2011-2013  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; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include <assert.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #include <fnmatch.h>
24 #include <limits.h>
25 #include <stdarg.h>
26 #include <stddef.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <sys/stat.h>
32 #include <sys/utsname.h>
33 
34 #include <shared/hash.h>
35 #include <shared/util.h>
36 
37 #include "libkmod.h"
38 #include "libkmod-internal.h"
39 #include "libkmod-index.h"
40 
41 #define KMOD_HASH_SIZE (256)
42 #define KMOD_LRU_MAX (128)
43 #define _KMOD_INDEX_MODULES_SIZE KMOD_INDEX_MODULES_BUILTIN + 1
44 
45 /**
46  * SECTION:libkmod
47  * @short_description: libkmod context
48  *
49  * The context contains the default values for the library user,
50  * and is passed to all library operations.
51  */
52 
53 static const struct {
54 	const char *fn;
55 	const char *prefix;
56 } index_files[] = {
57 	[KMOD_INDEX_MODULES_DEP] = { .fn = "modules.dep", .prefix = "" },
58 	[KMOD_INDEX_MODULES_ALIAS] = { .fn = "modules.alias", .prefix = "alias " },
59 	[KMOD_INDEX_MODULES_SYMBOL] = { .fn = "modules.symbols", .prefix = "alias "},
60 	[KMOD_INDEX_MODULES_BUILTIN_ALIAS] = { .fn = "modules.builtin.alias", .prefix = "" },
61 	[KMOD_INDEX_MODULES_BUILTIN] = { .fn = "modules.builtin", .prefix = ""},
62 };
63 
64 static const char *const default_config_paths[] = {
65 	SYSCONFDIR "/modprobe.d",
66 	"/run/modprobe.d",
67 	"/usr/local/lib/modprobe.d",
68 	DISTCONFDIR "/modprobe.d",
69 	"/lib/modprobe.d",
70 	NULL
71 };
72 
73 /**
74  * kmod_ctx:
75  *
76  * Opaque object representing the library context.
77  */
78 struct kmod_ctx {
79 	int refcount;
80 	int log_priority;
81 	void (*log_fn)(void *data,
82 			int priority, const char *file, int line,
83 			const char *fn, const char *format, va_list args);
84 	void *log_data;
85 	const void *userdata;
86 	char *dirname;
87 	enum kmod_file_compression_type kernel_compression;
88 	struct kmod_config *config;
89 	struct hash *modules_by_name;
90 	struct index_mm *indexes[_KMOD_INDEX_MODULES_SIZE];
91 	unsigned long long indexes_stamp[_KMOD_INDEX_MODULES_SIZE];
92 };
93 
kmod_log(const struct kmod_ctx * ctx,int priority,const char * file,int line,const char * fn,const char * format,...)94 void kmod_log(const struct kmod_ctx *ctx,
95 		int priority, const char *file, int line, const char *fn,
96 		const char *format, ...)
97 {
98 	va_list args;
99 
100 	if (ctx->log_fn == NULL)
101 		return;
102 
103 	va_start(args, format);
104 	ctx->log_fn(ctx->log_data, priority, file, line, fn, format, args);
105 	va_end(args);
106 }
107 
108 _printf_format_(6, 0)
log_filep(void * data,int priority,const char * file,int line,const char * fn,const char * format,va_list args)109 static void log_filep(void *data,
110 			int priority, const char *file, int line,
111 			const char *fn, const char *format, va_list args)
112 {
113 	FILE *fp = data;
114 #ifdef ENABLE_DEBUG
115 	char buf[16];
116 	const char *priname;
117 	switch (priority) {
118 	case LOG_EMERG:
119 		priname = "EMERGENCY";
120 		break;
121 	case LOG_ALERT:
122 		priname = "ALERT";
123 		break;
124 	case LOG_CRIT:
125 		priname = "CRITICAL";
126 		break;
127 	case LOG_ERR:
128 		priname = "ERROR";
129 		break;
130 	case LOG_WARNING:
131 		priname = "WARNING";
132 		break;
133 	case LOG_NOTICE:
134 		priname = "NOTICE";
135 		break;
136 	case LOG_INFO:
137 		priname = "INFO";
138 		break;
139 	case LOG_DEBUG:
140 		priname = "DEBUG";
141 		break;
142 	default:
143 		snprintf(buf, sizeof(buf), "L:%d", priority);
144 		priname = buf;
145 	}
146 	fprintf(fp, "libkmod: %s %s:%d %s: ", priname, file, line, fn);
147 #else
148 	fprintf(fp, "libkmod: %s: ", fn);
149 #endif
150 	vfprintf(fp, format, args);
151 }
152 
153 
154 /**
155  * kmod_get_dirname:
156  * @ctx: kmod library context
157  *
158  * Retrieve the absolute path used for linux modules in this context. The path
159  * is computed from the arguments to kmod_new().
160  */
kmod_get_dirname(const struct kmod_ctx * ctx)161 KMOD_EXPORT const char *kmod_get_dirname(const struct kmod_ctx *ctx)
162 {
163 	return ctx->dirname;
164 }
165 
166 /**
167  * kmod_get_userdata:
168  * @ctx: kmod library context
169  *
170  * Retrieve stored data pointer from library context. This might be useful
171  * to access from callbacks.
172  *
173  * Returns: stored userdata
174  */
kmod_get_userdata(const struct kmod_ctx * ctx)175 KMOD_EXPORT void *kmod_get_userdata(const struct kmod_ctx *ctx)
176 {
177 	if (ctx == NULL)
178 		return NULL;
179 	return (void *)ctx->userdata;
180 }
181 
182 /**
183  * kmod_set_userdata:
184  * @ctx: kmod library context
185  * @userdata: data pointer
186  *
187  * Store custom @userdata in the library context.
188  */
kmod_set_userdata(struct kmod_ctx * ctx,const void * userdata)189 KMOD_EXPORT void kmod_set_userdata(struct kmod_ctx *ctx, const void *userdata)
190 {
191 	if (ctx == NULL)
192 		return;
193 	ctx->userdata = userdata;
194 }
195 
log_priority(const char * priority)196 static int log_priority(const char *priority)
197 {
198 	char *endptr;
199 	int prio;
200 
201 	prio = strtol(priority, &endptr, 10);
202 	if (endptr[0] == '\0' || isspace(endptr[0]))
203 		return prio;
204 	if (strncmp(priority, "err", 3) == 0)
205 		return LOG_ERR;
206 	if (strncmp(priority, "info", 4) == 0)
207 		return LOG_INFO;
208 	if (strncmp(priority, "debug", 5) == 0)
209 		return LOG_DEBUG;
210 	return 0;
211 }
212 
213 static const char *dirname_default_prefix = MODULE_DIRECTORY;
214 
get_kernel_release(const char * dirname)215 static char *get_kernel_release(const char *dirname)
216 {
217 	struct utsname u;
218 	char *p;
219 
220 	if (dirname != NULL)
221 		return path_make_absolute_cwd(dirname);
222 
223 	if (uname(&u) < 0)
224 		return NULL;
225 
226 	if (asprintf(&p, "%s/%s", dirname_default_prefix, u.release) < 0)
227 		return NULL;
228 
229 	return p;
230 }
231 
get_kernel_compression(struct kmod_ctx * ctx)232 static enum kmod_file_compression_type get_kernel_compression(struct kmod_ctx *ctx)
233 {
234 	const char *path = "/sys/module/compression";
235 	char buf[16];
236 	int fd;
237 	int err;
238 
239 	fd = open(path, O_RDONLY|O_CLOEXEC);
240 	if (fd < 0) {
241 		/* Not having the file is not an error: kernel may be too old */
242 		DBG(ctx, "could not open '%s' for reading: %m\n", path);
243 		return KMOD_FILE_COMPRESSION_NONE;
244 	}
245 
246 	err = read_str_safe(fd, buf, sizeof(buf));
247 	close(fd);
248 	if (err < 0) {
249 		ERR(ctx, "could not read from '%s': %s\n",
250 		    path, strerror(-err));
251 		return KMOD_FILE_COMPRESSION_NONE;
252 	}
253 
254 	if (streq(buf, "zstd\n"))
255 		return KMOD_FILE_COMPRESSION_ZSTD;
256 	else if (streq(buf, "xz\n"))
257 		return KMOD_FILE_COMPRESSION_XZ;
258 	else if (streq(buf, "gzip\n"))
259 		return KMOD_FILE_COMPRESSION_ZLIB;
260 
261 	ERR(ctx, "unknown kernel compression %s", buf);
262 
263 	return KMOD_FILE_COMPRESSION_NONE;
264 }
265 
266 /**
267  * kmod_new:
268  * @dirname: what to consider as linux module's directory, if NULL
269  *           defaults to $MODULE_DIRECTORY/`uname -r`. If it's relative,
270  *           it's treated as relative to the current working directory.
271  *           Otherwise, give an absolute dirname.
272  * @config_paths: ordered array of paths (directories or files) where
273  *                to load from user-defined configuration parameters such as
274  *                alias, blacklists, commands (install, remove). If NULL
275  *                defaults to /etc/modprobe.d, /run/modprobe.d,
276  *                /usr/local/lib/modprobe.d, DISTCONFDIR/modprobe.d, and
277  *                /lib/modprobe.d. Give an empty vector if configuration should
278  *                not be read. This array must be null terminated.
279  *
280  * Create kmod library context. This reads the kmod configuration
281  * and fills in the default values.
282  *
283  * The initial refcount is 1, and needs to be decremented to
284  * release the resources of the kmod library context.
285  *
286  * Returns: a new kmod library context
287  */
kmod_new(const char * dirname,const char * const * config_paths)288 KMOD_EXPORT struct kmod_ctx *kmod_new(const char *dirname,
289 					const char * const *config_paths)
290 {
291 	const char *env;
292 	struct kmod_ctx *ctx;
293 	int err;
294 
295 	ctx = calloc(1, sizeof(struct kmod_ctx));
296 	if (!ctx)
297 		return NULL;
298 
299 	ctx->refcount = 1;
300 	ctx->log_fn = log_filep;
301 	ctx->log_data = stderr;
302 	ctx->log_priority = LOG_ERR;
303 
304 	ctx->dirname = get_kernel_release(dirname);
305 
306 	/* environment overwrites config */
307 	env = secure_getenv("KMOD_LOG");
308 	if (env != NULL)
309 		kmod_set_log_priority(ctx, log_priority(env));
310 
311 	ctx->kernel_compression = get_kernel_compression(ctx);
312 
313 	if (config_paths == NULL)
314 		config_paths = default_config_paths;
315 	err = kmod_config_new(ctx, &ctx->config, config_paths);
316 	if (err < 0) {
317 		ERR(ctx, "could not create config\n");
318 		goto fail;
319 	}
320 
321 	ctx->modules_by_name = hash_new(KMOD_HASH_SIZE, NULL);
322 	if (ctx->modules_by_name == NULL) {
323 		ERR(ctx, "could not create by-name hash\n");
324 		goto fail;
325 	}
326 
327 	INFO(ctx, "ctx %p created\n", ctx);
328 	DBG(ctx, "log_priority=%d\n", ctx->log_priority);
329 
330 	return ctx;
331 
332 fail:
333 	free(ctx->modules_by_name);
334 	free(ctx->dirname);
335 	free(ctx);
336 	return NULL;
337 }
338 
339 /**
340  * kmod_ref:
341  * @ctx: kmod library context
342  *
343  * Take a reference of the kmod library context.
344  *
345  * Returns: the passed kmod library context
346  */
kmod_ref(struct kmod_ctx * ctx)347 KMOD_EXPORT struct kmod_ctx *kmod_ref(struct kmod_ctx *ctx)
348 {
349 	if (ctx == NULL)
350 		return NULL;
351 	ctx->refcount++;
352 	return ctx;
353 }
354 
355 /**
356  * kmod_unref:
357  * @ctx: kmod library context
358  *
359  * Drop a reference of the kmod library context. If the refcount
360  * reaches zero, the resources of the context will be released.
361  *
362  * Returns: the passed kmod library context or NULL if it's freed
363  */
kmod_unref(struct kmod_ctx * ctx)364 KMOD_EXPORT struct kmod_ctx *kmod_unref(struct kmod_ctx *ctx)
365 {
366 	if (ctx == NULL)
367 		return NULL;
368 
369 	if (--ctx->refcount > 0)
370 		return ctx;
371 
372 	INFO(ctx, "context %p released\n", ctx);
373 
374 	kmod_unload_resources(ctx);
375 	hash_free(ctx->modules_by_name);
376 	free(ctx->dirname);
377 	if (ctx->config)
378 		kmod_config_free(ctx->config);
379 
380 	free(ctx);
381 	return NULL;
382 }
383 
384 /**
385  * kmod_set_log_fn:
386  * @ctx: kmod library context
387  * @log_fn: function to be called for logging messages
388  * @data: data to pass to log function
389  *
390  * The built-in logging writes to stderr. It can be
391  * overridden by a custom function, to plug log messages
392  * into the user's logging functionality.
393  */
kmod_set_log_fn(struct kmod_ctx * ctx,void (* log_fn)(void * data,int priority,const char * file,int line,const char * fn,const char * format,va_list args),const void * data)394 KMOD_EXPORT void kmod_set_log_fn(struct kmod_ctx *ctx,
395 					void (*log_fn)(void *data,
396 						int priority, const char *file,
397 						int line, const char *fn,
398 						const char *format, va_list args),
399 					const void *data)
400 {
401 	if (ctx == NULL)
402 		return;
403 	ctx->log_fn = log_fn;
404 	ctx->log_data = (void *)data;
405 	INFO(ctx, "custom logging function %p registered\n", log_fn);
406 }
407 
408 /**
409  * kmod_get_log_priority:
410  * @ctx: kmod library context
411  *
412  * Returns: the current logging priority
413  */
kmod_get_log_priority(const struct kmod_ctx * ctx)414 KMOD_EXPORT int kmod_get_log_priority(const struct kmod_ctx *ctx)
415 {
416 	if (ctx == NULL)
417 		return -1;
418 	return ctx->log_priority;
419 }
420 
421 /**
422  * kmod_set_log_priority:
423  * @ctx: kmod library context
424  * @priority: the new logging priority
425  *
426  * Set the current logging priority. The value controls which messages
427  * are logged.
428  */
kmod_set_log_priority(struct kmod_ctx * ctx,int priority)429 KMOD_EXPORT void kmod_set_log_priority(struct kmod_ctx *ctx, int priority)
430 {
431 	if (ctx == NULL)
432 		return;
433 	ctx->log_priority = priority;
434 }
435 
kmod_pool_get_module(struct kmod_ctx * ctx,const char * key)436 struct kmod_module *kmod_pool_get_module(struct kmod_ctx *ctx,
437 							const char *key)
438 {
439 	struct kmod_module *mod;
440 
441 	mod = hash_find(ctx->modules_by_name, key);
442 
443 	DBG(ctx, "get module name='%s' found=%p\n", key, mod);
444 
445 	return mod;
446 }
447 
kmod_pool_add_module(struct kmod_ctx * ctx,struct kmod_module * mod,const char * key)448 void kmod_pool_add_module(struct kmod_ctx *ctx, struct kmod_module *mod,
449 							const char *key)
450 {
451 	DBG(ctx, "add %p key='%s'\n", mod, key);
452 
453 	hash_add(ctx->modules_by_name, key, mod);
454 }
455 
kmod_pool_del_module(struct kmod_ctx * ctx,struct kmod_module * mod,const char * key)456 void kmod_pool_del_module(struct kmod_ctx *ctx, struct kmod_module *mod,
457 							const char *key)
458 {
459 	DBG(ctx, "del %p key='%s'\n", mod, key);
460 
461 	hash_del(ctx->modules_by_name, key);
462 }
463 
kmod_lookup_alias_from_alias_bin(struct kmod_ctx * ctx,enum kmod_index index_number,const char * name,struct kmod_list ** list)464 static int kmod_lookup_alias_from_alias_bin(struct kmod_ctx *ctx,
465 						enum kmod_index index_number,
466 						const char *name,
467 						struct kmod_list **list)
468 {
469 	int err, nmatch = 0;
470 	struct index_file *idx;
471 	struct index_value *realnames, *realname;
472 
473 	if (ctx->indexes[index_number] != NULL) {
474 		DBG(ctx, "use mmaped index '%s' for name=%s\n",
475 			index_files[index_number].fn, name);
476 		realnames = index_mm_searchwild(ctx->indexes[index_number],
477 									name);
478 	} else {
479 		char fn[PATH_MAX];
480 
481 		snprintf(fn, sizeof(fn), "%s/%s.bin", ctx->dirname,
482 					index_files[index_number].fn);
483 
484 		DBG(ctx, "file=%s name=%s\n", fn, name);
485 
486 		idx = index_file_open(fn);
487 		if (idx == NULL)
488 			return -ENOSYS;
489 
490 		realnames = index_searchwild(idx, name);
491 		index_file_close(idx);
492 	}
493 
494 	for (realname = realnames; realname; realname = realname->next) {
495 		struct kmod_module *mod;
496 
497 		err = kmod_module_new_from_alias(ctx, name, realname->value, &mod);
498 		if (err < 0) {
499 			ERR(ctx, "Could not create module for alias=%s realname=%s: %s\n",
500 			    name, realname->value, strerror(-err));
501 			goto fail;
502 		}
503 
504 		*list = kmod_list_append(*list, mod);
505 		nmatch++;
506 	}
507 
508 	index_values_free(realnames);
509 	return nmatch;
510 
511 fail:
512 	*list = kmod_list_remove_n_latest(*list, nmatch);
513 	index_values_free(realnames);
514 	return err;
515 
516 }
517 
kmod_lookup_alias_from_symbols_file(struct kmod_ctx * ctx,const char * name,struct kmod_list ** list)518 int kmod_lookup_alias_from_symbols_file(struct kmod_ctx *ctx, const char *name,
519 						struct kmod_list **list)
520 {
521 	if (!strstartswith(name, "symbol:"))
522 		return 0;
523 
524 	return kmod_lookup_alias_from_alias_bin(ctx, KMOD_INDEX_MODULES_SYMBOL,
525 								name, list);
526 }
527 
kmod_lookup_alias_from_aliases_file(struct kmod_ctx * ctx,const char * name,struct kmod_list ** list)528 int kmod_lookup_alias_from_aliases_file(struct kmod_ctx *ctx, const char *name,
529 						struct kmod_list **list)
530 {
531 	return kmod_lookup_alias_from_alias_bin(ctx, KMOD_INDEX_MODULES_ALIAS,
532 								name, list);
533 }
534 
lookup_builtin_file(struct kmod_ctx * ctx,const char * name)535 static char *lookup_builtin_file(struct kmod_ctx *ctx, const char *name)
536 {
537 	char *line;
538 
539 	if (ctx->indexes[KMOD_INDEX_MODULES_BUILTIN]) {
540 		DBG(ctx, "use mmaped index '%s' modname=%s\n",
541 				index_files[KMOD_INDEX_MODULES_BUILTIN].fn,
542 				name);
543 		line = index_mm_search(ctx->indexes[KMOD_INDEX_MODULES_BUILTIN],
544 									name);
545 	} else {
546 		struct index_file *idx;
547 		char fn[PATH_MAX];
548 
549 		snprintf(fn, sizeof(fn), "%s/%s.bin", ctx->dirname,
550 				index_files[KMOD_INDEX_MODULES_BUILTIN].fn);
551 		DBG(ctx, "file=%s modname=%s\n", fn, name);
552 
553 		idx = index_file_open(fn);
554 		if (idx == NULL) {
555 			DBG(ctx, "could not open builtin file '%s'\n", fn);
556 			return NULL;
557 		}
558 
559 		line = index_search(idx, name);
560 		index_file_close(idx);
561 	}
562 
563 	return line;
564 }
565 
kmod_lookup_alias_from_kernel_builtin_file(struct kmod_ctx * ctx,const char * name,struct kmod_list ** list)566 int kmod_lookup_alias_from_kernel_builtin_file(struct kmod_ctx *ctx,
567 						const char *name,
568 						struct kmod_list **list)
569 {
570 	struct kmod_list *l;
571 	int ret;
572 
573 	assert(*list == NULL);
574 
575 	ret = kmod_lookup_alias_from_alias_bin(ctx,
576 					       KMOD_INDEX_MODULES_BUILTIN_ALIAS,
577 					       name, list);
578 
579 	kmod_list_foreach(l, *list) {
580 		struct kmod_module *mod = l->data;
581 		kmod_module_set_builtin(mod, true);
582 	}
583 
584 	return ret;
585 }
586 
kmod_lookup_alias_from_builtin_file(struct kmod_ctx * ctx,const char * name,struct kmod_list ** list)587 int kmod_lookup_alias_from_builtin_file(struct kmod_ctx *ctx, const char *name,
588 						struct kmod_list **list)
589 {
590 	char *line;
591 	int err = 0;
592 
593 	assert(*list == NULL);
594 
595 	line = lookup_builtin_file(ctx, name);
596 	if (line != NULL) {
597 		struct kmod_module *mod;
598 
599 		err = kmod_module_new_from_name(ctx, name, &mod);
600 		if (err < 0) {
601 			ERR(ctx, "Could not create module from name %s: %s\n",
602 							name, strerror(-err));
603 			goto finish;
604 		}
605 
606 		/* already mark it as builtin since it's being created from
607 		 * this index */
608 		kmod_module_set_builtin(mod, true);
609 		*list = kmod_list_append(*list, mod);
610 		if (*list == NULL)
611 			err = -ENOMEM;
612 	}
613 
614 finish:
615 	free(line);
616 	return err;
617 }
618 
kmod_lookup_alias_is_builtin(struct kmod_ctx * ctx,const char * name)619 bool kmod_lookup_alias_is_builtin(struct kmod_ctx *ctx, const char *name)
620 {
621 	_cleanup_free_ char *line;
622 
623 	line = lookup_builtin_file(ctx, name);
624 
625 	return line != NULL;
626 }
627 
kmod_search_moddep(struct kmod_ctx * ctx,const char * name)628 char *kmod_search_moddep(struct kmod_ctx *ctx, const char *name)
629 {
630 	struct index_file *idx;
631 	char fn[PATH_MAX];
632 	char *line;
633 
634 	if (ctx->indexes[KMOD_INDEX_MODULES_DEP]) {
635 		DBG(ctx, "use mmaped index '%s' modname=%s\n",
636 				index_files[KMOD_INDEX_MODULES_DEP].fn, name);
637 		return index_mm_search(ctx->indexes[KMOD_INDEX_MODULES_DEP],
638 									name);
639 	}
640 
641 	snprintf(fn, sizeof(fn), "%s/%s.bin", ctx->dirname,
642 					index_files[KMOD_INDEX_MODULES_DEP].fn);
643 
644 	DBG(ctx, "file=%s modname=%s\n", fn, name);
645 
646 	idx = index_file_open(fn);
647 	if (idx == NULL) {
648 		DBG(ctx, "could not open moddep file '%s'\n", fn);
649 		return NULL;
650 	}
651 
652 	line = index_search(idx, name);
653 	index_file_close(idx);
654 
655 	return line;
656 }
657 
kmod_lookup_alias_from_moddep_file(struct kmod_ctx * ctx,const char * name,struct kmod_list ** list)658 int kmod_lookup_alias_from_moddep_file(struct kmod_ctx *ctx, const char *name,
659 						struct kmod_list **list)
660 {
661 	char *line;
662 	int n = 0;
663 
664 	/*
665 	 * Module names do not contain ':'. Return early if we know it will
666 	 * not be found.
667 	 */
668 	if (strchr(name, ':'))
669 		return 0;
670 
671 	line = kmod_search_moddep(ctx, name);
672 	if (line != NULL) {
673 		struct kmod_module *mod;
674 
675 		n = kmod_module_new_from_name(ctx, name, &mod);
676 		if (n < 0) {
677 			ERR(ctx, "Could not create module from name %s: %s\n",
678 			    name, strerror(-n));
679 			goto finish;
680 		}
681 
682 		*list = kmod_list_append(*list, mod);
683 		kmod_module_parse_depline(mod, line);
684 	}
685 
686 finish:
687 	free(line);
688 
689 	return n;
690 }
691 
kmod_lookup_alias_from_config(struct kmod_ctx * ctx,const char * name,struct kmod_list ** list)692 int kmod_lookup_alias_from_config(struct kmod_ctx *ctx, const char *name,
693 						struct kmod_list **list)
694 {
695 	struct kmod_config *config = ctx->config;
696 	struct kmod_list *l;
697 	int err, nmatch = 0;
698 
699 	kmod_list_foreach(l, config->aliases) {
700 		const char *aliasname = kmod_alias_get_name(l);
701 		const char *modname = kmod_alias_get_modname(l);
702 
703 		if (fnmatch(aliasname, name, 0) == 0) {
704 			struct kmod_module *mod;
705 
706 			err = kmod_module_new_from_alias(ctx, aliasname,
707 								modname, &mod);
708 			if (err < 0) {
709 				ERR(ctx, "Could not create module for alias=%s modname=%s: %s\n",
710 				    name, modname, strerror(-err));
711 				goto fail;
712 			}
713 
714 			*list = kmod_list_append(*list, mod);
715 			nmatch++;
716 		}
717 	}
718 
719 	return nmatch;
720 
721 fail:
722 	*list = kmod_list_remove_n_latest(*list, nmatch);
723 	return err;
724 }
725 
kmod_lookup_alias_from_commands(struct kmod_ctx * ctx,const char * name,struct kmod_list ** list)726 int kmod_lookup_alias_from_commands(struct kmod_ctx *ctx, const char *name,
727 						struct kmod_list **list)
728 {
729 	struct kmod_config *config = ctx->config;
730 	struct kmod_list *l, *node;
731 	int err, nmatch = 0;
732 
733 	kmod_list_foreach(l, config->install_commands) {
734 		const char *modname = kmod_command_get_modname(l);
735 
736 		if (streq(modname, name)) {
737 			const char *cmd = kmod_command_get_command(l);
738 			struct kmod_module *mod;
739 
740 			err = kmod_module_new_from_name(ctx, modname, &mod);
741 			if (err < 0) {
742 				ERR(ctx, "Could not create module from name %s: %s\n",
743 				    modname, strerror(-err));
744 				return err;
745 			}
746 
747 			node = kmod_list_append(*list, mod);
748 			if (node == NULL) {
749 				ERR(ctx, "out of memory\n");
750 				return -ENOMEM;
751 			}
752 
753 			*list = node;
754 			nmatch = 1;
755 
756 			kmod_module_set_install_commands(mod, cmd);
757 
758 			/*
759 			 * match only the first one, like modprobe from
760 			 * module-init-tools does
761 			 */
762 			break;
763 		}
764 	}
765 
766 	if (nmatch)
767 		return nmatch;
768 
769 	kmod_list_foreach(l, config->remove_commands) {
770 		const char *modname = kmod_command_get_modname(l);
771 
772 		if (streq(modname, name)) {
773 			const char *cmd = kmod_command_get_command(l);
774 			struct kmod_module *mod;
775 
776 			err = kmod_module_new_from_name(ctx, modname, &mod);
777 			if (err < 0) {
778 				ERR(ctx, "Could not create module from name %s: %s\n",
779 				    modname, strerror(-err));
780 				return err;
781 			}
782 
783 			node = kmod_list_append(*list, mod);
784 			if (node == NULL) {
785 				ERR(ctx, "out of memory\n");
786 				return -ENOMEM;
787 			}
788 
789 			*list = node;
790 			nmatch = 1;
791 
792 			kmod_module_set_remove_commands(mod, cmd);
793 
794 			/*
795 			 * match only the first one, like modprobe from
796 			 * module-init-tools does
797 			 */
798 			break;
799 		}
800 	}
801 
802 	return nmatch;
803 }
804 
kmod_set_modules_visited(struct kmod_ctx * ctx,bool visited)805 void kmod_set_modules_visited(struct kmod_ctx *ctx, bool visited)
806 {
807 	struct hash_iter iter;
808 	const void *v;
809 
810 	hash_iter_init(ctx->modules_by_name, &iter);
811 	while (hash_iter_next(&iter, NULL, &v))
812 		kmod_module_set_visited((struct kmod_module *)v, visited);
813 }
814 
kmod_set_modules_required(struct kmod_ctx * ctx,bool required)815 void kmod_set_modules_required(struct kmod_ctx *ctx, bool required)
816 {
817 	struct hash_iter iter;
818 	const void *v;
819 
820 	hash_iter_init(ctx->modules_by_name, &iter);
821 	while (hash_iter_next(&iter, NULL, &v))
822 		kmod_module_set_required((struct kmod_module *)v, required);
823 }
824 
is_cache_invalid(const char * path,unsigned long long stamp)825 static bool is_cache_invalid(const char *path, unsigned long long stamp)
826 {
827 	struct stat st;
828 
829 	if (stat(path, &st) < 0)
830 		return true;
831 
832 	if (stamp != stat_mstamp(&st))
833 		return true;
834 
835 	return false;
836 }
837 
838 /**
839  * kmod_validate_resources:
840  * @ctx: kmod library context
841  *
842  * Check if indexes and configuration files changed on disk and the current
843  * context is not valid anymore.
844  *
845  * Returns: KMOD_RESOURCES_OK if resources are still valid,
846  * KMOD_RESOURCES_MUST_RELOAD if it's sufficient to call
847  * kmod_unload_resources() and kmod_load_resources() or
848  * KMOD_RESOURCES_MUST_RECREATE if @ctx must be re-created.
849  */
kmod_validate_resources(struct kmod_ctx * ctx)850 KMOD_EXPORT int kmod_validate_resources(struct kmod_ctx *ctx)
851 {
852 	struct kmod_list *l;
853 	size_t i;
854 
855 	if (ctx == NULL || ctx->config == NULL)
856 		return KMOD_RESOURCES_MUST_RECREATE;
857 
858 	kmod_list_foreach(l, ctx->config->paths) {
859 		struct kmod_config_path *cf = l->data;
860 
861 		if (is_cache_invalid(cf->path, cf->stamp))
862 			return KMOD_RESOURCES_MUST_RECREATE;
863 	}
864 
865 	for (i = 0; i < _KMOD_INDEX_MODULES_SIZE; i++) {
866 		char path[PATH_MAX];
867 
868 		if (ctx->indexes[i] == NULL)
869 			continue;
870 
871 		snprintf(path, sizeof(path), "%s/%s.bin", ctx->dirname,
872 						index_files[i].fn);
873 
874 		if (is_cache_invalid(path, ctx->indexes_stamp[i]))
875 			return KMOD_RESOURCES_MUST_RELOAD;
876 	}
877 
878 	return KMOD_RESOURCES_OK;
879 }
880 
881 /**
882  * kmod_load_resources:
883  * @ctx: kmod library context
884  *
885  * Load indexes and keep them open in @ctx. This way it's faster to lookup
886  * information within the indexes. If this function is not called before a
887  * search, the necessary index is always opened and closed.
888  *
889  * If user will do more than one or two lookups, insertions, deletions, most
890  * likely it's good to call this function first. Particularly in a daemon like
891  * udev that on bootup issues hundreds of calls to lookup the index, calling
892  * this function will speedup the searches.
893  *
894  * Returns: 0 on success or < 0 otherwise.
895  */
kmod_load_resources(struct kmod_ctx * ctx)896 KMOD_EXPORT int kmod_load_resources(struct kmod_ctx *ctx)
897 {
898 	int ret = 0;
899 	size_t i;
900 
901 	if (ctx == NULL)
902 		return -ENOENT;
903 
904 	for (i = 0; i < _KMOD_INDEX_MODULES_SIZE; i++) {
905 		char path[PATH_MAX];
906 
907 		if (ctx->indexes[i] != NULL) {
908 			INFO(ctx, "Index %s already loaded\n",
909 							index_files[i].fn);
910 			continue;
911 		}
912 
913 		snprintf(path, sizeof(path), "%s/%s.bin", ctx->dirname,
914 							index_files[i].fn);
915 		ret = index_mm_open(ctx, path, &ctx->indexes_stamp[i],
916 				    &ctx->indexes[i]);
917 
918 		/*
919 		 * modules.builtin.alias are considered optional since it's
920 		 * recently added and older installations may not have it;
921 		 * we allow failing for any reason
922 		 */
923 		if (ret) {
924 			if (i != KMOD_INDEX_MODULES_BUILTIN_ALIAS)
925 				break;
926 			ret = 0;
927 		}
928 	}
929 
930 	if (ret)
931 		kmod_unload_resources(ctx);
932 
933 	return ret;
934 }
935 
936 /**
937  * kmod_unload_resources:
938  * @ctx: kmod library context
939  *
940  * Unload all the indexes. This will free the resources to maintain the index
941  * open and all subsequent searches will need to open and close the index.
942  *
943  * User is free to call kmod_load_resources() and kmod_unload_resources() as
944  * many times as wanted during the lifecycle of @ctx. For example, if a daemon
945  * knows that when starting up it will lookup a lot of modules, it could call
946  * kmod_load_resources() and after the first burst of searches is gone, it
947  * could free the resources by calling kmod_unload_resources().
948  *
949  * Returns: 0 on success or < 0 otherwise.
950  */
kmod_unload_resources(struct kmod_ctx * ctx)951 KMOD_EXPORT void kmod_unload_resources(struct kmod_ctx *ctx)
952 {
953 	size_t i;
954 
955 	if (ctx == NULL)
956 		return;
957 
958 	for (i = 0; i < _KMOD_INDEX_MODULES_SIZE; i++) {
959 		if (ctx->indexes[i] != NULL) {
960 			index_mm_close(ctx->indexes[i]);
961 			ctx->indexes[i] = NULL;
962 			ctx->indexes_stamp[i] = 0;
963 		}
964 	}
965 }
966 
967 /**
968  * kmod_dump_index:
969  * @ctx: kmod library context
970  * @type: index to dump, valid indexes are
971  * KMOD_INDEX_MODULES_DEP: index of module dependencies;
972  * KMOD_INDEX_MODULES_ALIAS: index of module aliases;
973  * KMOD_INDEX_MODULES_SYMBOL: index of symbol aliases;
974  * KMOD_INDEX_MODULES_BUILTIN: index of builtin module.
975  * @fd: file descriptor to dump index to
976  *
977  * Dump index to file descriptor. Note that this function doesn't use stdio.h
978  * so call fflush() before calling this function to be sure data is written in
979  * order.
980  *
981  * Returns: 0 on success or < 0 otherwise.
982  */
kmod_dump_index(struct kmod_ctx * ctx,enum kmod_index type,int fd)983 KMOD_EXPORT int kmod_dump_index(struct kmod_ctx *ctx, enum kmod_index type,
984 									int fd)
985 {
986 	if (ctx == NULL)
987 		return -ENOSYS;
988 
989 	if (type < 0 || type >= _KMOD_INDEX_MODULES_SIZE)
990 		return -ENOENT;
991 
992 	if (ctx->indexes[type] != NULL) {
993 		DBG(ctx, "use mmaped index '%s'\n", index_files[type].fn);
994 		index_mm_dump(ctx->indexes[type], fd,
995 						index_files[type].prefix);
996 	} else {
997 		char fn[PATH_MAX];
998 		struct index_file *idx;
999 
1000 		snprintf(fn, sizeof(fn), "%s/%s.bin", ctx->dirname,
1001 						index_files[type].fn);
1002 
1003 		DBG(ctx, "file=%s\n", fn);
1004 
1005 		idx = index_file_open(fn);
1006 		if (idx == NULL)
1007 			return -ENOSYS;
1008 
1009 		index_dump(idx, fd, index_files[type].prefix);
1010 		index_file_close(idx);
1011 	}
1012 
1013 	return 0;
1014 }
1015 
kmod_get_config(const struct kmod_ctx * ctx)1016 const struct kmod_config *kmod_get_config(const struct kmod_ctx *ctx)
1017 {
1018 	return ctx->config;
1019 }
1020 
kmod_get_kernel_compression(const struct kmod_ctx * ctx)1021 enum kmod_file_compression_type kmod_get_kernel_compression(const struct kmod_ctx *ctx)
1022 {
1023 	return ctx->kernel_compression;
1024 }
1025