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