]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/journal/catalog.c
catalog: use structured initialization more
[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 { '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]; /* One byte is used for termination, so the maximum allowed
50 * length of the string is actually 31 bytes. */
51 le64_t offset;
52 } CatalogItem;
53
54 static void catalog_hash_func(const CatalogItem *i, struct siphash *state) {
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 DEFINE_HASH_OPS(catalog_hash_ops, CatalogItem, catalog_hash_func, catalog_compare_func);
73
74 static bool next_header(const char **s) {
75 const char *e;
76
77 e = strchr(*s, '\n');
78
79 /* Unexpected end */
80 if (!e)
81 return false;
82
83 /* End of headers */
84 if (e == *s)
85 return false;
86
87 *s = e + 1;
88 return true;
89 }
90
91 static const char *skip_header(const char *s) {
92 while (next_header(&s))
93 ;
94 return s;
95 }
96
97 static char *combine_entries(const char *one, const char *two) {
98 const char *b1, *b2;
99 size_t l1, l2, n;
100 char *dest, *p;
101
102 /* Find split point of headers to body */
103 b1 = skip_header(one);
104 b2 = skip_header(two);
105
106 l1 = strlen(one);
107 l2 = strlen(two);
108 dest = new(char, l1 + l2 + 1);
109 if (!dest) {
110 log_oom();
111 return NULL;
112 }
113
114 p = dest;
115
116 /* Headers from @one */
117 n = b1 - one;
118 p = mempcpy(p, one, n);
119
120 /* Headers from @two, these will only be found if not present above */
121 n = b2 - two;
122 p = mempcpy(p, two, n);
123
124 /* Body from @one */
125 n = l1 - (b1 - one);
126 if (n > 0) {
127 memcpy(p, b1, n);
128 p += n;
129
130 /* Body from @two */
131 } else {
132 n = l2 - (b2 - two);
133 memcpy(p, b2, n);
134 p += n;
135 }
136
137 assert(p - dest <= (ptrdiff_t)(l1 + l2));
138 p[0] = '\0';
139 return dest;
140 }
141
142 static int finish_item(
143 Hashmap *h,
144 sd_id128_t id,
145 const char *language,
146 char *payload, size_t payload_size) {
147
148 _cleanup_free_ CatalogItem *i = NULL;
149 _cleanup_free_ char *prev = NULL, *combined = NULL;
150
151 assert(h);
152 assert(payload);
153 assert(payload_size > 0);
154
155 i = new0(CatalogItem, 1);
156 if (!i)
157 return log_oom();
158
159 i->id = id;
160 if (language) {
161 assert(strlen(language) > 1 && strlen(language) < 32);
162 strcpy(i->language, language);
163 }
164
165 prev = hashmap_get(h, i);
166 if (prev) {
167 /* Already have such an item, combine them */
168 combined = combine_entries(payload, prev);
169 if (!combined)
170 return log_oom();
171
172 if (hashmap_update(h, i, combined) < 0)
173 return log_oom();
174 combined = NULL;
175 } else {
176 /* A new item */
177 combined = memdup(payload, payload_size + 1);
178 if (!combined)
179 return log_oom();
180
181 if (hashmap_put(h, i, combined) < 0)
182 return log_oom();
183 i = NULL;
184 combined = NULL;
185 }
186
187 return 0;
188 }
189
190 int catalog_file_lang(const char* filename, char **lang) {
191 char *beg, *end, *_lang;
192
193 end = endswith(filename, ".catalog");
194 if (!end)
195 return 0;
196
197 beg = end - 1;
198 while (beg > filename && !IN_SET(*beg, '.', '/') && end - beg < 32)
199 beg--;
200
201 if (*beg != '.' || end <= beg + 1)
202 return 0;
203
204 _lang = strndup(beg + 1, end - beg - 1);
205 if (!_lang)
206 return -ENOMEM;
207
208 *lang = _lang;
209 return 1;
210 }
211
212 static int catalog_entry_lang(
213 const char* filename,
214 unsigned line,
215 const char* t,
216 const char* deflang,
217 char **ret) {
218
219 size_t c;
220 char *z;
221
222 c = strlen(t);
223 if (c < 2)
224 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
225 "[%s:%u] Language too short.", filename, line);
226 if (c > 31)
227 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
228 "[%s:%u] language too long.", filename, line);
229
230 if (deflang) {
231 if (streq(t, deflang)) {
232 log_warning("[%s:%u] language specified unnecessarily", filename, line);
233 return 0;
234 }
235
236 log_warning("[%s:%u] language differs from default for file", filename, line);
237 }
238
239 z = strdup(t);
240 if (!z)
241 return -ENOMEM;
242
243 *ret = z;
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(
375 const char *database,
376 struct strbuf *sb,
377 CatalogItem *items,
378 size_t n) {
379
380 _cleanup_fclose_ FILE *w = NULL;
381 _cleanup_free_ char *p = NULL;
382 CatalogHeader header;
383 size_t k;
384 int r;
385
386 r = mkdir_parents(database, 0755);
387 if (r < 0)
388 return log_error_errno(r, "Failed to create parent directories of %s: %m", database);
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 header = (CatalogHeader) {
396 .signature = CATALOG_SIGNATURE,
397 .header_size = htole64(ALIGN_TO(sizeof(CatalogHeader), 8)),
398 .catalog_item_size = htole64(sizeof(CatalogItem)),
399 .n_items = htole64(n),
400 };
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, (const uint8_t[]) 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 (!isempty(loc) && !STR_IN_SET(loc, "C", "POSIX")) {
566 size_t len;
567
568 len = strcspn(loc, ".@");
569 if (len > sizeof(key.language) - 1)
570 log_debug("LC_MESSAGES value too long, ignoring: \"%.*s\"", (int) len, loc);
571 else {
572 strncpy(key.language, loc, len);
573 key.language[len] = '\0';
574
575 f = bsearch(&key,
576 (const uint8_t*) p + le64toh(h->header_size),
577 le64toh(h->n_items),
578 le64toh(h->catalog_item_size),
579 (comparison_fn_t) catalog_compare_func);
580 if (!f) {
581 char *e;
582
583 e = strchr(key.language, '_');
584 if (e) {
585 *e = 0;
586 f = bsearch(&key,
587 (const uint8_t*) p + le64toh(h->header_size),
588 le64toh(h->n_items),
589 le64toh(h->catalog_item_size),
590 (comparison_fn_t) catalog_compare_func);
591 }
592 }
593 }
594 }
595
596 if (!f) {
597 zero(key.language);
598 f = bsearch(&key,
599 (const uint8_t*) p + le64toh(h->header_size),
600 le64toh(h->n_items),
601 le64toh(h->catalog_item_size),
602 (comparison_fn_t) catalog_compare_func);
603 }
604
605 if (!f)
606 return NULL;
607
608 return (const char*) p +
609 le64toh(h->header_size) +
610 le64toh(h->n_items) * le64toh(h->catalog_item_size) +
611 le64toh(f->offset);
612 }
613
614 int catalog_get(const char* database, sd_id128_t id, char **_text) {
615 _cleanup_close_ int fd = -1;
616 void *p = NULL;
617 struct stat st = {};
618 char *text = NULL;
619 int r;
620 const char *s;
621
622 assert(_text);
623
624 r = open_mmap(database, &fd, &st, &p);
625 if (r < 0)
626 return r;
627
628 s = find_id(p, id);
629 if (!s) {
630 r = -ENOENT;
631 goto finish;
632 }
633
634 text = strdup(s);
635 if (!text) {
636 r = -ENOMEM;
637 goto finish;
638 }
639
640 *_text = text;
641 r = 0;
642
643 finish:
644 if (p)
645 munmap(p, st.st_size);
646
647 return r;
648 }
649
650 static char *find_header(const char *s, const char *header) {
651
652 for (;;) {
653 const char *v;
654
655 v = startswith(s, header);
656 if (v) {
657 v += strspn(v, WHITESPACE);
658 return strndup(v, strcspn(v, NEWLINE));
659 }
660
661 if (!next_header(&s))
662 return NULL;
663 }
664 }
665
666 static void dump_catalog_entry(FILE *f, sd_id128_t id, const char *s, bool oneline) {
667 if (oneline) {
668 _cleanup_free_ char *subject = NULL, *defined_by = NULL;
669
670 subject = find_header(s, "Subject:");
671 defined_by = find_header(s, "Defined-By:");
672
673 fprintf(f, SD_ID128_FORMAT_STR " %s: %s\n",
674 SD_ID128_FORMAT_VAL(id),
675 strna(defined_by), strna(subject));
676 } else
677 fprintf(f, "-- " SD_ID128_FORMAT_STR "\n%s\n",
678 SD_ID128_FORMAT_VAL(id), s);
679 }
680
681 int catalog_list(FILE *f, const char *database, bool oneline) {
682 _cleanup_close_ int fd = -1;
683 void *p = NULL;
684 struct stat st;
685 const CatalogHeader *h;
686 const CatalogItem *items;
687 int r;
688 unsigned n;
689 sd_id128_t last_id;
690 bool last_id_set = false;
691
692 r = open_mmap(database, &fd, &st, &p);
693 if (r < 0)
694 return r;
695
696 h = p;
697 items = (const CatalogItem*) ((const uint8_t*) p + le64toh(h->header_size));
698
699 for (n = 0; n < le64toh(h->n_items); n++) {
700 const char *s;
701
702 if (last_id_set && sd_id128_equal(last_id, items[n].id))
703 continue;
704
705 assert_se(s = find_id(p, items[n].id));
706
707 dump_catalog_entry(f, items[n].id, s, oneline);
708
709 last_id_set = true;
710 last_id = items[n].id;
711 }
712
713 munmap(p, st.st_size);
714
715 return 0;
716 }
717
718 int catalog_list_items(FILE *f, const char *database, bool oneline, char **items) {
719 char **item;
720 int r = 0;
721
722 STRV_FOREACH(item, items) {
723 sd_id128_t id;
724 int k;
725 _cleanup_free_ char *msg = NULL;
726
727 k = sd_id128_from_string(*item, &id);
728 if (k < 0) {
729 log_error_errno(k, "Failed to parse id128 '%s': %m", *item);
730 if (r == 0)
731 r = k;
732 continue;
733 }
734
735 k = catalog_get(database, id, &msg);
736 if (k < 0) {
737 log_full_errno(k == -ENOENT ? LOG_NOTICE : LOG_ERR, k,
738 "Failed to retrieve catalog entry for '%s': %m", *item);
739 if (r == 0)
740 r = k;
741 continue;
742 }
743
744 dump_catalog_entry(f, id, msg, oneline);
745 }
746
747 return r;
748 }