chiark / gitweb /
include <poll.h> instead of <sys/poll.h>
[elogind.git] / src / hwdb / hwdb.c
1 /***
2   This file is part of systemd.
3
4   Copyright 2012 Kay Sievers <kay@vrfy.org>
5
6   systemd is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as published by
8   the Free Software Foundation; either version 2.1 of the License, or
9   (at your option) any later version.
10
11   systemd is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   Lesser General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <getopt.h>
23 #include <string.h>
24 #include <ctype.h>
25
26 #include "util.h"
27 #include "strbuf.h"
28 #include "conf-files.h"
29 #include "strv.h"
30 #include "mkdir.h"
31 #include "fileio.h"
32 #include "verbs.h"
33 #include "build.h"
34
35 #include "hwdb-internal.h"
36 #include "hwdb-util.h"
37
38 /*
39  * Generic udev properties, key/value database based on modalias strings.
40  * Uses a Patricia/radix trie to index all matches for efficient lookup.
41  */
42
43 static const char *arg_hwdb_bin_dir = "/etc/udev";
44 static const char *arg_root = "";
45
46 static const char * const conf_file_dirs[] = {
47         "/etc/udev/hwdb.d",
48         UDEVLIBEXECDIR "/hwdb.d",
49         NULL
50 };
51
52 /* in-memory trie objects */
53 struct trie {
54         struct trie_node *root;
55         struct strbuf *strings;
56
57         size_t nodes_count;
58         size_t children_count;
59         size_t values_count;
60 };
61
62 struct trie_node {
63         /* prefix, common part for all children of this node */
64         size_t prefix_off;
65
66         /* sorted array of pointers to children nodes */
67         struct trie_child_entry *children;
68         uint8_t children_count;
69
70         /* sorted array of key/value pairs */
71         struct trie_value_entry *values;
72         size_t values_count;
73 };
74
75 /* children array item with char (0-255) index */
76 struct trie_child_entry {
77         uint8_t c;
78         struct trie_node *child;
79 };
80
81 /* value array item with key/value pairs */
82 struct trie_value_entry {
83         size_t key_off;
84         size_t value_off;
85 };
86
87 static int trie_children_cmp(const void *v1, const void *v2) {
88         const struct trie_child_entry *n1 = v1;
89         const struct trie_child_entry *n2 = v2;
90
91         return n1->c - n2->c;
92 }
93
94 static int node_add_child(struct trie *trie, struct trie_node *node, struct trie_node *node_child, uint8_t c) {
95         struct trie_child_entry *child;
96
97         /* extend array, add new entry, sort for bisection */
98         child = realloc(node->children, (node->children_count + 1) * sizeof(struct trie_child_entry));
99         if (!child)
100                 return -ENOMEM;
101
102         node->children = child;
103         trie->children_count++;
104         node->children[node->children_count].c = c;
105         node->children[node->children_count].child = node_child;
106         node->children_count++;
107         qsort(node->children, node->children_count, sizeof(struct trie_child_entry), trie_children_cmp);
108         trie->nodes_count++;
109
110         return 0;
111 }
112
113 static struct trie_node *node_lookup(const struct trie_node *node, uint8_t c) {
114         struct trie_child_entry *child;
115         struct trie_child_entry search;
116
117         search.c = c;
118         child = bsearch(&search, node->children, node->children_count, sizeof(struct trie_child_entry), trie_children_cmp);
119         if (child)
120                 return child->child;
121         return NULL;
122 }
123
124 static void trie_node_cleanup(struct trie_node *node) {
125         size_t i;
126
127         for (i = 0; i < node->children_count; i++)
128                 trie_node_cleanup(node->children[i].child);
129         free(node->children);
130         free(node->values);
131         free(node);
132 }
133
134 static void trie_free(struct trie *trie) {
135         if (!trie)
136                 return;
137
138         if (trie->root)
139                 trie_node_cleanup(trie->root);
140
141         strbuf_cleanup(trie->strings);
142         free(trie);
143 }
144
145 DEFINE_TRIVIAL_CLEANUP_FUNC(struct trie*, trie_free);
146
147 static int trie_values_cmp(const void *v1, const void *v2, void *arg) {
148         const struct trie_value_entry *val1 = v1;
149         const struct trie_value_entry *val2 = v2;
150         struct trie *trie = arg;
151
152         return strcmp(trie->strings->buf + val1->key_off,
153                       trie->strings->buf + val2->key_off);
154 }
155
156 static int trie_node_add_value(struct trie *trie, struct trie_node *node,
157                           const char *key, const char *value) {
158         ssize_t k, v;
159         struct trie_value_entry *val;
160
161         k = strbuf_add_string(trie->strings, key, strlen(key));
162         if (k < 0)
163                 return k;
164         v = strbuf_add_string(trie->strings, value, strlen(value));
165         if (v < 0)
166                 return v;
167
168         if (node->values_count) {
169                 struct trie_value_entry search = {
170                         .key_off = k,
171                         .value_off = v,
172                 };
173
174                 val = xbsearch_r(&search, node->values, node->values_count, sizeof(struct trie_value_entry), trie_values_cmp, trie);
175                 if (val) {
176                         /* replace existing earlier key with new value */
177                         val->value_off = v;
178                         return 0;
179                 }
180         }
181
182         /* extend array, add new entry, sort for bisection */
183         val = realloc(node->values, (node->values_count + 1) * sizeof(struct trie_value_entry));
184         if (!val)
185                 return -ENOMEM;
186         trie->values_count++;
187         node->values = val;
188         node->values[node->values_count].key_off = k;
189         node->values[node->values_count].value_off = v;
190         node->values_count++;
191         qsort_r(node->values, node->values_count, sizeof(struct trie_value_entry), trie_values_cmp, trie);
192         return 0;
193 }
194
195 static int trie_insert(struct trie *trie, struct trie_node *node, const char *search,
196                        const char *key, const char *value) {
197         size_t i = 0;
198         int err = 0;
199
200         for (;;) {
201                 size_t p;
202                 uint8_t c;
203                 struct trie_node *child;
204
205                 for (p = 0; (c = trie->strings->buf[node->prefix_off + p]); p++) {
206                         _cleanup_free_ char *s = NULL;
207                         ssize_t off;
208                         _cleanup_free_ struct trie_node *new_child = NULL;
209
210                         if (c == search[i + p])
211                                 continue;
212
213                         /* split node */
214                         new_child = new0(struct trie_node, 1);
215                         if (!new_child)
216                                 return -ENOMEM;
217
218                         /* move values from parent to child */
219                         new_child->prefix_off = node->prefix_off + p+1;
220                         new_child->children = node->children;
221                         new_child->children_count = node->children_count;
222                         new_child->values = node->values;
223                         new_child->values_count = node->values_count;
224
225                         /* update parent; use strdup() because the source gets realloc()d */
226                         s = strndup(trie->strings->buf + node->prefix_off, p);
227                         if (!s)
228                                 return -ENOMEM;
229
230                         off = strbuf_add_string(trie->strings, s, p);
231                         if (off < 0)
232                                 return off;
233
234                         node->prefix_off = off;
235                         node->children = NULL;
236                         node->children_count = 0;
237                         node->values = NULL;
238                         node->values_count = 0;
239                         err = node_add_child(trie, node, new_child, c);
240                         if (err < 0)
241                                 return err;
242
243                         new_child = NULL; /* avoid cleanup */
244                         break;
245                 }
246                 i += p;
247
248                 c = search[i];
249                 if (c == '\0')
250                         return trie_node_add_value(trie, node, key, value);
251
252                 child = node_lookup(node, c);
253                 if (!child) {
254                         ssize_t off;
255
256                         /* new child */
257                         child = new0(struct trie_node, 1);
258                         if (!child)
259                                 return -ENOMEM;
260
261                         off = strbuf_add_string(trie->strings, search + i+1, strlen(search + i+1));
262                         if (off < 0) {
263                                 free(child);
264                                 return off;
265                         }
266
267                         child->prefix_off = off;
268                         err = node_add_child(trie, node, child, c);
269                         if (err < 0) {
270                                 free(child);
271                                 return err;
272                         }
273
274                         return trie_node_add_value(trie, child, key, value);
275                 }
276
277                 node = child;
278                 i++;
279         }
280 }
281
282 struct trie_f {
283         FILE *f;
284         struct trie *trie;
285         uint64_t strings_off;
286
287         uint64_t nodes_count;
288         uint64_t children_count;
289         uint64_t values_count;
290 };
291
292 /* calculate the storage space for the nodes, children arrays, value arrays */
293 static void trie_store_nodes_size(struct trie_f *trie, struct trie_node *node) {
294         uint64_t i;
295
296         for (i = 0; i < node->children_count; i++)
297                 trie_store_nodes_size(trie, node->children[i].child);
298
299         trie->strings_off += sizeof(struct trie_node_f);
300         for (i = 0; i < node->children_count; i++)
301                 trie->strings_off += sizeof(struct trie_child_entry_f);
302         for (i = 0; i < node->values_count; i++)
303                 trie->strings_off += sizeof(struct trie_value_entry_f);
304 }
305
306 static int64_t trie_store_nodes(struct trie_f *trie, struct trie_node *node) {
307         uint64_t i;
308         struct trie_node_f n = {
309                 .prefix_off = htole64(trie->strings_off + node->prefix_off),
310                 .children_count = node->children_count,
311                 .values_count = htole64(node->values_count),
312         };
313         struct trie_child_entry_f *children = NULL;
314         int64_t node_off;
315
316         if (node->children_count) {
317                 children = new0(struct trie_child_entry_f, node->children_count);
318                 if (!children)
319                         return -ENOMEM;
320         }
321
322         /* post-order recursion */
323         for (i = 0; i < node->children_count; i++) {
324                 int64_t child_off;
325
326                 child_off = trie_store_nodes(trie, node->children[i].child);
327                 if (child_off < 0) {
328                         free(children);
329                         return child_off;
330                 }
331                 children[i].c = node->children[i].c;
332                 children[i].child_off = htole64(child_off);
333         }
334
335         /* write node */
336         node_off = ftello(trie->f);
337         fwrite(&n, sizeof(struct trie_node_f), 1, trie->f);
338         trie->nodes_count++;
339
340         /* append children array */
341         if (node->children_count) {
342                 fwrite(children, sizeof(struct trie_child_entry_f), node->children_count, trie->f);
343                 trie->children_count += node->children_count;
344                 free(children);
345         }
346
347         /* append values array */
348         for (i = 0; i < node->values_count; i++) {
349                 struct trie_value_entry_f v = {
350                         .key_off = htole64(trie->strings_off + node->values[i].key_off),
351                         .value_off = htole64(trie->strings_off + node->values[i].value_off),
352                 };
353
354                 fwrite(&v, sizeof(struct trie_value_entry_f), 1, trie->f);
355                 trie->values_count++;
356         }
357
358         return node_off;
359 }
360
361 static int trie_store(struct trie *trie, const char *filename) {
362         struct trie_f t = {
363                 .trie = trie,
364         };
365         _cleanup_free_ char *filename_tmp = NULL;
366         int64_t pos;
367         int64_t root_off;
368         int64_t size;
369         struct trie_header_f h = {
370                 .signature = HWDB_SIG,
371                 .tool_version = htole64(atoi(VERSION)),
372                 .header_size = htole64(sizeof(struct trie_header_f)),
373                 .node_size = htole64(sizeof(struct trie_node_f)),
374                 .child_entry_size = htole64(sizeof(struct trie_child_entry_f)),
375                 .value_entry_size = htole64(sizeof(struct trie_value_entry_f)),
376         };
377         int err;
378
379         /* calculate size of header, nodes, children entries, value entries */
380         t.strings_off = sizeof(struct trie_header_f);
381         trie_store_nodes_size(&t, trie->root);
382
383         err = fopen_temporary(filename , &t.f, &filename_tmp);
384         if (err < 0)
385                 return err;
386         fchmod(fileno(t.f), 0444);
387
388         /* write nodes */
389         err = fseeko(t.f, sizeof(struct trie_header_f), SEEK_SET);
390         if (err < 0) {
391                 fclose(t.f);
392                 unlink_noerrno(filename_tmp);
393                 return -errno;
394         }
395         root_off = trie_store_nodes(&t, trie->root);
396         h.nodes_root_off = htole64(root_off);
397         pos = ftello(t.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, t.f);
402         h.strings_len = htole64(trie->strings->len);
403
404         /* write header */
405         size = ftello(t.f);
406         h.file_size = htole64(size);
407         err = fseeko(t.f, 0, SEEK_SET);
408         if (err < 0) {
409                 fclose(t.f);
410                 unlink_noerrno(filename_tmp);
411                 return -errno;
412         }
413         fwrite(&h, sizeof(struct trie_header_f), 1, t.f);
414         err = ferror(t.f);
415         if (err)
416                 err = -errno;
417         fclose(t.f);
418         if (err < 0 || rename(filename_tmp, filename) < 0) {
419                 unlink_noerrno(filename_tmp);
420                 return err < 0 ? err : -errno;
421         }
422
423         log_debug("=== trie on-disk ===");
424         log_debug("size:             %8"PRIi64" bytes", size);
425         log_debug("header:           %8zu bytes", sizeof(struct trie_header_f));
426         log_debug("nodes:            %8"PRIu64" bytes (%8"PRIu64")",
427                   t.nodes_count * sizeof(struct trie_node_f), t.nodes_count);
428         log_debug("child pointers:   %8"PRIu64" bytes (%8"PRIu64")",
429                   t.children_count * sizeof(struct trie_child_entry_f), t.children_count);
430         log_debug("value pointers:   %8"PRIu64" bytes (%8"PRIu64")",
431                   t.values_count * sizeof(struct trie_value_entry_f), t.values_count);
432         log_debug("string store:     %8zu bytes", trie->strings->len);
433         log_debug("strings start:    %8"PRIu64, t.strings_off);
434
435         return 0;
436 }
437
438 static int insert_data(struct trie *trie, char **match_list, char *line, const char *filename) {
439         char *value, **entry;
440
441         value = strchr(line, '=');
442         if (!value) {
443                 log_error("Error, key/value pair expected but got '%s' in '%s':", line, filename);
444                 return -EINVAL;
445         }
446
447         value[0] = '\0';
448         value++;
449
450         /* libudev requires properties to start with a space */
451         while (isblank(line[0]) && isblank(line[1]))
452                 line++;
453
454         if (line[0] == '\0' || value[0] == '\0') {
455                 log_error("Error, empty key or value '%s' in '%s':", line, filename);
456                 return -EINVAL;
457         }
458
459         STRV_FOREACH(entry, match_list)
460                 trie_insert(trie, trie->root, *entry, line, value);
461
462         return 0;
463 }
464
465 static int import_file(struct trie *trie, const char *filename) {
466         enum {
467                 HW_NONE,
468                 HW_MATCH,
469                 HW_DATA,
470         } state = HW_NONE;
471         _cleanup_fclose_ FILE *f = NULL;
472         char line[LINE_MAX];
473         _cleanup_strv_free_ char **match_list = NULL;
474         char *match = NULL;
475         int r;
476
477         f = fopen(filename, "re");
478         if (!f)
479                 return -errno;
480
481         while (fgets(line, sizeof(line), f)) {
482                 size_t len;
483                 char *pos;
484
485                 /* comment line */
486                 if (line[0] == '#')
487                         continue;
488
489                 /* strip trailing comment */
490                 pos = strchr(line, '#');
491                 if (pos)
492                         pos[0] = '\0';
493
494                 /* strip trailing whitespace */
495                 len = strlen(line);
496                 while (len > 0 && isspace(line[len-1]))
497                         len--;
498                 line[len] = '\0';
499
500                 switch (state) {
501                 case HW_NONE:
502                         if (len == 0)
503                                 break;
504
505                         if (line[0] == ' ') {
506                                 log_error("Error, MATCH expected but got '%s' in '%s':", line, filename);
507                                 break;
508                         }
509
510                         /* start of record, first match */
511                         state = HW_MATCH;
512
513                         match = strdup(line);
514                         if (!match)
515                                 return -ENOMEM;
516
517                         r = strv_consume(&match_list, match);
518                         if (r < 0)
519                                 return r;
520
521                         break;
522
523                 case HW_MATCH:
524                         if (len == 0) {
525                                 log_error("Error, DATA expected but got empty line in '%s':", filename);
526                                 state = HW_NONE;
527                                 strv_clear(match_list);
528                                 break;
529                         }
530
531                         /* another match */
532                         if (line[0] != ' ') {
533                                 match = strdup(line);
534                                 if (!match)
535                                         return -ENOMEM;
536
537                                 r = strv_consume(&match_list, match);
538                                 if (r < 0)
539                                         return r;
540
541                                 break;
542                         }
543
544                         /* first data */
545                         state = HW_DATA;
546                         insert_data(trie, match_list, line, filename);
547                         break;
548
549                 case HW_DATA:
550                         /* end of record */
551                         if (len == 0) {
552                                 state = HW_NONE;
553                                 strv_clear(match_list);
554                                 break;
555                         }
556
557                         if (line[0] != ' ') {
558                                 log_error("Error, DATA expected but got '%s' in '%s':", line, filename);
559                                 state = HW_NONE;
560                                 strv_clear(match_list);
561                                 break;
562                         }
563
564                         insert_data(trie, match_list, line, filename);
565                         break;
566                 };
567         }
568
569         return 0;
570 }
571
572 static int hwdb_query(int argc, char *argv[], void *userdata) {
573         _cleanup_hwdb_unref_ sd_hwdb *hwdb = NULL;
574         const char *key, *value;
575         const char *modalias;
576         int r;
577
578         assert(argc >= 2);
579         assert(argv);
580
581         modalias = argv[1];
582
583         r = sd_hwdb_new(&hwdb);
584         if (r < 0)
585                 return r;
586
587         SD_HWDB_FOREACH_PROPERTY(hwdb, modalias, key, value)
588                 printf("%s=%s\n", key, value);
589
590         return 0;
591 }
592
593 static int hwdb_update(int argc, char *argv[], void *userdata) {
594         _cleanup_free_ char *hwdb_bin = NULL;
595         _cleanup_(trie_freep) struct trie *trie = NULL;
596         char **files, **f;
597         int r;
598
599         trie = new0(struct trie, 1);
600         if (!trie)
601                 return -ENOMEM;
602
603         /* string store */
604         trie->strings = strbuf_new();
605         if (!trie->strings)
606                 return -ENOMEM;
607
608         /* index */
609         trie->root = new0(struct trie_node, 1);
610         if (!trie->root)
611                 return -ENOMEM;
612
613         trie->nodes_count++;
614
615         r = conf_files_list_strv(&files, ".hwdb", arg_root, conf_file_dirs);
616         if (r < 0)
617                 return log_error_errno(r, "failed to enumerate hwdb files: %m");
618
619         STRV_FOREACH(f, files) {
620                 log_debug("reading file '%s'", *f);
621                 import_file(trie, *f);
622         }
623         strv_free(files);
624
625         strbuf_complete(trie->strings);
626
627         log_debug("=== trie in-memory ===");
628         log_debug("nodes:            %8zu bytes (%8zu)",
629                   trie->nodes_count * sizeof(struct trie_node), trie->nodes_count);
630         log_debug("children arrays:  %8zu bytes (%8zu)",
631                   trie->children_count * sizeof(struct trie_child_entry), trie->children_count);
632         log_debug("values arrays:    %8zu bytes (%8zu)",
633                   trie->values_count * sizeof(struct trie_value_entry), trie->values_count);
634         log_debug("strings:          %8zu bytes",
635                   trie->strings->len);
636         log_debug("strings incoming: %8zu bytes (%8zu)",
637                   trie->strings->in_len, trie->strings->in_count);
638         log_debug("strings dedup'ed: %8zu bytes (%8zu)",
639                   trie->strings->dedup_len, trie->strings->dedup_count);
640
641         hwdb_bin = strjoin(arg_root, "/", arg_hwdb_bin_dir, "/hwdb.bin", NULL);
642         if (!hwdb_bin)
643                 return -ENOMEM;
644
645         mkdir_parents(hwdb_bin, 0755);
646         r = trie_store(trie, hwdb_bin);
647         if (r < 0)
648                 return log_error_errno(r, "Failure writing database %s: %m", hwdb_bin);
649
650         return 0;
651 }
652
653 static void help(void) {
654         printf("Usage: %s OPTIONS COMMAND\n\n"
655                "Update or query the hardware database.\n\n"
656                "  -h --help            Show this help\n"
657                "     --version         Show package version\n"
658                "     --usr             Generate in " UDEVLIBEXECDIR " instead of /etc/udev\n"
659                "  -r --root=PATH       Alternative root path in the filesystem\n\n"
660                "Commands:\n"
661                "  update               Update the hwdb database\n"
662                "  query MODALIAS       Query database and print result\n",
663                program_invocation_short_name);
664 }
665
666 static int parse_argv(int argc, char *argv[]) {
667         enum {
668                 ARG_VERSION = 0x100,
669                 ARG_USR,
670         };
671
672         static const struct option options[] = {
673                 { "help",     no_argument,       NULL, 'h'         },
674                 { "version",  no_argument,       NULL, ARG_VERSION },
675                 { "usr",      no_argument,       NULL, ARG_USR     },
676                 { "root",     required_argument, NULL, 'r'         },
677                 {}
678         };
679
680         int c;
681
682         assert(argc >= 0);
683         assert(argv);
684
685         while ((c = getopt_long(argc, argv, "ut:r:h", options, NULL)) >= 0) {
686                 switch(c) {
687
688                 case 'h':
689                         help();
690                         return 0;
691
692                 case ARG_VERSION:
693                         puts(PACKAGE_STRING);
694                         puts(SYSTEMD_FEATURES);
695                         return 0;
696
697                 case ARG_USR:
698                         arg_hwdb_bin_dir = UDEVLIBEXECDIR;
699                         break;
700
701                 case 'r':
702                         arg_root = optarg;
703                         break;
704
705                 case '?':
706                         return -EINVAL;
707
708                 default:
709                         assert_not_reached("Unknown option");
710                 }
711         }
712
713         return 1;
714 }
715
716 static int hwdb_main(int argc, char *argv[]) {
717         const Verb verbs[] = {
718                 { "update", 1, 1, 0, hwdb_update },
719                 { "query",  2, 2, 0, hwdb_query  },
720                 {},
721         };
722
723         return dispatch_verb(argc, argv, verbs, NULL);
724 }
725
726 int main (int argc, char *argv[]) {
727         int r;
728
729         log_parse_environment();
730         log_open();
731
732         r = parse_argv(argc, argv);
733         if (r <= 0)
734                 goto finish;
735
736         r = hwdb_main(argc, argv);
737
738 finish:
739         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
740 }