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