chiark / gitweb /
bd510be51cea00202a50bee765a62711d6dd9242
[elogind.git] / src / journal / sd-journal.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2011 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <stddef.h>
25 #include <unistd.h>
26 #include <sys/inotify.h>
27
28 #include "sd-journal.h"
29 #include "journal-def.h"
30 #include "journal-file.h"
31 #include "hashmap.h"
32 #include "list.h"
33 #include "lookup3.h"
34
35 #define JOURNAL_FILES_MAX 1024
36
37 typedef struct Match Match;
38
39 struct Match {
40         char *data;
41         size_t size;
42         uint64_t le_hash;
43
44         LIST_FIELDS(Match, matches);
45 };
46
47 typedef enum location_type {
48         LOCATION_HEAD,
49         LOCATION_TAIL,
50         LOCATION_DISCRETE
51 } location_type_t;
52
53 typedef struct Location {
54         location_type_t type;
55
56         uint64_t seqnum;
57         sd_id128_t seqnum_id;
58         bool seqnum_set;
59
60         uint64_t realtime;
61         bool realtime_set;
62
63         uint64_t monotonic;
64         sd_id128_t boot_id;
65         bool monotonic_set;
66
67         uint64_t xor_hash;
68         bool xor_hash_set;
69 } Location;
70
71 struct sd_journal {
72         Hashmap *files;
73
74         Location current_location;
75         JournalFile *current_file;
76         uint64_t current_field;
77
78         int inotify_fd;
79         Hashmap *inotify_wd_dirs;
80         Hashmap *inotify_wd_roots;
81
82         LIST_HEAD(Match, matches);
83         unsigned n_matches;
84 };
85
86 static void detach_location(sd_journal *j) {
87         Iterator i;
88         JournalFile *f;
89
90         assert(j);
91
92         j->current_file = NULL;
93         j->current_field = 0;
94
95         HASHMAP_FOREACH(f, j->files, i)
96                 f->current_offset = 0;
97 }
98
99 static void reset_location(sd_journal *j) {
100         assert(j);
101
102         detach_location(j);
103         zero(j->current_location);
104 }
105
106 static void init_location(Location *l, JournalFile *f, Object *o) {
107         assert(l);
108         assert(f);
109         assert(o->object.type == OBJECT_ENTRY);
110
111         l->type = LOCATION_DISCRETE;
112         l->seqnum = le64toh(o->entry.seqnum);
113         l->seqnum_id = f->header->seqnum_id;
114         l->realtime = le64toh(o->entry.realtime);
115         l->monotonic = le64toh(o->entry.monotonic);
116         l->boot_id = le64toh(o->entry.boot_id);
117         l->xor_hash = le64toh(o->entry.xor_hash);
118
119         l->seqnum_set = l->realtime_set = l->monotonic_set = l->xor_hash_set = true;
120 }
121
122 static void set_location(sd_journal *j, JournalFile *f, Object *o, uint64_t offset) {
123         assert(j);
124         assert(f);
125         assert(o);
126
127         init_location(&j->current_location, f, o);
128
129         j->current_file = f;
130         j->current_field = 0;
131
132         f->current_offset = offset;
133 }
134
135 static int same_field(const void *_a, size_t s, const void *_b, size_t t) {
136         const uint8_t *a = _a, *b = _b;
137         size_t j;
138         bool a_good = false, b_good = false, different = false;
139
140         for (j = 0; j < s && j < t; j++) {
141
142                 if (a[j] == '=')
143                         a_good = true;
144                 if (b[j] == '=')
145                         b_good = true;
146                 if (a[j] != b[j])
147                         different = true;
148
149                 if (a_good && b_good)
150                         return different ? 0 : 1;
151         }
152
153         return -EINVAL;
154 }
155
156 int sd_journal_add_match(sd_journal *j, const void *data, size_t size) {
157         Match *m, *after = NULL;
158         uint64_t le_hash;
159
160         assert(j);
161
162         if (size <= 0)
163                 return -EINVAL;
164
165         assert(data);
166
167         le_hash = htole64(hash64(data, size));
168
169         LIST_FOREACH(matches, m, j->matches) {
170                 int r;
171
172                 if (m->le_hash == le_hash &&
173                     m->size == size &&
174                     memcmp(m->data, data, size) == 0)
175                         return 0;
176
177                 r = same_field(data, size, m->data, m->size);
178                 if (r < 0)
179                         return r;
180                 else if (r > 0)
181                         after = m;
182         }
183
184         m = new0(Match, 1);
185         if (!m)
186                 return -ENOMEM;
187
188         m->size = size;
189
190         m->data = malloc(m->size);
191         if (!m->data) {
192                 free(m);
193                 return -ENOMEM;
194         }
195
196         memcpy(m->data, data, size);
197         m->le_hash = le_hash;
198
199         /* Matches for the same fields we order adjacent to each
200          * other */
201         LIST_INSERT_AFTER(Match, matches, j->matches, after, m);
202         j->n_matches ++;
203
204         detach_location(j);
205
206         return 0;
207 }
208
209 void sd_journal_flush_matches(sd_journal *j) {
210         assert(j);
211
212         while (j->matches) {
213                 Match *m = j->matches;
214
215                 LIST_REMOVE(Match, matches, j->matches, m);
216                 free(m->data);
217                 free(m);
218         }
219
220         j->n_matches = 0;
221
222         detach_location(j);
223 }
224
225 static int compare_order(JournalFile *af, Object *ao,
226                          JournalFile *bf, Object *bo) {
227
228         uint64_t a, b;
229
230         assert(af);
231         assert(ao);
232         assert(bf);
233         assert(bo);
234
235         /* We operate on two different files here, hence we can access
236          * two objects at the same time, which we normally can't.
237          *
238          * If contents and timestamps match, these entries are
239          * identical, even if the seqnum does not match */
240
241         if (sd_id128_equal(ao->entry.boot_id, bo->entry.boot_id) &&
242             ao->entry.monotonic == bo->entry.monotonic &&
243             ao->entry.realtime == bo->entry.realtime &&
244             ao->entry.xor_hash == bo->entry.xor_hash)
245                 return 0;
246
247         if (sd_id128_equal(af->header->seqnum_id, bf->header->seqnum_id)) {
248
249                 /* If this is from the same seqnum source, compare
250                  * seqnums */
251                 a = le64toh(ao->entry.seqnum);
252                 b = le64toh(bo->entry.seqnum);
253
254                 if (a < b)
255                         return -1;
256                 if (a > b)
257                         return 1;
258
259                 /* Wow! This is weird, different data but the same
260                  * seqnums? Something is borked, but let's make the
261                  * best of it and compare by time. */
262         }
263
264         if (sd_id128_equal(ao->entry.boot_id, bo->entry.boot_id)) {
265
266                 /* If the boot id matches compare monotonic time */
267                 a = le64toh(ao->entry.monotonic);
268                 b = le64toh(bo->entry.monotonic);
269
270                 if (a < b)
271                         return -1;
272                 if (a > b)
273                         return 1;
274         }
275
276         /* Otherwise compare UTC time */
277         a = le64toh(ao->entry.realtime);
278         b = le64toh(ao->entry.realtime);
279
280         if (a < b)
281                 return -1;
282         if (a > b)
283                 return 1;
284
285         /* Finally, compare by contents */
286         a = le64toh(ao->entry.xor_hash);
287         b = le64toh(ao->entry.xor_hash);
288
289         if (a < b)
290                 return -1;
291         if (a > b)
292                 return 1;
293
294         return 0;
295 }
296
297 static int compare_with_location(JournalFile *af, Object *ao, Location *l) {
298         uint64_t a;
299
300         assert(af);
301         assert(ao);
302         assert(l);
303         assert(l->type == LOCATION_DISCRETE);
304
305         if (l->monotonic_set &&
306             sd_id128_equal(ao->entry.boot_id, l->boot_id) &&
307             l->realtime_set &&
308             le64toh(ao->entry.realtime) == l->realtime &&
309             l->xor_hash_set &&
310             le64toh(ao->entry.xor_hash) == l->xor_hash)
311                 return 0;
312
313         if (l->seqnum_set &&
314             sd_id128_equal(af->header->seqnum_id, l->seqnum_id)) {
315
316                 a = le64toh(ao->entry.seqnum);
317
318                 if (a < l->seqnum)
319                         return -1;
320                 if (a > l->seqnum)
321                         return 1;
322         }
323
324         if (l->monotonic_set &&
325             sd_id128_equal(ao->entry.boot_id, l->boot_id)) {
326
327                 a = le64toh(ao->entry.monotonic);
328
329                 if (a < l->monotonic)
330                         return -1;
331                 if (a > l->monotonic)
332                         return 1;
333         }
334
335         if (l->realtime_set) {
336
337                 a = le64toh(ao->entry.realtime);
338
339                 if (a < l->realtime)
340                         return -1;
341                 if (a > l->realtime)
342                         return 1;
343         }
344
345         if (l->xor_hash_set) {
346                 a = le64toh(ao->entry.xor_hash);
347
348                 if (a < l->xor_hash)
349                         return -1;
350                 if (a > l->xor_hash)
351                         return 1;
352         }
353
354         return 0;
355 }
356
357 static int find_location(sd_journal *j, JournalFile *f, direction_t direction, Object **ret, uint64_t *offset) {
358         Object *o = NULL;
359         uint64_t p = 0;
360         int r;
361
362         assert(j);
363
364         if (!j->matches) {
365                 /* No matches is simple */
366
367                 if (j->current_location.type == LOCATION_HEAD)
368                         r = journal_file_next_entry(f, NULL, 0, DIRECTION_DOWN, &o, &p);
369                 else if (j->current_location.type == LOCATION_TAIL)
370                         r = journal_file_next_entry(f, NULL, 0, DIRECTION_UP, &o, &p);
371                 else if (j->current_location.seqnum_set &&
372                          sd_id128_equal(j->current_location.seqnum_id, f->header->seqnum_id))
373                         r = journal_file_move_to_entry_by_seqnum(f, j->current_location.seqnum, direction, &o, &p);
374                 else if (j->current_location.monotonic_set)
375                         r = journal_file_move_to_entry_by_monotonic(f, j->current_location.boot_id, j->current_location.monotonic, direction, &o, &p);
376                 else if (j->current_location.realtime_set)
377                         r = journal_file_move_to_entry_by_realtime(f, j->current_location.realtime, direction, &o, &p);
378                 else
379                         r = journal_file_next_entry(f, NULL, 0, direction, &o, &p);
380
381                 if (r <= 0)
382                         return r;
383
384         } else  {
385                 Match *m, *term_match = NULL;
386                 Object *to = NULL;
387                 uint64_t tp = 0;
388
389                 /* We have matches, first, let's jump to the monotonic
390                  * position if we have any, since it implies a
391                  * match. */
392
393                 if (j->current_location.type == LOCATION_DISCRETE &&
394                     j->current_location.monotonic_set) {
395
396                         r = journal_file_move_to_entry_by_monotonic(f, j->current_location.boot_id, j->current_location.monotonic, direction, &o, &p);
397                         if (r <= 0)
398                                 return r;
399                 }
400
401                 LIST_FOREACH(matches, m, j->matches) {
402                         Object *c, *d;
403                         uint64_t cp, dp;
404
405                         r = journal_file_find_data_object_with_hash(f, m->data, m->size, m->le_hash, &d, &dp);
406                         if (r <= 0)
407                                 return r;
408
409                         if (j->current_location.type == LOCATION_HEAD)
410                                 r = journal_file_next_entry_for_data(f, NULL, 0, dp, DIRECTION_DOWN, &c, &cp);
411                         else if (j->current_location.type == LOCATION_TAIL)
412                                 r = journal_file_next_entry_for_data(f, NULL, 0, dp, DIRECTION_UP, &c, &cp);
413                         else if (j->current_location.seqnum_set &&
414                                  sd_id128_equal(j->current_location.seqnum_id, f->header->seqnum_id))
415                                 r = journal_file_move_to_entry_by_seqnum_for_data(f, dp, j->current_location.seqnum, direction, &c, &cp);
416                         else if (j->current_location.realtime_set)
417                                 r = journal_file_move_to_entry_by_realtime_for_data(f, dp, j->current_location.realtime, direction, &c, &cp);
418                         else
419                                 r = journal_file_next_entry_for_data(f, NULL, 0, dp, direction, &c, &cp);
420
421                         if (!term_match) {
422                                 term_match = m;
423
424                                 if (r > 0) {
425                                         to = c;
426                                         tp = cp;
427                                 }
428                         } else if (same_field(term_match->data, term_match->size, m->data, m->size)) {
429
430                                 /* Same field as previous match... */
431                                 if (r > 0) {
432
433                                         /* Find the earliest of the OR matches */
434
435                                         if (!to ||
436                                             (direction == DIRECTION_DOWN && cp < tp) ||
437                                             (direction == DIRECTION_UP && cp > tp)) {
438                                                 to = c;
439                                                 tp = tp;
440                                         }
441
442                                 }
443
444                         } else {
445
446                                 /* Previous term is finished, did anything match? */
447                                 if (!to)
448                                         return 0;
449
450                                 /* Find the last of the AND matches */
451                                 if (!o ||
452                                     (direction == DIRECTION_DOWN && tp > p) ||
453                                     (direction == DIRECTION_UP && tp < p)) {
454                                         o = to;
455                                         p = tp;
456                                 }
457
458                                 term_match = m;
459
460                                 if (r > 0) {
461                                         to = c;
462                                         tp = cp;
463                                 } else {
464                                         to = NULL;
465                                         tp = 0;
466                                 }
467                         }
468                 }
469
470                 /* Last term is finished, did anything match? */
471                 if (!to)
472                         return 0;
473
474                 if (!o ||
475                     (direction == DIRECTION_DOWN && tp > p) ||
476                     (direction == DIRECTION_UP && tp < p)) {
477                         o = to;
478                         p = tp;
479                 }
480
481                 if (!o)
482                         return 0;
483         }
484
485         if (ret)
486                 *ret = o;
487
488         if (offset)
489                 *offset = p;
490
491         return 1;
492 }
493
494 static int next_with_matches(sd_journal *j, JournalFile *f, direction_t direction, Object **ret, uint64_t *offset) {
495         int r;
496         uint64_t cp;
497         Object *c;
498
499         assert(j);
500         assert(f);
501         assert(ret);
502         assert(offset);
503
504         c = *ret;
505         cp = *offset;
506
507         if (!j->matches) {
508                 /* No matches is easy */
509
510                 r = journal_file_next_entry(f, c, cp, direction, &c, &cp);
511                 if (r <= 0)
512                         return r;
513
514                 if (ret)
515                         *ret = c;
516                 if (offset)
517                         *offset = cp;
518                 return 1;
519         }
520
521         /* So there are matches we have to adhere to, let's find the
522          * first entry that matches all of them */
523
524         for (;;) {
525                 uint64_t np, n;
526                 bool found, term_result = false;
527                 Match *m, *term_match = NULL;
528
529                 n = journal_file_entry_n_items(c);
530
531                 /* Make sure we don't match the entry we are starting
532                  * from. */
533                 found = cp > *offset;
534
535                 np = 0;
536                 LIST_FOREACH(matches, m, j->matches) {
537                         uint64_t q, k;
538
539                         /* Let's check if this is the beginning of a
540                          * new term, i.e. has a different field prefix
541                          * as the preceeding match. */
542                         if (!term_match) {
543                                 term_match = m;
544                                 term_result = false;
545                         } else if (!same_field(term_match->data, term_match->size, m->data, m->size)) {
546                                 if (!term_result)
547                                         found = false;
548
549                                 term_match = m;
550                                 term_result = false;
551                         }
552
553                         for (k = 0; k < n; k++)
554                                 if (c->entry.items[k].hash == m->le_hash)
555                                         break;
556
557                         if (k >= n) {
558                                 /* Hmm, didn't find any field that
559                                  * matched this rule, so ignore this
560                                  * match. Go on with next match */
561                                 continue;
562                         }
563
564                         term_result = true;
565
566                         /* Hmm, so, this field matched, let's remember
567                          * where we'd have to try next, in case the other
568                          * matches are not OK */
569
570                         r = journal_file_next_entry_for_data(f, c, cp, le64toh(c->entry.items[k].object_offset), direction, NULL, &q);
571                         if (r > 0) {
572
573                                 if (direction == DIRECTION_DOWN) {
574                                         if (q > np)
575                                                 np = q;
576                                 } else {
577                                         if (np == 0 || q < np)
578                                                 np = q;
579                                 }
580                         }
581                 }
582
583                 /* Check the last term */
584                 if (term_match && term_result)
585                         found = true;
586
587                 /* Did this entry match against all matches? */
588                 if (found) {
589                         if (ret)
590                                 *ret = c;
591                         if (offset)
592                                 *offset = cp;
593                         return 1;
594                 }
595
596                 /* Did we find a subsequent entry? */
597                 if (np == 0)
598                         return 0;
599
600                 /* Hmm, ok, this entry only matched partially, so
601                  * let's try another one */
602                 cp = np;
603         }
604 }
605
606 static int next_beyond_location(sd_journal *j, JournalFile *f, direction_t direction, Object **ret, uint64_t *offset) {
607         Object *c;
608         uint64_t cp;
609         int compare_value, r;
610
611         assert(j);
612         assert(f);
613
614         if (f->current_offset > 0) {
615                 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &c);
616                 if (r < 0)
617                         return r;
618
619                 cp = f->current_offset;
620
621                 r = next_with_matches(j, f, direction, &c, &cp);
622                 if (r <= 0)
623                         return r;
624
625                 compare_value = 1;
626         } else {
627                 r = find_location(j, f, direction, &c, &cp);
628                 if (r <= 0)
629                         return r;
630
631                 compare_value = 0;
632         }
633
634         for (;;) {
635                 bool found;
636
637                 if (j->current_location.type == LOCATION_DISCRETE) {
638                         int k;
639
640                         k = compare_with_location(f, c, &j->current_location);
641                         if (direction == DIRECTION_DOWN)
642                                 found = k >= compare_value;
643                         else
644                                 found = k <= -compare_value;
645                 } else
646                         found = true;
647
648                 if (found) {
649                         if (ret)
650                                 *ret = c;
651                         if (offset)
652                                 *offset = cp;
653                         return 1;
654                 }
655
656                 r = next_with_matches(j, f, direction, &c, &cp);
657                 if (r <= 0)
658                         return r;
659         }
660 }
661
662 static int real_journal_next(sd_journal *j, direction_t direction) {
663         JournalFile *f, *new_current = NULL;
664         Iterator i;
665         int r;
666         uint64_t new_offset = 0;
667         Object *new_entry = NULL;
668
669         assert(j);
670
671         HASHMAP_FOREACH(f, j->files, i) {
672                 Object *o;
673                 uint64_t p;
674                 bool found;
675
676                 r = next_beyond_location(j, f, direction, &o, &p);
677                 if (r < 0)
678                         return r;
679                 else if (r == 0)
680                         continue;
681
682                 if (!new_current)
683                         found = true;
684                 else {
685                         int k;
686
687                         k = compare_order(f, o, new_current, new_entry);
688
689                         if (direction == DIRECTION_DOWN)
690                                 found = k < 0;
691                         else
692                                 found = k > 0;
693                 }
694
695                 if (found) {
696                         new_current = f;
697                         new_entry = o;
698                         new_offset = p;
699                 }
700         }
701
702         if (!new_current)
703                 return 0;
704
705         set_location(j, new_current, new_entry, new_offset);
706
707         return 1;
708 }
709
710 int sd_journal_next(sd_journal *j) {
711         return real_journal_next(j, DIRECTION_DOWN);
712 }
713
714 int sd_journal_previous(sd_journal *j) {
715         return real_journal_next(j, DIRECTION_UP);
716 }
717
718 int sd_journal_next_skip(sd_journal *j, uint64_t skip) {
719         int c = 0, r;
720
721         assert(j);
722
723         while (skip > 0) {
724                 r = sd_journal_next(j);
725                 if (r < 0)
726                         return r;
727
728                 if (r == 0)
729                         return c;
730
731                 skip--;
732                 c++;
733         }
734
735         return c;
736 }
737
738 int sd_journal_previous_skip(sd_journal *j, uint64_t skip) {
739         int c = 0, r;
740
741         assert(j);
742
743         while (skip > 0) {
744                 r = sd_journal_previous(j);
745                 if (r < 0)
746                         return r;
747
748                 if (r == 0)
749                         return c;
750
751                 skip--;
752                 c++;
753         }
754
755         return 1;
756 }
757
758 int sd_journal_get_cursor(sd_journal *j, char **cursor) {
759         Object *o;
760         int r;
761         char bid[33], sid[33];
762
763         assert(j);
764         assert(cursor);
765
766         if (!j->current_file || j->current_file->current_offset <= 0)
767                 return -EADDRNOTAVAIL;
768
769         r = journal_file_move_to_object(j->current_file, OBJECT_ENTRY, j->current_file->current_offset, &o);
770         if (r < 0)
771                 return r;
772
773         sd_id128_to_string(j->current_file->header->seqnum_id, sid);
774         sd_id128_to_string(o->entry.boot_id, bid);
775
776         if (asprintf(cursor,
777                      "s=%s;i=%llx;b=%s;m=%llx;t=%llx;x=%llx;p=%s",
778                      sid, (unsigned long long) le64toh(o->entry.seqnum),
779                      bid, (unsigned long long) le64toh(o->entry.monotonic),
780                      (unsigned long long) le64toh(o->entry.realtime),
781                      (unsigned long long) le64toh(o->entry.xor_hash),
782                      file_name_from_path(j->current_file->path)) < 0)
783                 return -ENOMEM;
784
785         return 1;
786 }
787
788 int sd_journal_seek_cursor(sd_journal *j, const char *cursor) {
789         char *w;
790         size_t l;
791         char *state;
792         unsigned long long seqnum, monotonic, realtime, xor_hash;
793         bool
794                 seqnum_id_set = false,
795                 seqnum_set = false,
796                 boot_id_set = false,
797                 monotonic_set = false,
798                 realtime_set = false,
799                 xor_hash_set = false;
800         sd_id128_t seqnum_id, boot_id;
801
802         assert(j);
803         assert(cursor);
804
805         FOREACH_WORD_SEPARATOR(w, l, cursor, ";", state) {
806                 char *item;
807                 int k = 0;
808
809                 if (l < 2 || w[1] != '=')
810                         return -EINVAL;
811
812                 item = strndup(w, l);
813                 if (!item)
814                         return -ENOMEM;
815
816                 switch (w[0]) {
817
818                 case 's':
819                         seqnum_id_set = true;
820                         k = sd_id128_from_string(w+2, &seqnum_id);
821                         break;
822
823                 case 'i':
824                         seqnum_set = true;
825                         if (sscanf(w+2, "%llx", &seqnum) != 1)
826                                 k = -EINVAL;
827                         break;
828
829                 case 'b':
830                         boot_id_set = true;
831                         k = sd_id128_from_string(w+2, &boot_id);
832                         break;
833
834                 case 'm':
835                         monotonic_set = true;
836                         if (sscanf(w+2, "%llx", &monotonic) != 1)
837                                 k = -EINVAL;
838                         break;
839
840                 case 't':
841                         realtime_set = true;
842                         if (sscanf(w+2, "%llx", &realtime) != 1)
843                                 k = -EINVAL;
844                         break;
845
846                 case 'x':
847                         xor_hash_set = true;
848                         if (sscanf(w+2, "%llx", &xor_hash) != 1)
849                                 k = -EINVAL;
850                         break;
851                 }
852
853                 free(item);
854
855                 if (k < 0)
856                         return k;
857         }
858
859         if ((!seqnum_set || !seqnum_id_set) &&
860             (!monotonic_set || !boot_id_set) &&
861             !realtime_set)
862                 return -EINVAL;
863
864         reset_location(j);
865
866         j->current_location.type = LOCATION_DISCRETE;
867
868         if (realtime_set) {
869                 j->current_location.realtime = (uint64_t) realtime;
870                 j->current_location.realtime_set = true;
871         }
872
873         if (seqnum_set && seqnum_id_set) {
874                 j->current_location.seqnum = (uint64_t) seqnum;
875                 j->current_location.seqnum_id = seqnum_id;
876                 j->current_location.seqnum_set = true;
877         }
878
879         if (monotonic_set && boot_id_set) {
880                 j->current_location.monotonic = (uint64_t) monotonic;
881                 j->current_location.boot_id = boot_id;
882                 j->current_location.monotonic_set = true;
883         }
884
885         if (xor_hash_set) {
886                 j->current_location.xor_hash = (uint64_t) xor_hash;
887                 j->current_location.xor_hash_set = true;
888         }
889
890         return 0;
891 }
892
893 int sd_journal_seek_monotonic_usec(sd_journal *j, sd_id128_t boot_id, uint64_t usec) {
894         assert(j);
895
896         reset_location(j);
897         j->current_location.type = LOCATION_DISCRETE;
898         j->current_location.boot_id = boot_id;
899         j->current_location.monotonic = usec;
900         j->current_location.monotonic_set = true;
901
902         return 0;
903 }
904
905 int sd_journal_seek_realtime_usec(sd_journal *j, uint64_t usec) {
906         assert(j);
907
908         reset_location(j);
909         j->current_location.type = LOCATION_DISCRETE;
910         j->current_location.realtime = usec;
911         j->current_location.realtime_set = true;
912
913         return 0;
914 }
915
916 int sd_journal_seek_head(sd_journal *j) {
917         assert(j);
918
919         reset_location(j);
920         j->current_location.type = LOCATION_HEAD;
921
922         return 0;
923 }
924
925 int sd_journal_seek_tail(sd_journal *j) {
926         assert(j);
927
928         reset_location(j);
929         j->current_location.type = LOCATION_TAIL;
930
931         return 0;
932 }
933
934 static int add_file(sd_journal *j, const char *prefix, const char *dir, const char *filename) {
935         char *fn;
936         int r;
937         JournalFile *f;
938
939         assert(j);
940         assert(prefix);
941         assert(filename);
942
943         if (dir)
944                 fn = join(prefix, "/", dir, "/", filename, NULL);
945         else
946                 fn = join(prefix, "/", filename, NULL);
947
948         if (!fn)
949                 return -ENOMEM;
950
951         if (hashmap_get(j->files, fn)) {
952                 free(fn);
953                 return 0;
954         }
955
956         if (hashmap_size(j->files) >= JOURNAL_FILES_MAX) {
957                 log_debug("Too many open journal files, not adding %s, ignoring.", fn);
958                 free(fn);
959                 return 0;
960         }
961
962         r = journal_file_open(fn, O_RDONLY, 0, NULL, &f);
963         free(fn);
964
965         if (r < 0) {
966                 if (errno == ENOENT)
967                         return 0;
968
969                 return r;
970         }
971
972         journal_file_dump(f);
973
974         r = hashmap_put(j->files, f->path, f);
975         if (r < 0) {
976                 journal_file_close(f);
977                 return r;
978         }
979
980         log_debug("File %s got added.", f->path);
981
982         return 0;
983 }
984
985 static int remove_file(sd_journal *j, const char *prefix, const char *dir, const char *filename) {
986         char *fn;
987         JournalFile *f;
988
989         assert(j);
990         assert(prefix);
991         assert(filename);
992
993         if (dir)
994                 fn = join(prefix, "/", dir, "/", filename, NULL);
995         else
996                 fn = join(prefix, "/", filename, NULL);
997
998         if (!fn)
999                 return -ENOMEM;
1000
1001         f = hashmap_get(j->files, fn);
1002         free(fn);
1003
1004         if (!f)
1005                 return 0;
1006
1007         hashmap_remove(j->files, f->path);
1008         journal_file_close(f);
1009
1010         log_debug("File %s got removed.", f->path);
1011         return 0;
1012 }
1013
1014 static int add_directory(sd_journal *j, const char *prefix, const char *dir) {
1015         char *fn;
1016         int r;
1017         DIR *d;
1018         int wd;
1019
1020         assert(j);
1021         assert(prefix);
1022         assert(dir);
1023
1024         fn = join(prefix, "/", dir, NULL);
1025         if (!fn)
1026                 return -ENOMEM;
1027
1028         d = opendir(fn);
1029
1030         if (!d) {
1031                 free(fn);
1032                 if (errno == ENOENT)
1033                         return 0;
1034
1035                 return -errno;
1036         }
1037
1038         wd = inotify_add_watch(j->inotify_fd, fn,
1039                                IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB|IN_DELETE|
1040                                IN_DELETE_SELF|IN_MOVE_SELF|IN_UNMOUNT|
1041                                IN_DONT_FOLLOW|IN_ONLYDIR);
1042         if (wd > 0) {
1043                 if (hashmap_put(j->inotify_wd_dirs, INT_TO_PTR(wd), fn) < 0)
1044                         inotify_rm_watch(j->inotify_fd, wd);
1045                 else
1046                         fn = NULL;
1047         }
1048
1049         free(fn);
1050
1051         for (;;) {
1052                 struct dirent buf, *de;
1053
1054                 r = readdir_r(d, &buf, &de);
1055                 if (r != 0 || !de)
1056                         break;
1057
1058                 if (!dirent_is_file_with_suffix(de, ".journal"))
1059                         continue;
1060
1061                 r = add_file(j, prefix, dir, de->d_name);
1062                 if (r < 0)
1063                         log_debug("Failed to add file %s/%s/%s: %s", prefix, dir, de->d_name, strerror(-r));
1064         }
1065
1066         closedir(d);
1067
1068         log_debug("Directory %s/%s got added.", prefix, dir);
1069
1070         return 0;
1071 }
1072
1073 static void remove_directory_wd(sd_journal *j, int wd) {
1074         char *p;
1075
1076         assert(j);
1077         assert(wd > 0);
1078
1079         if (j->inotify_fd >= 0)
1080                 inotify_rm_watch(j->inotify_fd, wd);
1081
1082         p = hashmap_remove(j->inotify_wd_dirs, INT_TO_PTR(wd));
1083
1084         if (p) {
1085                 log_debug("Directory %s got removed.", p);
1086                 free(p);
1087         }
1088 }
1089
1090 static void add_root_wd(sd_journal *j, const char *p) {
1091         int wd;
1092         char *k;
1093
1094         assert(j);
1095         assert(p);
1096
1097         wd = inotify_add_watch(j->inotify_fd, p,
1098                                IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB|IN_DELETE|
1099                                IN_DONT_FOLLOW|IN_ONLYDIR);
1100         if (wd <= 0)
1101                 return;
1102
1103         k = strdup(p);
1104         if (!k || hashmap_put(j->inotify_wd_roots, INT_TO_PTR(wd), k) < 0) {
1105                 inotify_rm_watch(j->inotify_fd, wd);
1106                 free(k);
1107         }
1108 }
1109
1110 static void remove_root_wd(sd_journal *j, int wd) {
1111         char *p;
1112
1113         assert(j);
1114         assert(wd > 0);
1115
1116         if (j->inotify_fd >= 0)
1117                 inotify_rm_watch(j->inotify_fd, wd);
1118
1119         p = hashmap_remove(j->inotify_wd_roots, INT_TO_PTR(wd));
1120
1121         if (p) {
1122                 log_debug("Root %s got removed.", p);
1123                 free(p);
1124         }
1125 }
1126
1127 int sd_journal_open(sd_journal **ret) {
1128         sd_journal *j;
1129         const char *p;
1130         const char search_paths[] =
1131                 "/run/log/journal\0"
1132                 "/var/log/journal\0";
1133         int r;
1134
1135         assert(ret);
1136
1137         j = new0(sd_journal, 1);
1138         if (!j)
1139                 return -ENOMEM;
1140
1141         j->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
1142         if (j->inotify_fd < 0) {
1143                 r = -errno;
1144                 goto fail;
1145         }
1146
1147         j->files = hashmap_new(string_hash_func, string_compare_func);
1148         if (!j->files) {
1149                 r = -ENOMEM;
1150                 goto fail;
1151         }
1152
1153         j->inotify_wd_dirs = hashmap_new(trivial_hash_func, trivial_compare_func);
1154         j->inotify_wd_roots = hashmap_new(trivial_hash_func, trivial_compare_func);
1155
1156         if (!j->inotify_wd_dirs || !j->inotify_wd_roots) {
1157                 r = -ENOMEM;
1158                 goto fail;
1159         }
1160
1161         /* We ignore most errors here, since the idea is to only open
1162          * what's actually accessible, and ignore the rest. */
1163
1164         NULSTR_FOREACH(p, search_paths) {
1165                 DIR *d;
1166
1167                 d = opendir(p);
1168                 if (!d) {
1169                         if (errno != ENOENT)
1170                                 log_debug("Failed to open %s: %m", p);
1171                         continue;
1172                 }
1173
1174                 add_root_wd(j, p);
1175
1176                 for (;;) {
1177                         struct dirent buf, *de;
1178                         sd_id128_t id;
1179
1180                         r = readdir_r(d, &buf, &de);
1181                         if (r != 0 || !de)
1182                                 break;
1183
1184                         if (dirent_is_file_with_suffix(de, ".journal")) {
1185                                 r = add_file(j, p, NULL, de->d_name);
1186                                 if (r < 0)
1187                                         log_debug("Failed to add file %s/%s: %s", p, de->d_name, strerror(-r));
1188
1189                         } else if ((de->d_type == DT_DIR || de->d_type == DT_UNKNOWN) &&
1190                                    sd_id128_from_string(de->d_name, &id) >= 0) {
1191
1192                                 r = add_directory(j, p, de->d_name);
1193                                 if (r < 0)
1194                                         log_debug("Failed to add directory %s/%s: %s", p, de->d_name, strerror(-r));
1195                         }
1196                 }
1197
1198                 closedir(d);
1199         }
1200
1201         *ret = j;
1202         return 0;
1203
1204 fail:
1205         sd_journal_close(j);
1206
1207         return r;
1208 };
1209
1210 void sd_journal_close(sd_journal *j) {
1211         assert(j);
1212
1213         if (j->inotify_wd_dirs) {
1214                 void *k;
1215
1216                 while ((k = hashmap_first_key(j->inotify_wd_dirs)))
1217                         remove_directory_wd(j, PTR_TO_INT(k));
1218
1219                 hashmap_free(j->inotify_wd_dirs);
1220         }
1221
1222         if (j->inotify_wd_roots) {
1223                 void *k;
1224
1225                 while ((k = hashmap_first_key(j->inotify_wd_roots)))
1226                         remove_root_wd(j, PTR_TO_INT(k));
1227
1228                 hashmap_free(j->inotify_wd_roots);
1229         }
1230
1231         if (j->files) {
1232                 JournalFile *f;
1233
1234                 while ((f = hashmap_steal_first(j->files)))
1235                         journal_file_close(f);
1236
1237                 hashmap_free(j->files);
1238         }
1239
1240         sd_journal_flush_matches(j);
1241
1242         if (j->inotify_fd >= 0)
1243                 close_nointr_nofail(j->inotify_fd);
1244
1245         free(j);
1246 }
1247
1248 int sd_journal_get_realtime_usec(sd_journal *j, uint64_t *ret) {
1249         Object *o;
1250         JournalFile *f;
1251         int r;
1252
1253         assert(j);
1254         assert(ret);
1255
1256         f = j->current_file;
1257         if (!f)
1258                 return -EADDRNOTAVAIL;
1259
1260         if (f->current_offset <= 0)
1261                 return -EADDRNOTAVAIL;
1262
1263         r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
1264         if (r < 0)
1265                 return r;
1266
1267         *ret = le64toh(o->entry.realtime);
1268         return 0;
1269 }
1270
1271 int sd_journal_get_monotonic_usec(sd_journal *j, uint64_t *ret, sd_id128_t *ret_boot_id) {
1272         Object *o;
1273         JournalFile *f;
1274         int r;
1275         sd_id128_t id;
1276
1277         assert(j);
1278         assert(ret);
1279
1280         f = j->current_file;
1281         if (!f)
1282                 return -EADDRNOTAVAIL;
1283
1284         if (f->current_offset <= 0)
1285                 return -EADDRNOTAVAIL;
1286
1287         r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
1288         if (r < 0)
1289                 return r;
1290
1291         if (ret_boot_id)
1292                 *ret_boot_id = o->entry.boot_id;
1293         else {
1294                 r = sd_id128_get_boot(&id);
1295                 if (r < 0)
1296                         return r;
1297
1298                 if (!sd_id128_equal(id, o->entry.boot_id))
1299                         return -ENOENT;
1300         }
1301
1302         *ret = le64toh(o->entry.monotonic);
1303         return 0;
1304 }
1305
1306 int sd_journal_get_data(sd_journal *j, const char *field, const void **data, size_t *size) {
1307         JournalFile *f;
1308         uint64_t i, n;
1309         size_t field_length;
1310         int r;
1311         Object *o;
1312
1313         assert(j);
1314         assert(field);
1315         assert(data);
1316         assert(size);
1317
1318         if (isempty(field) || strchr(field, '='))
1319                 return -EINVAL;
1320
1321         f = j->current_file;
1322         if (!f)
1323                 return -EADDRNOTAVAIL;
1324
1325         if (f->current_offset <= 0)
1326                 return -EADDRNOTAVAIL;
1327
1328         r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
1329         if (r < 0)
1330                 return r;
1331
1332         field_length = strlen(field);
1333
1334         n = journal_file_entry_n_items(o);
1335         for (i = 0; i < n; i++) {
1336                 uint64_t p, l, le_hash;
1337                 size_t t;
1338
1339                 p = le64toh(o->entry.items[i].object_offset);
1340                 le_hash = o->entry.items[j->current_field].hash;
1341                 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
1342                 if (r < 0)
1343                         return r;
1344
1345                 if (le_hash != o->data.hash)
1346                         return -EBADMSG;
1347
1348                 l = le64toh(o->object.size) - offsetof(Object, data.payload);
1349
1350                 if (l >= field_length+1 &&
1351                     memcmp(o->data.payload, field, field_length) == 0 &&
1352                     o->data.payload[field_length] == '=') {
1353
1354                         t = (size_t) l;
1355
1356                         if ((uint64_t) t != l)
1357                                 return -E2BIG;
1358
1359                         *data = o->data.payload;
1360                         *size = t;
1361
1362                         return 0;
1363                 }
1364
1365                 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
1366                 if (r < 0)
1367                         return r;
1368         }
1369
1370         return -ENOENT;
1371 }
1372
1373 int sd_journal_enumerate_data(sd_journal *j, const void **data, size_t *size) {
1374         JournalFile *f;
1375         uint64_t p, l, n, le_hash;
1376         int r;
1377         Object *o;
1378         size_t t;
1379
1380         assert(j);
1381         assert(data);
1382         assert(size);
1383
1384         f = j->current_file;
1385         if (!f)
1386                 return -EADDRNOTAVAIL;
1387
1388         if (f->current_offset <= 0)
1389                 return -EADDRNOTAVAIL;
1390
1391         r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
1392         if (r < 0)
1393                 return r;
1394
1395         n = journal_file_entry_n_items(o);
1396         if (j->current_field >= n)
1397                 return 0;
1398
1399         p = le64toh(o->entry.items[j->current_field].object_offset);
1400         le_hash = o->entry.items[j->current_field].hash;
1401         r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
1402         if (r < 0)
1403                 return r;
1404
1405         if (le_hash != o->data.hash)
1406                 return -EBADMSG;
1407
1408         l = le64toh(o->object.size) - offsetof(Object, data.payload);
1409         t = (size_t) l;
1410
1411         /* We can't read objects larger than 4G on a 32bit machine */
1412         if ((uint64_t) t != l)
1413                 return -E2BIG;
1414
1415         *data = o->data.payload;
1416         *size = t;
1417
1418         j->current_field ++;
1419
1420         return 1;
1421 }
1422
1423 void sd_journal_restart_data(sd_journal *j) {
1424         assert(j);
1425
1426         j->current_field = 0;
1427 }
1428
1429 int sd_journal_get_fd(sd_journal *j) {
1430         assert(j);
1431
1432         return j->inotify_fd;
1433 }
1434
1435 static void process_inotify_event(sd_journal *j, struct inotify_event *e) {
1436         char *p;
1437         int r;
1438
1439         assert(j);
1440         assert(e);
1441
1442         /* Is this a subdirectory we watch? */
1443         p = hashmap_get(j->inotify_wd_dirs, INT_TO_PTR(e->wd));
1444         if (p) {
1445
1446                 if (!(e->mask & IN_ISDIR) && e->len > 0 && endswith(e->name, ".journal")) {
1447
1448                         /* Event for a journal file */
1449
1450                         if (e->mask & (IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB)) {
1451                                 r = add_file(j, p, NULL, e->name);
1452                                 if (r < 0)
1453                                         log_debug("Failed to add file %s/%s: %s", p, e->name, strerror(-r));
1454                         } else if (e->mask & (IN_DELETE|IN_UNMOUNT)) {
1455
1456                                 r = remove_file(j, p, NULL, e->name);
1457                                 if (r < 0)
1458                                         log_debug("Failed to remove file %s/%s: %s", p, e->name, strerror(-r));
1459                         }
1460
1461                 } else if (e->len == 0) {
1462
1463                         /* Event for the directory itself */
1464
1465                         if (e->mask & (IN_DELETE_SELF|IN_MOVE_SELF|IN_UNMOUNT))
1466                                 remove_directory_wd(j, e->wd);
1467                 }
1468
1469                 return;
1470         }
1471
1472         /* Must be the root directory then? */
1473         p = hashmap_get(j->inotify_wd_roots, INT_TO_PTR(e->wd));
1474         if (p) {
1475                 sd_id128_t id;
1476
1477                 if (!(e->mask & IN_ISDIR) && e->len > 0 && endswith(e->name, ".journal")) {
1478
1479                         /* Event for a journal file */
1480
1481                         if (e->mask & (IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB)) {
1482                                 r = add_file(j, p, NULL, e->name);
1483                                 if (r < 0)
1484                                         log_debug("Failed to add file %s/%s: %s", p, e->name, strerror(-r));
1485                         } else if (e->mask & (IN_DELETE|IN_UNMOUNT)) {
1486
1487                                 r = remove_file(j, p, NULL, e->name);
1488                                 if (r < 0)
1489                                         log_debug("Failed to remove file %s/%s: %s", p, e->name, strerror(-r));
1490                         }
1491
1492                 } else if ((e->mask & IN_ISDIR) && e->len > 0 && sd_id128_from_string(e->name, &id) >= 0) {
1493
1494                         /* Event for subdirectory */
1495
1496                         if (e->mask & (IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB)) {
1497
1498                                 r = add_directory(j, p, e->name);
1499                                 if (r < 0)
1500                                         log_debug("Failed to add directory %s/%s: %s", p, e->name, strerror(-r));
1501                         }
1502                 }
1503
1504                 return;
1505         }
1506
1507         if (e->mask & IN_IGNORED)
1508                 return;
1509
1510         log_warning("Unknown inotify event.");
1511 }
1512
1513 int sd_journal_process(sd_journal *j) {
1514         uint8_t buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1515
1516         assert(j);
1517
1518         for (;;) {
1519                 struct inotify_event *e;
1520                 ssize_t l;
1521
1522                 l = read(j->inotify_fd, buffer, sizeof(buffer));
1523                 if (l < 0) {
1524                         if (errno == EINTR || errno == EAGAIN)
1525                                 return 0;
1526
1527                         return -errno;
1528                 }
1529
1530                 e = (struct inotify_event*) buffer;
1531                 while (l > 0) {
1532                         size_t step;
1533
1534                         process_inotify_event(j, e);
1535
1536                         step = sizeof(struct inotify_event) + e->len;
1537                         assert(step <= (size_t) l);
1538
1539                         e = (struct inotify_event*) ((uint8_t*) e + step);
1540                         l -= step;
1541                 }
1542         }
1543 }