Debian Codegraph @

src/shared/hwdb-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <ctype.h>
4 #include <stdio.h>
5 #include <sys/stat.h>
6 #include <unistd.h>
7
8 #include "alloc-util.h"
9 #include "conf-files.h"
10 #include "errno-util.h"
11 #include "fd-util.h"
12 #include "fileio.h"
13 #include "fs-util.h"
14 #include "hwdb-internal.h"
15 #include "hwdb-util.h"
16 #include "label-util.h"
17 #include "log.h"
18 #include "mkdir.h"
19 #include "nulstr-util.h"
20 #include "path-util.h"
21 #include "sort-util.h"
22 #include "strbuf.h"
23 #include "string-util.h"
24 #include "strv.h"
25 #include "time-util.h"
26 #include "tmpfile-util.h"
27 #include "verbs.h"
28
29 static const char* const conf_file_dirs[] = {
30 "/etc/udev/hwdb.d",
31 UDEVLIBEXECDIR "/hwdb.d",
32 NULL
33 };
34
35 /*
36 * Generic udev properties, key-value database based on modalias strings.
37 * Uses a Patricia/radix trie to index all matches for efficient lookup.
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 size_t filename_off;
74 uint32_t line_number;
75 uint16_t file_priority;
76 };
77
78 static int trie_children_cmp(const struct trie_child_entry *a, const struct trie_child_entry *b) {
79 return CMP(a->c, b->c);
80 }
81
82 static int node_add_child(struct trie *trie, struct trie_node *node, struct trie_node *node_child, uint8_t c) {
83 /* extend array, add new entry, sort for bisection */
84 if (!GREEDY_REALLOC(node->children, node->children_count + 1))
85 return -ENOMEM;
86
87 trie->children_count++;
88 node->children[node->children_count++] = (struct trie_child_entry) {
89 .c = c,
90 .child = node_child,
91 };
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 = typesafe_bsearch(&search, node->children, node->children_count, trie_children_cmp);
104 if (child)
105 return child->child;
106 return NULL;
107 }
108
109 static void trie_node_cleanup(struct trie_node *node) {
110 if (!node)
111 return;
112
113 for (size_t i = 0; i < node->children_count; i++)
114 trie_node_cleanup(node->children[i].child);
115 free(node->children);
116 free(node->values);
117 free(node);
118 }
119
120 static struct trie* trie_free(struct trie *trie) {
121 if (!trie)
122 return NULL;
123
124 trie_node_cleanup(trie->root);
125 strbuf_free(trie->strings);
126 return mfree(trie);
127 }
128
129 DEFINE_TRIVIAL_CLEANUP_FUNC(struct trie*, trie_free);
130
131 static int trie_values_cmp(const struct trie_value_entry *a, const struct trie_value_entry *b, struct trie *trie) {
132 return strcmp(trie->strings->buf + a->key_off,
133 trie->strings->buf + b->key_off);
134 }
135
136 static int trie_node_add_value(struct trie *trie, struct trie_node *node,
137 const char *key, const char *value,
138 const char *filename, uint16_t file_priority, uint32_t line_number, bool compat) {
139 ssize_t k, v, fn = 0;
140
141 k = strbuf_add_string(trie->strings, key);
142 if (k < 0)
143 return k;
144 v = strbuf_add_string(trie->strings, value);
145 if (v < 0)
146 return v;
147
148 if (!compat) {
149 fn = strbuf_add_string(trie->strings, filename);
150 if (fn < 0)
151 return fn;
152 }
153
154 if (node->values_count) {
155 struct trie_value_entry search = {
156 .key_off = k,
157 .value_off = v,
158 }, *val;
159
160 val = typesafe_bsearch_r(&search, node->values, node->values_count, trie_values_cmp, trie);
161 if (val) {
162 /* At this point we have 2 identical properties on the same match-string.
163 * Since we process files in order, we just replace the previous value. */
164 val->value_off = v;
165 val->filename_off = fn;
166 val->file_priority = file_priority;
167 val->line_number = line_number;
168 return 0;
169 }
170 }
171
172 /* extend array, add new entry, sort for bisection */
173 if (!GREEDY_REALLOC(node->values, node->values_count + 1))
174 return -ENOMEM;
175
176 trie->values_count++;
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 typesafe_qsort_r(node->values, node->values_count, trie_values_cmp, trie);
185 return 0;
186 }
187
188 static int trie_insert(struct trie *trie, struct trie_node *node, const char *search,
189 const char *key, const char *value,
190 const char *filename, uint16_t file_priority, uint32_t line_number, bool compat) {
191 int r = 0;
192
193 assert(node);
194
195 for (size_t i = 0;; i++) {
196 size_t p;
197 char 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_full(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);
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 }
275 }
276
277 struct trie_f {
278 struct trie *trie;
279 uint64_t strings_off;
280
281 uint64_t nodes_count;
282 uint64_t children_count;
283 uint64_t values_count;
284 };
285
286 /* calculate the storage space for the nodes, children arrays, value arrays */
287 static void trie_store_nodes_size(struct trie_f *trie, struct trie_node *node, bool compat) {
288 for (uint64_t i = 0; i < node->children_count; i++)
289 trie_store_nodes_size(trie, node->children[i].child, compat);
290
291 trie->strings_off += sizeof(struct trie_node_f);
292 for (uint64_t i = 0; i < node->children_count; i++)
293 trie->strings_off += sizeof(struct trie_child_entry_f);
294 for (uint64_t i = 0; i < node->values_count; i++)
295 trie->strings_off += compat ? sizeof(struct trie_value_entry_f) : sizeof(struct trie_value_entry2_f);
296 }
297
298 static int64_t trie_store_nodes(struct trie_f *trie, FILE *f, struct trie_node *node, bool compat) {
299 _cleanup_free_ struct trie_child_entry_f *children = NULL;
300 int64_t node_off;
301
302 assert(trie);
303 assert(f);
304 assert(node);
305
306 if (node->children_count) {
307 children = new(struct trie_child_entry_f, node->children_count);
308 if (!children)
309 return -ENOMEM;
310 }
311
312 /* post-order recursion */
313 for (uint64_t i = 0; i < node->children_count; i++) {
314 int64_t child_off;
315
316 child_off = trie_store_nodes(trie, f, node->children[i].child, compat);
317 if (child_off < 0)
318 return child_off;
319
320 children[i] = (struct trie_child_entry_f) {
321 .c = node->children[i].c,
322 .child_off = htole64(child_off),
323 };
324 }
325
326 struct trie_node_f n = {
327 .prefix_off = htole64(trie->strings_off + node->prefix_off),
328 .children_count = node->children_count,
329 .values_count = htole64(node->values_count),
330 };
331
332 /* write node */
333 node_off = ftello(f);
334 fwrite(&n, sizeof(struct trie_node_f), 1, 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, f);
340 trie->children_count += node->children_count;
341 }
342
343 /* append values array */
344 for (uint64_t 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, 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 .strings_off = sizeof(struct trie_header_f),
364 };
365 _cleanup_(unlink_and_freep) char *filename_tmp = NULL;
366 _cleanup_fclose_ FILE *f = NULL;
367 int64_t pos, root_off, size;
368 int r;
369
370 assert(trie);
371 assert(filename);
372
373 /* calculate size of header, nodes, children entries, value entries */
374 trie_store_nodes_size(&t, trie->root, compat);
375
376 r = fopen_tmpfile_linkable(filename, O_WRONLY|O_CLOEXEC, &filename_tmp, &f);
377 if (r < 0)
378 return r;
379
380 if (fchmod(fileno(f), 0444) < 0)
381 return -errno;
382
383 struct trie_header_f h = {
384 .signature = HWDB_SIG,
385 .tool_version = htole64(PROJECT_VERSION),
386 .header_size = htole64(sizeof(struct trie_header_f)),
387 .node_size = htole64(sizeof(struct trie_node_f)),
388 .child_entry_size = htole64(sizeof(struct trie_child_entry_f)),
389 .value_entry_size = htole64(compat ? sizeof(struct trie_value_entry_f) : sizeof(struct trie_value_entry2_f)),
390 };
391
392 /* write nodes */
393 if (fseeko(f, sizeof(struct trie_header_f), SEEK_SET) < 0)
394 return -errno;
395
396 root_off = trie_store_nodes(&t, f, trie->root, compat);
397 h.nodes_root_off = htole64(root_off);
398 pos = ftello(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, f);
403 h.strings_len = htole64(trie->strings->len);
404
405 /* write header */
406 size = ftello(f);
407 h.file_size = htole64(size);
408 if (fseeko(f, 0, SEEK_SET) < 0)
409 return -errno;
410 fwrite(&h, sizeof(struct trie_header_f), 1, f);
411
412 r = flink_tmpfile(f, filename_tmp, filename, LINK_TMPFILE_REPLACE|LINK_TMPFILE_SYNC);
413 if (r < 0)
414 return r;
415
416 filename_tmp = mfree(filename_tmp);
417
418 /* write succeeded */
419
420 log_debug("=== trie on-disk ===");
421 log_debug("size: %8"PRIi64" bytes", size);
422 log_debug("header: %8zu bytes", sizeof(struct trie_header_f));
423 log_debug("nodes: %8"PRIu64" bytes (%8"PRIu64")",
424 t.nodes_count * sizeof(struct trie_node_f), t.nodes_count);
425 log_debug("child pointers: %8"PRIu64" bytes (%8"PRIu64")",
426 t.children_count * sizeof(struct trie_child_entry_f), t.children_count);
427 log_debug("value pointers: %8"PRIu64" bytes (%8"PRIu64")",
428 t.values_count * (compat ? sizeof(struct trie_value_entry_f) : sizeof(struct trie_value_entry2_f)), t.values_count);
429 log_debug("string store: %8zu bytes", trie->strings->len);
430 log_debug("strings start: %8"PRIu64, t.strings_off);
431 return 0;
432 }
433
434 static int insert_data(struct trie *trie, char **match_list, char *line, const char *filename,
435 uint16_t file_priority, uint32_t line_number, bool compat) {
436 char *value;
437
438 assert(line[0] == ' ');
439
440 value = strchr(line, '=');
441 if (!value)
442 return log_syntax(NULL, LOG_WARNING, filename, line_number, SYNTHETIC_ERRNO(EINVAL),
443 "Key-value pair expected but got \"%s\", ignoring.", line);
444
445 value[0] = '\0';
446 value++;
447
448 /* Replace multiple leading spaces by a single space */
449 while (isblank(line[0]) && isblank(line[1]))
450 line++;
451
452 if (isempty(line + 1))
453 return log_syntax(NULL, LOG_WARNING, filename, line_number, SYNTHETIC_ERRNO(EINVAL),
454 "Empty key in \"%s=%s\", ignoring.",
455 line, value);
456
457 STRV_FOREACH(entry, match_list)
458 trie_insert(trie, trie->root, *entry, line, value, filename, file_priority, line_number, compat);
459
460 return 0;
461 }
462
463 static int import_file(struct trie *trie, int fd, const char *filename, uint16_t file_priority, bool compat) {
464 enum {
465 HW_NONE,
466 HW_MATCH,
467 HW_DATA,
468 } state = HW_NONE;
469 _cleanup_fclose_ FILE *f = NULL;
470 _cleanup_strv_free_ char **match_list = NULL;
471 uint32_t line_number = 0;
472 int r;
473
474 assert(trie);
475 assert(fd >= 0);
476 assert(filename);
477
478 f = fopen(FORMAT_PROC_FD_PATH(fd), "re");
479 if (!f)
480 return -errno;
481
482 for (;;) {
483 _cleanup_free_ char *line = NULL;
484 size_t len;
485 char *pos;
486
487 r = read_line_full(f, LONG_LINE_MAX, READ_LINE_NOT_A_TTY, &line);
488 if (r < 0)
489 return r;
490 if (r == 0)
491 break;
492
493 line_number++;
494
495 /* comment line */
496 if (line[0] == '#')
497 continue;
498
499 /* strip trailing comment */
500 pos = strchr(line, '#');
501 if (pos)
502 pos[0] = '\0';
503
504 /* strip trailing whitespace */
505 len = strlen(line);
506 while (len > 0 && isspace(line[len-1]))
507 len--;
508 line[len] = '\0';
509
510 switch (state) {
511 case HW_NONE:
512 if (len == 0)
513 break;
514
515 if (line[0] == ' ') {
516 log_syntax(NULL, LOG_WARNING, filename, line_number, 0,
517 "Match expected but got indented property \"%s\", ignoring line.", line);
518 break;
519 }
520
521 /* start of record, first match */
522 state = HW_MATCH;
523
524 r = strv_extend(&match_list, line);
525 if (r < 0)
526 return r;
527 break;
528
529 case HW_MATCH:
530 if (len == 0) {
531 log_syntax(NULL, LOG_WARNING, filename, line_number, 0,
532 "Property expected, ignoring record with no properties.");
533 state = HW_NONE;
534 match_list = strv_free(match_list);
535 break;
536 }
537
538 if (line[0] != ' ') {
539 /* another match */
540 r = strv_extend(&match_list, line);
541 if (r < 0)
542 return r;
543 break;
544 }
545
546 /* first data */
547 state = HW_DATA;
548 (void) insert_data(trie, match_list, line, filename, file_priority, line_number, compat);
549 break;
550
551 case HW_DATA:
552 if (len == 0) {
553 /* end of record */
554 state = HW_NONE;
555 match_list = strv_free(match_list);
556 break;
557 }
558
559 if (line[0] != ' ') {
560 log_syntax(NULL, LOG_WARNING, filename, line_number, 0,
561 "Property or empty line expected, got \"%s\", ignoring record.", line);
562 state = HW_NONE;
563 match_list = strv_free(match_list);
564 break;
565 }
566
567 (void) insert_data(trie, match_list, line, filename, file_priority, line_number, compat);
568 break;
569 };
570 }
571
572 if (state == HW_MATCH)
573 log_syntax(NULL, LOG_WARNING, filename, line_number, 0,
574 "Property expected, ignoring record with no properties.");
575
576 return r;
577 }
578
579 int hwdb_update(const char *root, const char *hwdb_bin_dir, bool strict, bool compat) {
580 _cleanup_free_ char *hwdb_bin = NULL;
581 _cleanup_(trie_freep) struct trie *trie = NULL;
582 uint16_t file_priority = 1;
583 int r, ret = 0;
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 hwdb_bin = path_join(root, hwdb_bin_dir ?: "/etc/udev", "hwdb.bin");
591 if (!hwdb_bin)
592 return -ENOMEM;
593
594 trie = new0(struct trie, 1);
595 if (!trie)
596 return -ENOMEM;
597
598 /* string store */
599 trie->strings = strbuf_new();
600 if (!trie->strings)
601 return -ENOMEM;
602
603 /* index */
604 trie->root = new0(struct trie_node, 1);
605 if (!trie->root)
606 return -ENOMEM;
607
608 trie->nodes_count++;
609
610 ConfFile **files = NULL;
611 size_t n_files = 0;
612
613 CLEANUP_ARRAY(files, n_files, conf_file_free_array);
614
615 r = conf_files_list_strv_full(".hwdb", root,
616 CONF_FILES_REGULAR | CONF_FILES_FILTER_MASKED | CONF_FILES_WARN,
617 conf_file_dirs, &files, &n_files);
618 if (r < 0)
619 return log_error_errno(r, "Failed to enumerate hwdb files: %m");
620
621 if (n_files == 0) {
622 if (unlink(hwdb_bin) < 0) {
623 if (errno != ENOENT)
624 return log_error_errno(errno, "Failed to remove compiled hwdb database %s: %m", hwdb_bin);
625
626 log_info("No hwdb files found, skipping.");
627 } else
628 log_info("No hwdb files found, compiled hwdb database %s removed.", hwdb_bin);
629
630 return 0;
631 }
632
633 FOREACH_ARRAY(i, files, n_files) {
634 ConfFile *c = *i;
635
636 log_debug("Reading file \"%s\" -> \"%s\"", c->original_path, c->resolved_path);
637 RET_GATHER(ret, import_file(trie, c->fd, c->original_path, file_priority++, compat));
638 }
639
640 strbuf_complete(trie->strings);
641
642 log_debug("=== trie in-memory ===");
643 log_debug("nodes: %8zu bytes (%8zu)",
644 trie->nodes_count * sizeof(struct trie_node), trie->nodes_count);
645 log_debug("children arrays: %8zu bytes (%8zu)",
646 trie->children_count * sizeof(struct trie_child_entry), trie->children_count);
647 log_debug("values arrays: %8zu bytes (%8zu)",
648 trie->values_count * sizeof(struct trie_value_entry), trie->values_count);
649 log_debug("strings: %8zu bytes",
650 trie->strings->len);
651 log_debug("strings incoming: %8zu bytes (%8zu)",
652 trie->strings->in_len, trie->strings->in_count);
653 log_debug("strings dedup'ed: %8zu bytes (%8zu)",
654 trie->strings->dedup_len, trie->strings->dedup_count);
655
656 (void) mkdir_parents_label(hwdb_bin, 0755);
657 r = trie_store(trie, hwdb_bin, compat);
658 if (r < 0)
659 return log_error_errno(r, "Failed to write database %s: %m", hwdb_bin);
660
661 r = label_fix(hwdb_bin, 0);
662 if (r < 0)
663 return r;
664
665 return strict ? ret : 0;
666 }
667
668 int hwdb_query(const char *modalias, const char *root) {
669 _cleanup_(sd_hwdb_unrefp) sd_hwdb *hwdb = NULL;
670 const char *key, *value;
671 int r;
672
673 assert(modalias);
674
675 if (!isempty(root))
676 NULSTR_FOREACH(p, HWDB_BIN_PATHS) {
677 _cleanup_free_ char *hwdb_bin = NULL;
678
679 hwdb_bin = path_join(root, p);
680 if (!hwdb_bin)
681 return -ENOMEM;
682
683 r = sd_hwdb_new_from_path(hwdb_bin, &hwdb);
684 if (r >= 0)
685 break;
686 }
687 else
688 r = sd_hwdb_new(&hwdb);
689 if (r < 0)
690 return r;
691
692 SD_HWDB_FOREACH_PROPERTY(hwdb, modalias, key, value)
693 printf("%s=%s\n", key, value);
694
695 return 0;
696 }
697
698 bool hwdb_should_reload(sd_hwdb *hwdb) {
699 bool found = false;
700 struct stat st;
701
702 if (!hwdb)
703 return false;
704 if (!hwdb->f)
705 return false;
706
707 /* if hwdb.bin doesn't exist anywhere, we need to update */
708 NULSTR_FOREACH(p, HWDB_BIN_PATHS)
709 if (stat(p, &st) >= 0) {
710 found = true;
711 break;
712 }
713 if (!found)
714 return true;
715
716 if (timespec_load(&hwdb->st.st_mtim) != timespec_load(&st.st_mtim))
717 return true;
718 return false;
719 }
720
721 int hwdb_bypass(void) {
722 return should_bypass("SYSTEMD_HWDB_UPDATE");
723 }