]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/hwdb/hwdb.c
man: remove recommendation to pull in slices from slices.target
[thirdparty/systemd.git] / src / hwdb / hwdb.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <ctype.h>
4 #include <getopt.h>
5 #include <stdlib.h>
6 #include <string.h>
7
8 #include "alloc-util.h"
9 #include "conf-files.h"
10 #include "fd-util.h"
11 #include "fileio.h"
12 #include "fs-util.h"
13 #include "hwdb-internal.h"
14 #include "hwdb-util.h"
15 #include "label.h"
16 #include "mkdir.h"
17 #include "path-util.h"
18 #include "selinux-util.h"
19 #include "strbuf.h"
20 #include "string-util.h"
21 #include "strv.h"
22 #include "terminal-util.h"
23 #include "util.h"
24 #include "verbs.h"
25
26 /*
27 * Generic udev properties, key-value database based on modalias strings.
28 * Uses a Patricia/radix trie to index all matches for efficient lookup.
29 */
30
31 static const char *arg_hwdb_bin_dir = "/etc/udev";
32 static const char *arg_root = "";
33 static bool arg_strict;
34
35 static const char * const conf_file_dirs[] = {
36 "/etc/udev/hwdb.d",
37 UDEVLIBEXECDIR "/hwdb.d",
38 NULL
39 };
40
41 /* in-memory trie objects */
42 struct trie {
43 struct trie_node *root;
44 struct strbuf *strings;
45
46 size_t nodes_count;
47 size_t children_count;
48 size_t values_count;
49 };
50
51 struct trie_node {
52 /* prefix, common part for all children of this node */
53 size_t prefix_off;
54
55 /* sorted array of pointers to children nodes */
56 struct trie_child_entry *children;
57 uint8_t children_count;
58
59 /* sorted array of key-value pairs */
60 struct trie_value_entry *values;
61 size_t values_count;
62 };
63
64 /* children array item with char (0-255) index */
65 struct trie_child_entry {
66 uint8_t c;
67 struct trie_node *child;
68 };
69
70 /* value array item with key-value pairs */
71 struct trie_value_entry {
72 size_t key_off;
73 size_t value_off;
74 size_t filename_off;
75 uint32_t line_number;
76 uint16_t file_priority;
77 };
78
79 static int trie_children_cmp(const void *v1, const void *v2) {
80 const struct trie_child_entry *n1 = v1;
81 const struct trie_child_entry *n2 = v2;
82
83 return n1->c - n2->c;
84 }
85
86 static int node_add_child(struct trie *trie, struct trie_node *node, struct trie_node *node_child, uint8_t c) {
87 struct trie_child_entry *child;
88
89 /* extend array, add new entry, sort for bisection */
90 child = reallocarray(node->children, node->children_count + 1, sizeof(struct trie_child_entry));
91 if (!child)
92 return -ENOMEM;
93
94 node->children = child;
95 trie->children_count++;
96 node->children[node->children_count].c = c;
97 node->children[node->children_count].child = node_child;
98 node->children_count++;
99 qsort(node->children, node->children_count, sizeof(struct trie_child_entry), trie_children_cmp);
100 trie->nodes_count++;
101
102 return 0;
103 }
104
105 static struct trie_node *node_lookup(const struct trie_node *node, uint8_t c) {
106 struct trie_child_entry *child;
107 struct trie_child_entry search;
108
109 search.c = c;
110 child = bsearch_safe(&search, node->children, node->children_count, sizeof(struct trie_child_entry), trie_children_cmp);
111 if (child)
112 return child->child;
113 return NULL;
114 }
115
116 static void trie_node_cleanup(struct trie_node *node) {
117 size_t i;
118
119 for (i = 0; i < node->children_count; i++)
120 trie_node_cleanup(node->children[i].child);
121 free(node->children);
122 free(node->values);
123 free(node);
124 }
125
126 static void trie_free(struct trie *trie) {
127 if (!trie)
128 return;
129
130 if (trie->root)
131 trie_node_cleanup(trie->root);
132
133 strbuf_cleanup(trie->strings);
134 free(trie);
135 }
136
137 DEFINE_TRIVIAL_CLEANUP_FUNC(struct trie*, trie_free);
138
139 static int trie_values_cmp(const void *v1, const void *v2, void *arg) {
140 const struct trie_value_entry *val1 = v1;
141 const struct trie_value_entry *val2 = v2;
142 struct trie *trie = arg;
143
144 return strcmp(trie->strings->buf + val1->key_off,
145 trie->strings->buf + val2->key_off);
146 }
147
148 static int trie_node_add_value(struct trie *trie, struct trie_node *node,
149 const char *key, const char *value,
150 const char *filename, uint16_t file_priority, uint32_t line_number) {
151 ssize_t k, v, fn;
152 struct trie_value_entry *val;
153
154 k = strbuf_add_string(trie->strings, key, strlen(key));
155 if (k < 0)
156 return k;
157 v = strbuf_add_string(trie->strings, value, strlen(value));
158 if (v < 0)
159 return v;
160 fn = strbuf_add_string(trie->strings, filename, strlen(filename));
161 if (fn < 0)
162 return fn;
163
164 if (node->values_count) {
165 struct trie_value_entry search = {
166 .key_off = k,
167 .value_off = v,
168 };
169
170 val = xbsearch_r(&search, node->values, node->values_count, sizeof(struct trie_value_entry), trie_values_cmp, trie);
171 if (val) {
172 /* At this point we have 2 identical properties on the same match-string.
173 * Since we process files in order, we just replace the previous value.
174 */
175 val->value_off = v;
176 val->filename_off = fn;
177 val->file_priority = file_priority;
178 val->line_number = line_number;
179 return 0;
180 }
181 }
182
183 /* extend array, add new entry, sort for bisection */
184 val = reallocarray(node->values, node->values_count + 1, sizeof(struct trie_value_entry));
185 if (!val)
186 return -ENOMEM;
187 trie->values_count++;
188 node->values = val;
189 node->values[node->values_count].key_off = k;
190 node->values[node->values_count].value_off = v;
191 node->values[node->values_count].filename_off = fn;
192 node->values[node->values_count].file_priority = file_priority;
193 node->values[node->values_count].line_number = line_number;
194 node->values_count++;
195 qsort_r(node->values, node->values_count, sizeof(struct trie_value_entry), trie_values_cmp, trie);
196 return 0;
197 }
198
199 static int trie_insert(struct trie *trie, struct trie_node *node, const char *search,
200 const char *key, const char *value,
201 const char *filename, uint16_t file_priority, uint32_t line_number) {
202 size_t i = 0;
203 int r = 0;
204
205 for (;;) {
206 size_t p;
207 uint8_t c;
208 struct trie_node *child;
209
210 for (p = 0; (c = trie->strings->buf[node->prefix_off + p]); p++) {
211 _cleanup_free_ char *s = NULL;
212 ssize_t off;
213 _cleanup_free_ struct trie_node *new_child = NULL;
214
215 if (c == search[i + p])
216 continue;
217
218 /* split node */
219 new_child = new0(struct trie_node, 1);
220 if (!new_child)
221 return -ENOMEM;
222
223 /* move values from parent to child */
224 new_child->prefix_off = node->prefix_off + p+1;
225 new_child->children = node->children;
226 new_child->children_count = node->children_count;
227 new_child->values = node->values;
228 new_child->values_count = node->values_count;
229
230 /* update parent; use strdup() because the source gets realloc()d */
231 s = strndup(trie->strings->buf + node->prefix_off, p);
232 if (!s)
233 return -ENOMEM;
234
235 off = strbuf_add_string(trie->strings, s, p);
236 if (off < 0)
237 return off;
238
239 node->prefix_off = off;
240 node->children = NULL;
241 node->children_count = 0;
242 node->values = NULL;
243 node->values_count = 0;
244 r = node_add_child(trie, node, new_child, c);
245 if (r < 0)
246 return r;
247
248 new_child = NULL; /* avoid cleanup */
249 break;
250 }
251 i += p;
252
253 c = search[i];
254 if (c == '\0')
255 return trie_node_add_value(trie, node, key, value, filename, file_priority, line_number);
256
257 child = node_lookup(node, c);
258 if (!child) {
259 ssize_t off;
260
261 /* new child */
262 child = new0(struct trie_node, 1);
263 if (!child)
264 return -ENOMEM;
265
266 off = strbuf_add_string(trie->strings, search + i+1, strlen(search + i+1));
267 if (off < 0) {
268 free(child);
269 return off;
270 }
271
272 child->prefix_off = off;
273 r = node_add_child(trie, node, child, c);
274 if (r < 0) {
275 free(child);
276 return r;
277 }
278
279 return trie_node_add_value(trie, child, key, value, filename, file_priority, line_number);
280 }
281
282 node = child;
283 i++;
284 }
285 }
286
287 struct trie_f {
288 FILE *f;
289 struct trie *trie;
290 uint64_t strings_off;
291
292 uint64_t nodes_count;
293 uint64_t children_count;
294 uint64_t values_count;
295 };
296
297 /* calculate the storage space for the nodes, children arrays, value arrays */
298 static void trie_store_nodes_size(struct trie_f *trie, struct trie_node *node) {
299 uint64_t i;
300
301 for (i = 0; i < node->children_count; i++)
302 trie_store_nodes_size(trie, node->children[i].child);
303
304 trie->strings_off += sizeof(struct trie_node_f);
305 for (i = 0; i < node->children_count; i++)
306 trie->strings_off += sizeof(struct trie_child_entry_f);
307 for (i = 0; i < node->values_count; i++)
308 trie->strings_off += sizeof(struct trie_value_entry2_f);
309 }
310
311 static int64_t trie_store_nodes(struct trie_f *trie, struct trie_node *node) {
312 uint64_t i;
313 struct trie_node_f n = {
314 .prefix_off = htole64(trie->strings_off + node->prefix_off),
315 .children_count = node->children_count,
316 .values_count = htole64(node->values_count),
317 };
318 _cleanup_free_ struct trie_child_entry_f *children = NULL;
319 int64_t node_off;
320
321 if (node->children_count) {
322 children = new(struct trie_child_entry_f, node->children_count);
323 if (!children)
324 return -ENOMEM;
325 }
326
327 /* post-order recursion */
328 for (i = 0; i < node->children_count; i++) {
329 int64_t child_off;
330
331 child_off = trie_store_nodes(trie, node->children[i].child);
332 if (child_off < 0)
333 return child_off;
334
335 children[i] = (struct trie_child_entry_f) {
336 .c = node->children[i].c,
337 .child_off = htole64(child_off),
338 };
339 }
340
341 /* write node */
342 node_off = ftello(trie->f);
343 fwrite(&n, sizeof(struct trie_node_f), 1, trie->f);
344 trie->nodes_count++;
345
346 /* append children array */
347 if (node->children_count) {
348 fwrite(children, sizeof(struct trie_child_entry_f), node->children_count, trie->f);
349 trie->children_count += node->children_count;
350 }
351
352 /* append values array */
353 for (i = 0; i < node->values_count; i++) {
354 struct trie_value_entry2_f v = {
355 .key_off = htole64(trie->strings_off + node->values[i].key_off),
356 .value_off = htole64(trie->strings_off + node->values[i].value_off),
357 .filename_off = htole64(trie->strings_off + node->values[i].filename_off),
358 .line_number = htole32(node->values[i].line_number),
359 .file_priority = htole16(node->values[i].file_priority),
360 };
361
362 fwrite(&v, sizeof(struct trie_value_entry2_f), 1, trie->f);
363 }
364 trie->values_count += node->values_count;
365
366 return node_off;
367 }
368
369 static int trie_store(struct trie *trie, const char *filename) {
370 struct trie_f t = {
371 .trie = trie,
372 };
373 _cleanup_free_ char *filename_tmp = NULL;
374 int64_t pos;
375 int64_t root_off;
376 int64_t size;
377 struct trie_header_f h = {
378 .signature = HWDB_SIG,
379 .tool_version = htole64(atoi(PACKAGE_VERSION)),
380 .header_size = htole64(sizeof(struct trie_header_f)),
381 .node_size = htole64(sizeof(struct trie_node_f)),
382 .child_entry_size = htole64(sizeof(struct trie_child_entry_f)),
383 .value_entry_size = htole64(sizeof(struct trie_value_entry2_f)),
384 };
385 int r;
386
387 /* calculate size of header, nodes, children entries, value entries */
388 t.strings_off = sizeof(struct trie_header_f);
389 trie_store_nodes_size(&t, trie->root);
390
391 r = fopen_temporary(filename, &t.f, &filename_tmp);
392 if (r < 0)
393 return r;
394 fchmod(fileno(t.f), 0444);
395
396 /* write nodes */
397 if (fseeko(t.f, sizeof(struct trie_header_f), SEEK_SET) < 0)
398 goto error_fclose;
399
400 root_off = trie_store_nodes(&t, trie->root);
401 h.nodes_root_off = htole64(root_off);
402 pos = ftello(t.f);
403 h.nodes_len = htole64(pos - sizeof(struct trie_header_f));
404
405 /* write string buffer */
406 fwrite(trie->strings->buf, trie->strings->len, 1, t.f);
407 h.strings_len = htole64(trie->strings->len);
408
409 /* write header */
410 size = ftello(t.f);
411 h.file_size = htole64(size);
412 if (fseeko(t.f, 0, SEEK_SET) < 0)
413 goto error_fclose;
414 fwrite(&h, sizeof(struct trie_header_f), 1, t.f);
415
416 if (ferror(t.f))
417 goto error_fclose;
418 if (fflush(t.f) < 0)
419 goto error_fclose;
420 if (fsync(fileno(t.f)) < 0)
421 goto error_fclose;
422 if (rename(filename_tmp, filename) < 0)
423 goto error_fclose;
424
425 /* write succeeded */
426 fclose(t.f);
427
428 log_debug("=== trie on-disk ===");
429 log_debug("size: %8"PRIi64" bytes", size);
430 log_debug("header: %8zu bytes", sizeof(struct trie_header_f));
431 log_debug("nodes: %8"PRIu64" bytes (%8"PRIu64")",
432 t.nodes_count * sizeof(struct trie_node_f), t.nodes_count);
433 log_debug("child pointers: %8"PRIu64" bytes (%8"PRIu64")",
434 t.children_count * sizeof(struct trie_child_entry_f), t.children_count);
435 log_debug("value pointers: %8"PRIu64" bytes (%8"PRIu64")",
436 t.values_count * sizeof(struct trie_value_entry2_f), t.values_count);
437 log_debug("string store: %8zu bytes", trie->strings->len);
438 log_debug("strings start: %8"PRIu64, t.strings_off);
439 return 0;
440
441 error_fclose:
442 r = -errno;
443 fclose(t.f);
444 unlink(filename_tmp);
445 return r;
446 }
447
448 static int insert_data(struct trie *trie, char **match_list, char *line,
449 const char *filename, uint16_t file_priority, uint32_t line_number) {
450 char *value, **entry;
451
452 assert(line[0] == ' ');
453
454 value = strchr(line, '=');
455 if (!value)
456 return log_syntax(NULL, LOG_WARNING, filename, line_number, EINVAL,
457 "Key-value pair expected but got \"%s\", ignoring", line);
458
459 value[0] = '\0';
460 value++;
461
462 /* Replace multiple leading spaces by a single space */
463 while (isblank(line[0]) && isblank(line[1]))
464 line++;
465
466 if (isempty(line + 1) || isempty(value))
467 return log_syntax(NULL, LOG_WARNING, filename, line_number, EINVAL,
468 "Empty %s in \"%s=%s\", ignoring",
469 isempty(line + 1) ? "key" : "value",
470 line, value);
471
472 STRV_FOREACH(entry, match_list)
473 trie_insert(trie, trie->root, *entry, line, value, filename, file_priority, line_number);
474
475 return 0;
476 }
477
478 static int import_file(struct trie *trie, const char *filename, uint16_t file_priority) {
479 enum {
480 HW_NONE,
481 HW_MATCH,
482 HW_DATA,
483 } state = HW_NONE;
484 _cleanup_fclose_ FILE *f = NULL;
485 char line[LINE_MAX];
486 _cleanup_strv_free_ char **match_list = NULL;
487 uint32_t line_number = 0;
488 char *match = NULL;
489 int r = 0, err;
490
491 f = fopen(filename, "re");
492 if (!f)
493 return -errno;
494
495 while (fgets(line, sizeof(line), f)) {
496 size_t len;
497 char *pos;
498
499 ++line_number;
500
501 /* comment line */
502 if (line[0] == '#')
503 continue;
504
505 /* strip trailing comment */
506 pos = strchr(line, '#');
507 if (pos)
508 pos[0] = '\0';
509
510 /* strip trailing whitespace */
511 len = strlen(line);
512 while (len > 0 && isspace(line[len-1]))
513 len--;
514 line[len] = '\0';
515
516 switch (state) {
517 case HW_NONE:
518 if (len == 0)
519 break;
520
521 if (line[0] == ' ') {
522 log_syntax(NULL, LOG_WARNING, filename, line_number, EINVAL,
523 "Match expected but got indented property \"%s\", ignoring line", line);
524 r = -EINVAL;
525 break;
526 }
527
528 /* start of record, first match */
529 state = HW_MATCH;
530
531 match = strdup(line);
532 if (!match)
533 return -ENOMEM;
534
535 err = strv_consume(&match_list, match);
536 if (err < 0)
537 return err;
538
539 break;
540
541 case HW_MATCH:
542 if (len == 0) {
543 log_syntax(NULL, LOG_WARNING, filename, line_number, EINVAL,
544 "Property expected, ignoring record with no properties");
545 r = -EINVAL;
546 state = HW_NONE;
547 strv_clear(match_list);
548 break;
549 }
550
551 if (line[0] != ' ') {
552 /* another match */
553 match = strdup(line);
554 if (!match)
555 return -ENOMEM;
556
557 err = strv_consume(&match_list, match);
558 if (err < 0)
559 return err;
560
561 break;
562 }
563
564 /* first data */
565 state = HW_DATA;
566 err = insert_data(trie, match_list, line, filename, file_priority, line_number);
567 if (err < 0)
568 r = err;
569 break;
570
571 case HW_DATA:
572 if (len == 0) {
573 /* end of record */
574 state = HW_NONE;
575 strv_clear(match_list);
576 break;
577 }
578
579 if (line[0] != ' ') {
580 log_syntax(NULL, LOG_WARNING, filename, line_number, EINVAL,
581 "Property or empty line expected, got \"%s\", ignoring record", line);
582 r = -EINVAL;
583 state = HW_NONE;
584 strv_clear(match_list);
585 break;
586 }
587
588 err = insert_data(trie, match_list, line, filename, file_priority, line_number);
589 if (err < 0)
590 r = err;
591 break;
592 };
593 }
594
595 if (state == HW_MATCH)
596 log_syntax(NULL, LOG_WARNING, filename, line_number, EINVAL,
597 "Property expected, ignoring record with no properties");
598
599 return r;
600 }
601
602 static int hwdb_query(int argc, char *argv[], void *userdata) {
603 _cleanup_(sd_hwdb_unrefp) sd_hwdb *hwdb = NULL;
604 const char *key, *value;
605 const char *modalias;
606 int r;
607
608 assert(argc >= 2);
609 assert(argv);
610
611 modalias = argv[1];
612
613 r = sd_hwdb_new(&hwdb);
614 if (r < 0)
615 return r;
616
617 SD_HWDB_FOREACH_PROPERTY(hwdb, modalias, key, value)
618 printf("%s=%s\n", key, value);
619
620 return 0;
621 }
622
623 static int hwdb_update(int argc, char *argv[], void *userdata) {
624 _cleanup_free_ char *hwdb_bin = NULL;
625 _cleanup_(trie_freep) struct trie *trie = NULL;
626 _cleanup_strv_free_ char **files = NULL;
627 char **f;
628 uint16_t file_priority = 1;
629 int r = 0, err;
630
631 trie = new0(struct trie, 1);
632 if (!trie)
633 return -ENOMEM;
634
635 /* string store */
636 trie->strings = strbuf_new();
637 if (!trie->strings)
638 return -ENOMEM;
639
640 /* index */
641 trie->root = new0(struct trie_node, 1);
642 if (!trie->root)
643 return -ENOMEM;
644
645 trie->nodes_count++;
646
647 err = conf_files_list_strv(&files, ".hwdb", arg_root, 0, conf_file_dirs);
648 if (err < 0)
649 return log_error_errno(err, "Failed to enumerate hwdb files: %m");
650
651 STRV_FOREACH(f, files) {
652 log_debug("Reading file \"%s\"", *f);
653 err = import_file(trie, *f, file_priority++);
654 if (err < 0 && arg_strict)
655 r = err;
656 }
657
658 strbuf_complete(trie->strings);
659
660 log_debug("=== trie in-memory ===");
661 log_debug("nodes: %8zu bytes (%8zu)",
662 trie->nodes_count * sizeof(struct trie_node), trie->nodes_count);
663 log_debug("children arrays: %8zu bytes (%8zu)",
664 trie->children_count * sizeof(struct trie_child_entry), trie->children_count);
665 log_debug("values arrays: %8zu bytes (%8zu)",
666 trie->values_count * sizeof(struct trie_value_entry), trie->values_count);
667 log_debug("strings: %8zu bytes",
668 trie->strings->len);
669 log_debug("strings incoming: %8zu bytes (%8zu)",
670 trie->strings->in_len, trie->strings->in_count);
671 log_debug("strings dedup'ed: %8zu bytes (%8zu)",
672 trie->strings->dedup_len, trie->strings->dedup_count);
673
674 hwdb_bin = path_join(arg_root, arg_hwdb_bin_dir, "hwdb.bin");
675 if (!hwdb_bin)
676 return -ENOMEM;
677
678 mkdir_parents_label(hwdb_bin, 0755);
679 err = trie_store(trie, hwdb_bin);
680 if (err < 0)
681 return log_error_errno(err, "Failure writing database %s: %m", hwdb_bin);
682
683 err = label_fix(hwdb_bin, 0);
684 if (err < 0)
685 return err;
686
687 return r;
688 }
689
690 static int help(void) {
691 _cleanup_free_ char *link = NULL;
692 int r;
693
694 r = terminal_urlify_man("systemd-hwdb", "8", &link);
695 if (r < 0)
696 return log_oom();
697
698 printf("%s OPTIONS COMMAND\n\n"
699 "Update or query the hardware database.\n\n"
700 " -h --help Show this help\n"
701 " --version Show package version\n"
702 " -s --strict When updating, return non-zero exit value on any parsing error\n"
703 " --usr Generate in " UDEVLIBEXECDIR " instead of /etc/udev\n"
704 " -r --root=PATH Alternative root path in the filesystem\n\n"
705 "Commands:\n"
706 " update Update the hwdb database\n"
707 " query MODALIAS Query database and print result\n"
708 "\nSee the %s for details.\n"
709 , program_invocation_short_name
710 , link
711 );
712
713 return 0;
714 }
715
716 static int parse_argv(int argc, char *argv[]) {
717 enum {
718 ARG_VERSION = 0x100,
719 ARG_USR,
720 };
721
722 static const struct option options[] = {
723 { "help", no_argument, NULL, 'h' },
724 { "version", no_argument, NULL, ARG_VERSION },
725 { "usr", no_argument, NULL, ARG_USR },
726 { "strict", no_argument, NULL, 's' },
727 { "root", required_argument, NULL, 'r' },
728 {}
729 };
730
731 int c;
732
733 assert(argc >= 0);
734 assert(argv);
735
736 while ((c = getopt_long(argc, argv, "ust:r:h", options, NULL)) >= 0) {
737 switch(c) {
738
739 case 'h':
740 return help();
741
742 case ARG_VERSION:
743 return version();
744
745 case ARG_USR:
746 arg_hwdb_bin_dir = UDEVLIBEXECDIR;
747 break;
748
749 case 's':
750 arg_strict = true;
751 break;
752
753 case 'r':
754 arg_root = optarg;
755 break;
756
757 case '?':
758 return -EINVAL;
759
760 default:
761 assert_not_reached("Unknown option");
762 }
763 }
764
765 return 1;
766 }
767
768 static int hwdb_main(int argc, char *argv[]) {
769 static const Verb verbs[] = {
770 { "update", 1, 1, 0, hwdb_update },
771 { "query", 2, 2, 0, hwdb_query },
772 {},
773 };
774
775 return dispatch_verb(argc, argv, verbs, NULL);
776 }
777
778 int main (int argc, char *argv[]) {
779 int r;
780
781 log_parse_environment();
782 log_open();
783
784 r = parse_argv(argc, argv);
785 if (r <= 0)
786 goto finish;
787
788 mac_selinux_init();
789
790 r = hwdb_main(argc, argv);
791
792 finish:
793 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
794 }