]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/journal/catalog.c
tree-wide: use typesafe_qsort()
[thirdparty/systemd.git] / src / journal / catalog.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <locale.h>
6 #include <stdio.h>
7 #include <string.h>
8 #include <sys/mman.h>
9 #include <unistd.h>
10
11 #include "sd-id128.h"
12
13 #include "alloc-util.h"
14 #include "catalog.h"
15 #include "conf-files.h"
16 #include "fd-util.h"
17 #include "fileio.h"
18 #include "hashmap.h"
19 #include "log.h"
20 #include "mkdir.h"
21 #include "path-util.h"
22 #include "siphash24.h"
23 #include "sparse-endian.h"
24 #include "strbuf.h"
25 #include "string-util.h"
26 #include "strv.h"
27 #include "util.h"
28
29 const char * const catalog_file_dirs[] = {
30 "/usr/local/lib/systemd/catalog/",
31 "/usr/lib/systemd/catalog/",
32 NULL
33 };
34
35 #define CATALOG_SIGNATURE (uint8_t[]) { 'R', 'H', 'H', 'H', 'K', 'S', 'L', 'P' }
36
37 typedef struct CatalogHeader {
38 uint8_t signature[8]; /* "RHHHKSLP" */
39 le32_t compatible_flags;
40 le32_t incompatible_flags;
41 le64_t header_size;
42 le64_t n_items;
43 le64_t catalog_item_size;
44 } CatalogHeader;
45
46 typedef struct CatalogItem {
47 sd_id128_t id;
48 char language[32];
49 le64_t offset;
50 } CatalogItem;
51
52 static void catalog_hash_func(const void *p, struct siphash *state) {
53 const CatalogItem *i = p;
54
55 siphash24_compress(&i->id, sizeof(i->id), state);
56 siphash24_compress(i->language, strlen(i->language), state);
57 }
58
59 static int catalog_compare_func(const CatalogItem *a, const CatalogItem *b) {
60 unsigned k;
61 int r;
62
63 for (k = 0; k < ELEMENTSOF(b->id.bytes); k++) {
64 r = CMP(a->id.bytes[k], b->id.bytes[k]);
65 if (r != 0)
66 return r;
67 }
68
69 return strcmp(a->language, b->language);
70 }
71
72 const struct hash_ops catalog_hash_ops = {
73 .hash = catalog_hash_func,
74 .compare = (comparison_fn_t) catalog_compare_func,
75 };
76
77 static bool next_header(const char **s) {
78 const char *e;
79
80 e = strchr(*s, '\n');
81
82 /* Unexpected end */
83 if (!e)
84 return false;
85
86 /* End of headers */
87 if (e == *s)
88 return false;
89
90 *s = e + 1;
91 return true;
92 }
93
94 static const char *skip_header(const char *s) {
95 while (next_header(&s))
96 ;
97 return s;
98 }
99
100 static char *combine_entries(const char *one, const char *two) {
101 const char *b1, *b2;
102 size_t l1, l2, n;
103 char *dest, *p;
104
105 /* Find split point of headers to body */
106 b1 = skip_header(one);
107 b2 = skip_header(two);
108
109 l1 = strlen(one);
110 l2 = strlen(two);
111 dest = new(char, l1 + l2 + 1);
112 if (!dest) {
113 log_oom();
114 return NULL;
115 }
116
117 p = dest;
118
119 /* Headers from @one */
120 n = b1 - one;
121 p = mempcpy(p, one, n);
122
123 /* Headers from @two, these will only be found if not present above */
124 n = b2 - two;
125 p = mempcpy(p, two, n);
126
127 /* Body from @one */
128 n = l1 - (b1 - one);
129 if (n > 0) {
130 memcpy(p, b1, n);
131 p += n;
132
133 /* Body from @two */
134 } else {
135 n = l2 - (b2 - two);
136 memcpy(p, b2, n);
137 p += n;
138 }
139
140 assert(p - dest <= (ptrdiff_t)(l1 + l2));
141 p[0] = '\0';
142 return dest;
143 }
144
145 static int finish_item(
146 Hashmap *h,
147 sd_id128_t id,
148 const char *language,
149 char *payload, size_t payload_size) {
150
151 _cleanup_free_ CatalogItem *i = NULL;
152 _cleanup_free_ char *prev = NULL, *combined = NULL;
153
154 assert(h);
155 assert(payload);
156 assert(payload_size > 0);
157
158 i = new0(CatalogItem, 1);
159 if (!i)
160 return log_oom();
161
162 i->id = id;
163 if (language) {
164 assert(strlen(language) > 1 && strlen(language) < 32);
165 strcpy(i->language, language);
166 }
167
168 prev = hashmap_get(h, i);
169 if (prev) {
170 /* Already have such an item, combine them */
171 combined = combine_entries(payload, prev);
172 if (!combined)
173 return log_oom();
174
175 if (hashmap_update(h, i, combined) < 0)
176 return log_oom();
177 combined = NULL;
178 } else {
179 /* A new item */
180 combined = memdup(payload, payload_size + 1);
181 if (!combined)
182 return log_oom();
183
184 if (hashmap_put(h, i, combined) < 0)
185 return log_oom();
186 i = NULL;
187 combined = NULL;
188 }
189
190 return 0;
191 }
192
193 int catalog_file_lang(const char* filename, char **lang) {
194 char *beg, *end, *_lang;
195
196 end = endswith(filename, ".catalog");
197 if (!end)
198 return 0;
199
200 beg = end - 1;
201 while (beg > filename && !IN_SET(*beg, '.', '/') && end - beg < 32)
202 beg--;
203
204 if (*beg != '.' || end <= beg + 1)
205 return 0;
206
207 _lang = strndup(beg + 1, end - beg - 1);
208 if (!_lang)
209 return -ENOMEM;
210
211 *lang = _lang;
212 return 1;
213 }
214
215 static int catalog_entry_lang(const char* filename, int line,
216 const char* t, const char* deflang, char **lang) {
217 size_t c;
218
219 c = strlen(t);
220 if (c == 0) {
221 log_error("[%s:%u] Language too short.", filename, line);
222 return -EINVAL;
223 }
224 if (c > 31) {
225 log_error("[%s:%u] language too long.", filename, line);
226 return -EINVAL;
227 }
228
229 if (deflang) {
230 if (streq(t, deflang)) {
231 log_warning("[%s:%u] language specified unnecessarily",
232 filename, line);
233 return 0;
234 } else
235 log_warning("[%s:%u] language differs from default for file",
236 filename, line);
237 }
238
239 *lang = strdup(t);
240 if (!*lang)
241 return -ENOMEM;
242
243 return 0;
244 }
245
246 int catalog_import_file(Hashmap *h, const char *path) {
247 _cleanup_fclose_ FILE *f = NULL;
248 _cleanup_free_ char *payload = NULL;
249 size_t payload_size = 0, payload_allocated = 0;
250 unsigned n = 0;
251 sd_id128_t id;
252 _cleanup_free_ char *deflang = NULL, *lang = NULL;
253 bool got_id = false, empty_line = true;
254 int r;
255
256 assert(h);
257 assert(path);
258
259 f = fopen(path, "re");
260 if (!f)
261 return log_error_errno(errno, "Failed to open file %s: %m", path);
262
263 r = catalog_file_lang(path, &deflang);
264 if (r < 0)
265 log_error_errno(r, "Failed to determine language for file %s: %m", path);
266 if (r == 1)
267 log_debug("File %s has language %s.", path, deflang);
268
269 for (;;) {
270 char line[LINE_MAX];
271 size_t line_len;
272
273 if (!fgets(line, sizeof(line), f)) {
274 if (feof(f))
275 break;
276
277 return log_error_errno(errno, "Failed to read file %s: %m", path);
278 }
279
280 n++;
281
282 truncate_nl(line);
283
284 if (line[0] == 0) {
285 empty_line = true;
286 continue;
287 }
288
289 if (strchr(COMMENTS "\n", line[0]))
290 continue;
291
292 if (empty_line &&
293 strlen(line) >= 2+1+32 &&
294 line[0] == '-' &&
295 line[1] == '-' &&
296 line[2] == ' ' &&
297 IN_SET(line[2+1+32], ' ', '\0')) {
298
299 bool with_language;
300 sd_id128_t jd;
301
302 /* New entry */
303
304 with_language = line[2+1+32] != '\0';
305 line[2+1+32] = '\0';
306
307 if (sd_id128_from_string(line + 2 + 1, &jd) >= 0) {
308
309 if (got_id) {
310 if (payload_size == 0) {
311 log_error("[%s:%u] No payload text.", path, n);
312 return -EINVAL;
313 }
314
315 r = finish_item(h, id, lang ?: deflang, payload, payload_size);
316 if (r < 0)
317 return r;
318
319 lang = mfree(lang);
320 payload_size = 0;
321 }
322
323 if (with_language) {
324 char *t;
325
326 t = strstrip(line + 2 + 1 + 32 + 1);
327 r = catalog_entry_lang(path, n, t, deflang, &lang);
328 if (r < 0)
329 return r;
330 }
331
332 got_id = true;
333 empty_line = false;
334 id = jd;
335
336 continue;
337 }
338 }
339
340 /* Payload */
341 if (!got_id) {
342 log_error("[%s:%u] Got payload before ID.", path, n);
343 return -EINVAL;
344 }
345
346 line_len = strlen(line);
347 if (!GREEDY_REALLOC(payload, payload_allocated,
348 payload_size + (empty_line ? 1 : 0) + line_len + 1 + 1))
349 return log_oom();
350
351 if (empty_line)
352 payload[payload_size++] = '\n';
353 memcpy(payload + payload_size, line, line_len);
354 payload_size += line_len;
355 payload[payload_size++] = '\n';
356 payload[payload_size] = '\0';
357
358 empty_line = false;
359 }
360
361 if (got_id) {
362 if (payload_size == 0) {
363 log_error("[%s:%u] No payload text.", path, n);
364 return -EINVAL;
365 }
366
367 r = finish_item(h, id, lang ?: deflang, payload, payload_size);
368 if (r < 0)
369 return r;
370 }
371
372 return 0;
373 }
374
375 static int64_t write_catalog(const char *database, struct strbuf *sb,
376 CatalogItem *items, size_t n) {
377 CatalogHeader header;
378 _cleanup_fclose_ FILE *w = NULL;
379 int r;
380 _cleanup_free_ char *d, *p = NULL;
381 size_t k;
382
383 d = dirname_malloc(database);
384 if (!d)
385 return log_oom();
386
387 r = mkdir_p(d, 0775);
388 if (r < 0)
389 return log_error_errno(r, "Recursive mkdir %s: %m", d);
390
391 r = fopen_temporary(database, &w, &p);
392 if (r < 0)
393 return log_error_errno(r, "Failed to open database for writing: %s: %m",
394 database);
395
396 zero(header);
397 memcpy(header.signature, CATALOG_SIGNATURE, sizeof(header.signature));
398 header.header_size = htole64(ALIGN_TO(sizeof(CatalogHeader), 8));
399 header.catalog_item_size = htole64(sizeof(CatalogItem));
400 header.n_items = htole64(n);
401
402 r = -EIO;
403
404 k = fwrite(&header, 1, sizeof(header), w);
405 if (k != sizeof(header)) {
406 log_error("%s: failed to write header.", p);
407 goto error;
408 }
409
410 k = fwrite(items, 1, n * sizeof(CatalogItem), w);
411 if (k != n * sizeof(CatalogItem)) {
412 log_error("%s: failed to write database.", p);
413 goto error;
414 }
415
416 k = fwrite(sb->buf, 1, sb->len, w);
417 if (k != sb->len) {
418 log_error("%s: failed to write strings.", p);
419 goto error;
420 }
421
422 r = fflush_and_check(w);
423 if (r < 0) {
424 log_error_errno(r, "%s: failed to write database: %m", p);
425 goto error;
426 }
427
428 fchmod(fileno(w), 0644);
429
430 if (rename(p, database) < 0) {
431 r = log_error_errno(errno, "rename (%s -> %s) failed: %m", p, database);
432 goto error;
433 }
434
435 return ftello(w);
436
437 error:
438 (void) unlink(p);
439 return r;
440 }
441
442 int catalog_update(const char* database, const char* root, const char* const* dirs) {
443 _cleanup_strv_free_ char **files = NULL;
444 char **f;
445 _cleanup_(strbuf_cleanupp) struct strbuf *sb = NULL;
446 _cleanup_hashmap_free_free_free_ Hashmap *h = NULL;
447 _cleanup_free_ CatalogItem *items = NULL;
448 ssize_t offset;
449 char *payload;
450 CatalogItem *i;
451 Iterator j;
452 unsigned n;
453 int r;
454 int64_t sz;
455
456 h = hashmap_new(&catalog_hash_ops);
457 sb = strbuf_new();
458 if (!h || !sb)
459 return log_oom();
460
461 r = conf_files_list_strv(&files, ".catalog", root, 0, dirs);
462 if (r < 0)
463 return log_error_errno(r, "Failed to get catalog files: %m");
464
465 STRV_FOREACH(f, files) {
466 log_debug("Reading file '%s'", *f);
467 r = catalog_import_file(h, *f);
468 if (r < 0)
469 return log_error_errno(r, "Failed to import file '%s': %m", *f);
470 }
471
472 if (hashmap_size(h) <= 0) {
473 log_info("No items in catalog.");
474 return 0;
475 } else
476 log_debug("Found %u items in catalog.", hashmap_size(h));
477
478 items = new(CatalogItem, hashmap_size(h));
479 if (!items)
480 return log_oom();
481
482 n = 0;
483 HASHMAP_FOREACH_KEY(payload, i, h, j) {
484 log_debug("Found " SD_ID128_FORMAT_STR ", language %s",
485 SD_ID128_FORMAT_VAL(i->id),
486 isempty(i->language) ? "C" : i->language);
487
488 offset = strbuf_add_string(sb, payload, strlen(payload));
489 if (offset < 0)
490 return log_oom();
491
492 i->offset = htole64((uint64_t) offset);
493 items[n++] = *i;
494 }
495
496 assert(n == hashmap_size(h));
497 typesafe_qsort(items, n, catalog_compare_func);
498
499 strbuf_complete(sb);
500
501 sz = write_catalog(database, sb, items, n);
502 if (sz < 0)
503 return log_error_errno(sz, "Failed to write %s: %m", database);
504
505 log_debug("%s: wrote %u items, with %zu bytes of strings, %"PRIi64" total size.",
506 database, n, sb->len, sz);
507 return 0;
508 }
509
510 static int open_mmap(const char *database, int *_fd, struct stat *_st, void **_p) {
511 const CatalogHeader *h;
512 int fd;
513 void *p;
514 struct stat st;
515
516 assert(_fd);
517 assert(_st);
518 assert(_p);
519
520 fd = open(database, O_RDONLY|O_CLOEXEC);
521 if (fd < 0)
522 return -errno;
523
524 if (fstat(fd, &st) < 0) {
525 safe_close(fd);
526 return -errno;
527 }
528
529 if (st.st_size < (off_t) sizeof(CatalogHeader)) {
530 safe_close(fd);
531 return -EINVAL;
532 }
533
534 p = mmap(NULL, PAGE_ALIGN(st.st_size), PROT_READ, MAP_SHARED, fd, 0);
535 if (p == MAP_FAILED) {
536 safe_close(fd);
537 return -errno;
538 }
539
540 h = p;
541 if (memcmp(h->signature, CATALOG_SIGNATURE, sizeof(h->signature)) != 0 ||
542 le64toh(h->header_size) < sizeof(CatalogHeader) ||
543 le64toh(h->catalog_item_size) < sizeof(CatalogItem) ||
544 h->incompatible_flags != 0 ||
545 le64toh(h->n_items) <= 0 ||
546 st.st_size < (off_t) (le64toh(h->header_size) + le64toh(h->catalog_item_size) * le64toh(h->n_items))) {
547 safe_close(fd);
548 munmap(p, st.st_size);
549 return -EBADMSG;
550 }
551
552 *_fd = fd;
553 *_st = st;
554 *_p = p;
555
556 return 0;
557 }
558
559 static const char *find_id(void *p, sd_id128_t id) {
560 CatalogItem *f = NULL, key = { .id = id };
561 const CatalogHeader *h = p;
562 const char *loc;
563
564 loc = setlocale(LC_MESSAGES, NULL);
565 if (loc && loc[0] && !streq(loc, "C") && !streq(loc, "POSIX")) {
566 strncpy(key.language, loc, sizeof(key.language));
567 key.language[strcspn(key.language, ".@")] = 0;
568
569 f = bsearch(&key, (const uint8_t*) p + le64toh(h->header_size), le64toh(h->n_items), le64toh(h->catalog_item_size), (comparison_fn_t) catalog_compare_func);
570 if (!f) {
571 char *e;
572
573 e = strchr(key.language, '_');
574 if (e) {
575 *e = 0;
576 f = bsearch(&key, (const uint8_t*) p + le64toh(h->header_size), le64toh(h->n_items), le64toh(h->catalog_item_size), (comparison_fn_t) catalog_compare_func);
577 }
578 }
579 }
580
581 if (!f) {
582 zero(key.language);
583 f = bsearch(&key, (const uint8_t*) p + le64toh(h->header_size), le64toh(h->n_items), le64toh(h->catalog_item_size), (comparison_fn_t) catalog_compare_func);
584 }
585
586 if (!f)
587 return NULL;
588
589 return (const char*) p +
590 le64toh(h->header_size) +
591 le64toh(h->n_items) * le64toh(h->catalog_item_size) +
592 le64toh(f->offset);
593 }
594
595 int catalog_get(const char* database, sd_id128_t id, char **_text) {
596 _cleanup_close_ int fd = -1;
597 void *p = NULL;
598 struct stat st = {};
599 char *text = NULL;
600 int r;
601 const char *s;
602
603 assert(_text);
604
605 r = open_mmap(database, &fd, &st, &p);
606 if (r < 0)
607 return r;
608
609 s = find_id(p, id);
610 if (!s) {
611 r = -ENOENT;
612 goto finish;
613 }
614
615 text = strdup(s);
616 if (!text) {
617 r = -ENOMEM;
618 goto finish;
619 }
620
621 *_text = text;
622 r = 0;
623
624 finish:
625 if (p)
626 munmap(p, st.st_size);
627
628 return r;
629 }
630
631 static char *find_header(const char *s, const char *header) {
632
633 for (;;) {
634 const char *v;
635
636 v = startswith(s, header);
637 if (v) {
638 v += strspn(v, WHITESPACE);
639 return strndup(v, strcspn(v, NEWLINE));
640 }
641
642 if (!next_header(&s))
643 return NULL;
644 }
645 }
646
647 static void dump_catalog_entry(FILE *f, sd_id128_t id, const char *s, bool oneline) {
648 if (oneline) {
649 _cleanup_free_ char *subject = NULL, *defined_by = NULL;
650
651 subject = find_header(s, "Subject:");
652 defined_by = find_header(s, "Defined-By:");
653
654 fprintf(f, SD_ID128_FORMAT_STR " %s: %s\n",
655 SD_ID128_FORMAT_VAL(id),
656 strna(defined_by), strna(subject));
657 } else
658 fprintf(f, "-- " SD_ID128_FORMAT_STR "\n%s\n",
659 SD_ID128_FORMAT_VAL(id), s);
660 }
661
662 int catalog_list(FILE *f, const char *database, bool oneline) {
663 _cleanup_close_ int fd = -1;
664 void *p = NULL;
665 struct stat st;
666 const CatalogHeader *h;
667 const CatalogItem *items;
668 int r;
669 unsigned n;
670 sd_id128_t last_id;
671 bool last_id_set = false;
672
673 r = open_mmap(database, &fd, &st, &p);
674 if (r < 0)
675 return r;
676
677 h = p;
678 items = (const CatalogItem*) ((const uint8_t*) p + le64toh(h->header_size));
679
680 for (n = 0; n < le64toh(h->n_items); n++) {
681 const char *s;
682
683 if (last_id_set && sd_id128_equal(last_id, items[n].id))
684 continue;
685
686 assert_se(s = find_id(p, items[n].id));
687
688 dump_catalog_entry(f, items[n].id, s, oneline);
689
690 last_id_set = true;
691 last_id = items[n].id;
692 }
693
694 munmap(p, st.st_size);
695
696 return 0;
697 }
698
699 int catalog_list_items(FILE *f, const char *database, bool oneline, char **items) {
700 char **item;
701 int r = 0;
702
703 STRV_FOREACH(item, items) {
704 sd_id128_t id;
705 int k;
706 _cleanup_free_ char *msg = NULL;
707
708 k = sd_id128_from_string(*item, &id);
709 if (k < 0) {
710 log_error_errno(k, "Failed to parse id128 '%s': %m", *item);
711 if (r == 0)
712 r = k;
713 continue;
714 }
715
716 k = catalog_get(database, id, &msg);
717 if (k < 0) {
718 log_full_errno(k == -ENOENT ? LOG_NOTICE : LOG_ERR, k,
719 "Failed to retrieve catalog entry for '%s': %m", *item);
720 if (r == 0)
721 r = k;
722 continue;
723 }
724
725 dump_catalog_entry(f, id, msg, oneline);
726 }
727
728 return r;
729 }