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