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