]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/journal/catalog.c
Merge pull request #8135 from shawnl/arg_host
[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 void *a, const void *b) {
60 const CatalogItem *i = a, *j = b;
61 unsigned k;
62 int r;
63
64 for (k = 0; k < ELEMENTSOF(j->id.bytes); k++) {
65 r = CMP(i->id.bytes[k], j->id.bytes[k]);
66 if (r != 0)
67 return r;
68 }
69
70 return strcmp(i->language, j->language);
71 }
72
73 const struct hash_ops catalog_hash_ops = {
74 .hash = catalog_hash_func,
75 .compare = 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 == 0) {
222 log_error("[%s:%u] Language too short.", filename, line);
223 return -EINVAL;
224 }
225 if (c > 31) {
226 log_error("[%s:%u] language too long.", filename, line);
227 return -EINVAL;
228 }
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 char line[LINE_MAX];
272 size_t line_len;
273
274 if (!fgets(line, sizeof(line), f)) {
275 if (feof(f))
276 break;
277
278 return log_error_errno(errno, "Failed to read file %s: %m", path);
279 }
280
281 n++;
282
283 truncate_nl(line);
284
285 if (line[0] == 0) {
286 empty_line = true;
287 continue;
288 }
289
290 if (strchr(COMMENTS "\n", line[0]))
291 continue;
292
293 if (empty_line &&
294 strlen(line) >= 2+1+32 &&
295 line[0] == '-' &&
296 line[1] == '-' &&
297 line[2] == ' ' &&
298 IN_SET(line[2+1+32], ' ', '\0')) {
299
300 bool with_language;
301 sd_id128_t jd;
302
303 /* New entry */
304
305 with_language = line[2+1+32] != '\0';
306 line[2+1+32] = '\0';
307
308 if (sd_id128_from_string(line + 2 + 1, &jd) >= 0) {
309
310 if (got_id) {
311 if (payload_size == 0) {
312 log_error("[%s:%u] No payload text.", path, n);
313 return -EINVAL;
314 }
315
316 r = finish_item(h, id, lang ?: deflang, payload, payload_size);
317 if (r < 0)
318 return r;
319
320 lang = mfree(lang);
321 payload_size = 0;
322 }
323
324 if (with_language) {
325 char *t;
326
327 t = strstrip(line + 2 + 1 + 32 + 1);
328 r = catalog_entry_lang(path, n, t, deflang, &lang);
329 if (r < 0)
330 return r;
331 }
332
333 got_id = true;
334 empty_line = false;
335 id = jd;
336
337 continue;
338 }
339 }
340
341 /* Payload */
342 if (!got_id) {
343 log_error("[%s:%u] Got payload before ID.", path, n);
344 return -EINVAL;
345 }
346
347 line_len = strlen(line);
348 if (!GREEDY_REALLOC(payload, payload_allocated,
349 payload_size + (empty_line ? 1 : 0) + line_len + 1 + 1))
350 return log_oom();
351
352 if (empty_line)
353 payload[payload_size++] = '\n';
354 memcpy(payload + payload_size, line, line_len);
355 payload_size += line_len;
356 payload[payload_size++] = '\n';
357 payload[payload_size] = '\0';
358
359 empty_line = false;
360 }
361
362 if (got_id) {
363 if (payload_size == 0) {
364 log_error("[%s:%u] No payload text.", path, n);
365 return -EINVAL;
366 }
367
368 r = finish_item(h, id, lang ?: deflang, payload, payload_size);
369 if (r < 0)
370 return r;
371 }
372
373 return 0;
374 }
375
376 static int64_t write_catalog(const char *database, struct strbuf *sb,
377 CatalogItem *items, size_t n) {
378 CatalogHeader header;
379 _cleanup_fclose_ FILE *w = NULL;
380 int r;
381 _cleanup_free_ char *d, *p = NULL;
382 size_t k;
383
384 d = dirname_malloc(database);
385 if (!d)
386 return log_oom();
387
388 r = mkdir_p(d, 0775);
389 if (r < 0)
390 return log_error_errno(r, "Recursive mkdir %s: %m", d);
391
392 r = fopen_temporary(database, &w, &p);
393 if (r < 0)
394 return log_error_errno(r, "Failed to open database for writing: %s: %m",
395 database);
396
397 zero(header);
398 memcpy(header.signature, CATALOG_SIGNATURE, sizeof(header.signature));
399 header.header_size = htole64(ALIGN_TO(sizeof(CatalogHeader), 8));
400 header.catalog_item_size = htole64(sizeof(CatalogItem));
401 header.n_items = htole64(n);
402
403 r = -EIO;
404
405 k = fwrite(&header, 1, sizeof(header), w);
406 if (k != sizeof(header)) {
407 log_error("%s: failed to write header.", p);
408 goto error;
409 }
410
411 k = fwrite(items, 1, n * sizeof(CatalogItem), w);
412 if (k != n * sizeof(CatalogItem)) {
413 log_error("%s: failed to write database.", p);
414 goto error;
415 }
416
417 k = fwrite(sb->buf, 1, sb->len, w);
418 if (k != sb->len) {
419 log_error("%s: failed to write strings.", p);
420 goto error;
421 }
422
423 r = fflush_and_check(w);
424 if (r < 0) {
425 log_error_errno(r, "%s: failed to write database: %m", p);
426 goto error;
427 }
428
429 fchmod(fileno(w), 0644);
430
431 if (rename(p, database) < 0) {
432 r = log_error_errno(errno, "rename (%s -> %s) failed: %m", p, database);
433 goto error;
434 }
435
436 return ftello(w);
437
438 error:
439 (void) unlink(p);
440 return r;
441 }
442
443 int catalog_update(const char* database, const char* root, const char* const* dirs) {
444 _cleanup_strv_free_ char **files = NULL;
445 char **f;
446 _cleanup_(strbuf_cleanupp) struct strbuf *sb = NULL;
447 _cleanup_hashmap_free_free_free_ Hashmap *h = NULL;
448 _cleanup_free_ CatalogItem *items = NULL;
449 ssize_t offset;
450 char *payload;
451 CatalogItem *i;
452 Iterator j;
453 unsigned n;
454 int r;
455 int64_t sz;
456
457 h = hashmap_new(&catalog_hash_ops);
458 sb = strbuf_new();
459 if (!h || !sb)
460 return log_oom();
461
462 r = conf_files_list_strv(&files, ".catalog", root, 0, dirs);
463 if (r < 0)
464 return log_error_errno(r, "Failed to get catalog files: %m");
465
466 STRV_FOREACH(f, files) {
467 log_debug("Reading file '%s'", *f);
468 r = catalog_import_file(h, *f);
469 if (r < 0)
470 return log_error_errno(r, "Failed to import file '%s': %m", *f);
471 }
472
473 if (hashmap_size(h) <= 0) {
474 log_info("No items in catalog.");
475 return 0;
476 } else
477 log_debug("Found %u items in catalog.", hashmap_size(h));
478
479 items = new(CatalogItem, hashmap_size(h));
480 if (!items)
481 return log_oom();
482
483 n = 0;
484 HASHMAP_FOREACH_KEY(payload, i, h, j) {
485 log_debug("Found " SD_ID128_FORMAT_STR ", language %s",
486 SD_ID128_FORMAT_VAL(i->id),
487 isempty(i->language) ? "C" : i->language);
488
489 offset = strbuf_add_string(sb, payload, strlen(payload));
490 if (offset < 0)
491 return log_oom();
492
493 i->offset = htole64((uint64_t) offset);
494 items[n++] = *i;
495 }
496
497 assert(n == hashmap_size(h));
498 qsort_safe(items, n, sizeof(CatalogItem), catalog_compare_func);
499
500 strbuf_complete(sb);
501
502 sz = write_catalog(database, sb, items, n);
503 if (sz < 0)
504 return log_error_errno(sz, "Failed to write %s: %m", database);
505
506 log_debug("%s: wrote %u items, with %zu bytes of strings, %"PRIi64" total size.",
507 database, n, sb->len, sz);
508 return 0;
509 }
510
511 static int open_mmap(const char *database, int *_fd, struct stat *_st, void **_p) {
512 const CatalogHeader *h;
513 int fd;
514 void *p;
515 struct stat st;
516
517 assert(_fd);
518 assert(_st);
519 assert(_p);
520
521 fd = open(database, O_RDONLY|O_CLOEXEC);
522 if (fd < 0)
523 return -errno;
524
525 if (fstat(fd, &st) < 0) {
526 safe_close(fd);
527 return -errno;
528 }
529
530 if (st.st_size < (off_t) sizeof(CatalogHeader)) {
531 safe_close(fd);
532 return -EINVAL;
533 }
534
535 p = mmap(NULL, PAGE_ALIGN(st.st_size), PROT_READ, MAP_SHARED, fd, 0);
536 if (p == MAP_FAILED) {
537 safe_close(fd);
538 return -errno;
539 }
540
541 h = p;
542 if (memcmp(h->signature, CATALOG_SIGNATURE, sizeof(h->signature)) != 0 ||
543 le64toh(h->header_size) < sizeof(CatalogHeader) ||
544 le64toh(h->catalog_item_size) < sizeof(CatalogItem) ||
545 h->incompatible_flags != 0 ||
546 le64toh(h->n_items) <= 0 ||
547 st.st_size < (off_t) (le64toh(h->header_size) + le64toh(h->catalog_item_size) * le64toh(h->n_items))) {
548 safe_close(fd);
549 munmap(p, st.st_size);
550 return -EBADMSG;
551 }
552
553 *_fd = fd;
554 *_st = st;
555 *_p = p;
556
557 return 0;
558 }
559
560 static const char *find_id(void *p, sd_id128_t id) {
561 CatalogItem *f = NULL, key = { .id = id };
562 const CatalogHeader *h = p;
563 const char *loc;
564
565 loc = setlocale(LC_MESSAGES, NULL);
566 if (loc && loc[0] && !streq(loc, "C") && !streq(loc, "POSIX")) {
567 strncpy(key.language, loc, sizeof(key.language));
568 key.language[strcspn(key.language, ".@")] = 0;
569
570 f = bsearch(&key, (const uint8_t*) p + le64toh(h->header_size), le64toh(h->n_items), le64toh(h->catalog_item_size), catalog_compare_func);
571 if (!f) {
572 char *e;
573
574 e = strchr(key.language, '_');
575 if (e) {
576 *e = 0;
577 f = bsearch(&key, (const uint8_t*) p + le64toh(h->header_size), le64toh(h->n_items), le64toh(h->catalog_item_size), catalog_compare_func);
578 }
579 }
580 }
581
582 if (!f) {
583 zero(key.language);
584 f = bsearch(&key, (const uint8_t*) p + le64toh(h->header_size), le64toh(h->n_items), le64toh(h->catalog_item_size), catalog_compare_func);
585 }
586
587 if (!f)
588 return NULL;
589
590 return (const char*) p +
591 le64toh(h->header_size) +
592 le64toh(h->n_items) * le64toh(h->catalog_item_size) +
593 le64toh(f->offset);
594 }
595
596 int catalog_get(const char* database, sd_id128_t id, char **_text) {
597 _cleanup_close_ int fd = -1;
598 void *p = NULL;
599 struct stat st = {};
600 char *text = NULL;
601 int r;
602 const char *s;
603
604 assert(_text);
605
606 r = open_mmap(database, &fd, &st, &p);
607 if (r < 0)
608 return r;
609
610 s = find_id(p, id);
611 if (!s) {
612 r = -ENOENT;
613 goto finish;
614 }
615
616 text = strdup(s);
617 if (!text) {
618 r = -ENOMEM;
619 goto finish;
620 }
621
622 *_text = text;
623 r = 0;
624
625 finish:
626 if (p)
627 munmap(p, st.st_size);
628
629 return r;
630 }
631
632 static char *find_header(const char *s, const char *header) {
633
634 for (;;) {
635 const char *v;
636
637 v = startswith(s, header);
638 if (v) {
639 v += strspn(v, WHITESPACE);
640 return strndup(v, strcspn(v, NEWLINE));
641 }
642
643 if (!next_header(&s))
644 return NULL;
645 }
646 }
647
648 static void dump_catalog_entry(FILE *f, sd_id128_t id, const char *s, bool oneline) {
649 if (oneline) {
650 _cleanup_free_ char *subject = NULL, *defined_by = NULL;
651
652 subject = find_header(s, "Subject:");
653 defined_by = find_header(s, "Defined-By:");
654
655 fprintf(f, SD_ID128_FORMAT_STR " %s: %s\n",
656 SD_ID128_FORMAT_VAL(id),
657 strna(defined_by), strna(subject));
658 } else
659 fprintf(f, "-- " SD_ID128_FORMAT_STR "\n%s\n",
660 SD_ID128_FORMAT_VAL(id), s);
661 }
662
663 int catalog_list(FILE *f, const char *database, bool oneline) {
664 _cleanup_close_ int fd = -1;
665 void *p = NULL;
666 struct stat st;
667 const CatalogHeader *h;
668 const CatalogItem *items;
669 int r;
670 unsigned n;
671 sd_id128_t last_id;
672 bool last_id_set = false;
673
674 r = open_mmap(database, &fd, &st, &p);
675 if (r < 0)
676 return r;
677
678 h = p;
679 items = (const CatalogItem*) ((const uint8_t*) p + le64toh(h->header_size));
680
681 for (n = 0; n < le64toh(h->n_items); n++) {
682 const char *s;
683
684 if (last_id_set && sd_id128_equal(last_id, items[n].id))
685 continue;
686
687 assert_se(s = find_id(p, items[n].id));
688
689 dump_catalog_entry(f, items[n].id, s, oneline);
690
691 last_id_set = true;
692 last_id = items[n].id;
693 }
694
695 munmap(p, st.st_size);
696
697 return 0;
698 }
699
700 int catalog_list_items(FILE *f, const char *database, bool oneline, char **items) {
701 char **item;
702 int r = 0;
703
704 STRV_FOREACH(item, items) {
705 sd_id128_t id;
706 int k;
707 _cleanup_free_ char *msg = NULL;
708
709 k = sd_id128_from_string(*item, &id);
710 if (k < 0) {
711 log_error_errno(k, "Failed to parse id128 '%s': %m", *item);
712 if (r == 0)
713 r = k;
714 continue;
715 }
716
717 k = catalog_get(database, id, &msg);
718 if (k < 0) {
719 log_full_errno(k == -ENOENT ? LOG_NOTICE : LOG_ERR, k,
720 "Failed to retrieve catalog entry for '%s': %m", *item);
721 if (r == 0)
722 r = k;
723 continue;
724 }
725
726 dump_catalog_entry(f, id, msg, oneline);
727 }
728
729 return r;
730 }