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