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