Debian Codegraph @

src/libsystemd/sd-hwdb/sd-hwdb.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 /***
3 Copyright © 2008 Alan Jenkins <[email protected]>
4 ***/
5
6 #include <errno.h>
7 #include <fnmatch.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <sys/mman.h>
11 #include <sys/stat.h>
12
13 #include "sd-hwdb.h"
14
15 #include "alloc-util.h"
16 #include "fd-util.h"
17 #include "fileio.h"
18 #include "hashmap.h"
19 #include "hwdb-internal.h"
20 #include "log.h"
21 #include "nulstr-util.h"
22 #include "string-util.h"
23
24 struct linebuf {
25 char bytes[LINE_MAX];
26 size_t size;
27 size_t len;
28 };
29
30 static void linebuf_init(struct linebuf *buf) {
31 buf->size = 0;
32 buf->len = 0;
33 }
34
35 static const char *linebuf_get(struct linebuf *buf) {
36 if (buf->len + 1 >= sizeof(buf->bytes))
37 return NULL;
38 buf->bytes[buf->len] = '\0';
39 return buf->bytes;
40 }
41
42 static bool linebuf_add(struct linebuf *buf, const char *s, size_t len) {
43 if (buf->len + len >= sizeof(buf->bytes))
44 return false;
45 memcpy(buf->bytes + buf->len, s, len);
46 buf->len += len;
47 return true;
48 }
49
50 static bool linebuf_add_char(struct linebuf *buf, char c) {
51 if (buf->len + 1 >= sizeof(buf->bytes))
52 return false;
53 buf->bytes[buf->len++] = c;
54 return true;
55 }
56
57 static void linebuf_rem(struct linebuf *buf, size_t count) {
58 assert(buf->len >= count);
59 buf->len -= count;
60 }
61
62 static void linebuf_rem_char(struct linebuf *buf) {
63 linebuf_rem(buf, 1);
64 }
65
66 static const struct trie_child_entry_f *trie_node_child(sd_hwdb *hwdb, const struct trie_node_f *node, size_t idx) {
67 const char *base = (const char *)node;
68
69 base += le64toh(hwdb->head->node_size);
70 base += idx * le64toh(hwdb->head->child_entry_size);
71 return (const struct trie_child_entry_f *)base;
72 }
73
74 static const struct trie_value_entry_f *trie_node_value(sd_hwdb *hwdb, const struct trie_node_f *node, size_t idx) {
75 const char *base = (const char *)node;
76
77 base += le64toh(hwdb->head->node_size);
78 base += node->children_count * le64toh(hwdb->head->child_entry_size);
79 base += idx * le64toh(hwdb->head->value_entry_size);
80 return (const struct trie_value_entry_f *)base;
81 }
82
83 static const void* hwdb_at(sd_hwdb *hwdb, uint64_t off, uint64_t size) {
84 assert(hwdb);
85
86 uint64_t file_size = hwdb->st.st_size;
87
88 /* off == file_size is rejected too: a read at EOF is always OOB, and this keeps the
89 * boundary unambiguous even for a size == 0 caller (which would otherwise get a
90 * one-past-the-end pointer). */
91 if (off >= file_size)
92 return NULL;
93 if (file_size - off < size)
94 return NULL;
95
96 return (const uint8_t*) hwdb->map + off;
97 }
98
99 static const struct trie_node_f* trie_node_from_off(sd_hwdb *hwdb, le64_t off) {
100 assert(hwdb);
101 assert(hwdb->head);
102
103 uint64_t offset = le64toh(off);
104 uint64_t node_size = le64toh(hwdb->head->node_size);
105 uint64_t child_entry_size = le64toh(hwdb->head->child_entry_size);
106 uint64_t value_entry_size = le64toh(hwdb->head->value_entry_size);
107
108 if (node_size < sizeof(struct trie_node_f))
109 return NULL;
110 if (child_entry_size < sizeof(struct trie_child_entry_f))
111 return NULL;
112 if (value_entry_size < sizeof(struct trie_value_entry_f))
113 return NULL;
114
115 const struct trie_node_f *node = hwdb_at(hwdb, offset, node_size);
116 if (!node)
117 return NULL;
118
119 uint64_t children_bytes, values_bytes, total;
120 if (!MUL_SAFE(&children_bytes, (uint64_t) node->children_count, child_entry_size))
121 return NULL;
122 if (!MUL_SAFE(&values_bytes, le64toh(node->values_count), value_entry_size))
123 return NULL;
124 if (!ADD_SAFE(&total, node_size, children_bytes))
125 return NULL;
126 if (!INC_SAFE(&total, values_bytes))
127 return NULL;
128
129 if (!hwdb_at(hwdb, offset, total))
130 return NULL;
131
132 return node;
133 }
134
135 static const char* trie_string(sd_hwdb *hwdb, le64_t off) {
136 assert(hwdb);
137
138 uint64_t file_size = hwdb->st.st_size;
139 uint64_t offset = le64toh(off);
140
141 const char *p = hwdb_at(hwdb, offset, /* size= */ 1);
142 if (!p)
143 return NULL;
144
145 /* Clamp to SIZE_MAX so memchr()'s size_t arg cannot truncate on 32-bit. */
146 size_t avail = (size_t) MIN(file_size - offset, (uint64_t) SIZE_MAX);
147 if (!memchr(p, '\0', avail))
148 return NULL;
149
150 return p;
151 }
152
153 static int trie_children_cmp_f(const void *v1, const void *v2) {
154 const struct trie_child_entry_f *n1 = v1;
155 const struct trie_child_entry_f *n2 = v2;
156
157 return n1->c - n2->c;
158 }
159
160 static const struct trie_node_f *node_lookup_f(sd_hwdb *hwdb, const struct trie_node_f *node, uint8_t c) {
161 const struct trie_child_entry_f *child;
162 struct trie_child_entry_f search;
163
164 search.c = c;
165 child = bsearch(&search, (const char *)node + le64toh(hwdb->head->node_size), node->children_count,
166 le64toh(hwdb->head->child_entry_size), trie_children_cmp_f);
167 if (child)
168 /* Treat corrupt child offsets like lookup misses. */
169 return trie_node_from_off(hwdb, child->child_off);
170
171 return NULL;
172 }
173
174 static int hwdb_add_property(sd_hwdb *hwdb, const struct trie_value_entry_f *entry) {
175 const char *key;
176 int r;
177
178 assert(hwdb);
179
180 key = trie_string(hwdb, entry->key_off);
181 if (!key)
182 return -EBADMSG;
183
184 /*
185 * Silently ignore all properties which do not start with a
186 * space; future extensions might use additional prefixes.
187 */
188 if (key[0] != ' ')
189 return 0;
190
191 key++;
192
193 if (le64toh(hwdb->head->value_entry_size) >= sizeof(struct trie_value_entry2_f)) {
194 const struct trie_value_entry2_f *old, *entry2;
195
196 entry2 = (const struct trie_value_entry2_f *)entry;
197 old = ordered_hashmap_get(hwdb->properties, key);
198 if (old) {
199 /* On duplicates, we order by filename priority and line-number.
200 *
201 * v2 of the format had 64 bits for the line number.
202 * v3 reuses top 32 bits of line_number to store the priority.
203 * We check the top bits — if they are zero we have v2 format.
204 * This means that v2 clients will print wrong line numbers with
205 * v3 data.
206 *
207 * For v3 data: we compare the priority (of the source file)
208 * and the line number.
209 *
210 * For v2 data: we rely on the fact that the filenames in the hwdb
211 * are added in the order of priority (higher later), because they
212 * are *processed* in the order of priority. So we compare the
213 * indices to determine which file had higher priority. Comparing
214 * the strings alphabetically would be useless, because those are
215 * full paths, and e.g. /usr/lib would sort after /etc, even
216 * though it has lower priority. This is not reliable because of
217 * suffix compression, but should work for the most common case of
218 * /usr/lib/udev/hwbd.d and /etc/udev/hwdb.d, and is better than
219 * not doing the comparison at all.
220 */
221 bool lower;
222
223 if (entry2->file_priority == 0)
224 lower = entry2->filename_off < old->filename_off ||
225 (entry2->filename_off == old->filename_off && entry2->line_number < old->line_number);
226 else
227 lower = entry2->file_priority < old->file_priority ||
228 (entry2->file_priority == old->file_priority && entry2->line_number < old->line_number);
229 if (lower)
230 return 0;
231 }
232 }
233
234 r = ordered_hashmap_ensure_replace(&hwdb->properties, &string_hash_ops, key, (void *) entry);
235 if (r < 0)
236 return r;
237
238 hwdb->properties_modified = true;
239
240 return 0;
241 }
242
243 /* Cap recursion depth so a corrupt hwdb.bin whose children offsets form a
244 * cycle (or just a deep linear chain) cannot exhaust the stack. Real-world
245 * hwdb files do not approach this; the deepest legitimate trie key is well
246 * under a kilobyte. */
247 #define HWDB_RECURSION_MAX 2048U
248
249 static int trie_fnmatch_f(sd_hwdb *hwdb, const struct trie_node_f *node, size_t p,
250 struct linebuf *buf, const char *search, unsigned depth) {
251 size_t len;
252 size_t i;
253 const char *prefix;
254 int err;
255
256 assert(hwdb);
257 assert(node);
258
259 if (depth >= HWDB_RECURSION_MAX)
260 return -EBADMSG;
261
262 prefix = trie_string(hwdb, node->prefix_off);
263 if (!prefix)
264 return -EBADMSG;
265
266 len = strlen(prefix);
267 if (p > len)
268 return -EBADMSG;
269 len -= p;
270
271 if (!linebuf_add(buf, prefix + p, len))
272 return -EINVAL;
273
274 for (i = 0; i < node->children_count; i++) {
275 const struct trie_child_entry_f *child = trie_node_child(hwdb, node, i);
276 const struct trie_node_f *child_node;
277
278 linebuf_add_char(buf, child->c);
279 child_node = trie_node_from_off(hwdb, child->child_off);
280 if (!child_node)
281 return -EBADMSG;
282
283 err = trie_fnmatch_f(hwdb, child_node, 0, buf, search, depth + 1);
284 if (err < 0)
285 return err;
286 linebuf_rem_char(buf);
287 }
288
289 if (le64toh(node->values_count) != 0) {
290 const char *line = linebuf_get(buf);
291 if (!line)
292 return -EBADMSG;
293
294 if (fnmatch(line, search, 0) == 0)
295 for (i = 0; i < le64toh(node->values_count); i++) {
296 err = hwdb_add_property(hwdb, trie_node_value(hwdb, node, i));
297 if (err < 0)
298 return err;
299 }
300 }
301
302 linebuf_rem(buf, len);
303 return 0;
304 }
305
306 static int trie_search_f(sd_hwdb *hwdb, const char *search) {
307 struct linebuf buf;
308 const struct trie_node_f *node;
309 size_t i = 0;
310 int err;
311
312 linebuf_init(&buf);
313
314 node = trie_node_from_off(hwdb, hwdb->head->nodes_root_off);
315 if (!node)
316 return -EBADMSG;
317
318 while (node) {
319 const struct trie_node_f *child;
320 size_t p = 0;
321
322 if (node->prefix_off) {
323 const char *prefix;
324 char c;
325
326 prefix = trie_string(hwdb, node->prefix_off);
327 if (!prefix)
328 return -EBADMSG;
329
330 for (; (c = prefix[p]); p++) {
331 if (IN_SET(c, '*', '?', '['))
332 return trie_fnmatch_f(hwdb, node, p, &buf, search + i + p, 0);
333 if (c != search[i + p])
334 return 0;
335 }
336 i += p;
337 }
338
339 child = node_lookup_f(hwdb, node, '*');
340 if (child) {
341 linebuf_add_char(&buf, '*');
342 err = trie_fnmatch_f(hwdb, child, 0, &buf, search + i, 0);
343 if (err < 0)
344 return err;
345 linebuf_rem_char(&buf);
346 }
347
348 child = node_lookup_f(hwdb, node, '?');
349 if (child) {
350 linebuf_add_char(&buf, '?');
351 err = trie_fnmatch_f(hwdb, child, 0, &buf, search + i, 0);
352 if (err < 0)
353 return err;
354 linebuf_rem_char(&buf);
355 }
356
357 child = node_lookup_f(hwdb, node, '[');
358 if (child) {
359 linebuf_add_char(&buf, '[');
360 err = trie_fnmatch_f(hwdb, child, 0, &buf, search + i, 0);
361 if (err < 0)
362 return err;
363 linebuf_rem_char(&buf);
364 }
365
366 if (search[i] == '\0') {
367 size_t n;
368
369 for (n = 0; n < le64toh(node->values_count); n++) {
370 err = hwdb_add_property(hwdb, trie_node_value(hwdb, node, n));
371 if (err < 0)
372 return err;
373 }
374 return 0;
375 }
376
377 child = node_lookup_f(hwdb, node, search[i]);
378 node = child;
379 i++;
380 }
381 return 0;
382 }
383
384 static int hwdb_new(const char *path, sd_hwdb **ret) {
385 _cleanup_(sd_hwdb_unrefp) sd_hwdb *hwdb = NULL;
386 const char sig[] = HWDB_SIG;
387
388 assert_return(ret, -EINVAL);
389
390 hwdb = new0(sd_hwdb, 1);
391 if (!hwdb)
392 return -ENOMEM;
393
394 hwdb->n_ref = 1;
395
396 /* Find hwdb.bin in the explicit path if provided, or iterate over HWDB_BIN_PATHS otherwise */
397 if (!isempty(path)) {
398 log_debug("Trying to open \"%s\"...", path);
399 hwdb->f = fopen(path, "re");
400 if (!hwdb->f)
401 return log_debug_errno(errno, "Failed to open %s: %m", path);
402 } else {
403 NULSTR_FOREACH(p, HWDB_BIN_PATHS) {
404 log_debug("Trying to open \"%s\"...", p);
405 hwdb->f = fopen(p, "re");
406 if (hwdb->f) {
407 path = p;
408 break;
409 }
410 if (errno != ENOENT)
411 return log_debug_errno(errno, "Failed to open %s: %m", p);
412 }
413
414 if (!hwdb->f)
415 return log_debug_errno(SYNTHETIC_ERRNO(ENOENT),
416 "hwdb.bin does not exist, please run 'systemd-hwdb update'.");
417 }
418
419 if (fstat(fileno(hwdb->f), &hwdb->st) < 0)
420 return log_debug_errno(errno, "Failed to stat %s: %m", path);
421 if (hwdb->st.st_size < (off_t) offsetof(struct trie_header_f, strings_len) + 8)
422 return log_debug_errno(SYNTHETIC_ERRNO(EIO), "File %s is too short.", path);
423 if (file_offset_beyond_memory_size(hwdb->st.st_size))
424 return log_debug_errno(SYNTHETIC_ERRNO(EFBIG), "File %s is too long.", path);
425
426 hwdb->map = mmap(NULL, hwdb->st.st_size, PROT_READ, MAP_SHARED, fileno(hwdb->f), 0);
427 if (hwdb->map == MAP_FAILED)
428 return log_debug_errno(errno, "Failed to map %s: %m", path);
429
430 if (memcmp(hwdb->map, sig, sizeof(hwdb->head->signature)) != 0 ||
431 (size_t) hwdb->st.st_size != le64toh(hwdb->head->file_size))
432 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
433 "Failed to recognize the format of %s.", path);
434
435 log_debug("=== trie on-disk ===");
436 log_debug("tool version: %"PRIu64, le64toh(hwdb->head->tool_version));
437 log_debug("file size: %8"PRIi64" bytes", hwdb->st.st_size);
438 log_debug("header size %8"PRIu64" bytes", le64toh(hwdb->head->header_size));
439 log_debug("strings %8"PRIu64" bytes", le64toh(hwdb->head->strings_len));
440 log_debug("nodes %8"PRIu64" bytes", le64toh(hwdb->head->nodes_len));
441
442 *ret = TAKE_PTR(hwdb);
443
444 return 0;
445 }
446
447 _public_ int sd_hwdb_new_from_path(const char *path, sd_hwdb **ret) {
448 assert_return(!isempty(path), -EINVAL);
449
450 return hwdb_new(path, ret);
451 }
452
453 _public_ int sd_hwdb_new(sd_hwdb **ret) {
454 return hwdb_new(NULL, ret);
455 }
456
457 static sd_hwdb *hwdb_free(sd_hwdb *hwdb) {
458 assert(hwdb);
459
460 if (hwdb->map)
461 munmap((void *)hwdb->map, hwdb->st.st_size);
462 safe_fclose(hwdb->f);
463 ordered_hashmap_free(hwdb->properties);
464 return mfree(hwdb);
465 }
466
467 DEFINE_PUBLIC_TRIVIAL_REF_UNREF_FUNC(sd_hwdb, sd_hwdb, hwdb_free)
468
469 static int properties_prepare(sd_hwdb *hwdb, const char *modalias) {
470 assert(hwdb);
471 assert(modalias);
472
473 ordered_hashmap_clear(hwdb->properties);
474 hwdb->properties_modified = true;
475
476 return trie_search_f(hwdb, modalias);
477 }
478
479 _public_ int sd_hwdb_get(sd_hwdb *hwdb, const char *modalias, const char *key, const char **ret) {
480 const struct trie_value_entry_f *entry;
481 const char *value;
482 int r;
483
484 assert_return(hwdb, -EINVAL);
485 assert_return(hwdb->f, -EINVAL);
486 assert_return(modalias, -EINVAL);
487 assert_return(ret, -EINVAL);
488
489 r = properties_prepare(hwdb, modalias);
490 if (r < 0)
491 return r;
492
493 entry = ordered_hashmap_get(hwdb->properties, key);
494 if (!entry)
495 return -ENOENT;
496
497 value = trie_string(hwdb, entry->value_off);
498 if (!value)
499 return -EBADMSG;
500
501 *ret = value;
502
503 return 0;
504 }
505
506 _public_ int sd_hwdb_seek(sd_hwdb *hwdb, const char *modalias) {
507 int r;
508
509 assert_return(hwdb, -EINVAL);
510 assert_return(hwdb->f, -EINVAL);
511 assert_return(modalias, -EINVAL);
512
513 r = properties_prepare(hwdb, modalias);
514 if (r < 0)
515 return r;
516
517 hwdb->properties_modified = false;
518 hwdb->properties_iterator = ITERATOR_FIRST;
519
520 return 0;
521 }
522
523 _public_ int sd_hwdb_enumerate(sd_hwdb *hwdb, const char **ret_key, const char **ret_value) {
524 const struct trie_value_entry_f *entry;
525 const char *v;
526 const void *k;
527
528 assert_return(hwdb, -EINVAL);
529 assert_return(ret_key, -EINVAL);
530 assert_return(ret_value, -EINVAL);
531
532 if (hwdb->properties_modified)
533 return -EAGAIN;
534
535 if (!ordered_hashmap_iterate(hwdb->properties, &hwdb->properties_iterator, (void **)&entry, &k))
536 return 0;
537
538 v = trie_string(hwdb, entry->value_off);
539 if (!v)
540 return -EBADMSG;
541
542 *ret_key = k;
543 *ret_value = v;
544
545 return 1;
546 }