Debian Codegraph @

src/libsystemd/sd-journal/catalog.c

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