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