]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/libsystemd/sd-hwdb/hwdb-util.c
Merge pull request #11827 from keszybz/pkgconfig-variables
[thirdparty/systemd.git] / src / libsystemd / sd-hwdb / hwdb-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <ctype.h>
4 #include <stdio.h>
5
6 #include "alloc-util.h"
7 #include "conf-files.h"
8 #include "fd-util.h"
9 #include "fileio.h"
10 #include "fs-util.h"
11 #include "hwdb-internal.h"
12 #include "hwdb-util.h"
13 #include "label.h"
14 #include "mkdir.h"
15 #include "path-util.h"
16 #include "strbuf.h"
17 #include "string-util.h"
18 #include "strv.h"
19 #include "tmpfile-util.h"
20
21 static const char *default_hwdb_bin_dir = "/etc/udev";
22 static const char * const conf_file_dirs[] = {
23 "/etc/udev/hwdb.d",
24 UDEVLIBEXECDIR "/hwdb.d",
25 NULL
26 };
27
28 /*
29 * Generic udev properties, key-value database based on modalias strings.
30 * Uses a Patricia/radix trie to index all matches for efficient lookup.
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 size_t filename_off;
67 uint32_t line_number;
68 uint16_t file_priority;
69 };
70
71 static int trie_children_cmp(const struct trie_child_entry *a, const struct trie_child_entry *b) {
72 return CMP(a->c, b->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 typesafe_qsort(node->children, node->children_count, 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 = typesafe_bsearch(&search, node->children, node->children_count, trie_children_cmp);
100 if (child)
101 return child->child;
102 return NULL;
103 }
104
105 static void trie_node_cleanup(struct trie_node *node) {
106 size_t i;
107
108 if (!node)
109 return;
110
111 for (i = 0; i < node->children_count; i++)
112 trie_node_cleanup(node->children[i].child);
113 free(node->children);
114 free(node->values);
115 free(node);
116 }
117
118 static void trie_free(struct trie *trie) {
119 if (!trie)
120 return;
121
122 trie_node_cleanup(trie->root);
123 strbuf_cleanup(trie->strings);
124 free(trie);
125 }
126
127 DEFINE_TRIVIAL_CLEANUP_FUNC(struct trie*, trie_free);
128
129 static int trie_values_cmp(const struct trie_value_entry *a, const struct trie_value_entry *b, struct trie *trie) {
130 return strcmp(trie->strings->buf + a->key_off,
131 trie->strings->buf + b->key_off);
132 }
133
134 static int trie_node_add_value(struct trie *trie, struct trie_node *node,
135 const char *key, const char *value,
136 const char *filename, uint16_t file_priority, uint32_t line_number, bool compat) {
137 ssize_t k, v, fn = 0;
138 struct trie_value_entry *val;
139
140 k = strbuf_add_string(trie->strings, key, strlen(key));
141 if (k < 0)
142 return k;
143 v = strbuf_add_string(trie->strings, value, strlen(value));
144 if (v < 0)
145 return v;
146
147 if (!compat) {
148 fn = strbuf_add_string(trie->strings, filename, strlen(filename));
149 if (fn < 0)
150 return fn;
151 }
152
153 if (node->values_count) {
154 struct trie_value_entry search = {
155 .key_off = k,
156 .value_off = v,
157 };
158
159 val = typesafe_bsearch_r(&search, node->values, node->values_count, trie_values_cmp, trie);
160 if (val) {
161 /* At this point we have 2 identical properties on the same match-string.
162 * Since we process files in order, we just replace the previous value. */
163 val->value_off = v;
164 val->filename_off = fn;
165 val->file_priority = file_priority;
166 val->line_number = line_number;
167 return 0;
168 }
169 }
170
171 /* extend array, add new entry, sort for bisection */
172 val = reallocarray(node->values, node->values_count + 1, sizeof(struct trie_value_entry));
173 if (!val)
174 return -ENOMEM;
175 trie->values_count++;
176 node->values = val;
177 node->values[node->values_count] = (struct trie_value_entry) {
178 .key_off = k,
179 .value_off = v,
180 .filename_off = fn,
181 .file_priority = file_priority,
182 .line_number = line_number,
183 };
184 node->values_count++;
185 typesafe_qsort_r(node->values, node->values_count, trie_values_cmp, trie);
186 return 0;
187 }
188
189 static int trie_insert(struct trie *trie, struct trie_node *node, const char *search,
190 const char *key, const char *value,
191 const char *filename, uint16_t file_priority, uint32_t line_number, bool compat) {
192 size_t i = 0;
193 int r = 0;
194
195 for (;;) {
196 size_t p;
197 uint8_t c;
198 struct trie_node *child;
199
200 for (p = 0; (c = trie->strings->buf[node->prefix_off + p]); p++) {
201 _cleanup_free_ struct trie_node *new_child = NULL;
202 _cleanup_free_ char *s = NULL;
203 ssize_t off;
204
205 if (c == search[i + p])
206 continue;
207
208 /* split node */
209 new_child = new(struct trie_node, 1);
210 if (!new_child)
211 return -ENOMEM;
212
213 /* move values from parent to child */
214 *new_child = (struct trie_node) {
215 .prefix_off = node->prefix_off + p+1,
216 .children = node->children,
217 .children_count = node->children_count,
218 .values = node->values,
219 .values_count = node->values_count,
220 };
221
222 /* update parent; use strdup() because the source gets realloc()d */
223 s = strndup(trie->strings->buf + node->prefix_off, p);
224 if (!s)
225 return -ENOMEM;
226
227 off = strbuf_add_string(trie->strings, s, p);
228 if (off < 0)
229 return off;
230
231 *node = (struct trie_node) {
232 .prefix_off = off,
233 };
234 r = node_add_child(trie, node, new_child, c);
235 if (r < 0)
236 return r;
237
238 new_child = NULL; /* avoid cleanup */
239 break;
240 }
241 i += p;
242
243 c = search[i];
244 if (c == '\0')
245 return trie_node_add_value(trie, node, key, value, filename, file_priority, line_number, compat);
246
247 child = node_lookup(node, c);
248 if (!child) {
249 _cleanup_free_ struct trie_node *new_child = NULL;
250 ssize_t off;
251
252 /* new child */
253 new_child = new(struct trie_node, 1);
254 if (!new_child)
255 return -ENOMEM;
256
257 off = strbuf_add_string(trie->strings, search + i+1, strlen(search + i+1));
258 if (off < 0)
259 return off;
260
261 *new_child = (struct trie_node) {
262 .prefix_off = off,
263 };
264
265 r = node_add_child(trie, node, new_child, c);
266 if (r < 0)
267 return r;
268
269 child = TAKE_PTR(new_child);
270 return trie_node_add_value(trie, child, key, value, filename, file_priority, line_number, compat);
271 }
272
273 node = child;
274 i++;
275 }
276 }
277
278 struct trie_f {
279 FILE *f;
280 struct trie *trie;
281 uint64_t strings_off;
282
283 uint64_t nodes_count;
284 uint64_t children_count;
285 uint64_t values_count;
286 };
287
288 /* calculate the storage space for the nodes, children arrays, value arrays */
289 static void trie_store_nodes_size(struct trie_f *trie, struct trie_node *node, bool compat) {
290 uint64_t i;
291
292 for (i = 0; i < node->children_count; i++)
293 trie_store_nodes_size(trie, node->children[i].child, compat);
294
295 trie->strings_off += sizeof(struct trie_node_f);
296 for (i = 0; i < node->children_count; i++)
297 trie->strings_off += sizeof(struct trie_child_entry_f);
298 for (i = 0; i < node->values_count; i++)
299 trie->strings_off += compat ? sizeof(struct trie_value_entry_f) : sizeof(struct trie_value_entry2_f);
300 }
301
302 static int64_t trie_store_nodes(struct trie_f *trie, struct trie_node *node, bool compat) {
303 uint64_t i;
304 struct trie_node_f n = {
305 .prefix_off = htole64(trie->strings_off + node->prefix_off),
306 .children_count = node->children_count,
307 .values_count = htole64(node->values_count),
308 };
309 _cleanup_free_ struct trie_child_entry_f *children = NULL;
310 int64_t node_off;
311
312 if (node->children_count) {
313 children = new(struct trie_child_entry_f, node->children_count);
314 if (!children)
315 return -ENOMEM;
316 }
317
318 /* post-order recursion */
319 for (i = 0; i < node->children_count; i++) {
320 int64_t child_off;
321
322 child_off = trie_store_nodes(trie, node->children[i].child, compat);
323 if (child_off < 0)
324 return child_off;
325
326 children[i] = (struct trie_child_entry_f) {
327 .c = node->children[i].c,
328 .child_off = htole64(child_off),
329 };
330 }
331
332 /* write node */
333 node_off = ftello(trie->f);
334 fwrite(&n, sizeof(struct trie_node_f), 1, trie->f);
335 trie->nodes_count++;
336
337 /* append children array */
338 if (node->children_count) {
339 fwrite(children, sizeof(struct trie_child_entry_f), node->children_count, trie->f);
340 trie->children_count += node->children_count;
341 }
342
343 /* append values array */
344 for (i = 0; i < node->values_count; i++) {
345 struct trie_value_entry2_f v = {
346 .key_off = htole64(trie->strings_off + node->values[i].key_off),
347 .value_off = htole64(trie->strings_off + node->values[i].value_off),
348 .filename_off = htole64(trie->strings_off + node->values[i].filename_off),
349 .line_number = htole32(node->values[i].line_number),
350 .file_priority = htole16(node->values[i].file_priority),
351 };
352
353 fwrite(&v, compat ? sizeof(struct trie_value_entry_f) : sizeof(struct trie_value_entry2_f), 1, trie->f);
354 }
355 trie->values_count += node->values_count;
356
357 return node_off;
358 }
359
360 static int trie_store(struct trie *trie, const char *filename, bool compat) {
361 struct trie_f t = {
362 .trie = trie,
363 };
364 _cleanup_free_ char *filename_tmp = NULL;
365 int64_t pos;
366 int64_t root_off;
367 int64_t size;
368 struct trie_header_f h = {
369 .signature = HWDB_SIG,
370 .tool_version = htole64(PROJECT_VERSION),
371 .header_size = htole64(sizeof(struct trie_header_f)),
372 .node_size = htole64(sizeof(struct trie_node_f)),
373 .child_entry_size = htole64(sizeof(struct trie_child_entry_f)),
374 .value_entry_size = htole64(compat ? sizeof(struct trie_value_entry_f) : sizeof(struct trie_value_entry2_f)),
375 };
376 int r;
377
378 /* calculate size of header, nodes, children entries, value entries */
379 t.strings_off = sizeof(struct trie_header_f);
380 trie_store_nodes_size(&t, trie->root, compat);
381
382 r = fopen_temporary(filename, &t.f, &filename_tmp);
383 if (r < 0)
384 return r;
385 fchmod(fileno(t.f), 0444);
386
387 /* write nodes */
388 if (fseeko(t.f, sizeof(struct trie_header_f), SEEK_SET) < 0)
389 goto error_fclose;
390
391 root_off = trie_store_nodes(&t, trie->root, compat);
392 h.nodes_root_off = htole64(root_off);
393 pos = ftello(t.f);
394 h.nodes_len = htole64(pos - sizeof(struct trie_header_f));
395
396 /* write string buffer */
397 fwrite(trie->strings->buf, trie->strings->len, 1, t.f);
398 h.strings_len = htole64(trie->strings->len);
399
400 /* write header */
401 size = ftello(t.f);
402 h.file_size = htole64(size);
403 if (fseeko(t.f, 0, SEEK_SET) < 0)
404 goto error_fclose;
405 fwrite(&h, sizeof(struct trie_header_f), 1, t.f);
406
407 if (ferror(t.f))
408 goto error_fclose;
409 if (fflush(t.f) < 0)
410 goto error_fclose;
411 if (fsync(fileno(t.f)) < 0)
412 goto error_fclose;
413 if (rename(filename_tmp, filename) < 0)
414 goto error_fclose;
415
416 /* write succeeded */
417 fclose(t.f);
418
419 log_debug("=== trie on-disk ===");
420 log_debug("size: %8"PRIi64" bytes", size);
421 log_debug("header: %8zu bytes", sizeof(struct trie_header_f));
422 log_debug("nodes: %8"PRIu64" bytes (%8"PRIu64")",
423 t.nodes_count * sizeof(struct trie_node_f), t.nodes_count);
424 log_debug("child pointers: %8"PRIu64" bytes (%8"PRIu64")",
425 t.children_count * sizeof(struct trie_child_entry_f), t.children_count);
426 log_debug("value pointers: %8"PRIu64" bytes (%8"PRIu64")",
427 t.values_count * (compat ? sizeof(struct trie_value_entry_f) : sizeof(struct trie_value_entry2_f)), t.values_count);
428 log_debug("string store: %8zu bytes", trie->strings->len);
429 log_debug("strings start: %8"PRIu64, t.strings_off);
430 return 0;
431
432 error_fclose:
433 r = -errno;
434 fclose(t.f);
435 unlink(filename_tmp);
436 return r;
437 }
438
439 static int insert_data(struct trie *trie, char **match_list, char *line, const char *filename,
440 uint16_t file_priority, uint32_t line_number, bool compat) {
441 char *value, **entry;
442
443 assert(line[0] == ' ');
444
445 value = strchr(line, '=');
446 if (!value)
447 return log_syntax(NULL, LOG_WARNING, filename, line_number, EINVAL,
448 "Key-value pair expected but got \"%s\", ignoring", line);
449
450 value[0] = '\0';
451 value++;
452
453 /* Replace multiple leading spaces by a single space */
454 while (isblank(line[0]) && isblank(line[1]))
455 line++;
456
457 if (isempty(line + 1) || isempty(value))
458 return log_syntax(NULL, LOG_WARNING, filename, line_number, EINVAL,
459 "Empty %s in \"%s=%s\", ignoring",
460 isempty(line + 1) ? "key" : "value",
461 line, value);
462
463 STRV_FOREACH(entry, match_list)
464 trie_insert(trie, trie->root, *entry, line, value, filename, file_priority, line_number, compat);
465
466 return 0;
467 }
468
469 static int import_file(struct trie *trie, const char *filename, uint16_t file_priority, bool compat) {
470 enum {
471 HW_NONE,
472 HW_MATCH,
473 HW_DATA,
474 } state = HW_NONE;
475 _cleanup_fclose_ FILE *f = NULL;
476 _cleanup_strv_free_ char **match_list = NULL;
477 uint32_t line_number = 0;
478 char *match = NULL;
479 int r = 0, err;
480
481 f = fopen(filename, "re");
482 if (!f)
483 return -errno;
484
485 for (;;) {
486 _cleanup_free_ char *line = NULL;
487 size_t len;
488 char *pos;
489
490 r = read_line(f, LONG_LINE_MAX, &line);
491 if (r < 0)
492 return r;
493 if (r == 0)
494 break;
495
496 ++line_number;
497
498 /* comment line */
499 if (line[0] == '#')
500 continue;
501
502 /* strip trailing comment */
503 pos = strchr(line, '#');
504 if (pos)
505 pos[0] = '\0';
506
507 /* strip trailing whitespace */
508 len = strlen(line);
509 while (len > 0 && isspace(line[len-1]))
510 len--;
511 line[len] = '\0';
512
513 switch (state) {
514 case HW_NONE:
515 if (len == 0)
516 break;
517
518 if (line[0] == ' ') {
519 log_syntax(NULL, LOG_WARNING, filename, line_number, EINVAL,
520 "Match expected but got indented property \"%s\", ignoring line", line);
521 r = -EINVAL;
522 break;
523 }
524
525 /* start of record, first match */
526 state = HW_MATCH;
527
528 match = strdup(line);
529 if (!match)
530 return -ENOMEM;
531
532 err = strv_consume(&match_list, match);
533 if (err < 0)
534 return err;
535
536 break;
537
538 case HW_MATCH:
539 if (len == 0) {
540 log_syntax(NULL, LOG_WARNING, filename, line_number, EINVAL,
541 "Property expected, ignoring record with no properties");
542 r = -EINVAL;
543 state = HW_NONE;
544 strv_clear(match_list);
545 break;
546 }
547
548 if (line[0] != ' ') {
549 /* another match */
550 match = strdup(line);
551 if (!match)
552 return -ENOMEM;
553
554 err = strv_consume(&match_list, match);
555 if (err < 0)
556 return err;
557
558 break;
559 }
560
561 /* first data */
562 state = HW_DATA;
563 err = insert_data(trie, match_list, line, filename, file_priority, line_number, compat);
564 if (err < 0)
565 r = err;
566 break;
567
568 case HW_DATA:
569 if (len == 0) {
570 /* end of record */
571 state = HW_NONE;
572 strv_clear(match_list);
573 break;
574 }
575
576 if (line[0] != ' ') {
577 log_syntax(NULL, LOG_WARNING, filename, line_number, EINVAL,
578 "Property or empty line expected, got \"%s\", ignoring record", line);
579 r = -EINVAL;
580 state = HW_NONE;
581 strv_clear(match_list);
582 break;
583 }
584
585 err = insert_data(trie, match_list, line, filename, file_priority, line_number, compat);
586 if (err < 0)
587 r = err;
588 break;
589 };
590 }
591
592 if (state == HW_MATCH)
593 log_syntax(NULL, LOG_WARNING, filename, line_number, EINVAL,
594 "Property expected, ignoring record with no properties");
595
596 return r;
597 }
598
599 int hwdb_update(const char *root, const char *hwdb_bin_dir, bool strict, bool compat) {
600 _cleanup_free_ char *hwdb_bin = NULL;
601 _cleanup_(trie_freep) struct trie *trie = NULL;
602 _cleanup_strv_free_ char **files = NULL;
603 char **f;
604 uint16_t file_priority = 1;
605 int r = 0, err;
606
607 /* The argument 'compat' controls the format version of database. If false, then hwdb.bin will be created with
608 * additional information such that priority, line number, and filename of database source. If true, then hwdb.bin
609 * will be created without the information. systemd-hwdb command should set the argument false, and 'udevadm hwdb'
610 * command should set it true. */
611
612 trie = new0(struct trie, 1);
613 if (!trie)
614 return -ENOMEM;
615
616 /* string store */
617 trie->strings = strbuf_new();
618 if (!trie->strings)
619 return -ENOMEM;
620
621 /* index */
622 trie->root = new0(struct trie_node, 1);
623 if (!trie->root)
624 return -ENOMEM;
625
626 trie->nodes_count++;
627
628 err = conf_files_list_strv(&files, ".hwdb", root, 0, conf_file_dirs);
629 if (err < 0)
630 return log_error_errno(err, "Failed to enumerate hwdb files: %m");
631
632 STRV_FOREACH(f, files) {
633 log_debug("Reading file \"%s\"", *f);
634 err = import_file(trie, *f, file_priority++, compat);
635 if (err < 0 && strict)
636 r = err;
637 }
638
639 strbuf_complete(trie->strings);
640
641 log_debug("=== trie in-memory ===");
642 log_debug("nodes: %8zu bytes (%8zu)",
643 trie->nodes_count * sizeof(struct trie_node), trie->nodes_count);
644 log_debug("children arrays: %8zu bytes (%8zu)",
645 trie->children_count * sizeof(struct trie_child_entry), trie->children_count);
646 log_debug("values arrays: %8zu bytes (%8zu)",
647 trie->values_count * sizeof(struct trie_value_entry), trie->values_count);
648 log_debug("strings: %8zu bytes",
649 trie->strings->len);
650 log_debug("strings incoming: %8zu bytes (%8zu)",
651 trie->strings->in_len, trie->strings->in_count);
652 log_debug("strings dedup'ed: %8zu bytes (%8zu)",
653 trie->strings->dedup_len, trie->strings->dedup_count);
654
655 hwdb_bin = path_join(root, hwdb_bin_dir ?: default_hwdb_bin_dir, "hwdb.bin");
656 if (!hwdb_bin)
657 return -ENOMEM;
658
659 mkdir_parents_label(hwdb_bin, 0755);
660 err = trie_store(trie, hwdb_bin, compat);
661 if (err < 0)
662 return log_error_errno(err, "Failed to write database %s: %m", hwdb_bin);
663
664 err = label_fix(hwdb_bin, 0);
665 if (err < 0)
666 return err;
667
668 return r;
669 }
670
671 int hwdb_query(const char *modalias) {
672 _cleanup_(sd_hwdb_unrefp) sd_hwdb *hwdb = NULL;
673 const char *key, *value;
674 int r;
675
676 assert(modalias);
677
678 r = sd_hwdb_new(&hwdb);
679 if (r < 0)
680 return r;
681
682 SD_HWDB_FOREACH_PROPERTY(hwdb, modalias, key, value)
683 printf("%s=%s\n", key, value);
684
685 return 0;
686 }