]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/hwdb-util.c
Merge pull request #28014 from bluca/portable_fixes
[thirdparty/systemd.git] / src / shared / hwdb-util.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <ctype.h>
4 #include <stdio.h>
5 #include <sys/stat.h>
6
7 #include "alloc-util.h"
8 #include "conf-files.h"
9 #include "fd-util.h"
10 #include "fileio.h"
11 #include "fs-util.h"
12 #include "hwdb-internal.h"
13 #include "hwdb-util.h"
14 #include "label-util.h"
15 #include "mkdir-label.h"
16 #include "nulstr-util.h"
17 #include "path-util.h"
18 #include "sort-util.h"
19 #include "strbuf.h"
20 #include "string-util.h"
21 #include "strv.h"
22 #include "tmpfile-util.h"
23
24 static const char* const conf_file_dirs[] = {
25 "/etc/udev/hwdb.d",
26 UDEVLIBEXECDIR "/hwdb.d",
27 NULL
28 };
29
30 /*
31 * Generic udev properties, key-value database based on modalias strings.
32 * Uses a Patricia/radix trie to index all matches for efficient lookup.
33 */
34
35 /* in-memory trie objects */
36 struct trie {
37 struct trie_node *root;
38 struct strbuf *strings;
39
40 size_t nodes_count;
41 size_t children_count;
42 size_t values_count;
43 };
44
45 struct trie_node {
46 /* prefix, common part for all children of this node */
47 size_t prefix_off;
48
49 /* sorted array of pointers to children nodes */
50 struct trie_child_entry *children;
51 uint8_t children_count;
52
53 /* sorted array of key-value pairs */
54 struct trie_value_entry *values;
55 size_t values_count;
56 };
57
58 /* children array item with char (0-255) index */
59 struct trie_child_entry {
60 uint8_t c;
61 struct trie_node *child;
62 };
63
64 /* value array item with key-value pairs */
65 struct trie_value_entry {
66 size_t key_off;
67 size_t value_off;
68 size_t filename_off;
69 uint32_t line_number;
70 uint16_t file_priority;
71 };
72
73 static int trie_children_cmp(const struct trie_child_entry *a, const struct trie_child_entry *b) {
74 return CMP(a->c, b->c);
75 }
76
77 static int node_add_child(struct trie *trie, struct trie_node *node, struct trie_node *node_child, uint8_t c) {
78 struct trie_child_entry *child;
79
80 /* extend array, add new entry, sort for bisection */
81 child = reallocarray(node->children, node->children_count + 1, sizeof(struct trie_child_entry));
82 if (!child)
83 return -ENOMEM;
84
85 node->children = child;
86 trie->children_count++;
87 node->children[node->children_count].c = c;
88 node->children[node->children_count].child = node_child;
89 node->children_count++;
90 typesafe_qsort(node->children, node->children_count, trie_children_cmp);
91 trie->nodes_count++;
92
93 return 0;
94 }
95
96 static struct trie_node *node_lookup(const struct trie_node *node, uint8_t c) {
97 struct trie_child_entry *child;
98 struct trie_child_entry search;
99
100 search.c = c;
101 child = typesafe_bsearch(&search, node->children, node->children_count, 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 if (!node)
109 return;
110
111 for (size_t 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 struct trie* trie_free(struct trie *trie) {
119 if (!trie)
120 return NULL;
121
122 trie_node_cleanup(trie->root);
123 strbuf_free(trie->strings);
124 return mfree(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 int r = 0;
193
194 for (size_t i = 0;; i++) {
195 size_t p;
196 uint8_t c;
197 struct trie_node *child;
198
199 for (p = 0; (c = trie->strings->buf[node->prefix_off + p]); p++) {
200 _cleanup_free_ struct trie_node *new_child = NULL;
201 _cleanup_free_ char *s = NULL;
202 ssize_t off;
203
204 if (c == search[i + p])
205 continue;
206
207 /* split node */
208 new_child = new(struct trie_node, 1);
209 if (!new_child)
210 return -ENOMEM;
211
212 /* move values from parent to child */
213 *new_child = (struct trie_node) {
214 .prefix_off = node->prefix_off + p+1,
215 .children = node->children,
216 .children_count = node->children_count,
217 .values = node->values,
218 .values_count = node->values_count,
219 };
220
221 /* update parent; use strdup() because the source gets realloc()d */
222 s = strndup(trie->strings->buf + node->prefix_off, p);
223 if (!s)
224 return -ENOMEM;
225
226 off = strbuf_add_string(trie->strings, s, p);
227 if (off < 0)
228 return off;
229
230 *node = (struct trie_node) {
231 .prefix_off = off,
232 };
233 r = node_add_child(trie, node, new_child, c);
234 if (r < 0)
235 return r;
236
237 new_child = NULL; /* avoid cleanup */
238 break;
239 }
240 i += p;
241
242 c = search[i];
243 if (c == '\0')
244 return trie_node_add_value(trie, node, key, value, filename, file_priority, line_number, compat);
245
246 child = node_lookup(node, c);
247 if (!child) {
248 _cleanup_free_ struct trie_node *new_child = NULL;
249 ssize_t off;
250
251 /* new child */
252 new_child = new(struct trie_node, 1);
253 if (!new_child)
254 return -ENOMEM;
255
256 off = strbuf_add_string(trie->strings, search + i+1, strlen(search + i+1));
257 if (off < 0)
258 return off;
259
260 *new_child = (struct trie_node) {
261 .prefix_off = off,
262 };
263
264 r = node_add_child(trie, node, new_child, c);
265 if (r < 0)
266 return r;
267
268 child = TAKE_PTR(new_child);
269 return trie_node_add_value(trie, child, key, value, filename, file_priority, line_number, compat);
270 }
271
272 node = child;
273 }
274 }
275
276 struct trie_f {
277 struct trie *trie;
278 uint64_t strings_off;
279
280 uint64_t nodes_count;
281 uint64_t children_count;
282 uint64_t values_count;
283 };
284
285 /* calculate the storage space for the nodes, children arrays, value arrays */
286 static void trie_store_nodes_size(struct trie_f *trie, struct trie_node *node, bool compat) {
287 for (uint64_t i = 0; i < node->children_count; i++)
288 trie_store_nodes_size(trie, node->children[i].child, compat);
289
290 trie->strings_off += sizeof(struct trie_node_f);
291 for (uint64_t i = 0; i < node->children_count; i++)
292 trie->strings_off += sizeof(struct trie_child_entry_f);
293 for (uint64_t i = 0; i < node->values_count; i++)
294 trie->strings_off += compat ? sizeof(struct trie_value_entry_f) : sizeof(struct trie_value_entry2_f);
295 }
296
297 static int64_t trie_store_nodes(struct trie_f *trie, FILE *f, struct trie_node *node, bool compat) {
298 _cleanup_free_ struct trie_child_entry_f *children = NULL;
299 int64_t node_off;
300
301 assert(trie);
302 assert(f);
303 assert(node);
304
305 if (node->children_count) {
306 children = new(struct trie_child_entry_f, node->children_count);
307 if (!children)
308 return -ENOMEM;
309 }
310
311 /* post-order recursion */
312 for (uint64_t i = 0; i < node->children_count; i++) {
313 int64_t child_off;
314
315 child_off = trie_store_nodes(trie, f, node->children[i].child, compat);
316 if (child_off < 0)
317 return child_off;
318
319 children[i] = (struct trie_child_entry_f) {
320 .c = node->children[i].c,
321 .child_off = htole64(child_off),
322 };
323 }
324
325 struct trie_node_f n = {
326 .prefix_off = htole64(trie->strings_off + node->prefix_off),
327 .children_count = node->children_count,
328 .values_count = htole64(node->values_count),
329 };
330
331 /* write node */
332 node_off = ftello(f);
333 fwrite(&n, sizeof(struct trie_node_f), 1, f);
334 trie->nodes_count++;
335
336 /* append children array */
337 if (node->children_count) {
338 fwrite(children, sizeof(struct trie_child_entry_f), node->children_count, f);
339 trie->children_count += node->children_count;
340 }
341
342 /* append values array */
343 for (uint64_t i = 0; i < node->values_count; i++) {
344 struct trie_value_entry2_f v = {
345 .key_off = htole64(trie->strings_off + node->values[i].key_off),
346 .value_off = htole64(trie->strings_off + node->values[i].value_off),
347 .filename_off = htole64(trie->strings_off + node->values[i].filename_off),
348 .line_number = htole32(node->values[i].line_number),
349 .file_priority = htole16(node->values[i].file_priority),
350 };
351
352 fwrite(&v, compat ? sizeof(struct trie_value_entry_f) : sizeof(struct trie_value_entry2_f), 1, f);
353 }
354 trie->values_count += node->values_count;
355
356 return node_off;
357 }
358
359 static int trie_store(struct trie *trie, const char *filename, bool compat) {
360 struct trie_f t = {
361 .trie = trie,
362 .strings_off = sizeof(struct trie_header_f),
363 };
364 _cleanup_(unlink_and_freep) char *filename_tmp = NULL;
365 _cleanup_fclose_ FILE *f = NULL;
366 int64_t pos, root_off, size;
367 int r;
368
369 assert(trie);
370 assert(filename);
371
372 /* calculate size of header, nodes, children entries, value entries */
373 trie_store_nodes_size(&t, trie->root, compat);
374
375 r = fopen_tmpfile_linkable(filename, O_WRONLY|O_CLOEXEC, &filename_tmp, &f);
376 if (r < 0)
377 return r;
378
379 if (fchmod(fileno(f), 0444) < 0)
380 return -errno;
381
382 struct trie_header_f h = {
383 .signature = HWDB_SIG,
384 .tool_version = htole64(PROJECT_VERSION),
385 .header_size = htole64(sizeof(struct trie_header_f)),
386 .node_size = htole64(sizeof(struct trie_node_f)),
387 .child_entry_size = htole64(sizeof(struct trie_child_entry_f)),
388 .value_entry_size = htole64(compat ? sizeof(struct trie_value_entry_f) : sizeof(struct trie_value_entry2_f)),
389 };
390
391 /* write nodes */
392 if (fseeko(f, sizeof(struct trie_header_f), SEEK_SET) < 0)
393 return -errno;
394
395 root_off = trie_store_nodes(&t, f, trie->root, compat);
396 h.nodes_root_off = htole64(root_off);
397 pos = ftello(f);
398 h.nodes_len = htole64(pos - sizeof(struct trie_header_f));
399
400 /* write string buffer */
401 fwrite(trie->strings->buf, trie->strings->len, 1, f);
402 h.strings_len = htole64(trie->strings->len);
403
404 /* write header */
405 size = ftello(f);
406 h.file_size = htole64(size);
407 if (fseeko(f, 0, SEEK_SET) < 0)
408 return -errno;
409 fwrite(&h, sizeof(struct trie_header_f), 1, f);
410
411 r = flink_tmpfile(f, filename_tmp, filename, LINK_TMPFILE_REPLACE|LINK_TMPFILE_SYNC);
412 if (r < 0)
413 return r;
414
415 /* write succeeded */
416
417 log_debug("=== trie on-disk ===");
418 log_debug("size: %8"PRIi64" bytes", size);
419 log_debug("header: %8zu bytes", sizeof(struct trie_header_f));
420 log_debug("nodes: %8"PRIu64" bytes (%8"PRIu64")",
421 t.nodes_count * sizeof(struct trie_node_f), t.nodes_count);
422 log_debug("child pointers: %8"PRIu64" bytes (%8"PRIu64")",
423 t.children_count * sizeof(struct trie_child_entry_f), t.children_count);
424 log_debug("value pointers: %8"PRIu64" bytes (%8"PRIu64")",
425 t.values_count * (compat ? sizeof(struct trie_value_entry_f) : sizeof(struct trie_value_entry2_f)), t.values_count);
426 log_debug("string store: %8zu bytes", trie->strings->len);
427 log_debug("strings start: %8"PRIu64, t.strings_off);
428 return 0;
429 }
430
431 static int insert_data(struct trie *trie, char **match_list, char *line, const char *filename,
432 uint16_t file_priority, uint32_t line_number, bool compat) {
433 char *value;
434
435 assert(line[0] == ' ');
436
437 value = strchr(line, '=');
438 if (!value)
439 return log_syntax(NULL, LOG_WARNING, filename, line_number, SYNTHETIC_ERRNO(EINVAL),
440 "Key-value pair expected but got \"%s\", ignoring.", line);
441
442 value[0] = '\0';
443 value++;
444
445 /* Replace multiple leading spaces by a single space */
446 while (isblank(line[0]) && isblank(line[1]))
447 line++;
448
449 if (isempty(line + 1))
450 return log_syntax(NULL, LOG_WARNING, filename, line_number, SYNTHETIC_ERRNO(EINVAL),
451 "Empty key in \"%s=%s\", ignoring.",
452 line, value);
453
454 STRV_FOREACH(entry, match_list)
455 trie_insert(trie, trie->root, *entry, line, value, filename, file_priority, line_number, compat);
456
457 return 0;
458 }
459
460 static int import_file(struct trie *trie, const char *filename, uint16_t file_priority, bool compat) {
461 enum {
462 HW_NONE,
463 HW_MATCH,
464 HW_DATA,
465 } state = HW_NONE;
466 _cleanup_fclose_ FILE *f = NULL;
467 _cleanup_strv_free_ char **match_list = NULL;
468 uint32_t line_number = 0;
469 int r, err;
470
471 f = fopen(filename, "re");
472 if (!f)
473 return -errno;
474
475 for (;;) {
476 _cleanup_free_ char *line = NULL;
477 size_t len;
478 char *pos;
479
480 r = read_line_full(f, LONG_LINE_MAX, READ_LINE_NOT_A_TTY, &line);
481 if (r < 0)
482 return r;
483 if (r == 0)
484 break;
485
486 line_number ++;
487
488 /* comment line */
489 if (line[0] == '#')
490 continue;
491
492 /* strip trailing comment */
493 pos = strchr(line, '#');
494 if (pos)
495 pos[0] = '\0';
496
497 /* strip trailing whitespace */
498 len = strlen(line);
499 while (len > 0 && isspace(line[len-1]))
500 len--;
501 line[len] = '\0';
502
503 switch (state) {
504 case HW_NONE:
505 if (len == 0)
506 break;
507
508 if (line[0] == ' ') {
509 r = log_syntax(NULL, LOG_WARNING, filename, line_number, SYNTHETIC_ERRNO(EINVAL),
510 "Match expected but got indented property \"%s\", ignoring line.", line);
511 break;
512 }
513
514 /* start of record, first match */
515 state = HW_MATCH;
516
517 err = strv_extend(&match_list, line);
518 if (err < 0)
519 return err;
520
521 break;
522
523 case HW_MATCH:
524 if (len == 0) {
525 r = log_syntax(NULL, LOG_WARNING, filename, line_number, SYNTHETIC_ERRNO(EINVAL),
526 "Property expected, ignoring record with no properties.");
527 state = HW_NONE;
528 match_list = strv_free(match_list);
529 break;
530 }
531
532 if (line[0] != ' ') {
533 /* another match */
534 err = strv_extend(&match_list, line);
535 if (err < 0)
536 return err;
537
538 break;
539 }
540
541 /* first data */
542 state = HW_DATA;
543 err = insert_data(trie, match_list, line, filename, file_priority, line_number, compat);
544 if (err < 0)
545 r = err;
546 break;
547
548 case HW_DATA:
549 if (len == 0) {
550 /* end of record */
551 state = HW_NONE;
552 match_list = strv_free(match_list);
553 break;
554 }
555
556 if (line[0] != ' ') {
557 r = log_syntax(NULL, LOG_WARNING, filename, line_number, SYNTHETIC_ERRNO(EINVAL),
558 "Property or empty line expected, got \"%s\", ignoring record.", line);
559 state = HW_NONE;
560 match_list = strv_free(match_list);
561 break;
562 }
563
564 err = insert_data(trie, match_list, line, filename, file_priority, line_number, compat);
565 if (err < 0)
566 r = err;
567 break;
568 };
569 }
570
571 if (state == HW_MATCH)
572 log_syntax(NULL, LOG_WARNING, filename, line_number, 0,
573 "Property expected, ignoring record with no properties.");
574
575 return r;
576 }
577
578 int hwdb_update(const char *root, const char *hwdb_bin_dir, bool strict, bool compat) {
579 _cleanup_free_ char *hwdb_bin = NULL;
580 _cleanup_(trie_freep) struct trie *trie = NULL;
581 _cleanup_strv_free_ char **files = NULL;
582 uint16_t file_priority = 1;
583 int r = 0, err;
584
585 /* The argument 'compat' controls the format version of database. If false, then hwdb.bin will be
586 * created with additional information such that priority, line number, and filename of database
587 * source. If true, then hwdb.bin will be created without the information. systemd-hwdb command
588 * should set the argument false, and 'udevadm hwdb' command should set it true. */
589
590 trie = new0(struct trie, 1);
591 if (!trie)
592 return -ENOMEM;
593
594 /* string store */
595 trie->strings = strbuf_new();
596 if (!trie->strings)
597 return -ENOMEM;
598
599 /* index */
600 trie->root = new0(struct trie_node, 1);
601 if (!trie->root)
602 return -ENOMEM;
603
604 trie->nodes_count++;
605
606 err = conf_files_list_strv(&files, ".hwdb", root, 0, conf_file_dirs);
607 if (err < 0)
608 return log_error_errno(err, "Failed to enumerate hwdb files: %m");
609
610 STRV_FOREACH(f, files) {
611 log_debug("Reading file \"%s\"", *f);
612 err = import_file(trie, *f, file_priority++, compat);
613 if (err < 0 && strict)
614 r = err;
615 }
616
617 strbuf_complete(trie->strings);
618
619 log_debug("=== trie in-memory ===");
620 log_debug("nodes: %8zu bytes (%8zu)",
621 trie->nodes_count * sizeof(struct trie_node), trie->nodes_count);
622 log_debug("children arrays: %8zu bytes (%8zu)",
623 trie->children_count * sizeof(struct trie_child_entry), trie->children_count);
624 log_debug("values arrays: %8zu bytes (%8zu)",
625 trie->values_count * sizeof(struct trie_value_entry), trie->values_count);
626 log_debug("strings: %8zu bytes",
627 trie->strings->len);
628 log_debug("strings incoming: %8zu bytes (%8zu)",
629 trie->strings->in_len, trie->strings->in_count);
630 log_debug("strings dedup'ed: %8zu bytes (%8zu)",
631 trie->strings->dedup_len, trie->strings->dedup_count);
632
633 hwdb_bin = path_join(root, hwdb_bin_dir ?: "/etc/udev", "hwdb.bin");
634 if (!hwdb_bin)
635 return -ENOMEM;
636
637 (void) mkdir_parents_label(hwdb_bin, 0755);
638 err = trie_store(trie, hwdb_bin, compat);
639 if (err < 0)
640 return log_error_errno(err, "Failed to write database %s: %m", hwdb_bin);
641
642 err = label_fix(hwdb_bin, 0);
643 if (err < 0)
644 return err;
645
646 return r;
647 }
648
649 int hwdb_query(const char *modalias, const char *root) {
650 _cleanup_(sd_hwdb_unrefp) sd_hwdb *hwdb = NULL;
651 const char *key, *value;
652 int r;
653
654 assert(modalias);
655
656 if (!isempty(root))
657 NULSTR_FOREACH(p, hwdb_bin_paths) {
658 _cleanup_free_ char *hwdb_bin = NULL;
659
660 hwdb_bin = path_join(root, p);
661 if (!hwdb_bin)
662 return -ENOMEM;
663
664 r = sd_hwdb_new_from_path(hwdb_bin, &hwdb);
665 if (r >= 0)
666 break;
667 }
668 else
669 r = sd_hwdb_new(&hwdb);
670 if (r < 0)
671 return r;
672
673 SD_HWDB_FOREACH_PROPERTY(hwdb, modalias, key, value)
674 printf("%s=%s\n", key, value);
675
676 return 0;
677 }
678
679 bool hwdb_should_reload(sd_hwdb *hwdb) {
680 bool found = false;
681 struct stat st;
682
683 if (!hwdb)
684 return false;
685 if (!hwdb->f)
686 return false;
687
688 /* if hwdb.bin doesn't exist anywhere, we need to update */
689 NULSTR_FOREACH(p, hwdb_bin_paths)
690 if (stat(p, &st) >= 0) {
691 found = true;
692 break;
693 }
694 if (!found)
695 return true;
696
697 if (timespec_load(&hwdb->st.st_mtim) != timespec_load(&st.st_mtim))
698 return true;
699 return false;
700 }