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