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