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