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