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