]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/libsystemd/sd-journal/sd-journal.c
Merge pull request #22098 from DaanDeMeyer/journal-corrupt-2
[thirdparty/systemd.git] / src / libsystemd / sd-journal / sd-journal.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <inttypes.h>
6 #include <linux/magic.h>
7 #include <poll.h>
8 #include <stddef.h>
9 #include <sys/inotify.h>
10 #include <sys/vfs.h>
11 #include <unistd.h>
12
13 #include "sd-journal.h"
14
15 #include "alloc-util.h"
16 #include "catalog.h"
17 #include "compress.h"
18 #include "dirent-util.h"
19 #include "env-file.h"
20 #include "escape.h"
21 #include "fd-util.h"
22 #include "fileio.h"
23 #include "format-util.h"
24 #include "fs-util.h"
25 #include "hashmap.h"
26 #include "hostname-util.h"
27 #include "id128-util.h"
28 #include "inotify-util.h"
29 #include "io-util.h"
30 #include "journal-def.h"
31 #include "journal-file.h"
32 #include "journal-internal.h"
33 #include "list.h"
34 #include "lookup3.h"
35 #include "nulstr-util.h"
36 #include "path-util.h"
37 #include "process-util.h"
38 #include "replace-var.h"
39 #include "stat-util.h"
40 #include "stdio-util.h"
41 #include "string-util.h"
42 #include "strv.h"
43 #include "syslog-util.h"
44
45 #define JOURNAL_FILES_MAX 7168
46
47 #define JOURNAL_FILES_RECHECK_USEC (2 * USEC_PER_SEC)
48
49 /* The maximum size of variable values we'll expand in catalog entries. We bind this to PATH_MAX for now, as
50 * we want to be able to show all officially valid paths at least */
51 #define REPLACE_VAR_MAX PATH_MAX
52
53 #define DEFAULT_DATA_THRESHOLD (64*1024)
54
55 static void remove_file_real(sd_journal *j, JournalFile *f);
56
57 static bool journal_pid_changed(sd_journal *j) {
58 assert(j);
59
60 /* We don't support people creating a journal object and
61 * keeping it around over a fork(). Let's complain. */
62
63 return j->original_pid != getpid_cached();
64 }
65
66 static int journal_put_error(sd_journal *j, int r, const char *path) {
67 _cleanup_free_ char *copy = NULL;
68 int k;
69
70 /* Memorize an error we encountered, and store which
71 * file/directory it was generated from. Note that we store
72 * only *one* path per error code, as the error code is the
73 * key into the hashmap, and the path is the value. This means
74 * we keep track only of all error kinds, but not of all error
75 * locations. This has the benefit that the hashmap cannot
76 * grow beyond bounds.
77 *
78 * We return an error here only if we didn't manage to
79 * memorize the real error. */
80
81 if (r >= 0)
82 return r;
83
84 if (path) {
85 copy = strdup(path);
86 if (!copy)
87 return -ENOMEM;
88 }
89
90 k = hashmap_ensure_put(&j->errors, NULL, INT_TO_PTR(r), copy);
91 if (k < 0) {
92 if (k == -EEXIST)
93 return 0;
94
95 return k;
96 }
97
98 TAKE_PTR(copy);
99 return 0;
100 }
101
102 static void detach_location(sd_journal *j) {
103 JournalFile *f;
104
105 assert(j);
106
107 j->current_file = NULL;
108 j->current_field = 0;
109
110 ORDERED_HASHMAP_FOREACH(f, j->files)
111 journal_file_reset_location(f);
112 }
113
114 static void init_location(Location *l, LocationType type, JournalFile *f, Object *o) {
115 assert(l);
116 assert(IN_SET(type, LOCATION_DISCRETE, LOCATION_SEEK));
117 assert(f);
118
119 *l = (Location) {
120 .type = type,
121 .seqnum = le64toh(o->entry.seqnum),
122 .seqnum_id = f->header->seqnum_id,
123 .realtime = le64toh(o->entry.realtime),
124 .monotonic = le64toh(o->entry.monotonic),
125 .boot_id = o->entry.boot_id,
126 .xor_hash = le64toh(o->entry.xor_hash),
127 .seqnum_set = true,
128 .realtime_set = true,
129 .monotonic_set = true,
130 .xor_hash_set = true,
131 };
132 }
133
134 static void set_location(sd_journal *j, JournalFile *f, Object *o) {
135 assert(j);
136 assert(f);
137 assert(o);
138
139 init_location(&j->current_location, LOCATION_DISCRETE, f, o);
140
141 j->current_file = f;
142 j->current_field = 0;
143
144 /* Let f know its candidate entry was picked. */
145 assert(f->location_type == LOCATION_SEEK);
146 f->location_type = LOCATION_DISCRETE;
147 }
148
149 static int match_is_valid(const void *data, size_t size) {
150 const char *b, *p;
151
152 assert(data);
153
154 if (size < 2)
155 return false;
156
157 if (((char*) data)[0] == '_' && ((char*) data)[1] == '_')
158 return false;
159
160 b = data;
161 for (p = b; p < b + size; p++) {
162
163 if (*p == '=')
164 return p > b;
165
166 if (*p == '_')
167 continue;
168
169 if (*p >= 'A' && *p <= 'Z')
170 continue;
171
172 if (*p >= '0' && *p <= '9')
173 continue;
174
175 return false;
176 }
177
178 return false;
179 }
180
181 static bool same_field(const void *_a, size_t s, const void *_b, size_t t) {
182 const uint8_t *a = _a, *b = _b;
183 size_t j;
184
185 for (j = 0; j < s && j < t; j++) {
186
187 if (a[j] != b[j])
188 return false;
189
190 if (a[j] == '=')
191 return true;
192 }
193
194 assert_not_reached();
195 }
196
197 static Match *match_new(Match *p, MatchType t) {
198 Match *m;
199
200 m = new(Match, 1);
201 if (!m)
202 return NULL;
203
204 *m = (Match) {
205 .type = t,
206 .parent = p,
207 };
208
209 if (p)
210 LIST_PREPEND(matches, p->matches, m);
211
212 return m;
213 }
214
215 static Match *match_free(Match *m) {
216 assert(m);
217
218 while (m->matches)
219 match_free(m->matches);
220
221 if (m->parent)
222 LIST_REMOVE(matches, m->parent->matches, m);
223
224 free(m->data);
225 return mfree(m);
226 }
227
228 static Match *match_free_if_empty(Match *m) {
229 if (!m || m->matches)
230 return m;
231
232 return match_free(m);
233 }
234
235 _public_ int sd_journal_add_match(sd_journal *j, const void *data, size_t size) {
236 Match *l3, *l4, *add_here = NULL, *m = NULL;
237 uint64_t hash;
238
239 assert_return(j, -EINVAL);
240 assert_return(!journal_pid_changed(j), -ECHILD);
241 assert_return(data, -EINVAL);
242
243 if (size == 0)
244 size = strlen(data);
245
246 assert_return(match_is_valid(data, size), -EINVAL);
247
248 /* level 0: AND term
249 * level 1: OR terms
250 * level 2: AND terms
251 * level 3: OR terms
252 * level 4: concrete matches */
253
254 if (!j->level0) {
255 j->level0 = match_new(NULL, MATCH_AND_TERM);
256 if (!j->level0)
257 return -ENOMEM;
258 }
259
260 if (!j->level1) {
261 j->level1 = match_new(j->level0, MATCH_OR_TERM);
262 if (!j->level1)
263 return -ENOMEM;
264 }
265
266 if (!j->level2) {
267 j->level2 = match_new(j->level1, MATCH_AND_TERM);
268 if (!j->level2)
269 return -ENOMEM;
270 }
271
272 assert(j->level0->type == MATCH_AND_TERM);
273 assert(j->level1->type == MATCH_OR_TERM);
274 assert(j->level2->type == MATCH_AND_TERM);
275
276 /* Old-style Jenkins (unkeyed) hashing only here. We do not cover new-style siphash (keyed) hashing
277 * here, since it's different for each file, and thus can't be pre-calculated in the Match object. */
278 hash = jenkins_hash64(data, size);
279
280 LIST_FOREACH(matches, l3, j->level2->matches) {
281 assert(l3->type == MATCH_OR_TERM);
282
283 LIST_FOREACH(matches, l4, l3->matches) {
284 assert(l4->type == MATCH_DISCRETE);
285
286 /* Exactly the same match already? Then ignore
287 * this addition */
288 if (l4->hash == hash &&
289 l4->size == size &&
290 memcmp(l4->data, data, size) == 0)
291 return 0;
292
293 /* Same field? Then let's add this to this OR term */
294 if (same_field(data, size, l4->data, l4->size)) {
295 add_here = l3;
296 break;
297 }
298 }
299
300 if (add_here)
301 break;
302 }
303
304 if (!add_here) {
305 add_here = match_new(j->level2, MATCH_OR_TERM);
306 if (!add_here)
307 goto fail;
308 }
309
310 m = match_new(add_here, MATCH_DISCRETE);
311 if (!m)
312 goto fail;
313
314 m->hash = hash;
315 m->size = size;
316 m->data = memdup(data, size);
317 if (!m->data)
318 goto fail;
319
320 detach_location(j);
321
322 return 0;
323
324 fail:
325 match_free(m);
326 match_free_if_empty(add_here);
327 j->level2 = match_free_if_empty(j->level2);
328 j->level1 = match_free_if_empty(j->level1);
329 j->level0 = match_free_if_empty(j->level0);
330
331 return -ENOMEM;
332 }
333
334 _public_ int sd_journal_add_conjunction(sd_journal *j) {
335 assert_return(j, -EINVAL);
336 assert_return(!journal_pid_changed(j), -ECHILD);
337
338 if (!j->level0)
339 return 0;
340
341 if (!j->level1)
342 return 0;
343
344 if (!j->level1->matches)
345 return 0;
346
347 j->level1 = NULL;
348 j->level2 = NULL;
349
350 return 0;
351 }
352
353 _public_ int sd_journal_add_disjunction(sd_journal *j) {
354 assert_return(j, -EINVAL);
355 assert_return(!journal_pid_changed(j), -ECHILD);
356
357 if (!j->level0)
358 return 0;
359
360 if (!j->level1)
361 return 0;
362
363 if (!j->level2)
364 return 0;
365
366 if (!j->level2->matches)
367 return 0;
368
369 j->level2 = NULL;
370 return 0;
371 }
372
373 static char *match_make_string(Match *m) {
374 char *p = NULL, *r;
375 Match *i;
376 bool enclose = false;
377
378 if (!m)
379 return strdup("none");
380
381 if (m->type == MATCH_DISCRETE)
382 return cescape_length(m->data, m->size);
383
384 LIST_FOREACH(matches, i, m->matches) {
385 char *t, *k;
386
387 t = match_make_string(i);
388 if (!t)
389 return mfree(p);
390
391 if (p) {
392 k = strjoin(p, m->type == MATCH_OR_TERM ? " OR " : " AND ", t);
393 free(p);
394 free(t);
395
396 if (!k)
397 return NULL;
398
399 p = k;
400
401 enclose = true;
402 } else
403 p = t;
404 }
405
406 if (enclose) {
407 r = strjoin("(", p, ")");
408 free(p);
409 return r;
410 }
411
412 return p;
413 }
414
415 char *journal_make_match_string(sd_journal *j) {
416 assert(j);
417
418 return match_make_string(j->level0);
419 }
420
421 _public_ void sd_journal_flush_matches(sd_journal *j) {
422 if (!j)
423 return;
424
425 if (j->level0)
426 match_free(j->level0);
427
428 j->level0 = j->level1 = j->level2 = NULL;
429
430 detach_location(j);
431 }
432
433 _pure_ static int compare_with_location(const JournalFile *f, const Location *l, const JournalFile *current_file) {
434 int r;
435
436 assert(f);
437 assert(l);
438 assert(f->location_type == LOCATION_SEEK);
439 assert(IN_SET(l->type, LOCATION_DISCRETE, LOCATION_SEEK));
440
441 if (l->monotonic_set &&
442 sd_id128_equal(f->current_boot_id, l->boot_id) &&
443 l->realtime_set &&
444 f->current_realtime == l->realtime &&
445 l->xor_hash_set &&
446 f->current_xor_hash == l->xor_hash &&
447 l->seqnum_set &&
448 sd_id128_equal(f->header->seqnum_id, l->seqnum_id) &&
449 f->current_seqnum == l->seqnum &&
450 f != current_file)
451 return 0;
452
453 if (l->seqnum_set &&
454 sd_id128_equal(f->header->seqnum_id, l->seqnum_id)) {
455
456 r = CMP(f->current_seqnum, l->seqnum);
457 if (r != 0)
458 return r;
459 }
460
461 if (l->monotonic_set &&
462 sd_id128_equal(f->current_boot_id, l->boot_id)) {
463
464 r = CMP(f->current_monotonic, l->monotonic);
465 if (r != 0)
466 return r;
467 }
468
469 if (l->realtime_set) {
470
471 r = CMP(f->current_realtime, l->realtime);
472 if (r != 0)
473 return r;
474 }
475
476 if (l->xor_hash_set) {
477
478 r = CMP(f->current_xor_hash, l->xor_hash);
479 if (r != 0)
480 return r;
481 }
482
483 return 0;
484 }
485
486 static int next_for_match(
487 sd_journal *j,
488 Match *m,
489 JournalFile *f,
490 uint64_t after_offset,
491 direction_t direction,
492 Object **ret,
493 uint64_t *offset) {
494
495 int r;
496 uint64_t np = 0;
497 Object *n;
498
499 assert(j);
500 assert(m);
501 assert(f);
502
503 if (m->type == MATCH_DISCRETE) {
504 uint64_t dp, hash;
505
506 /* If the keyed hash logic is used, we need to calculate the hash fresh per file. Otherwise
507 * we can use what we pre-calculated. */
508 if (JOURNAL_HEADER_KEYED_HASH(f->header))
509 hash = journal_file_hash_data(f, m->data, m->size);
510 else
511 hash = m->hash;
512
513 r = journal_file_find_data_object_with_hash(f, m->data, m->size, hash, NULL, &dp);
514 if (r <= 0)
515 return r;
516
517 return journal_file_move_to_entry_by_offset_for_data(f, dp, after_offset, direction, ret, offset);
518
519 } else if (m->type == MATCH_OR_TERM) {
520 Match *i;
521
522 /* Find the earliest match beyond after_offset */
523
524 LIST_FOREACH(matches, i, m->matches) {
525 uint64_t cp;
526
527 r = next_for_match(j, i, f, after_offset, direction, NULL, &cp);
528 if (r < 0)
529 return r;
530 else if (r > 0) {
531 if (np == 0 || (direction == DIRECTION_DOWN ? cp < np : cp > np))
532 np = cp;
533 }
534 }
535
536 if (np == 0)
537 return 0;
538
539 } else if (m->type == MATCH_AND_TERM) {
540 Match *i, *last_moved;
541
542 /* Always jump to the next matching entry and repeat
543 * this until we find an offset that matches for all
544 * matches. */
545
546 if (!m->matches)
547 return 0;
548
549 r = next_for_match(j, m->matches, f, after_offset, direction, NULL, &np);
550 if (r <= 0)
551 return r;
552
553 assert(direction == DIRECTION_DOWN ? np >= after_offset : np <= after_offset);
554 last_moved = m->matches;
555
556 LIST_LOOP_BUT_ONE(matches, i, m->matches, last_moved) {
557 uint64_t cp;
558
559 r = next_for_match(j, i, f, np, direction, NULL, &cp);
560 if (r <= 0)
561 return r;
562
563 assert(direction == DIRECTION_DOWN ? cp >= np : cp <= np);
564 if (direction == DIRECTION_DOWN ? cp > np : cp < np) {
565 np = cp;
566 last_moved = i;
567 }
568 }
569 }
570
571 assert(np > 0);
572
573 r = journal_file_move_to_object(f, OBJECT_ENTRY, np, &n);
574 if (r < 0)
575 return r;
576
577 if (ret)
578 *ret = n;
579 if (offset)
580 *offset = np;
581
582 return 1;
583 }
584
585 static int find_location_for_match(
586 sd_journal *j,
587 Match *m,
588 JournalFile *f,
589 direction_t direction,
590 Object **ret,
591 uint64_t *offset) {
592
593 int r;
594
595 assert(j);
596 assert(m);
597 assert(f);
598
599 if (m->type == MATCH_DISCRETE) {
600 uint64_t dp, hash;
601
602 if (JOURNAL_HEADER_KEYED_HASH(f->header))
603 hash = journal_file_hash_data(f, m->data, m->size);
604 else
605 hash = m->hash;
606
607 r = journal_file_find_data_object_with_hash(f, m->data, m->size, hash, NULL, &dp);
608 if (r <= 0)
609 return r;
610
611 /* FIXME: missing: find by monotonic */
612
613 if (j->current_location.type == LOCATION_HEAD)
614 return journal_file_next_entry_for_data(f, dp, DIRECTION_DOWN, ret, offset);
615 if (j->current_location.type == LOCATION_TAIL)
616 return journal_file_next_entry_for_data(f, dp, DIRECTION_UP, ret, offset);
617 if (j->current_location.seqnum_set && sd_id128_equal(j->current_location.seqnum_id, f->header->seqnum_id))
618 return journal_file_move_to_entry_by_seqnum_for_data(f, dp, j->current_location.seqnum, direction, ret, offset);
619 if (j->current_location.monotonic_set) {
620 r = journal_file_move_to_entry_by_monotonic_for_data(f, dp, j->current_location.boot_id, j->current_location.monotonic, direction, ret, offset);
621 if (r != -ENOENT)
622 return r;
623 }
624 if (j->current_location.realtime_set)
625 return journal_file_move_to_entry_by_realtime_for_data(f, dp, j->current_location.realtime, direction, ret, offset);
626
627 return journal_file_next_entry_for_data(f, dp, direction, ret, offset);
628
629 } else if (m->type == MATCH_OR_TERM) {
630 uint64_t np = 0;
631 Object *n;
632 Match *i;
633
634 /* Find the earliest match */
635
636 LIST_FOREACH(matches, i, m->matches) {
637 uint64_t cp;
638
639 r = find_location_for_match(j, i, f, direction, NULL, &cp);
640 if (r < 0)
641 return r;
642 else if (r > 0) {
643 if (np == 0 || (direction == DIRECTION_DOWN ? np > cp : np < cp))
644 np = cp;
645 }
646 }
647
648 if (np == 0)
649 return 0;
650
651 r = journal_file_move_to_object(f, OBJECT_ENTRY, np, &n);
652 if (r < 0)
653 return r;
654
655 if (ret)
656 *ret = n;
657 if (offset)
658 *offset = np;
659
660 return 1;
661
662 } else {
663 Match *i;
664 uint64_t np = 0;
665
666 assert(m->type == MATCH_AND_TERM);
667
668 /* First jump to the last match, and then find the
669 * next one where all matches match */
670
671 if (!m->matches)
672 return 0;
673
674 LIST_FOREACH(matches, i, m->matches) {
675 uint64_t cp;
676
677 r = find_location_for_match(j, i, f, direction, NULL, &cp);
678 if (r <= 0)
679 return r;
680
681 if (np == 0 || (direction == DIRECTION_DOWN ? cp > np : cp < np))
682 np = cp;
683 }
684
685 return next_for_match(j, m, f, np, direction, ret, offset);
686 }
687 }
688
689 static int find_location_with_matches(
690 sd_journal *j,
691 JournalFile *f,
692 direction_t direction,
693 Object **ret,
694 uint64_t *offset) {
695
696 int r;
697
698 assert(j);
699 assert(f);
700 assert(ret);
701 assert(offset);
702
703 if (!j->level0) {
704 /* No matches is simple */
705
706 if (j->current_location.type == LOCATION_HEAD)
707 return journal_file_next_entry(f, 0, DIRECTION_DOWN, ret, offset);
708 if (j->current_location.type == LOCATION_TAIL)
709 return journal_file_next_entry(f, 0, DIRECTION_UP, ret, offset);
710 if (j->current_location.seqnum_set && sd_id128_equal(j->current_location.seqnum_id, f->header->seqnum_id))
711 return journal_file_move_to_entry_by_seqnum(f, j->current_location.seqnum, direction, ret, offset);
712 if (j->current_location.monotonic_set) {
713 r = journal_file_move_to_entry_by_monotonic(f, j->current_location.boot_id, j->current_location.monotonic, direction, ret, offset);
714 if (r != -ENOENT)
715 return r;
716 }
717 if (j->current_location.realtime_set)
718 return journal_file_move_to_entry_by_realtime(f, j->current_location.realtime, direction, ret, offset);
719
720 return journal_file_next_entry(f, 0, direction, ret, offset);
721 } else
722 return find_location_for_match(j, j->level0, f, direction, ret, offset);
723 }
724
725 static int next_with_matches(
726 sd_journal *j,
727 JournalFile *f,
728 direction_t direction,
729 Object **ret,
730 uint64_t *offset) {
731
732 assert(j);
733 assert(f);
734 assert(ret);
735 assert(offset);
736
737 /* No matches is easy. We simple advance the file
738 * pointer by one. */
739 if (!j->level0)
740 return journal_file_next_entry(f, f->current_offset, direction, ret, offset);
741
742 /* If we have a match then we look for the next matching entry
743 * with an offset at least one step larger */
744 return next_for_match(j, j->level0, f,
745 direction == DIRECTION_DOWN ? f->current_offset + 1
746 : f->current_offset - 1,
747 direction, ret, offset);
748 }
749
750 static int next_beyond_location(sd_journal *j, JournalFile *f, direction_t direction) {
751 Object *c;
752 uint64_t cp, n_entries;
753 int r;
754
755 assert(j);
756 assert(f);
757
758 n_entries = le64toh(f->header->n_entries);
759
760 /* If we hit EOF before, we don't need to look into this file again
761 * unless direction changed or new entries appeared. */
762 if (f->last_direction == direction && f->location_type == LOCATION_TAIL &&
763 n_entries == f->last_n_entries)
764 return 0;
765
766 f->last_n_entries = n_entries;
767
768 if (f->last_direction == direction && f->current_offset > 0) {
769 /* LOCATION_SEEK here means we did the work in a previous
770 * iteration and the current location already points to a
771 * candidate entry. */
772 if (f->location_type != LOCATION_SEEK) {
773 r = next_with_matches(j, f, direction, &c, &cp);
774 if (r <= 0)
775 return r;
776
777 journal_file_save_location(f, c, cp);
778 }
779 } else {
780 f->last_direction = direction;
781
782 r = find_location_with_matches(j, f, direction, &c, &cp);
783 if (r <= 0)
784 return r;
785
786 journal_file_save_location(f, c, cp);
787 }
788
789 /* OK, we found the spot, now let's advance until an entry
790 * that is actually different from what we were previously
791 * looking at. This is necessary to handle entries which exist
792 * in two (or more) journal files, and which shall all be
793 * suppressed but one. */
794
795 for (;;) {
796 bool found;
797
798 if (j->current_location.type == LOCATION_DISCRETE) {
799 int k;
800
801 k = compare_with_location(f, &j->current_location, j->current_file);
802
803 found = direction == DIRECTION_DOWN ? k > 0 : k < 0;
804 } else
805 found = true;
806
807 if (found)
808 return 1;
809
810 r = next_with_matches(j, f, direction, &c, &cp);
811 if (r <= 0)
812 return r;
813
814 journal_file_save_location(f, c, cp);
815 }
816 }
817
818 static int real_journal_next(sd_journal *j, direction_t direction) {
819 JournalFile *new_file = NULL;
820 unsigned i, n_files;
821 const void **files;
822 Object *o;
823 int r;
824
825 assert_return(j, -EINVAL);
826 assert_return(!journal_pid_changed(j), -ECHILD);
827
828 r = iterated_cache_get(j->files_cache, NULL, &files, &n_files);
829 if (r < 0)
830 return r;
831
832 for (i = 0; i < n_files; i++) {
833 JournalFile *f = (JournalFile *)files[i];
834 bool found;
835
836 r = next_beyond_location(j, f, direction);
837 if (r < 0) {
838 log_debug_errno(r, "Can't iterate through %s, ignoring: %m", f->path);
839 remove_file_real(j, f);
840 continue;
841 } else if (r == 0) {
842 f->location_type = LOCATION_TAIL;
843 continue;
844 }
845
846 if (!new_file)
847 found = true;
848 else {
849 int k;
850
851 k = journal_file_compare_locations(f, new_file);
852
853 found = direction == DIRECTION_DOWN ? k < 0 : k > 0;
854 }
855
856 if (found)
857 new_file = f;
858 }
859
860 if (!new_file)
861 return 0;
862
863 r = journal_file_move_to_object(new_file, OBJECT_ENTRY, new_file->current_offset, &o);
864 if (r < 0)
865 return r;
866
867 set_location(j, new_file, o);
868
869 return 1;
870 }
871
872 _public_ int sd_journal_next(sd_journal *j) {
873 return real_journal_next(j, DIRECTION_DOWN);
874 }
875
876 _public_ int sd_journal_previous(sd_journal *j) {
877 return real_journal_next(j, DIRECTION_UP);
878 }
879
880 static int real_journal_next_skip(sd_journal *j, direction_t direction, uint64_t skip) {
881 int c = 0, r;
882
883 assert_return(j, -EINVAL);
884 assert_return(!journal_pid_changed(j), -ECHILD);
885 assert_return(skip <= INT_MAX, -ERANGE);
886
887 if (skip == 0) {
888 /* If this is not a discrete skip, then at least
889 * resolve the current location */
890 if (j->current_location.type != LOCATION_DISCRETE) {
891 r = real_journal_next(j, direction);
892 if (r < 0)
893 return r;
894 }
895
896 return 0;
897 }
898
899 do {
900 r = real_journal_next(j, direction);
901 if (r < 0)
902 return r;
903
904 if (r == 0)
905 return c;
906
907 skip--;
908 c++;
909 } while (skip > 0);
910
911 return c;
912 }
913
914 _public_ int sd_journal_next_skip(sd_journal *j, uint64_t skip) {
915 return real_journal_next_skip(j, DIRECTION_DOWN, skip);
916 }
917
918 _public_ int sd_journal_previous_skip(sd_journal *j, uint64_t skip) {
919 return real_journal_next_skip(j, DIRECTION_UP, skip);
920 }
921
922 _public_ int sd_journal_get_cursor(sd_journal *j, char **cursor) {
923 Object *o;
924 int r;
925
926 assert_return(j, -EINVAL);
927 assert_return(!journal_pid_changed(j), -ECHILD);
928 assert_return(cursor, -EINVAL);
929
930 if (!j->current_file || j->current_file->current_offset <= 0)
931 return -EADDRNOTAVAIL;
932
933 r = journal_file_move_to_object(j->current_file, OBJECT_ENTRY, j->current_file->current_offset, &o);
934 if (r < 0)
935 return r;
936
937 if (asprintf(cursor,
938 "s=%s;i=%"PRIx64";b=%s;m=%"PRIx64";t=%"PRIx64";x=%"PRIx64,
939 SD_ID128_TO_STRING(j->current_file->header->seqnum_id), le64toh(o->entry.seqnum),
940 SD_ID128_TO_STRING(o->entry.boot_id), le64toh(o->entry.monotonic),
941 le64toh(o->entry.realtime),
942 le64toh(o->entry.xor_hash)) < 0)
943 return -ENOMEM;
944
945 return 0;
946 }
947
948 _public_ int sd_journal_seek_cursor(sd_journal *j, const char *cursor) {
949 unsigned long long seqnum, monotonic, realtime, xor_hash;
950 bool seqnum_id_set = false,
951 seqnum_set = false,
952 boot_id_set = false,
953 monotonic_set = false,
954 realtime_set = false,
955 xor_hash_set = false;
956 sd_id128_t seqnum_id, boot_id;
957 int r;
958
959 assert_return(j, -EINVAL);
960 assert_return(!journal_pid_changed(j), -ECHILD);
961 assert_return(!isempty(cursor), -EINVAL);
962
963 for (const char *p = cursor;;) {
964 _cleanup_free_ char *word = NULL;
965
966 r = extract_first_word(&p, &word, ";", EXTRACT_DONT_COALESCE_SEPARATORS);
967 if (r < 0)
968 return r;
969 if (r == 0)
970 break;
971
972 if (word[0] == '\0' || word[1] != '=')
973 return -EINVAL;
974
975 switch (word[0]) {
976 case 's':
977 seqnum_id_set = true;
978 r = sd_id128_from_string(word + 2, &seqnum_id);
979 if (r < 0)
980 return r;
981 break;
982
983 case 'i':
984 seqnum_set = true;
985 if (sscanf(word + 2, "%llx", &seqnum) != 1)
986 return -EINVAL;
987 break;
988
989 case 'b':
990 boot_id_set = true;
991 r = sd_id128_from_string(word + 2, &boot_id);
992 break;
993
994 case 'm':
995 monotonic_set = true;
996 if (sscanf(word + 2, "%llx", &monotonic) != 1)
997 return -EINVAL;
998 break;
999
1000 case 't':
1001 realtime_set = true;
1002 if (sscanf(word + 2, "%llx", &realtime) != 1)
1003 return -EINVAL;
1004 break;
1005
1006 case 'x':
1007 xor_hash_set = true;
1008 if (sscanf(word + 2, "%llx", &xor_hash) != 1)
1009 return -EINVAL;
1010 break;
1011 }
1012 }
1013
1014 if ((!seqnum_set || !seqnum_id_set) &&
1015 (!monotonic_set || !boot_id_set) &&
1016 !realtime_set)
1017 return -EINVAL;
1018
1019 detach_location(j);
1020 j->current_location = (Location) {
1021 .type = LOCATION_SEEK,
1022 };
1023
1024 if (realtime_set) {
1025 j->current_location.realtime = (uint64_t) realtime;
1026 j->current_location.realtime_set = true;
1027 }
1028
1029 if (seqnum_set && seqnum_id_set) {
1030 j->current_location.seqnum = (uint64_t) seqnum;
1031 j->current_location.seqnum_id = seqnum_id;
1032 j->current_location.seqnum_set = true;
1033 }
1034
1035 if (monotonic_set && boot_id_set) {
1036 j->current_location.monotonic = (uint64_t) monotonic;
1037 j->current_location.boot_id = boot_id;
1038 j->current_location.monotonic_set = true;
1039 }
1040
1041 if (xor_hash_set) {
1042 j->current_location.xor_hash = (uint64_t) xor_hash;
1043 j->current_location.xor_hash_set = true;
1044 }
1045
1046 return 0;
1047 }
1048
1049 _public_ int sd_journal_test_cursor(sd_journal *j, const char *cursor) {
1050 int r;
1051 Object *o;
1052
1053 assert_return(j, -EINVAL);
1054 assert_return(!journal_pid_changed(j), -ECHILD);
1055 assert_return(!isempty(cursor), -EINVAL);
1056
1057 if (!j->current_file || j->current_file->current_offset <= 0)
1058 return -EADDRNOTAVAIL;
1059
1060 r = journal_file_move_to_object(j->current_file, OBJECT_ENTRY, j->current_file->current_offset, &o);
1061 if (r < 0)
1062 return r;
1063
1064 for (;;) {
1065 _cleanup_free_ char *item = NULL;
1066 unsigned long long ll;
1067 sd_id128_t id;
1068 int k = 0;
1069
1070 r = extract_first_word(&cursor, &item, ";", EXTRACT_DONT_COALESCE_SEPARATORS);
1071 if (r < 0)
1072 return r;
1073
1074 if (r == 0)
1075 break;
1076
1077 if (strlen(item) < 2 || item[1] != '=')
1078 return -EINVAL;
1079
1080 switch (item[0]) {
1081
1082 case 's':
1083 k = sd_id128_from_string(item+2, &id);
1084 if (k < 0)
1085 return k;
1086 if (!sd_id128_equal(id, j->current_file->header->seqnum_id))
1087 return 0;
1088 break;
1089
1090 case 'i':
1091 if (sscanf(item+2, "%llx", &ll) != 1)
1092 return -EINVAL;
1093 if (ll != le64toh(o->entry.seqnum))
1094 return 0;
1095 break;
1096
1097 case 'b':
1098 k = sd_id128_from_string(item+2, &id);
1099 if (k < 0)
1100 return k;
1101 if (!sd_id128_equal(id, o->entry.boot_id))
1102 return 0;
1103 break;
1104
1105 case 'm':
1106 if (sscanf(item+2, "%llx", &ll) != 1)
1107 return -EINVAL;
1108 if (ll != le64toh(o->entry.monotonic))
1109 return 0;
1110 break;
1111
1112 case 't':
1113 if (sscanf(item+2, "%llx", &ll) != 1)
1114 return -EINVAL;
1115 if (ll != le64toh(o->entry.realtime))
1116 return 0;
1117 break;
1118
1119 case 'x':
1120 if (sscanf(item+2, "%llx", &ll) != 1)
1121 return -EINVAL;
1122 if (ll != le64toh(o->entry.xor_hash))
1123 return 0;
1124 break;
1125 }
1126 }
1127
1128 return 1;
1129 }
1130
1131 _public_ int sd_journal_seek_monotonic_usec(sd_journal *j, sd_id128_t boot_id, uint64_t usec) {
1132 assert_return(j, -EINVAL);
1133 assert_return(!journal_pid_changed(j), -ECHILD);
1134
1135 detach_location(j);
1136
1137 j->current_location = (Location) {
1138 .type = LOCATION_SEEK,
1139 .boot_id = boot_id,
1140 .monotonic = usec,
1141 .monotonic_set = true,
1142 };
1143
1144 return 0;
1145 }
1146
1147 _public_ int sd_journal_seek_realtime_usec(sd_journal *j, uint64_t usec) {
1148 assert_return(j, -EINVAL);
1149 assert_return(!journal_pid_changed(j), -ECHILD);
1150
1151 detach_location(j);
1152
1153 j->current_location = (Location) {
1154 .type = LOCATION_SEEK,
1155 .realtime = usec,
1156 .realtime_set = true,
1157 };
1158
1159 return 0;
1160 }
1161
1162 _public_ int sd_journal_seek_head(sd_journal *j) {
1163 assert_return(j, -EINVAL);
1164 assert_return(!journal_pid_changed(j), -ECHILD);
1165
1166 detach_location(j);
1167
1168 j->current_location = (Location) {
1169 .type = LOCATION_HEAD,
1170 };
1171
1172 return 0;
1173 }
1174
1175 _public_ int sd_journal_seek_tail(sd_journal *j) {
1176 assert_return(j, -EINVAL);
1177 assert_return(!journal_pid_changed(j), -ECHILD);
1178
1179 detach_location(j);
1180
1181 j->current_location = (Location) {
1182 .type = LOCATION_TAIL,
1183 };
1184
1185 return 0;
1186 }
1187
1188 static void check_network(sd_journal *j, int fd) {
1189 assert(j);
1190
1191 if (j->on_network)
1192 return;
1193
1194 j->on_network = fd_is_network_fs(fd);
1195 }
1196
1197 static bool file_has_type_prefix(const char *prefix, const char *filename) {
1198 const char *full, *tilded, *atted;
1199
1200 full = strjoina(prefix, ".journal");
1201 tilded = strjoina(full, "~");
1202 atted = strjoina(prefix, "@");
1203
1204 return STR_IN_SET(filename, full, tilded) ||
1205 startswith(filename, atted);
1206 }
1207
1208 static bool file_type_wanted(int flags, const char *filename) {
1209 assert(filename);
1210
1211 if (!endswith(filename, ".journal") && !endswith(filename, ".journal~"))
1212 return false;
1213
1214 /* no flags set → every type is OK */
1215 if (!(flags & (SD_JOURNAL_SYSTEM | SD_JOURNAL_CURRENT_USER)))
1216 return true;
1217
1218 if (flags & SD_JOURNAL_SYSTEM && file_has_type_prefix("system", filename))
1219 return true;
1220
1221 if (flags & SD_JOURNAL_CURRENT_USER) {
1222 char prefix[5 + DECIMAL_STR_MAX(uid_t) + 1];
1223
1224 xsprintf(prefix, "user-"UID_FMT, getuid());
1225
1226 if (file_has_type_prefix(prefix, filename))
1227 return true;
1228 }
1229
1230 return false;
1231 }
1232
1233 static bool path_has_prefix(sd_journal *j, const char *path, const char *prefix) {
1234 assert(j);
1235 assert(path);
1236 assert(prefix);
1237
1238 if (j->toplevel_fd >= 0)
1239 return false;
1240
1241 return path_startswith(path, prefix);
1242 }
1243
1244 static void track_file_disposition(sd_journal *j, JournalFile *f) {
1245 assert(j);
1246 assert(f);
1247
1248 if (!j->has_runtime_files && path_has_prefix(j, f->path, "/run"))
1249 j->has_runtime_files = true;
1250 else if (!j->has_persistent_files && path_has_prefix(j, f->path, "/var"))
1251 j->has_persistent_files = true;
1252 }
1253
1254 static const char *skip_slash(const char *p) {
1255
1256 if (!p)
1257 return NULL;
1258
1259 while (*p == '/')
1260 p++;
1261
1262 return p;
1263 }
1264
1265 static int add_any_file(
1266 sd_journal *j,
1267 int fd,
1268 const char *path) {
1269
1270 bool close_fd = false;
1271 JournalFile *f;
1272 struct stat st;
1273 int r, k;
1274
1275 assert(j);
1276 assert(fd >= 0 || path);
1277
1278 if (fd < 0) {
1279 if (j->toplevel_fd >= 0)
1280 /* If there's a top-level fd defined make the path relative, explicitly, since otherwise
1281 * openat() ignores the first argument. */
1282
1283 fd = openat(j->toplevel_fd, skip_slash(path), O_RDONLY|O_CLOEXEC|O_NONBLOCK);
1284 else
1285 fd = open(path, O_RDONLY|O_CLOEXEC|O_NONBLOCK);
1286 if (fd < 0) {
1287 r = log_debug_errno(errno, "Failed to open journal file %s: %m", path);
1288 goto finish;
1289 }
1290
1291 close_fd = true;
1292
1293 r = fd_nonblock(fd, false);
1294 if (r < 0) {
1295 r = log_debug_errno(errno, "Failed to turn off O_NONBLOCK for %s: %m", path);
1296 goto finish;
1297 }
1298 }
1299
1300 if (fstat(fd, &st) < 0) {
1301 r = log_debug_errno(errno, "Failed to fstat file '%s': %m", path);
1302 goto finish;
1303 }
1304
1305 r = stat_verify_regular(&st);
1306 if (r < 0) {
1307 log_debug_errno(r, "Refusing to open '%s', as it is not a regular file.", path);
1308 goto finish;
1309 }
1310
1311 f = ordered_hashmap_get(j->files, path);
1312 if (f) {
1313 if (f->last_stat.st_dev == st.st_dev &&
1314 f->last_stat.st_ino == st.st_ino) {
1315
1316 /* We already track this file, under the same path and with the same device/inode numbers, it's
1317 * hence really the same. Mark this file as seen in this generation. This is used to GC old
1318 * files in process_q_overflow() to detect journal files that are still there and discern them
1319 * from those which are gone. */
1320
1321 f->last_seen_generation = j->generation;
1322 r = 0;
1323 goto finish;
1324 }
1325
1326 /* So we tracked a file under this name, but it has a different inode/device. In that case, it got
1327 * replaced (probably due to rotation?), let's drop it hence from our list. */
1328 remove_file_real(j, f);
1329 f = NULL;
1330 }
1331
1332 if (ordered_hashmap_size(j->files) >= JOURNAL_FILES_MAX) {
1333 log_debug("Too many open journal files, not adding %s.", path);
1334 r = -ETOOMANYREFS;
1335 goto finish;
1336 }
1337
1338 r = journal_file_open(fd, path, O_RDONLY, 0, false, 0, false, NULL, j->mmap, NULL, &f);
1339 if (r < 0) {
1340 log_debug_errno(r, "Failed to open journal file %s: %m", path);
1341 goto finish;
1342 }
1343
1344 /* journal_file_dump(f); */
1345
1346 r = ordered_hashmap_put(j->files, f->path, f);
1347 if (r < 0) {
1348 f->close_fd = false; /* make sure journal_file_close() doesn't close the caller's fd (or our own). We'll let the caller do that, or ourselves */
1349 (void) journal_file_close(f);
1350 goto finish;
1351 }
1352
1353 close_fd = false; /* the fd is now owned by the JournalFile object */
1354
1355 f->last_seen_generation = j->generation;
1356
1357 track_file_disposition(j, f);
1358 check_network(j, f->fd);
1359
1360 j->current_invalidate_counter++;
1361
1362 log_debug("File %s added.", f->path);
1363
1364 r = 0;
1365
1366 finish:
1367 if (close_fd)
1368 safe_close(fd);
1369
1370 if (r < 0) {
1371 k = journal_put_error(j, r, path);
1372 if (k < 0)
1373 return k;
1374 }
1375
1376 return r;
1377 }
1378
1379 static int add_file_by_name(
1380 sd_journal *j,
1381 const char *prefix,
1382 const char *filename) {
1383
1384 const char *path;
1385
1386 assert(j);
1387 assert(prefix);
1388 assert(filename);
1389
1390 if (j->no_new_files)
1391 return 0;
1392
1393 if (!file_type_wanted(j->flags, filename))
1394 return 0;
1395
1396 path = prefix_roota(prefix, filename);
1397 return add_any_file(j, -1, path);
1398 }
1399
1400 static void remove_file_by_name(
1401 sd_journal *j,
1402 const char *prefix,
1403 const char *filename) {
1404
1405 const char *path;
1406 JournalFile *f;
1407
1408 assert(j);
1409 assert(prefix);
1410 assert(filename);
1411
1412 path = prefix_roota(prefix, filename);
1413 f = ordered_hashmap_get(j->files, path);
1414 if (!f)
1415 return;
1416
1417 remove_file_real(j, f);
1418 }
1419
1420 static void remove_file_real(sd_journal *j, JournalFile *f) {
1421 assert(j);
1422 assert(f);
1423
1424 (void) ordered_hashmap_remove(j->files, f->path);
1425
1426 log_debug("File %s removed.", f->path);
1427
1428 if (j->current_file == f) {
1429 j->current_file = NULL;
1430 j->current_field = 0;
1431 }
1432
1433 if (j->unique_file == f) {
1434 /* Jump to the next unique_file or NULL if that one was last */
1435 j->unique_file = ordered_hashmap_next(j->files, j->unique_file->path);
1436 j->unique_offset = 0;
1437 if (!j->unique_file)
1438 j->unique_file_lost = true;
1439 }
1440
1441 if (j->fields_file == f) {
1442 j->fields_file = ordered_hashmap_next(j->files, j->fields_file->path);
1443 j->fields_offset = 0;
1444 if (!j->fields_file)
1445 j->fields_file_lost = true;
1446 }
1447
1448 (void) journal_file_close(f);
1449
1450 j->current_invalidate_counter++;
1451 }
1452
1453 static int dirname_is_machine_id(const char *fn) {
1454 sd_id128_t id, machine;
1455 const char *e;
1456 int r;
1457
1458 /* Returns true if the specified directory name matches the local machine ID */
1459
1460 r = sd_id128_get_machine(&machine);
1461 if (r < 0)
1462 return r;
1463
1464 e = strchr(fn, '.');
1465 if (e) {
1466 const char *k;
1467
1468 /* Looks like it has a namespace suffix. Verify that. */
1469 if (!log_namespace_name_valid(e + 1))
1470 return false;
1471
1472 k = strndupa_safe(fn, e - fn);
1473 r = sd_id128_from_string(k, &id);
1474 } else
1475 r = sd_id128_from_string(fn, &id);
1476 if (r < 0)
1477 return r;
1478
1479 return sd_id128_equal(id, machine);
1480 }
1481
1482 static int dirname_has_namespace(const char *fn, const char *namespace) {
1483 const char *e;
1484
1485 /* Returns true if the specified directory name matches the specified namespace */
1486
1487 e = strchr(fn, '.');
1488 if (e) {
1489 const char *k;
1490
1491 if (!namespace)
1492 return false;
1493
1494 if (!streq(e + 1, namespace))
1495 return false;
1496
1497 k = strndupa_safe(fn, e - fn);
1498 return id128_is_valid(k);
1499 }
1500
1501 if (namespace)
1502 return false;
1503
1504 return id128_is_valid(fn);
1505 }
1506
1507 static bool dirent_is_journal_file(const struct dirent *de) {
1508 assert(de);
1509
1510 /* Returns true if the specified directory entry looks like a journal file we might be interested in */
1511
1512 if (!IN_SET(de->d_type, DT_REG, DT_LNK, DT_UNKNOWN))
1513 return false;
1514
1515 return endswith(de->d_name, ".journal") ||
1516 endswith(de->d_name, ".journal~");
1517 }
1518
1519 static bool dirent_is_journal_subdir(const struct dirent *de) {
1520 const char *e, *n;
1521 assert(de);
1522
1523 /* returns true if the specified directory entry looks like a directory that might contain journal
1524 * files we might be interested in, i.e. is either a 128bit ID or a 128bit ID suffixed by a
1525 * namespace. */
1526
1527 if (!IN_SET(de->d_type, DT_DIR, DT_LNK, DT_UNKNOWN))
1528 return false;
1529
1530 e = strchr(de->d_name, '.');
1531 if (!e)
1532 return id128_is_valid(de->d_name); /* No namespace */
1533
1534 n = strndupa_safe(de->d_name, e - de->d_name);
1535 if (!id128_is_valid(n))
1536 return false;
1537
1538 return log_namespace_name_valid(e + 1);
1539 }
1540
1541 static int directory_open(sd_journal *j, const char *path, DIR **ret) {
1542 DIR *d;
1543
1544 assert(j);
1545 assert(path);
1546 assert(ret);
1547
1548 if (j->toplevel_fd < 0)
1549 d = opendir(path);
1550 else
1551 /* Open the specified directory relative to the toplevel fd. Enforce that the path specified is
1552 * relative, by dropping the initial slash */
1553 d = xopendirat(j->toplevel_fd, skip_slash(path), 0);
1554 if (!d)
1555 return -errno;
1556
1557 *ret = d;
1558 return 0;
1559 }
1560
1561 static int add_directory(sd_journal *j, const char *prefix, const char *dirname);
1562
1563 static void directory_enumerate(sd_journal *j, Directory *m, DIR *d) {
1564 assert(j);
1565 assert(m);
1566 assert(d);
1567
1568 FOREACH_DIRENT_ALL(de, d, goto fail) {
1569 if (dirent_is_journal_file(de))
1570 (void) add_file_by_name(j, m->path, de->d_name);
1571
1572 if (m->is_root && dirent_is_journal_subdir(de))
1573 (void) add_directory(j, m->path, de->d_name);
1574 }
1575
1576 return;
1577 fail:
1578 log_debug_errno(errno, "Failed to enumerate directory %s, ignoring: %m", m->path);
1579 }
1580
1581 static void directory_watch(sd_journal *j, Directory *m, int fd, uint32_t mask) {
1582 int r;
1583
1584 assert(j);
1585 assert(m);
1586 assert(fd >= 0);
1587
1588 /* Watch this directory if that's enabled and if it not being watched yet. */
1589
1590 if (m->wd > 0) /* Already have a watch? */
1591 return;
1592 if (j->inotify_fd < 0) /* Not watching at all? */
1593 return;
1594
1595 m->wd = inotify_add_watch_fd(j->inotify_fd, fd, mask);
1596 if (m->wd < 0) {
1597 log_debug_errno(errno, "Failed to watch journal directory '%s', ignoring: %m", m->path);
1598 return;
1599 }
1600
1601 r = hashmap_put(j->directories_by_wd, INT_TO_PTR(m->wd), m);
1602 if (r == -EEXIST)
1603 log_debug_errno(r, "Directory '%s' already being watched under a different path, ignoring: %m", m->path);
1604 if (r < 0) {
1605 log_debug_errno(r, "Failed to add watch for journal directory '%s' to hashmap, ignoring: %m", m->path);
1606 (void) inotify_rm_watch(j->inotify_fd, m->wd);
1607 m->wd = -1;
1608 }
1609 }
1610
1611 static int add_directory(
1612 sd_journal *j,
1613 const char *prefix,
1614 const char *dirname) {
1615
1616 _cleanup_free_ char *path = NULL;
1617 _cleanup_closedir_ DIR *d = NULL;
1618 Directory *m;
1619 int r, k;
1620
1621 assert(j);
1622 assert(prefix);
1623
1624 /* Adds a journal file directory to watch. If the directory is already tracked this updates the inotify watch
1625 * and reenumerates directory contents */
1626
1627 path = path_join(prefix, dirname);
1628 if (!path) {
1629 r = -ENOMEM;
1630 goto fail;
1631 }
1632
1633 log_debug("Considering directory '%s'.", path);
1634
1635 /* We consider everything local that is in a directory for the local machine ID, or that is stored in /run */
1636 if ((j->flags & SD_JOURNAL_LOCAL_ONLY) &&
1637 !((dirname && dirname_is_machine_id(dirname) > 0) || path_has_prefix(j, path, "/run")))
1638 return 0;
1639
1640 if (dirname &&
1641 (!(FLAGS_SET(j->flags, SD_JOURNAL_ALL_NAMESPACES) ||
1642 dirname_has_namespace(dirname, j->namespace) > 0 ||
1643 (FLAGS_SET(j->flags, SD_JOURNAL_INCLUDE_DEFAULT_NAMESPACE) && dirname_has_namespace(dirname, NULL) > 0))))
1644 return 0;
1645
1646 r = directory_open(j, path, &d);
1647 if (r < 0) {
1648 log_debug_errno(r, "Failed to open directory '%s': %m", path);
1649 goto fail;
1650 }
1651
1652 m = hashmap_get(j->directories_by_path, path);
1653 if (!m) {
1654 m = new(Directory, 1);
1655 if (!m) {
1656 r = -ENOMEM;
1657 goto fail;
1658 }
1659
1660 *m = (Directory) {
1661 .is_root = false,
1662 .path = path,
1663 };
1664
1665 if (hashmap_put(j->directories_by_path, m->path, m) < 0) {
1666 free(m);
1667 r = -ENOMEM;
1668 goto fail;
1669 }
1670
1671 path = NULL; /* avoid freeing in cleanup */
1672 j->current_invalidate_counter++;
1673
1674 log_debug("Directory %s added.", m->path);
1675
1676 } else if (m->is_root)
1677 return 0; /* Don't 'downgrade' from root directory */
1678
1679 m->last_seen_generation = j->generation;
1680
1681 directory_watch(j, m, dirfd(d),
1682 IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB|IN_DELETE|
1683 IN_DELETE_SELF|IN_MOVE_SELF|IN_UNMOUNT|IN_MOVED_FROM|
1684 IN_ONLYDIR);
1685
1686 if (!j->no_new_files)
1687 directory_enumerate(j, m, d);
1688
1689 check_network(j, dirfd(d));
1690
1691 return 0;
1692
1693 fail:
1694 k = journal_put_error(j, r, path ?: prefix);
1695 if (k < 0)
1696 return k;
1697
1698 return r;
1699 }
1700
1701 static int add_root_directory(sd_journal *j, const char *p, bool missing_ok) {
1702
1703 _cleanup_closedir_ DIR *d = NULL;
1704 Directory *m;
1705 int r, k;
1706
1707 assert(j);
1708
1709 /* Adds a root directory to our set of directories to use. If the root directory is already in the set, we
1710 * update the inotify logic, and renumerate the directory entries. This call may hence be called to initially
1711 * populate the set, as well as to update it later. */
1712
1713 if (p) {
1714 /* If there's a path specified, use it. */
1715
1716 log_debug("Considering root directory '%s'.", p);
1717
1718 if ((j->flags & SD_JOURNAL_RUNTIME_ONLY) &&
1719 !path_has_prefix(j, p, "/run"))
1720 return -EINVAL;
1721
1722 if (j->prefix)
1723 p = strjoina(j->prefix, p);
1724
1725 r = directory_open(j, p, &d);
1726 if (r == -ENOENT && missing_ok)
1727 return 0;
1728 if (r < 0) {
1729 log_debug_errno(r, "Failed to open root directory %s: %m", p);
1730 goto fail;
1731 }
1732 } else {
1733 _cleanup_close_ int dfd = -1;
1734
1735 /* If there's no path specified, then we use the top-level fd itself. We duplicate the fd here, since
1736 * opendir() will take possession of the fd, and close it, which we don't want. */
1737
1738 p = "."; /* store this as "." in the directories hashmap */
1739
1740 dfd = fcntl(j->toplevel_fd, F_DUPFD_CLOEXEC, 3);
1741 if (dfd < 0) {
1742 r = -errno;
1743 goto fail;
1744 }
1745
1746 d = take_fdopendir(&dfd);
1747 if (!d) {
1748 r = -errno;
1749 goto fail;
1750 }
1751
1752 rewinddir(d);
1753 }
1754
1755 m = hashmap_get(j->directories_by_path, p);
1756 if (!m) {
1757 m = new0(Directory, 1);
1758 if (!m) {
1759 r = -ENOMEM;
1760 goto fail;
1761 }
1762
1763 m->is_root = true;
1764
1765 m->path = strdup(p);
1766 if (!m->path) {
1767 free(m);
1768 r = -ENOMEM;
1769 goto fail;
1770 }
1771
1772 if (hashmap_put(j->directories_by_path, m->path, m) < 0) {
1773 free(m->path);
1774 free(m);
1775 r = -ENOMEM;
1776 goto fail;
1777 }
1778
1779 j->current_invalidate_counter++;
1780
1781 log_debug("Root directory %s added.", m->path);
1782
1783 } else if (!m->is_root)
1784 return 0;
1785
1786 directory_watch(j, m, dirfd(d),
1787 IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB|IN_DELETE|
1788 IN_ONLYDIR);
1789
1790 if (!j->no_new_files)
1791 directory_enumerate(j, m, d);
1792
1793 check_network(j, dirfd(d));
1794
1795 return 0;
1796
1797 fail:
1798 k = journal_put_error(j, r, p);
1799 if (k < 0)
1800 return k;
1801
1802 return r;
1803 }
1804
1805 static void remove_directory(sd_journal *j, Directory *d) {
1806 assert(j);
1807
1808 if (d->wd > 0) {
1809 hashmap_remove(j->directories_by_wd, INT_TO_PTR(d->wd));
1810
1811 if (j->inotify_fd >= 0)
1812 (void) inotify_rm_watch(j->inotify_fd, d->wd);
1813 }
1814
1815 hashmap_remove(j->directories_by_path, d->path);
1816
1817 if (d->is_root)
1818 log_debug("Root directory %s removed.", d->path);
1819 else
1820 log_debug("Directory %s removed.", d->path);
1821
1822 free(d->path);
1823 free(d);
1824 }
1825
1826 static int add_search_paths(sd_journal *j) {
1827
1828 static const char search_paths[] =
1829 "/run/log/journal\0"
1830 "/var/log/journal\0";
1831 const char *p;
1832
1833 assert(j);
1834
1835 /* We ignore most errors here, since the idea is to only open
1836 * what's actually accessible, and ignore the rest. */
1837
1838 NULSTR_FOREACH(p, search_paths)
1839 (void) add_root_directory(j, p, true);
1840
1841 if (!(j->flags & SD_JOURNAL_LOCAL_ONLY))
1842 (void) add_root_directory(j, "/var/log/journal/remote", true);
1843
1844 return 0;
1845 }
1846
1847 static int add_current_paths(sd_journal *j) {
1848 JournalFile *f;
1849
1850 assert(j);
1851 assert(j->no_new_files);
1852
1853 /* Simply adds all directories for files we have open as directories. We don't expect errors here, so we
1854 * treat them as fatal. */
1855
1856 ORDERED_HASHMAP_FOREACH(f, j->files) {
1857 _cleanup_free_ char *dir = NULL;
1858 int r;
1859
1860 dir = dirname_malloc(f->path);
1861 if (!dir)
1862 return -ENOMEM;
1863
1864 r = add_directory(j, dir, NULL);
1865 if (r < 0)
1866 return r;
1867 }
1868
1869 return 0;
1870 }
1871
1872 static int allocate_inotify(sd_journal *j) {
1873 assert(j);
1874
1875 if (j->inotify_fd < 0) {
1876 j->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
1877 if (j->inotify_fd < 0)
1878 return -errno;
1879 }
1880
1881 return hashmap_ensure_allocated(&j->directories_by_wd, NULL);
1882 }
1883
1884 static sd_journal *journal_new(int flags, const char *path, const char *namespace) {
1885 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
1886
1887 j = new0(sd_journal, 1);
1888 if (!j)
1889 return NULL;
1890
1891 j->original_pid = getpid_cached();
1892 j->toplevel_fd = -1;
1893 j->inotify_fd = -1;
1894 j->flags = flags;
1895 j->data_threshold = DEFAULT_DATA_THRESHOLD;
1896
1897 if (path) {
1898 char *t;
1899
1900 t = strdup(path);
1901 if (!t)
1902 return NULL;
1903
1904 if (flags & SD_JOURNAL_OS_ROOT)
1905 j->prefix = t;
1906 else
1907 j->path = t;
1908 }
1909
1910 if (namespace) {
1911 j->namespace = strdup(namespace);
1912 if (!j->namespace)
1913 return NULL;
1914 }
1915
1916 j->files = ordered_hashmap_new(&path_hash_ops);
1917 if (!j->files)
1918 return NULL;
1919
1920 j->files_cache = ordered_hashmap_iterated_cache_new(j->files);
1921 j->directories_by_path = hashmap_new(&path_hash_ops);
1922 j->mmap = mmap_cache_new();
1923 if (!j->files_cache || !j->directories_by_path || !j->mmap)
1924 return NULL;
1925
1926 return TAKE_PTR(j);
1927 }
1928
1929 #define OPEN_ALLOWED_FLAGS \
1930 (SD_JOURNAL_LOCAL_ONLY | \
1931 SD_JOURNAL_RUNTIME_ONLY | \
1932 SD_JOURNAL_SYSTEM | \
1933 SD_JOURNAL_CURRENT_USER | \
1934 SD_JOURNAL_ALL_NAMESPACES | \
1935 SD_JOURNAL_INCLUDE_DEFAULT_NAMESPACE)
1936
1937 _public_ int sd_journal_open_namespace(sd_journal **ret, const char *namespace, int flags) {
1938 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
1939 int r;
1940
1941 assert_return(ret, -EINVAL);
1942 assert_return((flags & ~OPEN_ALLOWED_FLAGS) == 0, -EINVAL);
1943
1944 j = journal_new(flags, NULL, namespace);
1945 if (!j)
1946 return -ENOMEM;
1947
1948 r = add_search_paths(j);
1949 if (r < 0)
1950 return r;
1951
1952 *ret = TAKE_PTR(j);
1953 return 0;
1954 }
1955
1956 _public_ int sd_journal_open(sd_journal **ret, int flags) {
1957 return sd_journal_open_namespace(ret, NULL, flags);
1958 }
1959
1960 #define OPEN_CONTAINER_ALLOWED_FLAGS \
1961 (SD_JOURNAL_LOCAL_ONLY | SD_JOURNAL_SYSTEM)
1962
1963 _public_ int sd_journal_open_container(sd_journal **ret, const char *machine, int flags) {
1964 _cleanup_free_ char *root = NULL, *class = NULL;
1965 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
1966 char *p;
1967 int r;
1968
1969 /* This is deprecated, people should use machined's OpenMachineRootDirectory() call instead in
1970 * combination with sd_journal_open_directory_fd(). */
1971
1972 assert_return(machine, -EINVAL);
1973 assert_return(ret, -EINVAL);
1974 assert_return((flags & ~OPEN_CONTAINER_ALLOWED_FLAGS) == 0, -EINVAL);
1975 assert_return(hostname_is_valid(machine, 0), -EINVAL);
1976
1977 p = strjoina("/run/systemd/machines/", machine);
1978 r = parse_env_file(NULL, p,
1979 "ROOT", &root,
1980 "CLASS", &class);
1981 if (r == -ENOENT)
1982 return -EHOSTDOWN;
1983 if (r < 0)
1984 return r;
1985 if (!root)
1986 return -ENODATA;
1987
1988 if (!streq_ptr(class, "container"))
1989 return -EIO;
1990
1991 j = journal_new(flags, root, NULL);
1992 if (!j)
1993 return -ENOMEM;
1994
1995 r = add_search_paths(j);
1996 if (r < 0)
1997 return r;
1998
1999 *ret = TAKE_PTR(j);
2000 return 0;
2001 }
2002
2003 #define OPEN_DIRECTORY_ALLOWED_FLAGS \
2004 (SD_JOURNAL_OS_ROOT | \
2005 SD_JOURNAL_SYSTEM | SD_JOURNAL_CURRENT_USER )
2006
2007 _public_ int sd_journal_open_directory(sd_journal **ret, const char *path, int flags) {
2008 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
2009 int r;
2010
2011 assert_return(ret, -EINVAL);
2012 assert_return(path, -EINVAL);
2013 assert_return((flags & ~OPEN_DIRECTORY_ALLOWED_FLAGS) == 0, -EINVAL);
2014
2015 j = journal_new(flags, path, NULL);
2016 if (!j)
2017 return -ENOMEM;
2018
2019 if (flags & SD_JOURNAL_OS_ROOT)
2020 r = add_search_paths(j);
2021 else
2022 r = add_root_directory(j, path, false);
2023 if (r < 0)
2024 return r;
2025
2026 *ret = TAKE_PTR(j);
2027 return 0;
2028 }
2029
2030 _public_ int sd_journal_open_files(sd_journal **ret, const char **paths, int flags) {
2031 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
2032 const char **path;
2033 int r;
2034
2035 assert_return(ret, -EINVAL);
2036 assert_return(flags == 0, -EINVAL);
2037
2038 j = journal_new(flags, NULL, NULL);
2039 if (!j)
2040 return -ENOMEM;
2041
2042 STRV_FOREACH(path, paths) {
2043 r = add_any_file(j, -1, *path);
2044 if (r < 0)
2045 return r;
2046 }
2047
2048 j->no_new_files = true;
2049
2050 *ret = TAKE_PTR(j);
2051 return 0;
2052 }
2053
2054 #define OPEN_DIRECTORY_FD_ALLOWED_FLAGS \
2055 (SD_JOURNAL_OS_ROOT | \
2056 SD_JOURNAL_SYSTEM | SD_JOURNAL_CURRENT_USER )
2057
2058 _public_ int sd_journal_open_directory_fd(sd_journal **ret, int fd, int flags) {
2059 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
2060 struct stat st;
2061 int r;
2062
2063 assert_return(ret, -EINVAL);
2064 assert_return(fd >= 0, -EBADF);
2065 assert_return((flags & ~OPEN_DIRECTORY_FD_ALLOWED_FLAGS) == 0, -EINVAL);
2066
2067 if (fstat(fd, &st) < 0)
2068 return -errno;
2069
2070 if (!S_ISDIR(st.st_mode))
2071 return -EBADFD;
2072
2073 j = journal_new(flags, NULL, NULL);
2074 if (!j)
2075 return -ENOMEM;
2076
2077 j->toplevel_fd = fd;
2078
2079 if (flags & SD_JOURNAL_OS_ROOT)
2080 r = add_search_paths(j);
2081 else
2082 r = add_root_directory(j, NULL, false);
2083 if (r < 0)
2084 return r;
2085
2086 *ret = TAKE_PTR(j);
2087 return 0;
2088 }
2089
2090 _public_ int sd_journal_open_files_fd(sd_journal **ret, int fds[], unsigned n_fds, int flags) {
2091 JournalFile *f;
2092 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
2093 unsigned i;
2094 int r;
2095
2096 assert_return(ret, -EINVAL);
2097 assert_return(n_fds > 0, -EBADF);
2098 assert_return(flags == 0, -EINVAL);
2099
2100 j = journal_new(flags, NULL, NULL);
2101 if (!j)
2102 return -ENOMEM;
2103
2104 for (i = 0; i < n_fds; i++) {
2105 struct stat st;
2106
2107 if (fds[i] < 0) {
2108 r = -EBADF;
2109 goto fail;
2110 }
2111
2112 if (fstat(fds[i], &st) < 0) {
2113 r = -errno;
2114 goto fail;
2115 }
2116
2117 r = stat_verify_regular(&st);
2118 if (r < 0)
2119 goto fail;
2120
2121 r = add_any_file(j, fds[i], NULL);
2122 if (r < 0)
2123 goto fail;
2124 }
2125
2126 j->no_new_files = true;
2127 j->no_inotify = true;
2128
2129 *ret = TAKE_PTR(j);
2130 return 0;
2131
2132 fail:
2133 /* If we fail, make sure we don't take possession of the files we managed to make use of successfully, and they
2134 * remain open */
2135 ORDERED_HASHMAP_FOREACH(f, j->files)
2136 f->close_fd = false;
2137
2138 return r;
2139 }
2140
2141 _public_ void sd_journal_close(sd_journal *j) {
2142 Directory *d;
2143
2144 if (!j)
2145 return;
2146
2147 sd_journal_flush_matches(j);
2148
2149 ordered_hashmap_free_with_destructor(j->files, journal_file_close);
2150 iterated_cache_free(j->files_cache);
2151
2152 while ((d = hashmap_first(j->directories_by_path)))
2153 remove_directory(j, d);
2154
2155 while ((d = hashmap_first(j->directories_by_wd)))
2156 remove_directory(j, d);
2157
2158 hashmap_free(j->directories_by_path);
2159 hashmap_free(j->directories_by_wd);
2160
2161 safe_close(j->inotify_fd);
2162
2163 if (j->mmap) {
2164 mmap_cache_stats_log_debug(j->mmap);
2165 mmap_cache_unref(j->mmap);
2166 }
2167
2168 hashmap_free_free(j->errors);
2169
2170 free(j->path);
2171 free(j->prefix);
2172 free(j->namespace);
2173 free(j->unique_field);
2174 free(j->fields_buffer);
2175 free(j);
2176 }
2177
2178 _public_ int sd_journal_get_realtime_usec(sd_journal *j, uint64_t *ret) {
2179 Object *o;
2180 JournalFile *f;
2181 int r;
2182
2183 assert_return(j, -EINVAL);
2184 assert_return(!journal_pid_changed(j), -ECHILD);
2185 assert_return(ret, -EINVAL);
2186
2187 f = j->current_file;
2188 if (!f)
2189 return -EADDRNOTAVAIL;
2190
2191 if (f->current_offset <= 0)
2192 return -EADDRNOTAVAIL;
2193
2194 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
2195 if (r < 0)
2196 return r;
2197
2198 *ret = le64toh(o->entry.realtime);
2199 return 0;
2200 }
2201
2202 _public_ int sd_journal_get_monotonic_usec(sd_journal *j, uint64_t *ret, sd_id128_t *ret_boot_id) {
2203 Object *o;
2204 JournalFile *f;
2205 int r;
2206
2207 assert_return(j, -EINVAL);
2208 assert_return(!journal_pid_changed(j), -ECHILD);
2209
2210 f = j->current_file;
2211 if (!f)
2212 return -EADDRNOTAVAIL;
2213
2214 if (f->current_offset <= 0)
2215 return -EADDRNOTAVAIL;
2216
2217 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
2218 if (r < 0)
2219 return r;
2220
2221 if (ret_boot_id)
2222 *ret_boot_id = o->entry.boot_id;
2223 else {
2224 sd_id128_t id;
2225
2226 r = sd_id128_get_boot(&id);
2227 if (r < 0)
2228 return r;
2229
2230 if (!sd_id128_equal(id, o->entry.boot_id))
2231 return -ESTALE;
2232 }
2233
2234 if (ret)
2235 *ret = le64toh(o->entry.monotonic);
2236
2237 return 0;
2238 }
2239
2240 static bool field_is_valid(const char *field) {
2241 const char *p;
2242
2243 assert(field);
2244
2245 if (isempty(field))
2246 return false;
2247
2248 if (startswith(field, "__"))
2249 return false;
2250
2251 for (p = field; *p; p++) {
2252
2253 if (*p == '_')
2254 continue;
2255
2256 if (*p >= 'A' && *p <= 'Z')
2257 continue;
2258
2259 if (*p >= '0' && *p <= '9')
2260 continue;
2261
2262 return false;
2263 }
2264
2265 return true;
2266 }
2267
2268 _public_ int sd_journal_get_data(sd_journal *j, const char *field, const void **data, size_t *size) {
2269 JournalFile *f;
2270 uint64_t i, n;
2271 size_t field_length;
2272 int r;
2273 Object *o;
2274
2275 assert_return(j, -EINVAL);
2276 assert_return(!journal_pid_changed(j), -ECHILD);
2277 assert_return(field, -EINVAL);
2278 assert_return(data, -EINVAL);
2279 assert_return(size, -EINVAL);
2280 assert_return(field_is_valid(field), -EINVAL);
2281
2282 f = j->current_file;
2283 if (!f)
2284 return -EADDRNOTAVAIL;
2285
2286 if (f->current_offset <= 0)
2287 return -EADDRNOTAVAIL;
2288
2289 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
2290 if (r < 0)
2291 return r;
2292
2293 field_length = strlen(field);
2294
2295 n = journal_file_entry_n_items(o);
2296 for (i = 0; i < n; i++) {
2297 Object *d;
2298 uint64_t p, l;
2299 le64_t le_hash;
2300 size_t t;
2301 int compression;
2302
2303 p = le64toh(o->entry.items[i].object_offset);
2304 le_hash = o->entry.items[i].hash;
2305 r = journal_file_move_to_object(f, OBJECT_DATA, p, &d);
2306 if (IN_SET(r, -EADDRNOTAVAIL, -EBADMSG)) {
2307 log_debug_errno(r, "Entry item %"PRIu64" data object is bad, skipping over it: %m", i);
2308 continue;
2309 }
2310 if (r < 0)
2311 return r;
2312
2313 if (le_hash != d->data.hash) {
2314 log_debug("Entry item %"PRIu64" hash is bad, skipping over it.", i);
2315 continue;
2316 }
2317
2318 l = le64toh(d->object.size) - offsetof(Object, data.payload);
2319
2320 compression = d->object.flags & OBJECT_COMPRESSION_MASK;
2321 if (compression) {
2322 #if HAVE_COMPRESSION
2323 r = decompress_startswith(compression,
2324 d->data.payload, l,
2325 &f->compress_buffer,
2326 field, field_length, '=');
2327 if (r < 0)
2328 log_debug_errno(r, "Cannot decompress %s object of length %"PRIu64" at offset "OFSfmt": %m",
2329 object_compressed_to_string(compression), l, p);
2330 else if (r > 0) {
2331
2332 size_t rsize;
2333
2334 r = decompress_blob(compression,
2335 d->data.payload, l,
2336 &f->compress_buffer, &rsize,
2337 j->data_threshold);
2338 if (r < 0)
2339 return r;
2340
2341 *data = f->compress_buffer;
2342 *size = (size_t) rsize;
2343
2344 return 0;
2345 }
2346 #else
2347 return -EPROTONOSUPPORT;
2348 #endif
2349 } else if (l >= field_length+1 &&
2350 memcmp(d->data.payload, field, field_length) == 0 &&
2351 d->data.payload[field_length] == '=') {
2352
2353 t = (size_t) l;
2354
2355 if ((uint64_t) t != l)
2356 return -E2BIG;
2357
2358 *data = d->data.payload;
2359 *size = t;
2360
2361 return 0;
2362 }
2363 }
2364
2365 return -ENOENT;
2366 }
2367
2368 static int return_data(
2369 sd_journal *j,
2370 JournalFile *f,
2371 Object *o,
2372 const void **ret_data,
2373 size_t *ret_size) {
2374
2375 size_t t;
2376 uint64_t l;
2377 int compression;
2378
2379 assert(j);
2380 assert(f);
2381
2382 l = le64toh(READ_NOW(o->object.size));
2383 if (l < offsetof(Object, data.payload))
2384 return -EBADMSG;
2385 l -= offsetof(Object, data.payload);
2386
2387 /* We can't read objects larger than 4G on a 32bit machine */
2388 t = (size_t) l;
2389 if ((uint64_t) t != l)
2390 return -E2BIG;
2391
2392 compression = o->object.flags & OBJECT_COMPRESSION_MASK;
2393 if (compression) {
2394 #if HAVE_COMPRESSION
2395 size_t rsize;
2396 int r;
2397
2398 r = decompress_blob(
2399 compression,
2400 o->data.payload, l,
2401 &f->compress_buffer, &rsize,
2402 j->data_threshold);
2403 if (r < 0)
2404 return r;
2405
2406 if (ret_data)
2407 *ret_data = f->compress_buffer;
2408 if (ret_size)
2409 *ret_size = (size_t) rsize;
2410 #else
2411 return -EPROTONOSUPPORT;
2412 #endif
2413 } else {
2414 if (ret_data)
2415 *ret_data = o->data.payload;
2416 if (ret_size)
2417 *ret_size = t;
2418 }
2419
2420 return 0;
2421 }
2422
2423 _public_ int sd_journal_enumerate_data(sd_journal *j, const void **data, size_t *size) {
2424 JournalFile *f;
2425 Object *o;
2426 int r;
2427
2428 assert_return(j, -EINVAL);
2429 assert_return(!journal_pid_changed(j), -ECHILD);
2430 assert_return(data, -EINVAL);
2431 assert_return(size, -EINVAL);
2432
2433 f = j->current_file;
2434 if (!f)
2435 return -EADDRNOTAVAIL;
2436
2437 if (f->current_offset <= 0)
2438 return -EADDRNOTAVAIL;
2439
2440 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
2441 if (r < 0)
2442 return r;
2443
2444 for (uint64_t n = journal_file_entry_n_items(o); j->current_field < n; j->current_field++) {
2445 uint64_t p;
2446 le64_t le_hash;
2447
2448 p = le64toh(o->entry.items[j->current_field].object_offset);
2449 le_hash = o->entry.items[j->current_field].hash;
2450 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
2451 if (IN_SET(r, -EADDRNOTAVAIL, -EBADMSG)) {
2452 log_debug_errno(r, "Entry item %"PRIu64" data object is bad, skipping over it: %m", j->current_field);
2453 continue;
2454 }
2455 if (r < 0)
2456 return r;
2457
2458 if (le_hash != o->data.hash) {
2459 log_debug("Entry item %"PRIu64" hash is bad, skipping over it.", j->current_field);
2460 continue;
2461 }
2462
2463 r = return_data(j, f, o, data, size);
2464 if (r == -EBADMSG) {
2465 log_debug("Entry item %"PRIu64" data payload is bad, skipping over it.", j->current_field);
2466 continue;
2467 }
2468 if (r < 0)
2469 return r;
2470
2471 j->current_field++;
2472
2473 return 1;
2474 }
2475
2476 return 0;
2477 }
2478
2479 _public_ int sd_journal_enumerate_available_data(sd_journal *j, const void **data, size_t *size) {
2480 for (;;) {
2481 int r;
2482
2483 r = sd_journal_enumerate_data(j, data, size);
2484 if (r >= 0)
2485 return r;
2486 if (!JOURNAL_ERRNO_IS_UNAVAILABLE_FIELD(r))
2487 return r;
2488 j->current_field++; /* Try with the next field */
2489 }
2490 }
2491
2492 _public_ void sd_journal_restart_data(sd_journal *j) {
2493 if (!j)
2494 return;
2495
2496 j->current_field = 0;
2497 }
2498
2499 static int reiterate_all_paths(sd_journal *j) {
2500 assert(j);
2501
2502 if (j->no_new_files)
2503 return add_current_paths(j);
2504
2505 if (j->flags & SD_JOURNAL_OS_ROOT)
2506 return add_search_paths(j);
2507
2508 if (j->toplevel_fd >= 0)
2509 return add_root_directory(j, NULL, false);
2510
2511 if (j->path)
2512 return add_root_directory(j, j->path, true);
2513
2514 return add_search_paths(j);
2515 }
2516
2517 _public_ int sd_journal_get_fd(sd_journal *j) {
2518 int r;
2519
2520 assert_return(j, -EINVAL);
2521 assert_return(!journal_pid_changed(j), -ECHILD);
2522
2523 if (j->no_inotify)
2524 return -EMEDIUMTYPE;
2525
2526 if (j->inotify_fd >= 0)
2527 return j->inotify_fd;
2528
2529 r = allocate_inotify(j);
2530 if (r < 0)
2531 return r;
2532
2533 log_debug("Reiterating files to get inotify watches established.");
2534
2535 /* Iterate through all dirs again, to add them to the inotify */
2536 r = reiterate_all_paths(j);
2537 if (r < 0)
2538 return r;
2539
2540 return j->inotify_fd;
2541 }
2542
2543 _public_ int sd_journal_get_events(sd_journal *j) {
2544 int fd;
2545
2546 assert_return(j, -EINVAL);
2547 assert_return(!journal_pid_changed(j), -ECHILD);
2548
2549 fd = sd_journal_get_fd(j);
2550 if (fd < 0)
2551 return fd;
2552
2553 return POLLIN;
2554 }
2555
2556 _public_ int sd_journal_get_timeout(sd_journal *j, uint64_t *timeout_usec) {
2557 int fd;
2558
2559 assert_return(j, -EINVAL);
2560 assert_return(!journal_pid_changed(j), -ECHILD);
2561 assert_return(timeout_usec, -EINVAL);
2562
2563 fd = sd_journal_get_fd(j);
2564 if (fd < 0)
2565 return fd;
2566
2567 if (!j->on_network) {
2568 *timeout_usec = UINT64_MAX;
2569 return 0;
2570 }
2571
2572 /* If we are on the network we need to regularly check for
2573 * changes manually */
2574
2575 *timeout_usec = j->last_process_usec + JOURNAL_FILES_RECHECK_USEC;
2576 return 1;
2577 }
2578
2579 static void process_q_overflow(sd_journal *j) {
2580 JournalFile *f;
2581 Directory *m;
2582
2583 assert(j);
2584
2585 /* When the inotify queue overruns we need to enumerate and re-validate all journal files to bring our list
2586 * back in sync with what's on disk. For this we pick a new generation counter value. It'll be assigned to all
2587 * journal files we encounter. All journal files and all directories that don't carry it after reenumeration
2588 * are subject for unloading. */
2589
2590 log_debug("Inotify queue overrun, reiterating everything.");
2591
2592 j->generation++;
2593 (void) reiterate_all_paths(j);
2594
2595 ORDERED_HASHMAP_FOREACH(f, j->files) {
2596
2597 if (f->last_seen_generation == j->generation)
2598 continue;
2599
2600 log_debug("File '%s' hasn't been seen in this enumeration, removing.", f->path);
2601 remove_file_real(j, f);
2602 }
2603
2604 HASHMAP_FOREACH(m, j->directories_by_path) {
2605
2606 if (m->last_seen_generation == j->generation)
2607 continue;
2608
2609 if (m->is_root) /* Never GC root directories */
2610 continue;
2611
2612 log_debug("Directory '%s' hasn't been seen in this enumeration, removing.", f->path);
2613 remove_directory(j, m);
2614 }
2615
2616 log_debug("Reiteration complete.");
2617 }
2618
2619 static void process_inotify_event(sd_journal *j, const struct inotify_event *e) {
2620 Directory *d;
2621
2622 assert(j);
2623 assert(e);
2624
2625 if (e->mask & IN_Q_OVERFLOW) {
2626 process_q_overflow(j);
2627 return;
2628 }
2629
2630 /* Is this a subdirectory we watch? */
2631 d = hashmap_get(j->directories_by_wd, INT_TO_PTR(e->wd));
2632 if (d) {
2633 if (!(e->mask & IN_ISDIR) && e->len > 0 &&
2634 (endswith(e->name, ".journal") ||
2635 endswith(e->name, ".journal~"))) {
2636
2637 /* Event for a journal file */
2638
2639 if (e->mask & (IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB))
2640 (void) add_file_by_name(j, d->path, e->name);
2641 else if (e->mask & (IN_DELETE|IN_MOVED_FROM|IN_UNMOUNT))
2642 remove_file_by_name(j, d->path, e->name);
2643
2644 } else if (!d->is_root && e->len == 0) {
2645
2646 /* Event for a subdirectory */
2647
2648 if (e->mask & (IN_DELETE_SELF|IN_MOVE_SELF|IN_UNMOUNT))
2649 remove_directory(j, d);
2650
2651 } else if (d->is_root && (e->mask & IN_ISDIR) && e->len > 0 && id128_is_valid(e->name)) {
2652
2653 /* Event for root directory */
2654
2655 if (e->mask & (IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB))
2656 (void) add_directory(j, d->path, e->name);
2657 }
2658
2659 return;
2660 }
2661
2662 if (e->mask & IN_IGNORED)
2663 return;
2664
2665 log_debug("Unexpected inotify event.");
2666 }
2667
2668 static int determine_change(sd_journal *j) {
2669 bool b;
2670
2671 assert(j);
2672
2673 b = j->current_invalidate_counter != j->last_invalidate_counter;
2674 j->last_invalidate_counter = j->current_invalidate_counter;
2675
2676 return b ? SD_JOURNAL_INVALIDATE : SD_JOURNAL_APPEND;
2677 }
2678
2679 _public_ int sd_journal_process(sd_journal *j) {
2680 bool got_something = false;
2681
2682 assert_return(j, -EINVAL);
2683 assert_return(!journal_pid_changed(j), -ECHILD);
2684
2685 if (j->inotify_fd < 0) /* We have no inotify fd yet? Then there's noting to process. */
2686 return 0;
2687
2688 j->last_process_usec = now(CLOCK_MONOTONIC);
2689 j->last_invalidate_counter = j->current_invalidate_counter;
2690
2691 for (;;) {
2692 union inotify_event_buffer buffer;
2693 struct inotify_event *e;
2694 ssize_t l;
2695
2696 l = read(j->inotify_fd, &buffer, sizeof(buffer));
2697 if (l < 0) {
2698 if (ERRNO_IS_TRANSIENT(errno))
2699 return got_something ? determine_change(j) : SD_JOURNAL_NOP;
2700
2701 return -errno;
2702 }
2703
2704 got_something = true;
2705
2706 FOREACH_INOTIFY_EVENT(e, buffer, l)
2707 process_inotify_event(j, e);
2708 }
2709 }
2710
2711 _public_ int sd_journal_wait(sd_journal *j, uint64_t timeout_usec) {
2712 int r;
2713 uint64_t t;
2714
2715 assert_return(j, -EINVAL);
2716 assert_return(!journal_pid_changed(j), -ECHILD);
2717
2718 if (j->inotify_fd < 0) {
2719 JournalFile *f;
2720
2721 /* This is the first invocation, hence create the
2722 * inotify watch */
2723 r = sd_journal_get_fd(j);
2724 if (r < 0)
2725 return r;
2726
2727 /* Server might have done some vacuuming while we weren't watching.
2728 Get rid of the deleted files now so they don't stay around indefinitely. */
2729 ORDERED_HASHMAP_FOREACH(f, j->files) {
2730 r = journal_file_fstat(f);
2731 if (r == -EIDRM)
2732 remove_file_real(j, f);
2733 else if (r < 0) {
2734 log_debug_errno(r,"Failed to fstat() journal file '%s' : %m", f->path);
2735 continue;
2736 }
2737 }
2738
2739 /* The journal might have changed since the context
2740 * object was created and we weren't watching before,
2741 * hence don't wait for anything, and return
2742 * immediately. */
2743 return determine_change(j);
2744 }
2745
2746 r = sd_journal_get_timeout(j, &t);
2747 if (r < 0)
2748 return r;
2749
2750 if (t != UINT64_MAX) {
2751 t = usec_sub_unsigned(t, now(CLOCK_MONOTONIC));
2752
2753 if (timeout_usec == UINT64_MAX || timeout_usec > t)
2754 timeout_usec = t;
2755 }
2756
2757 do {
2758 r = fd_wait_for_event(j->inotify_fd, POLLIN, timeout_usec);
2759 } while (r == -EINTR);
2760
2761 if (r < 0)
2762 return r;
2763
2764 return sd_journal_process(j);
2765 }
2766
2767 _public_ int sd_journal_get_cutoff_realtime_usec(sd_journal *j, uint64_t *from, uint64_t *to) {
2768 JournalFile *f;
2769 bool first = true;
2770 uint64_t fmin = 0, tmax = 0;
2771 int r;
2772
2773 assert_return(j, -EINVAL);
2774 assert_return(!journal_pid_changed(j), -ECHILD);
2775 assert_return(from || to, -EINVAL);
2776 assert_return(from != to, -EINVAL);
2777
2778 ORDERED_HASHMAP_FOREACH(f, j->files) {
2779 usec_t fr, t;
2780
2781 r = journal_file_get_cutoff_realtime_usec(f, &fr, &t);
2782 if (r == -ENOENT)
2783 continue;
2784 if (r < 0)
2785 return r;
2786 if (r == 0)
2787 continue;
2788
2789 if (first) {
2790 fmin = fr;
2791 tmax = t;
2792 first = false;
2793 } else {
2794 fmin = MIN(fr, fmin);
2795 tmax = MAX(t, tmax);
2796 }
2797 }
2798
2799 if (from)
2800 *from = fmin;
2801 if (to)
2802 *to = tmax;
2803
2804 return first ? 0 : 1;
2805 }
2806
2807 _public_ int sd_journal_get_cutoff_monotonic_usec(
2808 sd_journal *j,
2809 sd_id128_t boot_id,
2810 uint64_t *ret_from,
2811 uint64_t *ret_to) {
2812
2813 uint64_t from = UINT64_MAX, to = UINT64_MAX;
2814 bool found = false;
2815 JournalFile *f;
2816 int r;
2817
2818 assert_return(j, -EINVAL);
2819 assert_return(!journal_pid_changed(j), -ECHILD);
2820 assert_return(ret_from != ret_to, -EINVAL);
2821
2822 ORDERED_HASHMAP_FOREACH(f, j->files) {
2823 usec_t ff, tt;
2824
2825 r = journal_file_get_cutoff_monotonic_usec(f, boot_id, &ff, &tt);
2826 if (r == -ENOENT)
2827 continue;
2828 if (r < 0)
2829 return r;
2830 if (r == 0)
2831 continue;
2832
2833 if (found) {
2834 from = MIN(ff, from);
2835 to = MAX(tt, to);
2836 } else {
2837 from = ff;
2838 to = tt;
2839 found = true;
2840 }
2841 }
2842
2843 if (ret_from)
2844 *ret_from = from;
2845 if (ret_to)
2846 *ret_to = to;
2847
2848 return found;
2849 }
2850
2851 void journal_print_header(sd_journal *j) {
2852 JournalFile *f;
2853 bool newline = false;
2854
2855 assert(j);
2856
2857 ORDERED_HASHMAP_FOREACH(f, j->files) {
2858 if (newline)
2859 putchar('\n');
2860 else
2861 newline = true;
2862
2863 journal_file_print_header(f);
2864 }
2865 }
2866
2867 _public_ int sd_journal_get_usage(sd_journal *j, uint64_t *ret) {
2868 JournalFile *f;
2869 uint64_t sum = 0;
2870
2871 assert_return(j, -EINVAL);
2872 assert_return(!journal_pid_changed(j), -ECHILD);
2873 assert_return(ret, -EINVAL);
2874
2875 ORDERED_HASHMAP_FOREACH(f, j->files) {
2876 struct stat st;
2877 uint64_t b;
2878
2879 if (fstat(f->fd, &st) < 0)
2880 return -errno;
2881
2882 b = (uint64_t) st.st_blocks;
2883 if (b > UINT64_MAX / 512)
2884 return -EOVERFLOW;
2885 b *= 512;
2886
2887 if (sum > UINT64_MAX - b)
2888 return -EOVERFLOW;
2889 sum += b;
2890 }
2891
2892 *ret = sum;
2893 return 0;
2894 }
2895
2896 _public_ int sd_journal_query_unique(sd_journal *j, const char *field) {
2897 int r;
2898
2899 assert_return(j, -EINVAL);
2900 assert_return(!journal_pid_changed(j), -ECHILD);
2901 assert_return(!isempty(field), -EINVAL);
2902 assert_return(field_is_valid(field), -EINVAL);
2903
2904 r = free_and_strdup(&j->unique_field, field);
2905 if (r < 0)
2906 return r;
2907
2908 j->unique_file = NULL;
2909 j->unique_offset = 0;
2910 j->unique_file_lost = false;
2911
2912 return 0;
2913 }
2914
2915 _public_ int sd_journal_enumerate_unique(
2916 sd_journal *j,
2917 const void **ret_data,
2918 size_t *ret_size) {
2919
2920 size_t k;
2921
2922 assert_return(j, -EINVAL);
2923 assert_return(!journal_pid_changed(j), -ECHILD);
2924 assert_return(j->unique_field, -EINVAL);
2925
2926 k = strlen(j->unique_field);
2927
2928 if (!j->unique_file) {
2929 if (j->unique_file_lost)
2930 return 0;
2931
2932 j->unique_file = ordered_hashmap_first(j->files);
2933 if (!j->unique_file)
2934 return 0;
2935
2936 j->unique_offset = 0;
2937 }
2938
2939 for (;;) {
2940 JournalFile *of;
2941 Object *o;
2942 const void *odata;
2943 size_t ol;
2944 bool found;
2945 int r;
2946
2947 /* Proceed to next data object in the field's linked list */
2948 if (j->unique_offset == 0) {
2949 r = journal_file_find_field_object(j->unique_file, j->unique_field, k, &o, NULL);
2950 if (r < 0)
2951 return r;
2952
2953 j->unique_offset = r > 0 ? le64toh(o->field.head_data_offset) : 0;
2954 } else {
2955 r = journal_file_move_to_object(j->unique_file, OBJECT_DATA, j->unique_offset, &o);
2956 if (r < 0)
2957 return r;
2958
2959 j->unique_offset = le64toh(o->data.next_field_offset);
2960 }
2961
2962 /* We reached the end of the list? Then start again, with the next file */
2963 if (j->unique_offset == 0) {
2964 j->unique_file = ordered_hashmap_next(j->files, j->unique_file->path);
2965 if (!j->unique_file)
2966 return 0;
2967
2968 continue;
2969 }
2970
2971 /* We do not use OBJECT_DATA context here, but OBJECT_UNUSED
2972 * instead, so that we can look at this data object at the same
2973 * time as one on another file */
2974 r = journal_file_move_to_object(j->unique_file, OBJECT_UNUSED, j->unique_offset, &o);
2975 if (r < 0)
2976 return r;
2977
2978 /* Let's do the type check by hand, since we used 0 context above. */
2979 if (o->object.type != OBJECT_DATA)
2980 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
2981 "%s:offset " OFSfmt ": object has type %d, expected %d",
2982 j->unique_file->path,
2983 j->unique_offset,
2984 o->object.type, OBJECT_DATA);
2985
2986 r = return_data(j, j->unique_file, o, &odata, &ol);
2987 if (r < 0)
2988 return r;
2989
2990 /* Check if we have at least the field name and "=". */
2991 if (ol <= k)
2992 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
2993 "%s:offset " OFSfmt ": object has size %zu, expected at least %zu",
2994 j->unique_file->path,
2995 j->unique_offset, ol, k + 1);
2996
2997 if (memcmp(odata, j->unique_field, k) != 0 || ((const char*) odata)[k] != '=')
2998 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
2999 "%s:offset " OFSfmt ": object does not start with \"%s=\"",
3000 j->unique_file->path,
3001 j->unique_offset,
3002 j->unique_field);
3003
3004 /* OK, now let's see if we already returned this data object by checking if it exists in the
3005 * earlier traversed files. */
3006 found = false;
3007 ORDERED_HASHMAP_FOREACH(of, j->files) {
3008 if (of == j->unique_file)
3009 break;
3010
3011 /* Skip this file it didn't have any fields indexed */
3012 if (JOURNAL_HEADER_CONTAINS(of->header, n_fields) && le64toh(of->header->n_fields) <= 0)
3013 continue;
3014
3015 /* We can reuse the hash from our current file only on old-style journal files
3016 * without keyed hashes. On new-style files we have to calculate the hash anew, to
3017 * take the per-file hash seed into consideration. */
3018 if (!JOURNAL_HEADER_KEYED_HASH(j->unique_file->header) && !JOURNAL_HEADER_KEYED_HASH(of->header))
3019 r = journal_file_find_data_object_with_hash(of, odata, ol, le64toh(o->data.hash), NULL, NULL);
3020 else
3021 r = journal_file_find_data_object(of, odata, ol, NULL, NULL);
3022 if (r < 0)
3023 return r;
3024 if (r > 0) {
3025 found = true;
3026 break;
3027 }
3028 }
3029
3030 if (found)
3031 continue;
3032
3033 r = return_data(j, j->unique_file, o, ret_data, ret_size);
3034 if (r < 0)
3035 return r;
3036
3037 return 1;
3038 }
3039 }
3040
3041 _public_ int sd_journal_enumerate_available_unique(sd_journal *j, const void **data, size_t *size) {
3042 for (;;) {
3043 int r;
3044
3045 r = sd_journal_enumerate_unique(j, data, size);
3046 if (r >= 0)
3047 return r;
3048 if (!JOURNAL_ERRNO_IS_UNAVAILABLE_FIELD(r))
3049 return r;
3050 /* Try with the next field. sd_journal_enumerate_unique() modifies state, so on the next try
3051 * we will access the next field. */
3052 }
3053 }
3054
3055 _public_ void sd_journal_restart_unique(sd_journal *j) {
3056 if (!j)
3057 return;
3058
3059 j->unique_file = NULL;
3060 j->unique_offset = 0;
3061 j->unique_file_lost = false;
3062 }
3063
3064 _public_ int sd_journal_enumerate_fields(sd_journal *j, const char **field) {
3065 int r;
3066
3067 assert_return(j, -EINVAL);
3068 assert_return(!journal_pid_changed(j), -ECHILD);
3069 assert_return(field, -EINVAL);
3070
3071 if (!j->fields_file) {
3072 if (j->fields_file_lost)
3073 return 0;
3074
3075 j->fields_file = ordered_hashmap_first(j->files);
3076 if (!j->fields_file)
3077 return 0;
3078
3079 j->fields_hash_table_index = 0;
3080 j->fields_offset = 0;
3081 }
3082
3083 for (;;) {
3084 JournalFile *f, *of;
3085 uint64_t m;
3086 Object *o;
3087 size_t sz;
3088 bool found;
3089
3090 f = j->fields_file;
3091
3092 if (j->fields_offset == 0) {
3093 bool eof = false;
3094
3095 /* We are not yet positioned at any field. Let's pick the first one */
3096 r = journal_file_map_field_hash_table(f);
3097 if (r < 0)
3098 return r;
3099
3100 m = le64toh(f->header->field_hash_table_size) / sizeof(HashItem);
3101 for (;;) {
3102 if (j->fields_hash_table_index >= m) {
3103 /* Reached the end of the hash table, go to the next file. */
3104 eof = true;
3105 break;
3106 }
3107
3108 j->fields_offset = le64toh(f->field_hash_table[j->fields_hash_table_index].head_hash_offset);
3109
3110 if (j->fields_offset != 0)
3111 break;
3112
3113 /* Empty hash table bucket, go to next one */
3114 j->fields_hash_table_index++;
3115 }
3116
3117 if (eof) {
3118 /* Proceed with next file */
3119 j->fields_file = ordered_hashmap_next(j->files, f->path);
3120 if (!j->fields_file) {
3121 *field = NULL;
3122 return 0;
3123 }
3124
3125 j->fields_offset = 0;
3126 j->fields_hash_table_index = 0;
3127 continue;
3128 }
3129
3130 } else {
3131 /* We are already positioned at a field. If so, let's figure out the next field from it */
3132
3133 r = journal_file_move_to_object(f, OBJECT_FIELD, j->fields_offset, &o);
3134 if (r < 0)
3135 return r;
3136
3137 j->fields_offset = le64toh(o->field.next_hash_offset);
3138 if (j->fields_offset == 0) {
3139 /* Reached the end of the hash table chain */
3140 j->fields_hash_table_index++;
3141 continue;
3142 }
3143 }
3144
3145 /* We use OBJECT_UNUSED here, so that the iterator below doesn't remove our mmap window */
3146 r = journal_file_move_to_object(f, OBJECT_UNUSED, j->fields_offset, &o);
3147 if (r < 0)
3148 return r;
3149
3150 /* Because we used OBJECT_UNUSED above, we need to do our type check manually */
3151 if (o->object.type != OBJECT_FIELD)
3152 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
3153 "%s:offset " OFSfmt ": object has type %i, expected %i",
3154 f->path, j->fields_offset,
3155 o->object.type, OBJECT_FIELD);
3156
3157 sz = le64toh(o->object.size) - offsetof(Object, field.payload);
3158
3159 /* Let's see if we already returned this field name before. */
3160 found = false;
3161 ORDERED_HASHMAP_FOREACH(of, j->files) {
3162 if (of == f)
3163 break;
3164
3165 /* Skip this file it didn't have any fields indexed */
3166 if (JOURNAL_HEADER_CONTAINS(of->header, n_fields) && le64toh(of->header->n_fields) <= 0)
3167 continue;
3168
3169 if (!JOURNAL_HEADER_KEYED_HASH(f->header) && !JOURNAL_HEADER_KEYED_HASH(of->header))
3170 r = journal_file_find_field_object_with_hash(of, o->field.payload, sz,
3171 le64toh(o->field.hash), NULL, NULL);
3172 else
3173 r = journal_file_find_field_object(of, o->field.payload, sz, NULL, NULL);
3174 if (r < 0)
3175 return r;
3176 if (r > 0) {
3177 found = true;
3178 break;
3179 }
3180 }
3181
3182 if (found)
3183 continue;
3184
3185 /* Check if this is really a valid string containing no NUL byte */
3186 if (memchr(o->field.payload, 0, sz))
3187 return -EBADMSG;
3188
3189 if (j->data_threshold > 0 && sz > j->data_threshold)
3190 sz = j->data_threshold;
3191
3192 if (!GREEDY_REALLOC(j->fields_buffer, sz + 1))
3193 return -ENOMEM;
3194
3195 memcpy(j->fields_buffer, o->field.payload, sz);
3196 j->fields_buffer[sz] = 0;
3197
3198 if (!field_is_valid(j->fields_buffer))
3199 return -EBADMSG;
3200
3201 *field = j->fields_buffer;
3202 return 1;
3203 }
3204 }
3205
3206 _public_ void sd_journal_restart_fields(sd_journal *j) {
3207 if (!j)
3208 return;
3209
3210 j->fields_file = NULL;
3211 j->fields_hash_table_index = 0;
3212 j->fields_offset = 0;
3213 j->fields_file_lost = false;
3214 }
3215
3216 _public_ int sd_journal_reliable_fd(sd_journal *j) {
3217 assert_return(j, -EINVAL);
3218 assert_return(!journal_pid_changed(j), -ECHILD);
3219
3220 return !j->on_network;
3221 }
3222
3223 static char *lookup_field(const char *field, void *userdata) {
3224 sd_journal *j = userdata;
3225 const void *data;
3226 size_t size, d;
3227 int r;
3228
3229 assert(field);
3230 assert(j);
3231
3232 r = sd_journal_get_data(j, field, &data, &size);
3233 if (r < 0 ||
3234 size > REPLACE_VAR_MAX)
3235 return strdup(field);
3236
3237 d = strlen(field) + 1;
3238
3239 return strndup((const char*) data + d, size - d);
3240 }
3241
3242 _public_ int sd_journal_get_catalog(sd_journal *j, char **ret) {
3243 const void *data;
3244 size_t size;
3245 sd_id128_t id;
3246 _cleanup_free_ char *text = NULL, *cid = NULL;
3247 char *t;
3248 int r;
3249
3250 assert_return(j, -EINVAL);
3251 assert_return(!journal_pid_changed(j), -ECHILD);
3252 assert_return(ret, -EINVAL);
3253
3254 r = sd_journal_get_data(j, "MESSAGE_ID", &data, &size);
3255 if (r < 0)
3256 return r;
3257
3258 cid = strndup((const char*) data + 11, size - 11);
3259 if (!cid)
3260 return -ENOMEM;
3261
3262 r = sd_id128_from_string(cid, &id);
3263 if (r < 0)
3264 return r;
3265
3266 r = catalog_get(CATALOG_DATABASE, id, &text);
3267 if (r < 0)
3268 return r;
3269
3270 t = replace_var(text, lookup_field, j);
3271 if (!t)
3272 return -ENOMEM;
3273
3274 *ret = t;
3275 return 0;
3276 }
3277
3278 _public_ int sd_journal_get_catalog_for_message_id(sd_id128_t id, char **ret) {
3279 assert_return(ret, -EINVAL);
3280
3281 return catalog_get(CATALOG_DATABASE, id, ret);
3282 }
3283
3284 _public_ int sd_journal_set_data_threshold(sd_journal *j, size_t sz) {
3285 assert_return(j, -EINVAL);
3286 assert_return(!journal_pid_changed(j), -ECHILD);
3287
3288 j->data_threshold = sz;
3289 return 0;
3290 }
3291
3292 _public_ int sd_journal_get_data_threshold(sd_journal *j, size_t *sz) {
3293 assert_return(j, -EINVAL);
3294 assert_return(!journal_pid_changed(j), -ECHILD);
3295 assert_return(sz, -EINVAL);
3296
3297 *sz = j->data_threshold;
3298 return 0;
3299 }
3300
3301 _public_ int sd_journal_has_runtime_files(sd_journal *j) {
3302 assert_return(j, -EINVAL);
3303
3304 return j->has_runtime_files;
3305 }
3306
3307 _public_ int sd_journal_has_persistent_files(sd_journal *j) {
3308 assert_return(j, -EINVAL);
3309
3310 return j->has_persistent_files;
3311 }