]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/libsystemd/sd-hwdb/hwdb-util.c
pkgconfig: define variables relative to ${prefix}/${rootprefix}/${sysconfdir}
[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
20 static const char *default_hwdb_bin_dir = "/etc/udev";
21 static const char * const conf_file_dirs[] = {
22 "/etc/udev/hwdb.d",
23 UDEVLIBEXECDIR "/hwdb.d",
24 NULL
25 };
26
27 /*
28 * Generic udev properties, key-value database based on modalias strings.
29 * Uses a Patricia/radix trie to index all matches for efficient lookup.
30 */
31
32 /* in-memory trie objects */
33 struct trie {
34 struct trie_node *root;
35 struct strbuf *strings;
36
37 size_t nodes_count;
38 size_t children_count;
39 size_t values_count;
40 };
41
42 struct trie_node {
43 /* prefix, common part for all children of this node */
44 size_t prefix_off;
45
46 /* sorted array of pointers to children nodes */
47 struct trie_child_entry *children;
48 uint8_t children_count;
49
50 /* sorted array of key-value pairs */
51 struct trie_value_entry *values;
52 size_t values_count;
53 };
54
55 /* children array item with char (0-255) index */
56 struct trie_child_entry {
57 uint8_t c;
58 struct trie_node *child;
59 };
60
61 /* value array item with key-value pairs */
62 struct trie_value_entry {
63 size_t key_off;
64 size_t value_off;
65 size_t filename_off;
66 uint32_t line_number;
67 uint16_t file_priority;
68 };
69
70 static int trie_children_cmp(const struct trie_child_entry *a, const struct trie_child_entry *b) {
71 return CMP(a->c, b->c);
72 }
73
74 static int node_add_child(struct trie *trie, struct trie_node *node, struct trie_node *node_child, uint8_t c) {
75 struct trie_child_entry *child;
76
77 /* extend array, add new entry, sort for bisection */
78 child = reallocarray(node->children, node->children_count + 1, sizeof(struct trie_child_entry));
79 if (!child)
80 return -ENOMEM;
81
82 node->children = child;
83 trie->children_count++;
84 node->children[node->children_count].c = c;
85 node->children[node->children_count].child = node_child;
86 node->children_count++;
87 typesafe_qsort(node->children, node->children_count, trie_children_cmp);
88 trie->nodes_count++;
89
90 return 0;
91 }
92
93 static struct trie_node *node_lookup(const struct trie_node *node, uint8_t c) {
94 struct trie_child_entry *child;
95 struct trie_child_entry search;
96
97 search.c = c;
98 child = typesafe_bsearch(&search, node->children, node->children_count, trie_children_cmp);
99 if (child)
100 return child->child;
101 return NULL;
102 }
103
104 static void trie_node_cleanup(struct trie_node *node) {
105 size_t i;
106
107 if (!node)
108 return;
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 void trie_free(struct trie *trie) {
118 if (!trie)
119 return;
120
121 trie_node_cleanup(trie->root);
122 strbuf_cleanup(trie->strings);
123 free(trie);
124 }
125
126 DEFINE_TRIVIAL_CLEANUP_FUNC(struct trie*, trie_free);
127
128 static int trie_values_cmp(const struct trie_value_entry *a, const struct trie_value_entry *b, struct trie *trie) {
129 return strcmp(trie->strings->buf + a->key_off,
130 trie->strings->buf + b->key_off);
131 }
132
133 static int trie_node_add_value(struct trie *trie, struct trie_node *node,
134 const char *key, const char *value,
135 const char *filename, uint16_t file_priority, uint32_t line_number, bool compat) {
136 ssize_t k, v, fn = 0;
137 struct trie_value_entry *val;
138
139 k = strbuf_add_string(trie->strings, key, strlen(key));
140 if (k < 0)
141 return k;
142 v = strbuf_add_string(trie->strings, value, strlen(value));
143 if (v < 0)
144 return v;
145
146 if (!compat) {
147 fn = strbuf_add_string(trie->strings, filename, strlen(filename));
148 if (fn < 0)
149 return fn;
150 }
151
152 if (node->values_count) {
153 struct trie_value_entry search = {
154 .key_off = k,
155 .value_off = v,
156 };
157
158 val = typesafe_bsearch_r(&search, node->values, node->values_count, trie_values_cmp, trie);
159 if (val) {
160 /* At this point we have 2 identical properties on the same match-string.
161 * Since we process files in order, we just replace the previous value. */
162 val->value_off = v;
163 val->filename_off = fn;
164 val->file_priority = file_priority;
165 val->line_number = line_number;
166 return 0;
167 }
168 }
169
170 /* extend array, add new entry, sort for bisection */
171 val = reallocarray(node->values, node->values_count + 1, sizeof(struct trie_value_entry));
172 if (!val)
173 return -ENOMEM;
174 trie->values_count++;
175 node->values = val;
176 node->values[node->values_count] = (struct trie_value_entry) {
177 .key_off = k,
178 .value_off = v,
179 .filename_off = fn,
180 .file_priority = file_priority,
181 .line_number = line_number,
182 };
183 node->values_count++;
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 size_t i = 0;
192 int r = 0;
193
194 for (;;) {
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 i++;
274 }
275 }
276
277 struct trie_f {
278 FILE *f;
279 struct trie *trie;
280 uint64_t strings_off;
281
282 uint64_t nodes_count;
283 uint64_t children_count;
284 uint64_t values_count;
285 };
286
287 /* calculate the storage space for the nodes, children arrays, value arrays */
288 static void trie_store_nodes_size(struct trie_f *trie, struct trie_node *node, bool compat) {
289 uint64_t i;
290
291 for (i = 0; i < node->children_count; i++)
292 trie_store_nodes_size(trie, node->children[i].child, compat);
293
294 trie->strings_off += sizeof(struct trie_node_f);
295 for (i = 0; i < node->children_count; i++)
296 trie->strings_off += sizeof(struct trie_child_entry_f);
297 for (i = 0; i < node->values_count; i++)
298 trie->strings_off += compat ? sizeof(struct trie_value_entry_f) : sizeof(struct trie_value_entry2_f);
299 }
300
301 static int64_t trie_store_nodes(struct trie_f *trie, struct trie_node *node, bool compat) {
302 uint64_t i;
303 struct trie_node_f n = {
304 .prefix_off = htole64(trie->strings_off + node->prefix_off),
305 .children_count = node->children_count,
306 .values_count = htole64(node->values_count),
307 };
308 _cleanup_free_ struct trie_child_entry_f *children = NULL;
309 int64_t node_off;
310
311 if (node->children_count) {
312 children = new(struct trie_child_entry_f, node->children_count);
313 if (!children)
314 return -ENOMEM;
315 }
316
317 /* post-order recursion */
318 for (i = 0; i < node->children_count; i++) {
319 int64_t child_off;
320
321 child_off = trie_store_nodes(trie, node->children[i].child, compat);
322 if (child_off < 0)
323 return child_off;
324
325 children[i] = (struct trie_child_entry_f) {
326 .c = node->children[i].c,
327 .child_off = htole64(child_off),
328 };
329 }
330
331 /* write node */
332 node_off = ftello(trie->f);
333 fwrite(&n, sizeof(struct trie_node_f), 1, trie->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, trie->f);
339 trie->children_count += node->children_count;
340 }
341
342 /* append values array */
343 for (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, trie->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 };
363 _cleanup_free_ char *filename_tmp = NULL;
364 int64_t pos;
365 int64_t root_off;
366 int64_t size;
367 struct trie_header_f h = {
368 .signature = HWDB_SIG,
369 .tool_version = htole64(atoi(PACKAGE_VERSION)),
370 .header_size = htole64(sizeof(struct trie_header_f)),
371 .node_size = htole64(sizeof(struct trie_node_f)),
372 .child_entry_size = htole64(sizeof(struct trie_child_entry_f)),
373 .value_entry_size = htole64(compat ? sizeof(struct trie_value_entry_f) : sizeof(struct trie_value_entry2_f)),
374 };
375 int r;
376
377 /* calculate size of header, nodes, children entries, value entries */
378 t.strings_off = sizeof(struct trie_header_f);
379 trie_store_nodes_size(&t, trie->root, compat);
380
381 r = fopen_temporary(filename, &t.f, &filename_tmp);
382 if (r < 0)
383 return r;
384 fchmod(fileno(t.f), 0444);
385
386 /* write nodes */
387 if (fseeko(t.f, sizeof(struct trie_header_f), SEEK_SET) < 0)
388 goto error_fclose;
389
390 root_off = trie_store_nodes(&t, trie->root, compat);
391 h.nodes_root_off = htole64(root_off);
392 pos = ftello(t.f);
393 h.nodes_len = htole64(pos - sizeof(struct trie_header_f));
394
395 /* write string buffer */
396 fwrite(trie->strings->buf, trie->strings->len, 1, t.f);
397 h.strings_len = htole64(trie->strings->len);
398
399 /* write header */
400 size = ftello(t.f);
401 h.file_size = htole64(size);
402 if (fseeko(t.f, 0, SEEK_SET) < 0)
403 goto error_fclose;
404 fwrite(&h, sizeof(struct trie_header_f), 1, t.f);
405
406 if (ferror(t.f))
407 goto error_fclose;
408 if (fflush(t.f) < 0)
409 goto error_fclose;
410 if (fsync(fileno(t.f)) < 0)
411 goto error_fclose;
412 if (rename(filename_tmp, filename) < 0)
413 goto error_fclose;
414
415 /* write succeeded */
416 fclose(t.f);
417
418 log_debug("=== trie on-disk ===");
419 log_debug("size: %8"PRIi64" bytes", size);
420 log_debug("header: %8zu bytes", sizeof(struct trie_header_f));
421 log_debug("nodes: %8"PRIu64" bytes (%8"PRIu64")",
422 t.nodes_count * sizeof(struct trie_node_f), t.nodes_count);
423 log_debug("child pointers: %8"PRIu64" bytes (%8"PRIu64")",
424 t.children_count * sizeof(struct trie_child_entry_f), t.children_count);
425 log_debug("value pointers: %8"PRIu64" bytes (%8"PRIu64")",
426 t.values_count * (compat ? sizeof(struct trie_value_entry_f) : sizeof(struct trie_value_entry2_f)), t.values_count);
427 log_debug("string store: %8zu bytes", trie->strings->len);
428 log_debug("strings start: %8"PRIu64, t.strings_off);
429 return 0;
430
431 error_fclose:
432 r = -errno;
433 fclose(t.f);
434 unlink(filename_tmp);
435 return r;
436 }
437
438 static int insert_data(struct trie *trie, char **match_list, char *line, const char *filename,
439 uint16_t file_priority, uint32_t line_number, bool compat) {
440 char *value, **entry;
441
442 assert(line[0] == ' ');
443
444 value = strchr(line, '=');
445 if (!value)
446 return log_syntax(NULL, LOG_WARNING, filename, line_number, EINVAL,
447 "Key-value pair expected but got \"%s\", ignoring", line);
448
449 value[0] = '\0';
450 value++;
451
452 /* Replace multiple leading spaces by a single space */
453 while (isblank(line[0]) && isblank(line[1]))
454 line++;
455
456 if (isempty(line + 1) || isempty(value))
457 return log_syntax(NULL, LOG_WARNING, filename, line_number, EINVAL,
458 "Empty %s in \"%s=%s\", ignoring",
459 isempty(line + 1) ? "key" : "value",
460 line, value);
461
462 STRV_FOREACH(entry, match_list)
463 trie_insert(trie, trie->root, *entry, line, value, filename, file_priority, line_number, compat);
464
465 return 0;
466 }
467
468 static int import_file(struct trie *trie, const char *filename, uint16_t file_priority, bool compat) {
469 enum {
470 HW_NONE,
471 HW_MATCH,
472 HW_DATA,
473 } state = HW_NONE;
474 _cleanup_fclose_ FILE *f = NULL;
475 _cleanup_strv_free_ char **match_list = NULL;
476 uint32_t line_number = 0;
477 char *match = NULL;
478 int r = 0, err;
479
480 f = fopen(filename, "re");
481 if (!f)
482 return -errno;
483
484 for (;;) {
485 _cleanup_free_ char *line = NULL;
486 size_t len;
487 char *pos;
488
489 r = read_line(f, LONG_LINE_MAX, &line);
490 if (r < 0)
491 return r;
492 if (r == 0)
493 break;
494
495 ++line_number;
496
497 /* comment line */
498 if (line[0] == '#')
499 continue;
500
501 /* strip trailing comment */
502 pos = strchr(line, '#');
503 if (pos)
504 pos[0] = '\0';
505
506 /* strip trailing whitespace */
507 len = strlen(line);
508 while (len > 0 && isspace(line[len-1]))
509 len--;
510 line[len] = '\0';
511
512 switch (state) {
513 case HW_NONE:
514 if (len == 0)
515 break;
516
517 if (line[0] == ' ') {
518 log_syntax(NULL, LOG_WARNING, filename, line_number, EINVAL,
519 "Match expected but got indented property \"%s\", ignoring line", line);
520 r = -EINVAL;
521 break;
522 }
523
524 /* start of record, first match */
525 state = HW_MATCH;
526
527 match = strdup(line);
528 if (!match)
529 return -ENOMEM;
530
531 err = strv_consume(&match_list, match);
532 if (err < 0)
533 return err;
534
535 break;
536
537 case HW_MATCH:
538 if (len == 0) {
539 log_syntax(NULL, LOG_WARNING, filename, line_number, EINVAL,
540 "Property expected, ignoring record with no properties");
541 r = -EINVAL;
542 state = HW_NONE;
543 strv_clear(match_list);
544 break;
545 }
546
547 if (line[0] != ' ') {
548 /* another match */
549 match = strdup(line);
550 if (!match)
551 return -ENOMEM;
552
553 err = strv_consume(&match_list, match);
554 if (err < 0)
555 return err;
556
557 break;
558 }
559
560 /* first data */
561 state = HW_DATA;
562 err = insert_data(trie, match_list, line, filename, file_priority, line_number, compat);
563 if (err < 0)
564 r = err;
565 break;
566
567 case HW_DATA:
568 if (len == 0) {
569 /* end of record */
570 state = HW_NONE;
571 strv_clear(match_list);
572 break;
573 }
574
575 if (line[0] != ' ') {
576 log_syntax(NULL, LOG_WARNING, filename, line_number, EINVAL,
577 "Property or empty line expected, got \"%s\", ignoring record", line);
578 r = -EINVAL;
579 state = HW_NONE;
580 strv_clear(match_list);
581 break;
582 }
583
584 err = insert_data(trie, match_list, line, filename, file_priority, line_number, compat);
585 if (err < 0)
586 r = err;
587 break;
588 };
589 }
590
591 if (state == HW_MATCH)
592 log_syntax(NULL, LOG_WARNING, filename, line_number, EINVAL,
593 "Property expected, ignoring record with no properties");
594
595 return r;
596 }
597
598 int hwdb_update(const char *root, const char *hwdb_bin_dir, bool strict, bool compat) {
599 _cleanup_free_ char *hwdb_bin = NULL;
600 _cleanup_(trie_freep) struct trie *trie = NULL;
601 _cleanup_strv_free_ char **files = NULL;
602 char **f;
603 uint16_t file_priority = 1;
604 int r = 0, err;
605
606 /* The argument 'compat' controls the format version of database. If false, then hwdb.bin will be created with
607 * additional information such that priority, line number, and filename of database source. If true, then hwdb.bin
608 * will be created without the information. systemd-hwdb command should set the argument false, and 'udevadm hwdb'
609 * command should set it true. */
610
611 trie = new0(struct trie, 1);
612 if (!trie)
613 return -ENOMEM;
614
615 /* string store */
616 trie->strings = strbuf_new();
617 if (!trie->strings)
618 return -ENOMEM;
619
620 /* index */
621 trie->root = new0(struct trie_node, 1);
622 if (!trie->root)
623 return -ENOMEM;
624
625 trie->nodes_count++;
626
627 err = conf_files_list_strv(&files, ".hwdb", root, 0, conf_file_dirs);
628 if (err < 0)
629 return log_error_errno(err, "Failed to enumerate hwdb files: %m");
630
631 STRV_FOREACH(f, files) {
632 log_debug("Reading file \"%s\"", *f);
633 err = import_file(trie, *f, file_priority++, compat);
634 if (err < 0 && strict)
635 r = err;
636 }
637
638 strbuf_complete(trie->strings);
639
640 log_debug("=== trie in-memory ===");
641 log_debug("nodes: %8zu bytes (%8zu)",
642 trie->nodes_count * sizeof(struct trie_node), trie->nodes_count);
643 log_debug("children arrays: %8zu bytes (%8zu)",
644 trie->children_count * sizeof(struct trie_child_entry), trie->children_count);
645 log_debug("values arrays: %8zu bytes (%8zu)",
646 trie->values_count * sizeof(struct trie_value_entry), trie->values_count);
647 log_debug("strings: %8zu bytes",
648 trie->strings->len);
649 log_debug("strings incoming: %8zu bytes (%8zu)",
650 trie->strings->in_len, trie->strings->in_count);
651 log_debug("strings dedup'ed: %8zu bytes (%8zu)",
652 trie->strings->dedup_len, trie->strings->dedup_count);
653
654 hwdb_bin = path_join(root, hwdb_bin_dir ?: default_hwdb_bin_dir, "hwdb.bin");
655 if (!hwdb_bin)
656 return -ENOMEM;
657
658 mkdir_parents_label(hwdb_bin, 0755);
659 err = trie_store(trie, hwdb_bin, compat);
660 if (err < 0)
661 return log_error_errno(err, "Failed to write database %s: %m", hwdb_bin);
662
663 err = label_fix(hwdb_bin, 0);
664 if (err < 0)
665 return err;
666
667 return r;
668 }
669
670 int hwdb_query(const char *modalias) {
671 _cleanup_(sd_hwdb_unrefp) sd_hwdb *hwdb = NULL;
672 const char *key, *value;
673 int r;
674
675 assert(modalias);
676
677 r = sd_hwdb_new(&hwdb);
678 if (r < 0)
679 return r;
680
681 SD_HWDB_FOREACH_PROPERTY(hwdb, modalias, key, value)
682 printf("%s=%s\n", key, value);
683
684 return 0;
685 }