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