]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/libsystemd/sd-journal/journal-file.c
Merge pull request #27553 from yuwata/sd-journal-generic-array-bisect
[thirdparty/systemd.git] / src / libsystemd / sd-journal / journal-file.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <linux/fs.h>
6 #include <linux/magic.h>
7 #include <pthread.h>
8 #include <stddef.h>
9 #include <sys/mman.h>
10 #include <sys/statvfs.h>
11 #include <sys/uio.h>
12 #include <unistd.h>
13
14 #include "sd-event.h"
15
16 #include "alloc-util.h"
17 #include "chattr-util.h"
18 #include "compress.h"
19 #include "env-util.h"
20 #include "fd-util.h"
21 #include "format-util.h"
22 #include "fs-util.h"
23 #include "id128-util.h"
24 #include "journal-authenticate.h"
25 #include "journal-def.h"
26 #include "journal-file.h"
27 #include "journal-internal.h"
28 #include "lookup3.h"
29 #include "memory-util.h"
30 #include "missing_threads.h"
31 #include "path-util.h"
32 #include "prioq.h"
33 #include "random-util.h"
34 #include "set.h"
35 #include "sort-util.h"
36 #include "stat-util.h"
37 #include "string-table.h"
38 #include "string-util.h"
39 #include "strv.h"
40 #include "sync-util.h"
41 #include "user-util.h"
42 #include "xattr-util.h"
43
44 #define DEFAULT_DATA_HASH_TABLE_SIZE (2047ULL*sizeof(HashItem))
45 #define DEFAULT_FIELD_HASH_TABLE_SIZE (333ULL*sizeof(HashItem))
46
47 #define DEFAULT_COMPRESS_THRESHOLD (512ULL)
48 #define MIN_COMPRESS_THRESHOLD (8ULL)
49
50 /* This is the minimum journal file size */
51 #define JOURNAL_FILE_SIZE_MIN (512 * 1024ULL) /* 512 KiB */
52 #define JOURNAL_COMPACT_SIZE_MAX UINT32_MAX /* 4 GiB */
53
54 /* These are the lower and upper bounds if we deduce the max_use value
55 * from the file system size */
56 #define MAX_USE_LOWER (1 * 1024 * 1024ULL) /* 1 MiB */
57 #define MAX_USE_UPPER (4 * 1024 * 1024 * 1024ULL) /* 4 GiB */
58
59 /* Those are the lower and upper bounds for the minimal use limit,
60 * i.e. how much we'll use even if keep_free suggests otherwise. */
61 #define MIN_USE_LOW (1 * 1024 * 1024ULL) /* 1 MiB */
62 #define MIN_USE_HIGH (16 * 1024 * 1024ULL) /* 16 MiB */
63
64 /* This is the upper bound if we deduce max_size from max_use */
65 #define MAX_SIZE_UPPER (128 * 1024 * 1024ULL) /* 128 MiB */
66
67 /* This is the upper bound if we deduce the keep_free value from the
68 * file system size */
69 #define KEEP_FREE_UPPER (4 * 1024 * 1024 * 1024ULL) /* 4 GiB */
70
71 /* This is the keep_free value when we can't determine the system
72 * size */
73 #define DEFAULT_KEEP_FREE (1024 * 1024ULL) /* 1 MB */
74
75 /* This is the default maximum number of journal files to keep around. */
76 #define DEFAULT_N_MAX_FILES 100
77
78 /* n_data was the first entry we added after the initial file format design */
79 #define HEADER_SIZE_MIN ALIGN64(offsetof(Header, n_data))
80
81 /* How many entries to keep in the entry array chain cache at max */
82 #define CHAIN_CACHE_MAX 20
83
84 /* How much to increase the journal file size at once each time we allocate something new. */
85 #define FILE_SIZE_INCREASE (8 * 1024 * 1024ULL) /* 8MB */
86
87 /* Reread fstat() of the file for detecting deletions at least this often */
88 #define LAST_STAT_REFRESH_USEC (5*USEC_PER_SEC)
89
90 /* The mmap context to use for the header we pick as one above the last defined typed */
91 #define CONTEXT_HEADER _OBJECT_TYPE_MAX
92
93 /* Longest hash chain to rotate after */
94 #define HASH_CHAIN_DEPTH_MAX 100
95
96 #ifdef __clang__
97 # pragma GCC diagnostic ignored "-Waddress-of-packed-member"
98 #endif
99
100 static int mmap_prot_from_open_flags(int flags) {
101 switch (flags & O_ACCMODE) {
102 case O_RDONLY:
103 return PROT_READ;
104 case O_WRONLY:
105 return PROT_WRITE;
106 case O_RDWR:
107 return PROT_READ|PROT_WRITE;
108 default:
109 assert_not_reached();
110 }
111 }
112
113 int journal_file_tail_end_by_pread(JournalFile *f, uint64_t *ret_offset) {
114 uint64_t p;
115 int r;
116
117 assert(f);
118 assert(f->header);
119 assert(ret_offset);
120
121 /* Same as journal_file_tail_end_by_mmap() below, but operates with pread() to avoid the mmap cache
122 * (and thus is thread safe) */
123
124 p = le64toh(f->header->tail_object_offset);
125 if (p == 0)
126 p = le64toh(f->header->header_size);
127 else {
128 Object tail;
129 uint64_t sz;
130
131 r = journal_file_read_object_header(f, OBJECT_UNUSED, p, &tail);
132 if (r < 0)
133 return r;
134
135 sz = le64toh(tail.object.size);
136 if (sz > UINT64_MAX - sizeof(uint64_t) + 1)
137 return -EBADMSG;
138
139 sz = ALIGN64(sz);
140 if (p > UINT64_MAX - sz)
141 return -EBADMSG;
142
143 p += sz;
144 }
145
146 *ret_offset = p;
147
148 return 0;
149 }
150
151 int journal_file_tail_end_by_mmap(JournalFile *f, uint64_t *ret_offset) {
152 uint64_t p;
153 int r;
154
155 assert(f);
156 assert(f->header);
157 assert(ret_offset);
158
159 /* Same as journal_file_tail_end_by_pread() above, but operates with the usual mmap logic */
160
161 p = le64toh(f->header->tail_object_offset);
162 if (p == 0)
163 p = le64toh(f->header->header_size);
164 else {
165 Object *tail;
166 uint64_t sz;
167
168 r = journal_file_move_to_object(f, OBJECT_UNUSED, p, &tail);
169 if (r < 0)
170 return r;
171
172 sz = le64toh(READ_NOW(tail->object.size));
173 if (sz > UINT64_MAX - sizeof(uint64_t) + 1)
174 return -EBADMSG;
175
176 sz = ALIGN64(sz);
177 if (p > UINT64_MAX - sz)
178 return -EBADMSG;
179
180 p += sz;
181 }
182
183 *ret_offset = p;
184
185 return 0;
186 }
187
188 int journal_file_set_offline_thread_join(JournalFile *f) {
189 int r;
190
191 assert(f);
192
193 if (f->offline_state == OFFLINE_JOINED)
194 return 0;
195
196 r = pthread_join(f->offline_thread, NULL);
197 if (r)
198 return -r;
199
200 f->offline_state = OFFLINE_JOINED;
201
202 if (mmap_cache_fd_got_sigbus(f->cache_fd))
203 return -EIO;
204
205 return 0;
206 }
207
208 static int journal_file_set_online(JournalFile *f) {
209 bool wait = true;
210
211 assert(f);
212
213 if (!journal_file_writable(f))
214 return -EPERM;
215
216 if (f->fd < 0 || !f->header)
217 return -EINVAL;
218
219 while (wait) {
220 switch (f->offline_state) {
221 case OFFLINE_JOINED:
222 /* No offline thread, no need to wait. */
223 wait = false;
224 break;
225
226 case OFFLINE_SYNCING: {
227 OfflineState tmp_state = OFFLINE_SYNCING;
228 if (!__atomic_compare_exchange_n(&f->offline_state, &tmp_state, OFFLINE_CANCEL,
229 false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST))
230 continue;
231 }
232 /* Canceled syncing prior to offlining, no need to wait. */
233 wait = false;
234 break;
235
236 case OFFLINE_AGAIN_FROM_SYNCING: {
237 OfflineState tmp_state = OFFLINE_AGAIN_FROM_SYNCING;
238 if (!__atomic_compare_exchange_n(&f->offline_state, &tmp_state, OFFLINE_CANCEL,
239 false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST))
240 continue;
241 }
242 /* Canceled restart from syncing, no need to wait. */
243 wait = false;
244 break;
245
246 case OFFLINE_AGAIN_FROM_OFFLINING: {
247 OfflineState tmp_state = OFFLINE_AGAIN_FROM_OFFLINING;
248 if (!__atomic_compare_exchange_n(&f->offline_state, &tmp_state, OFFLINE_CANCEL,
249 false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST))
250 continue;
251 }
252 /* Canceled restart from offlining, must wait for offlining to complete however. */
253 _fallthrough_;
254 default: {
255 int r;
256
257 r = journal_file_set_offline_thread_join(f);
258 if (r < 0)
259 return r;
260
261 wait = false;
262 break;
263 }
264 }
265 }
266
267 if (mmap_cache_fd_got_sigbus(f->cache_fd))
268 return -EIO;
269
270 switch (f->header->state) {
271 case STATE_ONLINE:
272 return 0;
273
274 case STATE_OFFLINE:
275 f->header->state = STATE_ONLINE;
276 (void) fsync(f->fd);
277 return 0;
278
279 default:
280 return -EINVAL;
281 }
282 }
283
284 JournalFile* journal_file_close(JournalFile *f) {
285 if (!f)
286 return NULL;
287
288 assert(f->newest_boot_id_prioq_idx == PRIOQ_IDX_NULL);
289
290 if (f->cache_fd)
291 mmap_cache_fd_free(f->cache_fd);
292
293 if (f->close_fd)
294 safe_close(f->fd);
295 free(f->path);
296
297 ordered_hashmap_free_free(f->chain_cache);
298
299 #if HAVE_COMPRESSION
300 free(f->compress_buffer);
301 #endif
302
303 #if HAVE_GCRYPT
304 if (f->fss_file)
305 munmap(f->fss_file, PAGE_ALIGN(f->fss_file_size));
306 else
307 free(f->fsprg_state);
308
309 free(f->fsprg_seed);
310
311 if (f->hmac)
312 gcry_md_close(f->hmac);
313 #endif
314
315 return mfree(f);
316 }
317
318 static bool keyed_hash_requested(void) {
319 static thread_local int cached = -1;
320 int r;
321
322 if (cached < 0) {
323 r = getenv_bool("SYSTEMD_JOURNAL_KEYED_HASH");
324 if (r < 0) {
325 if (r != -ENXIO)
326 log_debug_errno(r, "Failed to parse $SYSTEMD_JOURNAL_KEYED_HASH environment variable, ignoring: %m");
327 cached = true;
328 } else
329 cached = r;
330 }
331
332 return cached;
333 }
334
335 static bool compact_mode_requested(void) {
336 static thread_local int cached = -1;
337 int r;
338
339 if (cached < 0) {
340 r = getenv_bool("SYSTEMD_JOURNAL_COMPACT");
341 if (r < 0) {
342 if (r != -ENXIO)
343 log_debug_errno(r, "Failed to parse $SYSTEMD_JOURNAL_COMPACT environment variable, ignoring: %m");
344 cached = true;
345 } else
346 cached = r;
347 }
348
349 return cached;
350 }
351
352 #if HAVE_COMPRESSION
353 static Compression getenv_compression(void) {
354 Compression c;
355 const char *e;
356 int r;
357
358 e = getenv("SYSTEMD_JOURNAL_COMPRESS");
359 if (!e)
360 return DEFAULT_COMPRESSION;
361
362 r = parse_boolean(e);
363 if (r >= 0)
364 return r ? DEFAULT_COMPRESSION : COMPRESSION_NONE;
365
366 c = compression_from_string(e);
367 if (c < 0) {
368 log_debug_errno(c, "Failed to parse SYSTEMD_JOURNAL_COMPRESS value, ignoring: %s", e);
369 return DEFAULT_COMPRESSION;
370 }
371
372 if (!compression_supported(c)) {
373 log_debug("Unsupported compression algorithm specified, ignoring: %s", e);
374 return DEFAULT_COMPRESSION;
375 }
376
377 return c;
378 }
379 #endif
380
381 static Compression compression_requested(void) {
382 #if HAVE_COMPRESSION
383 static thread_local Compression cached = _COMPRESSION_INVALID;
384
385 if (cached < 0)
386 cached = getenv_compression();
387
388 return cached;
389 #else
390 return COMPRESSION_NONE;
391 #endif
392 }
393
394 static int journal_file_init_header(
395 JournalFile *f,
396 JournalFileFlags file_flags,
397 JournalFile *template) {
398
399 bool seal = false;
400 ssize_t k;
401 int r;
402
403 assert(f);
404
405 #if HAVE_GCRYPT
406 /* Try to load the FSPRG state, and if we can't, then just don't do sealing */
407 seal = FLAGS_SET(file_flags, JOURNAL_SEAL) && journal_file_fss_load(f) >= 0;
408 #endif
409
410 Header h = {
411 .header_size = htole64(ALIGN64(sizeof(h))),
412 .incompatible_flags = htole32(
413 FLAGS_SET(file_flags, JOURNAL_COMPRESS) * COMPRESSION_TO_HEADER_INCOMPATIBLE_FLAG(compression_requested()) |
414 keyed_hash_requested() * HEADER_INCOMPATIBLE_KEYED_HASH |
415 compact_mode_requested() * HEADER_INCOMPATIBLE_COMPACT),
416 .compatible_flags = htole32(
417 (seal * HEADER_COMPATIBLE_SEALED) |
418 HEADER_COMPATIBLE_TAIL_ENTRY_BOOT_ID),
419 };
420
421 assert_cc(sizeof(h.signature) == sizeof(HEADER_SIGNATURE));
422 memcpy(h.signature, HEADER_SIGNATURE, sizeof(HEADER_SIGNATURE));
423
424 r = sd_id128_randomize(&h.file_id);
425 if (r < 0)
426 return r;
427
428 r = sd_id128_get_machine(&h.machine_id);
429 if (r < 0 && !ERRNO_IS_MACHINE_ID_UNSET(r))
430 return r; /* If we have no valid machine ID (test environment?), let's simply leave the
431 * machine ID field all zeroes. */
432
433 if (template) {
434 h.seqnum_id = template->header->seqnum_id;
435 h.tail_entry_seqnum = template->header->tail_entry_seqnum;
436 } else
437 h.seqnum_id = h.file_id;
438
439 k = pwrite(f->fd, &h, sizeof(h), 0);
440 if (k < 0)
441 return -errno;
442 if (k != sizeof(h))
443 return -EIO;
444
445 return 0;
446 }
447
448 static int journal_file_refresh_header(JournalFile *f) {
449 int r;
450
451 assert(f);
452 assert(f->header);
453
454 /* We used to update the header's boot ID field here, but we don't do that anymore, as per
455 * HEADER_COMPATIBLE_TAIL_ENTRY_BOOT_ID */
456
457 r = journal_file_set_online(f);
458
459 /* Sync the online state to disk; likely just created a new file, also sync the directory this file
460 * is located in. */
461 (void) fsync_full(f->fd);
462
463 return r;
464 }
465
466 static bool warn_wrong_flags(const JournalFile *f, bool compatible) {
467 const uint32_t any = compatible ? HEADER_COMPATIBLE_ANY : HEADER_INCOMPATIBLE_ANY,
468 supported = compatible ? HEADER_COMPATIBLE_SUPPORTED : HEADER_INCOMPATIBLE_SUPPORTED;
469 const char *type = compatible ? "compatible" : "incompatible";
470 uint32_t flags;
471
472 assert(f);
473 assert(f->header);
474
475 flags = le32toh(compatible ? f->header->compatible_flags : f->header->incompatible_flags);
476
477 if (flags & ~supported) {
478 if (flags & ~any)
479 log_debug("Journal file %s has unknown %s flags 0x%"PRIx32,
480 f->path, type, flags & ~any);
481 flags = (flags & any) & ~supported;
482 if (flags) {
483 const char* strv[6];
484 size_t n = 0;
485 _cleanup_free_ char *t = NULL;
486
487 if (compatible) {
488 if (flags & HEADER_COMPATIBLE_SEALED)
489 strv[n++] = "sealed";
490 } else {
491 if (flags & HEADER_INCOMPATIBLE_COMPRESSED_XZ)
492 strv[n++] = "xz-compressed";
493 if (flags & HEADER_INCOMPATIBLE_COMPRESSED_LZ4)
494 strv[n++] = "lz4-compressed";
495 if (flags & HEADER_INCOMPATIBLE_COMPRESSED_ZSTD)
496 strv[n++] = "zstd-compressed";
497 if (flags & HEADER_INCOMPATIBLE_KEYED_HASH)
498 strv[n++] = "keyed-hash";
499 if (flags & HEADER_INCOMPATIBLE_COMPACT)
500 strv[n++] = "compact";
501 }
502 strv[n] = NULL;
503 assert(n < ELEMENTSOF(strv));
504
505 t = strv_join((char**) strv, ", ");
506 log_debug("Journal file %s uses %s %s %s disabled at compilation time.",
507 f->path, type, n > 1 ? "flags" : "flag", strnull(t));
508 }
509 return true;
510 }
511
512 return false;
513 }
514
515 static int journal_file_verify_header(JournalFile *f) {
516 uint64_t arena_size, header_size;
517
518 assert(f);
519 assert(f->header);
520
521 if (memcmp(f->header->signature, HEADER_SIGNATURE, 8))
522 return -EBADMSG;
523
524 /* In both read and write mode we refuse to open files with incompatible
525 * flags we don't know. */
526 if (warn_wrong_flags(f, false))
527 return -EPROTONOSUPPORT;
528
529 /* When open for writing we refuse to open files with compatible flags, too. */
530 if (journal_file_writable(f) && warn_wrong_flags(f, true))
531 return -EPROTONOSUPPORT;
532
533 if (f->header->state >= _STATE_MAX)
534 return -EBADMSG;
535
536 header_size = le64toh(READ_NOW(f->header->header_size));
537
538 /* The first addition was n_data, so check that we are at least this large */
539 if (header_size < HEADER_SIZE_MIN)
540 return -EBADMSG;
541
542 /* When open for writing we refuse to open files with a mismatch of the header size, i.e. writing to
543 * files implementing older or new header structures. */
544 if (journal_file_writable(f) && header_size != sizeof(Header))
545 return -EPROTONOSUPPORT;
546
547 if (JOURNAL_HEADER_SEALED(f->header) && !JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays))
548 return -EBADMSG;
549
550 arena_size = le64toh(READ_NOW(f->header->arena_size));
551
552 if (UINT64_MAX - header_size < arena_size || header_size + arena_size > (uint64_t) f->last_stat.st_size)
553 return -ENODATA;
554
555 if (le64toh(f->header->tail_object_offset) > header_size + arena_size)
556 return -ENODATA;
557
558 if (!VALID64(le64toh(f->header->data_hash_table_offset)) ||
559 !VALID64(le64toh(f->header->field_hash_table_offset)) ||
560 !VALID64(le64toh(f->header->tail_object_offset)) ||
561 !VALID64(le64toh(f->header->entry_array_offset)))
562 return -ENODATA;
563
564 if (JOURNAL_HEADER_CONTAINS(f->header, tail_entry_offset) &&
565 le64toh(f->header->tail_entry_offset) != 0 &&
566 !VALID64(le64toh(f->header->tail_entry_offset)))
567 return -ENODATA;
568
569 if (journal_file_writable(f)) {
570 sd_id128_t machine_id;
571 uint8_t state;
572 int r;
573
574 r = sd_id128_get_machine(&machine_id);
575 if (r < 0) {
576 if (!ERRNO_IS_MACHINE_ID_UNSET(r)) /* handle graceful if machine ID is not initialized yet */
577 return r;
578
579 machine_id = SD_ID128_NULL;
580 }
581
582 if (!sd_id128_equal(machine_id, f->header->machine_id))
583 return log_debug_errno(SYNTHETIC_ERRNO(EHOSTDOWN),
584 "Trying to open journal file from different host for writing, refusing.");
585
586 state = f->header->state;
587
588 if (state == STATE_ARCHIVED)
589 return -ESHUTDOWN; /* Already archived */
590 if (state == STATE_ONLINE)
591 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY),
592 "Journal file %s is already online. Assuming unclean closing.",
593 f->path);
594 if (state != STATE_OFFLINE)
595 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY),
596 "Journal file %s has unknown state %i.",
597 f->path, state);
598
599 if (f->header->field_hash_table_size == 0 || f->header->data_hash_table_size == 0)
600 return -EBADMSG;
601 }
602
603 return 0;
604 }
605
606 int journal_file_fstat(JournalFile *f) {
607 int r;
608
609 assert(f);
610 assert(f->fd >= 0);
611
612 if (fstat(f->fd, &f->last_stat) < 0)
613 return -errno;
614
615 f->last_stat_usec = now(CLOCK_MONOTONIC);
616
617 /* Refuse dealing with files that aren't regular */
618 r = stat_verify_regular(&f->last_stat);
619 if (r < 0)
620 return r;
621
622 /* Refuse appending to files that are already deleted */
623 if (f->last_stat.st_nlink <= 0)
624 return -EIDRM;
625
626 return 0;
627 }
628
629 static int journal_file_allocate(JournalFile *f, uint64_t offset, uint64_t size) {
630 uint64_t old_size, new_size, old_header_size, old_arena_size;
631 int r;
632
633 assert(f);
634 assert(f->header);
635
636 /* We assume that this file is not sparse, and we know that for sure, since we always call
637 * posix_fallocate() ourselves */
638
639 if (size > PAGE_ALIGN_DOWN(UINT64_MAX) - offset)
640 return -EINVAL;
641
642 if (mmap_cache_fd_got_sigbus(f->cache_fd))
643 return -EIO;
644
645 old_header_size = le64toh(READ_NOW(f->header->header_size));
646 old_arena_size = le64toh(READ_NOW(f->header->arena_size));
647 if (old_arena_size > PAGE_ALIGN_DOWN(UINT64_MAX) - old_header_size)
648 return -EBADMSG;
649
650 old_size = old_header_size + old_arena_size;
651
652 new_size = MAX(PAGE_ALIGN(offset + size), old_header_size);
653
654 if (new_size <= old_size) {
655
656 /* We already pre-allocated enough space, but before
657 * we write to it, let's check with fstat() if the
658 * file got deleted, in order make sure we don't throw
659 * away the data immediately. Don't check fstat() for
660 * all writes though, but only once ever 10s. */
661
662 if (f->last_stat_usec + LAST_STAT_REFRESH_USEC > now(CLOCK_MONOTONIC))
663 return 0;
664
665 return journal_file_fstat(f);
666 }
667
668 /* Allocate more space. */
669
670 if (f->metrics.max_size > 0 && new_size > f->metrics.max_size)
671 return -E2BIG;
672
673 /* Refuse to go over 4G in compact mode so offsets can be stored in 32-bit. */
674 if (JOURNAL_HEADER_COMPACT(f->header) && new_size > UINT32_MAX)
675 return -E2BIG;
676
677 if (new_size > f->metrics.min_size && f->metrics.keep_free > 0) {
678 struct statvfs svfs;
679
680 if (fstatvfs(f->fd, &svfs) >= 0) {
681 uint64_t available;
682
683 available = LESS_BY((uint64_t) svfs.f_bfree * (uint64_t) svfs.f_bsize, f->metrics.keep_free);
684
685 if (new_size - old_size > available)
686 return -E2BIG;
687 }
688 }
689
690 /* Increase by larger blocks at once */
691 new_size = DIV_ROUND_UP(new_size, FILE_SIZE_INCREASE) * FILE_SIZE_INCREASE;
692 if (f->metrics.max_size > 0 && new_size > f->metrics.max_size)
693 new_size = f->metrics.max_size;
694
695 /* Note that the glibc fallocate() fallback is very
696 inefficient, hence we try to minimize the allocation area
697 as we can. */
698 r = posix_fallocate_loop(f->fd, old_size, new_size - old_size);
699 if (r < 0)
700 return r;
701
702 f->header->arena_size = htole64(new_size - old_header_size);
703
704 return journal_file_fstat(f);
705 }
706
707 static unsigned type_to_context(ObjectType type) {
708 /* One context for each type, plus one catch-all for the rest */
709 assert_cc(_OBJECT_TYPE_MAX <= MMAP_CACHE_MAX_CONTEXTS);
710 assert_cc(CONTEXT_HEADER < MMAP_CACHE_MAX_CONTEXTS);
711 return type > OBJECT_UNUSED && type < _OBJECT_TYPE_MAX ? type : 0;
712 }
713
714 static int journal_file_move_to(
715 JournalFile *f,
716 ObjectType type,
717 bool keep_always,
718 uint64_t offset,
719 uint64_t size,
720 void **ret) {
721
722 int r;
723
724 assert(f);
725 assert(ret);
726
727 /* This function may clear, overwrite, or alter previously cached entries. After this function has
728 * been called, all objects except for one obtained by this function are invalidated and must be
729 * re-read before use. */
730
731 if (size <= 0)
732 return -EINVAL;
733
734 if (size > UINT64_MAX - offset)
735 return -EBADMSG;
736
737 /* Avoid SIGBUS on invalid accesses */
738 if (offset + size > (uint64_t) f->last_stat.st_size) {
739 /* Hmm, out of range? Let's refresh the fstat() data
740 * first, before we trust that check. */
741
742 r = journal_file_fstat(f);
743 if (r < 0)
744 return r;
745
746 if (offset + size > (uint64_t) f->last_stat.st_size)
747 return -EADDRNOTAVAIL;
748 }
749
750 return mmap_cache_fd_get(f->cache_fd, type_to_context(type), keep_always, offset, size, &f->last_stat, ret);
751 }
752
753 static uint64_t minimum_header_size(JournalFile *f, Object *o) {
754
755 static const uint64_t table[] = {
756 [OBJECT_DATA] = sizeof(DataObject),
757 [OBJECT_FIELD] = sizeof(FieldObject),
758 [OBJECT_ENTRY] = sizeof(EntryObject),
759 [OBJECT_DATA_HASH_TABLE] = sizeof(HashTableObject),
760 [OBJECT_FIELD_HASH_TABLE] = sizeof(HashTableObject),
761 [OBJECT_ENTRY_ARRAY] = sizeof(EntryArrayObject),
762 [OBJECT_TAG] = sizeof(TagObject),
763 };
764
765 assert(f);
766 assert(o);
767
768 if (o->object.type == OBJECT_DATA)
769 return journal_file_data_payload_offset(f);
770
771 if (o->object.type >= ELEMENTSOF(table) || table[o->object.type] <= 0)
772 return sizeof(ObjectHeader);
773
774 return table[o->object.type];
775 }
776
777 static int check_object_header(JournalFile *f, Object *o, ObjectType type, uint64_t offset) {
778 uint64_t s;
779
780 assert(f);
781 assert(o);
782
783 s = le64toh(READ_NOW(o->object.size));
784 if (s == 0)
785 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
786 "Attempt to move to uninitialized object: %" PRIu64,
787 offset);
788
789 if (s < sizeof(ObjectHeader))
790 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
791 "Attempt to move to overly short object with size %"PRIu64": %" PRIu64,
792 s, offset);
793
794 if (o->object.type <= OBJECT_UNUSED || o->object.type >= _OBJECT_TYPE_MAX)
795 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
796 "Attempt to move to object with invalid type (%u): %" PRIu64,
797 o->object.type, offset);
798
799 if (type > OBJECT_UNUSED && o->object.type != type)
800 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
801 "Found %s object while expecting %s object: %" PRIu64,
802 journal_object_type_to_string(o->object.type),
803 journal_object_type_to_string(type),
804 offset);
805
806 if (s < minimum_header_size(f, o))
807 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
808 "Size of %s object (%"PRIu64") is smaller than the minimum object size (%"PRIu64"): %" PRIu64,
809 journal_object_type_to_string(o->object.type),
810 s,
811 minimum_header_size(f, o),
812 offset);
813
814 return 0;
815 }
816
817 /* Lightweight object checks. We want this to be fast, so that we won't
818 * slowdown every journal_file_move_to_object() call too much. */
819 static int check_object(JournalFile *f, Object *o, uint64_t offset) {
820 assert(f);
821 assert(o);
822
823 switch (o->object.type) {
824
825 case OBJECT_DATA:
826 if ((le64toh(o->data.entry_offset) == 0) ^ (le64toh(o->data.n_entries) == 0))
827 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
828 "Bad data n_entries: %" PRIu64 ": %" PRIu64,
829 le64toh(o->data.n_entries),
830 offset);
831
832 if (le64toh(o->object.size) <= journal_file_data_payload_offset(f))
833 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
834 "Bad data size (<= %zu): %" PRIu64 ": %" PRIu64,
835 journal_file_data_payload_offset(f),
836 le64toh(o->object.size),
837 offset);
838
839 if (!VALID64(le64toh(o->data.next_hash_offset)) ||
840 !VALID64(le64toh(o->data.next_field_offset)) ||
841 !VALID64(le64toh(o->data.entry_offset)) ||
842 !VALID64(le64toh(o->data.entry_array_offset)))
843 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
844 "Invalid offset, next_hash_offset=" OFSfmt ", next_field_offset=" OFSfmt ", entry_offset=" OFSfmt ", entry_array_offset=" OFSfmt ": %" PRIu64,
845 le64toh(o->data.next_hash_offset),
846 le64toh(o->data.next_field_offset),
847 le64toh(o->data.entry_offset),
848 le64toh(o->data.entry_array_offset),
849 offset);
850
851 break;
852
853 case OBJECT_FIELD:
854 if (le64toh(o->object.size) <= offsetof(Object, field.payload))
855 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
856 "Bad field size (<= %zu): %" PRIu64 ": %" PRIu64,
857 offsetof(Object, field.payload),
858 le64toh(o->object.size),
859 offset);
860
861 if (!VALID64(le64toh(o->field.next_hash_offset)) ||
862 !VALID64(le64toh(o->field.head_data_offset)))
863 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
864 "Invalid offset, next_hash_offset=" OFSfmt ", head_data_offset=" OFSfmt ": %" PRIu64,
865 le64toh(o->field.next_hash_offset),
866 le64toh(o->field.head_data_offset),
867 offset);
868 break;
869
870 case OBJECT_ENTRY: {
871 uint64_t sz;
872
873 sz = le64toh(READ_NOW(o->object.size));
874 if (sz < offsetof(Object, entry.items) ||
875 (sz - offsetof(Object, entry.items)) % journal_file_entry_item_size(f) != 0)
876 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
877 "Bad entry size (<= %zu): %" PRIu64 ": %" PRIu64,
878 offsetof(Object, entry.items),
879 sz,
880 offset);
881
882 if ((sz - offsetof(Object, entry.items)) / journal_file_entry_item_size(f) <= 0)
883 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
884 "Invalid number items in entry: %" PRIu64 ": %" PRIu64,
885 (sz - offsetof(Object, entry.items)) / journal_file_entry_item_size(f),
886 offset);
887
888 if (le64toh(o->entry.seqnum) <= 0)
889 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
890 "Invalid entry seqnum: %" PRIx64 ": %" PRIu64,
891 le64toh(o->entry.seqnum),
892 offset);
893
894 if (!VALID_REALTIME(le64toh(o->entry.realtime)))
895 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
896 "Invalid entry realtime timestamp: %" PRIu64 ": %" PRIu64,
897 le64toh(o->entry.realtime),
898 offset);
899
900 if (!VALID_MONOTONIC(le64toh(o->entry.monotonic)))
901 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
902 "Invalid entry monotonic timestamp: %" PRIu64 ": %" PRIu64,
903 le64toh(o->entry.monotonic),
904 offset);
905
906 break;
907 }
908
909 case OBJECT_DATA_HASH_TABLE:
910 case OBJECT_FIELD_HASH_TABLE: {
911 uint64_t sz;
912
913 sz = le64toh(READ_NOW(o->object.size));
914 if (sz < offsetof(Object, hash_table.items) ||
915 (sz - offsetof(Object, hash_table.items)) % sizeof(HashItem) != 0 ||
916 (sz - offsetof(Object, hash_table.items)) / sizeof(HashItem) <= 0)
917 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
918 "Invalid %s hash table size: %" PRIu64 ": %" PRIu64,
919 journal_object_type_to_string(o->object.type),
920 sz,
921 offset);
922
923 break;
924 }
925
926 case OBJECT_ENTRY_ARRAY: {
927 uint64_t sz, next;
928
929 sz = le64toh(READ_NOW(o->object.size));
930 if (sz < offsetof(Object, entry_array.items) ||
931 (sz - offsetof(Object, entry_array.items)) % journal_file_entry_array_item_size(f) != 0 ||
932 (sz - offsetof(Object, entry_array.items)) / journal_file_entry_array_item_size(f) <= 0)
933 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
934 "Invalid object entry array size: %" PRIu64 ": %" PRIu64,
935 sz,
936 offset);
937 /* Here, we request that the offset of each entry array object is in strictly increasing order. */
938 next = le64toh(o->entry_array.next_entry_array_offset);
939 if (!VALID64(next) || (next > 0 && next <= offset))
940 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
941 "Invalid object entry array next_entry_array_offset: %" PRIu64 ": %" PRIu64,
942 next,
943 offset);
944
945 break;
946 }
947
948 case OBJECT_TAG:
949 if (le64toh(o->object.size) != sizeof(TagObject))
950 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
951 "Invalid object tag size: %" PRIu64 ": %" PRIu64,
952 le64toh(o->object.size),
953 offset);
954
955 if (!VALID_EPOCH(le64toh(o->tag.epoch)))
956 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
957 "Invalid object tag epoch: %" PRIu64 ": %" PRIu64,
958 le64toh(o->tag.epoch), offset);
959
960 break;
961 }
962
963 return 0;
964 }
965
966 int journal_file_move_to_object(JournalFile *f, ObjectType type, uint64_t offset, Object **ret) {
967 int r;
968 Object *o;
969
970 assert(f);
971
972 /* Even if this function fails, it may clear, overwrite, or alter previously cached entries. After
973 * this function has been called, all objects except for one obtained by this function are
974 * invalidated and must be re-read before use.. */
975
976 /* Objects may only be located at multiple of 64 bit */
977 if (!VALID64(offset))
978 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
979 "Attempt to move to %s object at non-64bit boundary: %" PRIu64,
980 journal_object_type_to_string(type),
981 offset);
982
983 /* Object may not be located in the file header */
984 if (offset < le64toh(f->header->header_size))
985 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
986 "Attempt to move to %s object located in file header: %" PRIu64,
987 journal_object_type_to_string(type),
988 offset);
989
990 r = journal_file_move_to(f, type, false, offset, sizeof(ObjectHeader), (void**) &o);
991 if (r < 0)
992 return r;
993
994 r = check_object_header(f, o, type, offset);
995 if (r < 0)
996 return r;
997
998 r = journal_file_move_to(f, type, false, offset, le64toh(READ_NOW(o->object.size)), (void**) &o);
999 if (r < 0)
1000 return r;
1001
1002 r = check_object_header(f, o, type, offset);
1003 if (r < 0)
1004 return r;
1005
1006 r = check_object(f, o, offset);
1007 if (r < 0)
1008 return r;
1009
1010 if (ret)
1011 *ret = o;
1012
1013 return 0;
1014 }
1015
1016 int journal_file_read_object_header(JournalFile *f, ObjectType type, uint64_t offset, Object *ret) {
1017 ssize_t n;
1018 Object o;
1019 int r;
1020
1021 assert(f);
1022
1023 /* Objects may only be located at multiple of 64 bit */
1024 if (!VALID64(offset))
1025 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
1026 "Attempt to read %s object at non-64bit boundary: %" PRIu64,
1027 journal_object_type_to_string(type), offset);
1028
1029 /* Object may not be located in the file header */
1030 if (offset < le64toh(f->header->header_size))
1031 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
1032 "Attempt to read %s object located in file header: %" PRIu64,
1033 journal_object_type_to_string(type), offset);
1034
1035 /* This will likely read too much data but it avoids having to call pread() twice. */
1036 n = pread(f->fd, &o, sizeof(o), offset);
1037 if (n < 0)
1038 return log_debug_errno(errno, "Failed to read journal %s object at offset: %" PRIu64,
1039 journal_object_type_to_string(type), offset);
1040
1041 if ((size_t) n < sizeof(o.object))
1042 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
1043 "Failed to read short %s object at offset: %" PRIu64,
1044 journal_object_type_to_string(type), offset);
1045
1046 r = check_object_header(f, &o, type, offset);
1047 if (r < 0)
1048 return r;
1049
1050 if ((size_t) n < minimum_header_size(f, &o))
1051 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
1052 "Short read while reading %s object: %" PRIu64,
1053 journal_object_type_to_string(type), offset);
1054
1055 r = check_object(f, &o, offset);
1056 if (r < 0)
1057 return r;
1058
1059 if (ret)
1060 *ret = o;
1061
1062 return 0;
1063 }
1064
1065 static uint64_t inc_seqnum(uint64_t seqnum) {
1066 if (seqnum < UINT64_MAX-1)
1067 return seqnum + 1;
1068
1069 return 1; /* skip over UINT64_MAX and 0 when we run out of seqnums and start again */
1070 }
1071
1072 static uint64_t journal_file_entry_seqnum(
1073 JournalFile *f,
1074 uint64_t *seqnum) {
1075
1076 uint64_t next_seqnum;
1077
1078 assert(f);
1079 assert(f->header);
1080
1081 /* Picks a new sequence number for the entry we are about to add and returns it. */
1082
1083 next_seqnum = inc_seqnum(le64toh(f->header->tail_entry_seqnum));
1084
1085 /* If an external seqnum counter was passed, we update both the local and the external one, and set
1086 * it to the maximum of both */
1087 if (seqnum)
1088 *seqnum = next_seqnum = MAX(inc_seqnum(*seqnum), next_seqnum);
1089
1090 f->header->tail_entry_seqnum = htole64(next_seqnum);
1091
1092 if (f->header->head_entry_seqnum == 0)
1093 f->header->head_entry_seqnum = htole64(next_seqnum);
1094
1095 return next_seqnum;
1096 }
1097
1098 int journal_file_append_object(
1099 JournalFile *f,
1100 ObjectType type,
1101 uint64_t size,
1102 Object **ret_object,
1103 uint64_t *ret_offset) {
1104
1105 int r;
1106 uint64_t p;
1107 Object *o;
1108
1109 assert(f);
1110 assert(f->header);
1111 assert(type > OBJECT_UNUSED && type < _OBJECT_TYPE_MAX);
1112 assert(size >= sizeof(ObjectHeader));
1113
1114 r = journal_file_set_online(f);
1115 if (r < 0)
1116 return r;
1117
1118 r = journal_file_tail_end_by_mmap(f, &p);
1119 if (r < 0)
1120 return r;
1121
1122 r = journal_file_allocate(f, p, size);
1123 if (r < 0)
1124 return r;
1125
1126 r = journal_file_move_to(f, type, false, p, size, (void**) &o);
1127 if (r < 0)
1128 return r;
1129
1130 o->object = (ObjectHeader) {
1131 .type = type,
1132 .size = htole64(size),
1133 };
1134
1135 f->header->tail_object_offset = htole64(p);
1136 f->header->n_objects = htole64(le64toh(f->header->n_objects) + 1);
1137
1138 if (ret_object)
1139 *ret_object = o;
1140
1141 if (ret_offset)
1142 *ret_offset = p;
1143
1144 return 0;
1145 }
1146
1147 static int journal_file_setup_data_hash_table(JournalFile *f) {
1148 uint64_t s, p;
1149 Object *o;
1150 int r;
1151
1152 assert(f);
1153 assert(f->header);
1154
1155 /* We estimate that we need 1 hash table entry per 768 bytes
1156 of journal file and we want to make sure we never get
1157 beyond 75% fill level. Calculate the hash table size for
1158 the maximum file size based on these metrics. */
1159
1160 s = (f->metrics.max_size * 4 / 768 / 3) * sizeof(HashItem);
1161 if (s < DEFAULT_DATA_HASH_TABLE_SIZE)
1162 s = DEFAULT_DATA_HASH_TABLE_SIZE;
1163
1164 log_debug("Reserving %"PRIu64" entries in data hash table.", s / sizeof(HashItem));
1165
1166 r = journal_file_append_object(f,
1167 OBJECT_DATA_HASH_TABLE,
1168 offsetof(Object, hash_table.items) + s,
1169 &o, &p);
1170 if (r < 0)
1171 return r;
1172
1173 memzero(o->hash_table.items, s);
1174
1175 f->header->data_hash_table_offset = htole64(p + offsetof(Object, hash_table.items));
1176 f->header->data_hash_table_size = htole64(s);
1177
1178 return 0;
1179 }
1180
1181 static int journal_file_setup_field_hash_table(JournalFile *f) {
1182 uint64_t s, p;
1183 Object *o;
1184 int r;
1185
1186 assert(f);
1187 assert(f->header);
1188
1189 /* We use a fixed size hash table for the fields as this
1190 * number should grow very slowly only */
1191
1192 s = DEFAULT_FIELD_HASH_TABLE_SIZE;
1193 log_debug("Reserving %"PRIu64" entries in field hash table.", s / sizeof(HashItem));
1194
1195 r = journal_file_append_object(f,
1196 OBJECT_FIELD_HASH_TABLE,
1197 offsetof(Object, hash_table.items) + s,
1198 &o, &p);
1199 if (r < 0)
1200 return r;
1201
1202 memzero(o->hash_table.items, s);
1203
1204 f->header->field_hash_table_offset = htole64(p + offsetof(Object, hash_table.items));
1205 f->header->field_hash_table_size = htole64(s);
1206
1207 return 0;
1208 }
1209
1210 int journal_file_map_data_hash_table(JournalFile *f) {
1211 uint64_t s, p;
1212 void *t;
1213 int r;
1214
1215 assert(f);
1216 assert(f->header);
1217
1218 if (f->data_hash_table)
1219 return 0;
1220
1221 p = le64toh(f->header->data_hash_table_offset);
1222 s = le64toh(f->header->data_hash_table_size);
1223
1224 r = journal_file_move_to(f,
1225 OBJECT_DATA_HASH_TABLE,
1226 true,
1227 p, s,
1228 &t);
1229 if (r < 0)
1230 return r;
1231
1232 f->data_hash_table = t;
1233 return 0;
1234 }
1235
1236 int journal_file_map_field_hash_table(JournalFile *f) {
1237 uint64_t s, p;
1238 void *t;
1239 int r;
1240
1241 assert(f);
1242 assert(f->header);
1243
1244 if (f->field_hash_table)
1245 return 0;
1246
1247 p = le64toh(f->header->field_hash_table_offset);
1248 s = le64toh(f->header->field_hash_table_size);
1249
1250 r = journal_file_move_to(f,
1251 OBJECT_FIELD_HASH_TABLE,
1252 true,
1253 p, s,
1254 &t);
1255 if (r < 0)
1256 return r;
1257
1258 f->field_hash_table = t;
1259 return 0;
1260 }
1261
1262 static int journal_file_link_field(
1263 JournalFile *f,
1264 Object *o,
1265 uint64_t offset,
1266 uint64_t hash) {
1267
1268 uint64_t p, h, m;
1269 int r;
1270
1271 assert(f);
1272 assert(f->header);
1273 assert(f->field_hash_table);
1274 assert(o);
1275 assert(offset > 0);
1276
1277 if (o->object.type != OBJECT_FIELD)
1278 return -EINVAL;
1279
1280 m = le64toh(READ_NOW(f->header->field_hash_table_size)) / sizeof(HashItem);
1281 if (m <= 0)
1282 return -EBADMSG;
1283
1284 /* This might alter the window we are looking at */
1285 o->field.next_hash_offset = o->field.head_data_offset = 0;
1286
1287 h = hash % m;
1288 p = le64toh(f->field_hash_table[h].tail_hash_offset);
1289 if (p == 0)
1290 f->field_hash_table[h].head_hash_offset = htole64(offset);
1291 else {
1292 r = journal_file_move_to_object(f, OBJECT_FIELD, p, &o);
1293 if (r < 0)
1294 return r;
1295
1296 o->field.next_hash_offset = htole64(offset);
1297 }
1298
1299 f->field_hash_table[h].tail_hash_offset = htole64(offset);
1300
1301 if (JOURNAL_HEADER_CONTAINS(f->header, n_fields))
1302 f->header->n_fields = htole64(le64toh(f->header->n_fields) + 1);
1303
1304 return 0;
1305 }
1306
1307 static int journal_file_link_data(
1308 JournalFile *f,
1309 Object *o,
1310 uint64_t offset,
1311 uint64_t hash) {
1312
1313 uint64_t p, h, m;
1314 int r;
1315
1316 assert(f);
1317 assert(f->header);
1318 assert(f->data_hash_table);
1319 assert(o);
1320 assert(offset > 0);
1321
1322 if (o->object.type != OBJECT_DATA)
1323 return -EINVAL;
1324
1325 m = le64toh(READ_NOW(f->header->data_hash_table_size)) / sizeof(HashItem);
1326 if (m <= 0)
1327 return -EBADMSG;
1328
1329 /* This might alter the window we are looking at */
1330 o->data.next_hash_offset = o->data.next_field_offset = 0;
1331 o->data.entry_offset = o->data.entry_array_offset = 0;
1332 o->data.n_entries = 0;
1333
1334 h = hash % m;
1335 p = le64toh(f->data_hash_table[h].tail_hash_offset);
1336 if (p == 0)
1337 /* Only entry in the hash table is easy */
1338 f->data_hash_table[h].head_hash_offset = htole64(offset);
1339 else {
1340 /* Move back to the previous data object, to patch in
1341 * pointer */
1342
1343 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
1344 if (r < 0)
1345 return r;
1346
1347 o->data.next_hash_offset = htole64(offset);
1348 }
1349
1350 f->data_hash_table[h].tail_hash_offset = htole64(offset);
1351
1352 if (JOURNAL_HEADER_CONTAINS(f->header, n_data))
1353 f->header->n_data = htole64(le64toh(f->header->n_data) + 1);
1354
1355 return 0;
1356 }
1357
1358 static int get_next_hash_offset(
1359 JournalFile *f,
1360 uint64_t *p,
1361 le64_t *next_hash_offset,
1362 uint64_t *depth,
1363 le64_t *header_max_depth) {
1364
1365 uint64_t nextp;
1366
1367 assert(f);
1368 assert(p);
1369 assert(next_hash_offset);
1370 assert(depth);
1371
1372 nextp = le64toh(READ_NOW(*next_hash_offset));
1373 if (nextp > 0) {
1374 if (nextp <= *p) /* Refuse going in loops */
1375 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
1376 "Detected hash item loop in %s, refusing.", f->path);
1377
1378 (*depth)++;
1379
1380 /* If the depth of this hash chain is larger than all others we have seen so far, record it */
1381 if (header_max_depth && journal_file_writable(f))
1382 *header_max_depth = htole64(MAX(*depth, le64toh(*header_max_depth)));
1383 }
1384
1385 *p = nextp;
1386 return 0;
1387 }
1388
1389 int journal_file_find_field_object_with_hash(
1390 JournalFile *f,
1391 const void *field,
1392 uint64_t size,
1393 uint64_t hash,
1394 Object **ret_object,
1395 uint64_t *ret_offset) {
1396
1397 uint64_t p, osize, h, m, depth = 0;
1398 int r;
1399
1400 assert(f);
1401 assert(f->header);
1402 assert(field);
1403 assert(size > 0);
1404
1405 /* If the field hash table is empty, we can't find anything */
1406 if (le64toh(f->header->field_hash_table_size) <= 0)
1407 return 0;
1408
1409 /* Map the field hash table, if it isn't mapped yet. */
1410 r = journal_file_map_field_hash_table(f);
1411 if (r < 0)
1412 return r;
1413
1414 osize = offsetof(Object, field.payload) + size;
1415
1416 m = le64toh(READ_NOW(f->header->field_hash_table_size)) / sizeof(HashItem);
1417 if (m <= 0)
1418 return -EBADMSG;
1419
1420 h = hash % m;
1421 p = le64toh(f->field_hash_table[h].head_hash_offset);
1422 while (p > 0) {
1423 Object *o;
1424
1425 r = journal_file_move_to_object(f, OBJECT_FIELD, p, &o);
1426 if (r < 0)
1427 return r;
1428
1429 if (le64toh(o->field.hash) == hash &&
1430 le64toh(o->object.size) == osize &&
1431 memcmp(o->field.payload, field, size) == 0) {
1432
1433 if (ret_object)
1434 *ret_object = o;
1435 if (ret_offset)
1436 *ret_offset = p;
1437
1438 return 1;
1439 }
1440
1441 r = get_next_hash_offset(
1442 f,
1443 &p,
1444 &o->field.next_hash_offset,
1445 &depth,
1446 JOURNAL_HEADER_CONTAINS(f->header, field_hash_chain_depth) ? &f->header->field_hash_chain_depth : NULL);
1447 if (r < 0)
1448 return r;
1449 }
1450
1451 return 0;
1452 }
1453
1454 uint64_t journal_file_hash_data(
1455 JournalFile *f,
1456 const void *data,
1457 size_t sz) {
1458
1459 assert(f);
1460 assert(f->header);
1461 assert(data || sz == 0);
1462
1463 /* We try to unify our codebase on siphash, hence new-styled journal files utilizing the keyed hash
1464 * function use siphash. Old journal files use the Jenkins hash. */
1465
1466 if (JOURNAL_HEADER_KEYED_HASH(f->header))
1467 return siphash24(data, sz, f->header->file_id.bytes);
1468
1469 return jenkins_hash64(data, sz);
1470 }
1471
1472 int journal_file_find_field_object(
1473 JournalFile *f,
1474 const void *field,
1475 uint64_t size,
1476 Object **ret_object,
1477 uint64_t *ret_offset) {
1478
1479 assert(f);
1480 assert(field);
1481 assert(size > 0);
1482
1483 return journal_file_find_field_object_with_hash(
1484 f,
1485 field, size,
1486 journal_file_hash_data(f, field, size),
1487 ret_object, ret_offset);
1488 }
1489
1490 int journal_file_find_data_object_with_hash(
1491 JournalFile *f,
1492 const void *data,
1493 uint64_t size,
1494 uint64_t hash,
1495 Object **ret_object,
1496 uint64_t *ret_offset) {
1497
1498 uint64_t p, h, m, depth = 0;
1499 int r;
1500
1501 assert(f);
1502 assert(f->header);
1503 assert(data || size == 0);
1504
1505 /* If there's no data hash table, then there's no entry. */
1506 if (le64toh(f->header->data_hash_table_size) <= 0)
1507 return 0;
1508
1509 /* Map the data hash table, if it isn't mapped yet. */
1510 r = journal_file_map_data_hash_table(f);
1511 if (r < 0)
1512 return r;
1513
1514 m = le64toh(READ_NOW(f->header->data_hash_table_size)) / sizeof(HashItem);
1515 if (m <= 0)
1516 return -EBADMSG;
1517
1518 h = hash % m;
1519 p = le64toh(f->data_hash_table[h].head_hash_offset);
1520
1521 while (p > 0) {
1522 Object *o;
1523 void *d;
1524 size_t rsize;
1525
1526 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
1527 if (r < 0)
1528 return r;
1529
1530 if (le64toh(o->data.hash) != hash)
1531 goto next;
1532
1533 r = journal_file_data_payload(f, o, p, NULL, 0, 0, &d, &rsize);
1534 if (r < 0)
1535 return r;
1536 assert(r > 0); /* journal_file_data_payload() always returns > 0 if no field is provided. */
1537
1538 if (memcmp_nn(data, size, d, rsize) == 0) {
1539 if (ret_object)
1540 *ret_object = o;
1541
1542 if (ret_offset)
1543 *ret_offset = p;
1544
1545 return 1;
1546 }
1547
1548 next:
1549 r = get_next_hash_offset(
1550 f,
1551 &p,
1552 &o->data.next_hash_offset,
1553 &depth,
1554 JOURNAL_HEADER_CONTAINS(f->header, data_hash_chain_depth) ? &f->header->data_hash_chain_depth : NULL);
1555 if (r < 0)
1556 return r;
1557 }
1558
1559 return 0;
1560 }
1561
1562 int journal_file_find_data_object(
1563 JournalFile *f,
1564 const void *data,
1565 uint64_t size,
1566 Object **ret_object,
1567 uint64_t *ret_offset) {
1568
1569 assert(f);
1570 assert(data || size == 0);
1571
1572 return journal_file_find_data_object_with_hash(
1573 f,
1574 data, size,
1575 journal_file_hash_data(f, data, size),
1576 ret_object, ret_offset);
1577 }
1578
1579 bool journal_field_valid(const char *p, size_t l, bool allow_protected) {
1580 /* We kinda enforce POSIX syntax recommendations for
1581 environment variables here, but make a couple of additional
1582 requirements.
1583
1584 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html */
1585
1586 assert(p);
1587
1588 if (l == SIZE_MAX)
1589 l = strlen(p);
1590
1591 /* No empty field names */
1592 if (l <= 0)
1593 return false;
1594
1595 /* Don't allow names longer than 64 chars */
1596 if (l > 64)
1597 return false;
1598
1599 /* Variables starting with an underscore are protected */
1600 if (!allow_protected && p[0] == '_')
1601 return false;
1602
1603 /* Don't allow digits as first character */
1604 if (ascii_isdigit(p[0]))
1605 return false;
1606
1607 /* Only allow A-Z0-9 and '_' */
1608 for (const char *a = p; a < p + l; a++)
1609 if ((*a < 'A' || *a > 'Z') &&
1610 !ascii_isdigit(*a) &&
1611 *a != '_')
1612 return false;
1613
1614 return true;
1615 }
1616
1617 static int journal_file_append_field(
1618 JournalFile *f,
1619 const void *field,
1620 uint64_t size,
1621 Object **ret_object,
1622 uint64_t *ret_offset) {
1623
1624 uint64_t hash, p;
1625 uint64_t osize;
1626 Object *o;
1627 int r;
1628
1629 assert(f);
1630 assert(field);
1631 assert(size > 0);
1632
1633 if (!journal_field_valid(field, size, true))
1634 return -EBADMSG;
1635
1636 hash = journal_file_hash_data(f, field, size);
1637
1638 r = journal_file_find_field_object_with_hash(f, field, size, hash, ret_object, ret_offset);
1639 if (r < 0)
1640 return r;
1641 if (r > 0)
1642 return 0;
1643
1644 osize = offsetof(Object, field.payload) + size;
1645 r = journal_file_append_object(f, OBJECT_FIELD, osize, &o, &p);
1646 if (r < 0)
1647 return r;
1648
1649 o->field.hash = htole64(hash);
1650 memcpy(o->field.payload, field, size);
1651
1652 r = journal_file_link_field(f, o, p, hash);
1653 if (r < 0)
1654 return r;
1655
1656 /* The linking might have altered the window, so let's only pass the offset to hmac which will
1657 * move to the object again if needed. */
1658
1659 #if HAVE_GCRYPT
1660 r = journal_file_hmac_put_object(f, OBJECT_FIELD, NULL, p);
1661 if (r < 0)
1662 return r;
1663 #endif
1664
1665 if (ret_object) {
1666 r = journal_file_move_to_object(f, OBJECT_FIELD, p, ret_object);
1667 if (r < 0)
1668 return r;
1669 }
1670
1671 if (ret_offset)
1672 *ret_offset = p;
1673
1674 return 0;
1675 }
1676
1677 static int maybe_compress_payload(JournalFile *f, uint8_t *dst, const uint8_t *src, uint64_t size, size_t *rsize) {
1678 assert(f);
1679 assert(f->header);
1680
1681 #if HAVE_COMPRESSION
1682 Compression c;
1683 int r;
1684
1685 c = JOURNAL_FILE_COMPRESSION(f);
1686 if (c == COMPRESSION_NONE || size < f->compress_threshold_bytes)
1687 return 0;
1688
1689 r = compress_blob(c, src, size, dst, size - 1, rsize);
1690 if (r < 0)
1691 return log_debug_errno(r, "Failed to compress data object using %s, ignoring: %m", compression_to_string(c));
1692
1693 log_debug("Compressed data object %"PRIu64" -> %zu using %s", size, *rsize, compression_to_string(c));
1694
1695 return 1; /* compressed */
1696 #else
1697 return 0;
1698 #endif
1699 }
1700
1701 static int journal_file_append_data(
1702 JournalFile *f,
1703 const void *data,
1704 uint64_t size,
1705 Object **ret_object,
1706 uint64_t *ret_offset) {
1707
1708 uint64_t hash, p, osize;
1709 Object *o, *fo;
1710 size_t rsize = 0;
1711 const void *eq;
1712 int r;
1713
1714 assert(f);
1715
1716 if (!data || size == 0)
1717 return -EINVAL;
1718
1719 hash = journal_file_hash_data(f, data, size);
1720
1721 r = journal_file_find_data_object_with_hash(f, data, size, hash, ret_object, ret_offset);
1722 if (r < 0)
1723 return r;
1724 if (r > 0)
1725 return 0;
1726
1727 eq = memchr(data, '=', size);
1728 if (!eq)
1729 return -EINVAL;
1730
1731 osize = journal_file_data_payload_offset(f) + size;
1732 r = journal_file_append_object(f, OBJECT_DATA, osize, &o, &p);
1733 if (r < 0)
1734 return r;
1735
1736 o->data.hash = htole64(hash);
1737
1738 r = maybe_compress_payload(f, journal_file_data_payload_field(f, o), data, size, &rsize);
1739 if (r <= 0)
1740 /* We don't really care failures, let's continue without compression */
1741 memcpy_safe(journal_file_data_payload_field(f, o), data, size);
1742 else {
1743 Compression c = JOURNAL_FILE_COMPRESSION(f);
1744
1745 assert(c >= 0 && c < _COMPRESSION_MAX && c != COMPRESSION_NONE);
1746
1747 o->object.size = htole64(journal_file_data_payload_offset(f) + rsize);
1748 o->object.flags |= COMPRESSION_TO_OBJECT_FLAG(c);
1749 }
1750
1751 r = journal_file_link_data(f, o, p, hash);
1752 if (r < 0)
1753 return r;
1754
1755 /* The linking might have altered the window, so let's refresh our pointer. */
1756 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
1757 if (r < 0)
1758 return r;
1759
1760 #if HAVE_GCRYPT
1761 r = journal_file_hmac_put_object(f, OBJECT_DATA, o, p);
1762 if (r < 0)
1763 return r;
1764 #endif
1765
1766 /* Create field object ... */
1767 r = journal_file_append_field(f, data, (uint8_t*) eq - (uint8_t*) data, &fo, NULL);
1768 if (r < 0)
1769 return r;
1770
1771 /* ... and link it in. */
1772 o->data.next_field_offset = fo->field.head_data_offset;
1773 fo->field.head_data_offset = le64toh(p);
1774
1775 if (ret_object)
1776 *ret_object = o;
1777
1778 if (ret_offset)
1779 *ret_offset = p;
1780
1781 return 0;
1782 }
1783
1784 static int maybe_decompress_payload(
1785 JournalFile *f,
1786 uint8_t *payload,
1787 uint64_t size,
1788 Compression compression,
1789 const char *field,
1790 size_t field_length,
1791 size_t data_threshold,
1792 void **ret_data,
1793 size_t *ret_size) {
1794
1795 assert(f);
1796
1797 /* We can't read objects larger than 4G on a 32bit machine */
1798 if ((uint64_t) (size_t) size != size)
1799 return -E2BIG;
1800
1801 if (compression != COMPRESSION_NONE) {
1802 #if HAVE_COMPRESSION
1803 size_t rsize;
1804 int r;
1805
1806 if (field) {
1807 r = decompress_startswith(compression, payload, size, &f->compress_buffer, field,
1808 field_length, '=');
1809 if (r < 0)
1810 return log_debug_errno(r,
1811 "Cannot decompress %s object of length %" PRIu64 ": %m",
1812 compression_to_string(compression),
1813 size);
1814 if (r == 0) {
1815 if (ret_data)
1816 *ret_data = NULL;
1817 if (ret_size)
1818 *ret_size = 0;
1819 return 0;
1820 }
1821 }
1822
1823 r = decompress_blob(compression, payload, size, &f->compress_buffer, &rsize, 0);
1824 if (r < 0)
1825 return r;
1826
1827 if (ret_data)
1828 *ret_data = f->compress_buffer;
1829 if (ret_size)
1830 *ret_size = rsize;
1831 #else
1832 return -EPROTONOSUPPORT;
1833 #endif
1834 } else {
1835 if (field && (size < field_length + 1 || memcmp(payload, field, field_length) != 0 || payload[field_length] != '=')) {
1836 if (ret_data)
1837 *ret_data = NULL;
1838 if (ret_size)
1839 *ret_size = 0;
1840 return 0;
1841 }
1842
1843 if (ret_data)
1844 *ret_data = payload;
1845 if (ret_size)
1846 *ret_size = (size_t) size;
1847 }
1848
1849 return 1;
1850 }
1851
1852 int journal_file_data_payload(
1853 JournalFile *f,
1854 Object *o,
1855 uint64_t offset,
1856 const char *field,
1857 size_t field_length,
1858 size_t data_threshold,
1859 void **ret_data,
1860 size_t *ret_size) {
1861
1862 uint64_t size;
1863 Compression c;
1864 int r;
1865
1866 assert(f);
1867 assert(!field == (field_length == 0)); /* These must be specified together. */
1868
1869 if (!o) {
1870 r = journal_file_move_to_object(f, OBJECT_DATA, offset, &o);
1871 if (r < 0)
1872 return r;
1873 }
1874
1875 size = le64toh(READ_NOW(o->object.size));
1876 if (size < journal_file_data_payload_offset(f))
1877 return -EBADMSG;
1878
1879 size -= journal_file_data_payload_offset(f);
1880
1881 c = COMPRESSION_FROM_OBJECT(o);
1882 if (c < 0)
1883 return -EPROTONOSUPPORT;
1884
1885 return maybe_decompress_payload(f, journal_file_data_payload_field(f, o), size, c, field,
1886 field_length, data_threshold, ret_data, ret_size);
1887 }
1888
1889 uint64_t journal_file_entry_n_items(JournalFile *f, Object *o) {
1890 uint64_t sz;
1891
1892 assert(f);
1893 assert(o);
1894
1895 if (o->object.type != OBJECT_ENTRY)
1896 return 0;
1897
1898 sz = le64toh(READ_NOW(o->object.size));
1899 if (sz < offsetof(Object, entry.items))
1900 return 0;
1901
1902 return (sz - offsetof(Object, entry.items)) / journal_file_entry_item_size(f);
1903 }
1904
1905 uint64_t journal_file_entry_array_n_items(JournalFile *f, Object *o) {
1906 uint64_t sz;
1907
1908 assert(f);
1909 assert(o);
1910
1911 if (o->object.type != OBJECT_ENTRY_ARRAY)
1912 return 0;
1913
1914 sz = le64toh(READ_NOW(o->object.size));
1915 if (sz < offsetof(Object, entry_array.items))
1916 return 0;
1917
1918 return (sz - offsetof(Object, entry_array.items)) / journal_file_entry_array_item_size(f);
1919 }
1920
1921 uint64_t journal_file_hash_table_n_items(Object *o) {
1922 uint64_t sz;
1923
1924 assert(o);
1925
1926 if (!IN_SET(o->object.type, OBJECT_DATA_HASH_TABLE, OBJECT_FIELD_HASH_TABLE))
1927 return 0;
1928
1929 sz = le64toh(READ_NOW(o->object.size));
1930 if (sz < offsetof(Object, hash_table.items))
1931 return 0;
1932
1933 return (sz - offsetof(Object, hash_table.items)) / sizeof(HashItem);
1934 }
1935
1936 static void write_entry_array_item(JournalFile *f, Object *o, uint64_t i, uint64_t p) {
1937 assert(f);
1938 assert(o);
1939
1940 if (JOURNAL_HEADER_COMPACT(f->header)) {
1941 assert(p <= UINT32_MAX);
1942 o->entry_array.items.compact[i] = htole32(p);
1943 } else
1944 o->entry_array.items.regular[i] = htole64(p);
1945 }
1946
1947 static int link_entry_into_array(
1948 JournalFile *f,
1949 le64_t *first,
1950 le64_t *idx,
1951 le32_t *tail,
1952 le32_t *tidx,
1953 uint64_t p) {
1954
1955 uint64_t n = 0, ap = 0, q, i, a, hidx;
1956 Object *o;
1957 int r;
1958
1959 assert(f);
1960 assert(f->header);
1961 assert(first);
1962 assert(idx);
1963 assert(p > 0);
1964
1965 a = tail ? le32toh(*tail) : le64toh(*first);
1966 hidx = le64toh(READ_NOW(*idx));
1967 i = tidx ? le32toh(READ_NOW(*tidx)) : hidx;
1968
1969 while (a > 0) {
1970 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
1971 if (r < 0)
1972 return r;
1973
1974 n = journal_file_entry_array_n_items(f, o);
1975 if (i < n) {
1976 write_entry_array_item(f, o, i, p);
1977 *idx = htole64(hidx + 1);
1978 if (tidx)
1979 *tidx = htole32(le32toh(*tidx) + 1);
1980 return 0;
1981 }
1982
1983 i -= n;
1984 ap = a;
1985 a = le64toh(o->entry_array.next_entry_array_offset);
1986 }
1987
1988 if (hidx > n)
1989 n = (hidx+1) * 2;
1990 else
1991 n = n * 2;
1992
1993 if (n < 4)
1994 n = 4;
1995
1996 r = journal_file_append_object(f, OBJECT_ENTRY_ARRAY,
1997 offsetof(Object, entry_array.items) + n * journal_file_entry_array_item_size(f),
1998 &o, &q);
1999 if (r < 0)
2000 return r;
2001
2002 #if HAVE_GCRYPT
2003 r = journal_file_hmac_put_object(f, OBJECT_ENTRY_ARRAY, o, q);
2004 if (r < 0)
2005 return r;
2006 #endif
2007
2008 write_entry_array_item(f, o, i, p);
2009
2010 if (ap == 0)
2011 *first = htole64(q);
2012 else {
2013 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, ap, &o);
2014 if (r < 0)
2015 return r;
2016
2017 o->entry_array.next_entry_array_offset = htole64(q);
2018 }
2019
2020 if (tail)
2021 *tail = htole32(q);
2022
2023 if (JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays))
2024 f->header->n_entry_arrays = htole64(le64toh(f->header->n_entry_arrays) + 1);
2025
2026 *idx = htole64(hidx + 1);
2027 if (tidx)
2028 *tidx = htole32(1);
2029
2030 return 0;
2031 }
2032
2033 static int link_entry_into_array_plus_one(
2034 JournalFile *f,
2035 le64_t *extra,
2036 le64_t *first,
2037 le64_t *idx,
2038 le32_t *tail,
2039 le32_t *tidx,
2040 uint64_t p) {
2041
2042 uint64_t hidx;
2043 int r;
2044
2045 assert(f);
2046 assert(extra);
2047 assert(first);
2048 assert(idx);
2049 assert(p > 0);
2050
2051 hidx = le64toh(READ_NOW(*idx));
2052 if (hidx == UINT64_MAX)
2053 return -EBADMSG;
2054 if (hidx == 0)
2055 *extra = htole64(p);
2056 else {
2057 le64_t i;
2058
2059 i = htole64(hidx - 1);
2060 r = link_entry_into_array(f, first, &i, tail, tidx, p);
2061 if (r < 0)
2062 return r;
2063 }
2064
2065 *idx = htole64(hidx + 1);
2066 return 0;
2067 }
2068
2069 static int journal_file_link_entry_item(JournalFile *f, uint64_t offset, uint64_t p) {
2070 Object *o;
2071 int r;
2072
2073 assert(f);
2074 assert(offset > 0);
2075
2076 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
2077 if (r < 0)
2078 return r;
2079
2080 return link_entry_into_array_plus_one(f,
2081 &o->data.entry_offset,
2082 &o->data.entry_array_offset,
2083 &o->data.n_entries,
2084 JOURNAL_HEADER_COMPACT(f->header) ? &o->data.compact.tail_entry_array_offset : NULL,
2085 JOURNAL_HEADER_COMPACT(f->header) ? &o->data.compact.tail_entry_array_n_entries : NULL,
2086 offset);
2087 }
2088
2089 static int journal_file_link_entry(
2090 JournalFile *f,
2091 Object *o,
2092 uint64_t offset,
2093 const EntryItem items[],
2094 size_t n_items) {
2095
2096 int r;
2097
2098 assert(f);
2099 assert(f->header);
2100 assert(o);
2101 assert(offset > 0);
2102
2103 if (o->object.type != OBJECT_ENTRY)
2104 return -EINVAL;
2105
2106 __atomic_thread_fence(__ATOMIC_SEQ_CST);
2107
2108 /* Link up the entry itself */
2109 r = link_entry_into_array(f,
2110 &f->header->entry_array_offset,
2111 &f->header->n_entries,
2112 JOURNAL_HEADER_CONTAINS(f->header, tail_entry_array_offset) ? &f->header->tail_entry_array_offset : NULL,
2113 JOURNAL_HEADER_CONTAINS(f->header, tail_entry_array_n_entries) ? &f->header->tail_entry_array_n_entries : NULL,
2114 offset);
2115 if (r < 0)
2116 return r;
2117
2118 /* log_debug("=> %s seqnr=%"PRIu64" n_entries=%"PRIu64, f->path, o->entry.seqnum, f->header->n_entries); */
2119
2120 if (f->header->head_entry_realtime == 0)
2121 f->header->head_entry_realtime = o->entry.realtime;
2122
2123 f->header->tail_entry_realtime = o->entry.realtime;
2124 f->header->tail_entry_monotonic = o->entry.monotonic;
2125 f->header->tail_entry_offset = offset;
2126 f->newest_mtime = 0; /* we have a new tail entry now, explicitly invalidate newest boot id/timestamp info */
2127
2128 /* Link up the items */
2129 for (uint64_t i = 0; i < n_items; i++) {
2130 int k;
2131
2132 /* If we fail to link an entry item because we can't allocate a new entry array, don't fail
2133 * immediately but try to link the other entry items since it might still be possible to link
2134 * those if they don't require a new entry array to be allocated. */
2135
2136 k = journal_file_link_entry_item(f, offset, items[i].object_offset);
2137 if (k == -E2BIG)
2138 r = k;
2139 else if (k < 0)
2140 return k;
2141 }
2142
2143 return r;
2144 }
2145
2146 static void write_entry_item(JournalFile *f, Object *o, uint64_t i, const EntryItem *item) {
2147 assert(f);
2148 assert(o);
2149 assert(item);
2150
2151 if (JOURNAL_HEADER_COMPACT(f->header)) {
2152 assert(item->object_offset <= UINT32_MAX);
2153 o->entry.items.compact[i].object_offset = htole32(item->object_offset);
2154 } else {
2155 o->entry.items.regular[i].object_offset = htole64(item->object_offset);
2156 o->entry.items.regular[i].hash = htole64(item->hash);
2157 }
2158 }
2159
2160 static int journal_file_append_entry_internal(
2161 JournalFile *f,
2162 const dual_timestamp *ts,
2163 const sd_id128_t *boot_id,
2164 const sd_id128_t *machine_id,
2165 uint64_t xor_hash,
2166 const EntryItem items[],
2167 size_t n_items,
2168 uint64_t *seqnum,
2169 sd_id128_t *seqnum_id,
2170 Object **ret_object,
2171 uint64_t *ret_offset) {
2172
2173 uint64_t np;
2174 uint64_t osize;
2175 Object *o;
2176 int r;
2177
2178 assert(f);
2179 assert(f->header);
2180 assert(ts);
2181 assert(items || n_items == 0);
2182
2183 if (f->strict_order) {
2184 /* If requested be stricter with ordering in this journal file, to make searching via
2185 * bisection fully deterministic. This is an optional feature, so that if desired journal
2186 * files can be written where the ordering is not strictly enforced (in which case bisection
2187 * will yield *a* result, but not the *only* result, when searching for points in
2188 * time). Strict ordering mode is enabled when journald originally writes the files, but
2189 * might not necessarily be if other tools (the remoting tools for example) write journal
2190 * files from combined sources.
2191 *
2192 * Typically, if any of the errors generated here are seen journald will just rotate the
2193 * journal files and start anew. */
2194
2195 if (ts->realtime < le64toh(f->header->tail_entry_realtime))
2196 return log_debug_errno(SYNTHETIC_ERRNO(EREMCHG),
2197 "Realtime timestamp %" PRIu64 " smaller than previous realtime "
2198 "timestamp %" PRIu64 ", refusing entry.",
2199 ts->realtime, le64toh(f->header->tail_entry_realtime));
2200
2201 if (!sd_id128_is_null(f->header->tail_entry_boot_id) && boot_id) {
2202
2203 if (!sd_id128_equal(f->header->tail_entry_boot_id, *boot_id))
2204 return log_debug_errno(SYNTHETIC_ERRNO(EREMOTE),
2205 "Boot ID to write is different from previous boot id, refusing entry.");
2206
2207 if (ts->monotonic < le64toh(f->header->tail_entry_monotonic))
2208 return log_debug_errno(SYNTHETIC_ERRNO(ENOTNAM),
2209 "Monotonic timestamp %" PRIu64 " smaller than previous monotonic "
2210 "timestamp %" PRIu64 ", refusing entry.",
2211 ts->monotonic, le64toh(f->header->tail_entry_monotonic));
2212 }
2213 }
2214
2215 if (seqnum_id) {
2216 /* Settle the passed in sequence number ID */
2217
2218 if (sd_id128_is_null(*seqnum_id))
2219 *seqnum_id = f->header->seqnum_id; /* Caller has none assigned, then copy the one from the file */
2220 else if (!sd_id128_equal(*seqnum_id, f->header->seqnum_id)) {
2221 /* Different seqnum IDs? We can't allow entries from multiple IDs end up in the same journal.*/
2222 if (le64toh(f->header->n_entries) == 0)
2223 f->header->seqnum_id = *seqnum_id; /* Caller has one, and file so far has no entries, then copy the one from the caller */
2224 else
2225 return log_debug_errno(SYNTHETIC_ERRNO(EILSEQ),
2226 "Sequence number IDs don't match, refusing entry.");
2227 }
2228 }
2229
2230 if (machine_id && sd_id128_is_null(f->header->machine_id))
2231 /* Initialize machine ID when not set yet */
2232 f->header->machine_id = *machine_id;
2233
2234 osize = offsetof(Object, entry.items) + (n_items * journal_file_entry_item_size(f));
2235
2236 r = journal_file_append_object(f, OBJECT_ENTRY, osize, &o, &np);
2237 if (r < 0)
2238 return r;
2239
2240 o->entry.seqnum = htole64(journal_file_entry_seqnum(f, seqnum));
2241 o->entry.realtime = htole64(ts->realtime);
2242 o->entry.monotonic = htole64(ts->monotonic);
2243 o->entry.xor_hash = htole64(xor_hash);
2244 if (boot_id)
2245 f->header->tail_entry_boot_id = *boot_id;
2246 o->entry.boot_id = f->header->tail_entry_boot_id;
2247
2248 for (size_t i = 0; i < n_items; i++)
2249 write_entry_item(f, o, i, &items[i]);
2250
2251 #if HAVE_GCRYPT
2252 r = journal_file_hmac_put_object(f, OBJECT_ENTRY, o, np);
2253 if (r < 0)
2254 return r;
2255 #endif
2256
2257 r = journal_file_link_entry(f, o, np, items, n_items);
2258 if (r < 0)
2259 return r;
2260
2261 if (ret_object)
2262 *ret_object = o;
2263
2264 if (ret_offset)
2265 *ret_offset = np;
2266
2267 return r;
2268 }
2269
2270 void journal_file_post_change(JournalFile *f) {
2271 assert(f);
2272
2273 if (f->fd < 0)
2274 return;
2275
2276 /* inotify() does not receive IN_MODIFY events from file
2277 * accesses done via mmap(). After each access we hence
2278 * trigger IN_MODIFY by truncating the journal file to its
2279 * current size which triggers IN_MODIFY. */
2280
2281 __atomic_thread_fence(__ATOMIC_SEQ_CST);
2282
2283 if (ftruncate(f->fd, f->last_stat.st_size) < 0)
2284 log_debug_errno(errno, "Failed to truncate file to its own size: %m");
2285 }
2286
2287 static int post_change_thunk(sd_event_source *timer, uint64_t usec, void *userdata) {
2288 assert(userdata);
2289
2290 journal_file_post_change(userdata);
2291
2292 return 1;
2293 }
2294
2295 static void schedule_post_change(JournalFile *f) {
2296 sd_event *e;
2297 int r;
2298
2299 assert(f);
2300 assert(f->post_change_timer);
2301
2302 assert_se(e = sd_event_source_get_event(f->post_change_timer));
2303
2304 /* If we are already going down, post the change immediately. */
2305 if (IN_SET(sd_event_get_state(e), SD_EVENT_EXITING, SD_EVENT_FINISHED))
2306 goto fail;
2307
2308 r = sd_event_source_get_enabled(f->post_change_timer, NULL);
2309 if (r < 0) {
2310 log_debug_errno(r, "Failed to get ftruncate timer state: %m");
2311 goto fail;
2312 }
2313 if (r > 0)
2314 return;
2315
2316 r = sd_event_source_set_time_relative(f->post_change_timer, f->post_change_timer_period);
2317 if (r < 0) {
2318 log_debug_errno(r, "Failed to set time for scheduling ftruncate: %m");
2319 goto fail;
2320 }
2321
2322 r = sd_event_source_set_enabled(f->post_change_timer, SD_EVENT_ONESHOT);
2323 if (r < 0) {
2324 log_debug_errno(r, "Failed to enable scheduled ftruncate: %m");
2325 goto fail;
2326 }
2327
2328 return;
2329
2330 fail:
2331 /* On failure, let's simply post the change immediately. */
2332 journal_file_post_change(f);
2333 }
2334
2335 /* Enable coalesced change posting in a timer on the provided sd_event instance */
2336 int journal_file_enable_post_change_timer(JournalFile *f, sd_event *e, usec_t t) {
2337 _cleanup_(sd_event_source_unrefp) sd_event_source *timer = NULL;
2338 int r;
2339
2340 assert(f);
2341 assert_return(!f->post_change_timer, -EINVAL);
2342 assert(e);
2343 assert(t);
2344
2345 r = sd_event_add_time(e, &timer, CLOCK_MONOTONIC, 0, 0, post_change_thunk, f);
2346 if (r < 0)
2347 return r;
2348
2349 r = sd_event_source_set_enabled(timer, SD_EVENT_OFF);
2350 if (r < 0)
2351 return r;
2352
2353 f->post_change_timer = TAKE_PTR(timer);
2354 f->post_change_timer_period = t;
2355
2356 return r;
2357 }
2358
2359 static int entry_item_cmp(const EntryItem *a, const EntryItem *b) {
2360 return CMP(ASSERT_PTR(a)->object_offset, ASSERT_PTR(b)->object_offset);
2361 }
2362
2363 static size_t remove_duplicate_entry_items(EntryItem items[], size_t n) {
2364 size_t j = 1;
2365
2366 assert(items || n == 0);
2367
2368 if (n <= 1)
2369 return n;
2370
2371 for (size_t i = 1; i < n; i++)
2372 if (items[i].object_offset != items[j - 1].object_offset)
2373 items[j++] = items[i];
2374
2375 return j;
2376 }
2377
2378 int journal_file_append_entry(
2379 JournalFile *f,
2380 const dual_timestamp *ts,
2381 const sd_id128_t *boot_id,
2382 const struct iovec iovec[],
2383 size_t n_iovec,
2384 uint64_t *seqnum,
2385 sd_id128_t *seqnum_id,
2386 Object **ret_object,
2387 uint64_t *ret_offset) {
2388
2389 _cleanup_free_ EntryItem *items_alloc = NULL;
2390 EntryItem *items;
2391 uint64_t xor_hash = 0;
2392 struct dual_timestamp _ts;
2393 sd_id128_t _boot_id, _machine_id, *machine_id;
2394 int r;
2395
2396 assert(f);
2397 assert(f->header);
2398 assert(iovec);
2399 assert(n_iovec > 0);
2400
2401 if (ts) {
2402 if (!VALID_REALTIME(ts->realtime))
2403 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
2404 "Invalid realtime timestamp %" PRIu64 ", refusing entry.",
2405 ts->realtime);
2406 if (!VALID_MONOTONIC(ts->monotonic))
2407 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
2408 "Invalid monotomic timestamp %" PRIu64 ", refusing entry.",
2409 ts->monotonic);
2410 } else {
2411 dual_timestamp_get(&_ts);
2412 ts = &_ts;
2413 }
2414
2415 if (!boot_id) {
2416 r = sd_id128_get_boot(&_boot_id);
2417 if (r < 0)
2418 return r;
2419
2420 boot_id = &_boot_id;
2421 }
2422
2423 r = sd_id128_get_machine(&_machine_id);
2424 if (r < 0) {
2425 if (!ERRNO_IS_MACHINE_ID_UNSET(r))
2426 return r;
2427
2428 /* If the machine ID is not initialized yet, handle gracefully */
2429 machine_id = NULL;
2430 } else
2431 machine_id = &_machine_id;
2432
2433 #if HAVE_GCRYPT
2434 r = journal_file_maybe_append_tag(f, ts->realtime);
2435 if (r < 0)
2436 return r;
2437 #endif
2438
2439 if (n_iovec < ALLOCA_MAX / sizeof(EntryItem) / 2)
2440 items = newa(EntryItem, n_iovec);
2441 else {
2442 items_alloc = new(EntryItem, n_iovec);
2443 if (!items_alloc)
2444 return -ENOMEM;
2445
2446 items = items_alloc;
2447 }
2448
2449 for (size_t i = 0; i < n_iovec; i++) {
2450 uint64_t p;
2451 Object *o;
2452
2453 r = journal_file_append_data(f, iovec[i].iov_base, iovec[i].iov_len, &o, &p);
2454 if (r < 0)
2455 return r;
2456
2457 /* When calculating the XOR hash field, we need to take special care if the "keyed-hash"
2458 * journal file flag is on. We use the XOR hash field to quickly determine the identity of a
2459 * specific record, and give records with otherwise identical position (i.e. match in seqno,
2460 * timestamp, …) a stable ordering. But for that we can't have it that the hash of the
2461 * objects in each file is different since they are keyed. Hence let's calculate the Jenkins
2462 * hash here for that. This also has the benefit that cursors for old and new journal files
2463 * are completely identical (they include the XOR hash after all). For classic Jenkins-hash
2464 * files things are easier, we can just take the value from the stored record directly. */
2465
2466 if (JOURNAL_HEADER_KEYED_HASH(f->header))
2467 xor_hash ^= jenkins_hash64(iovec[i].iov_base, iovec[i].iov_len);
2468 else
2469 xor_hash ^= le64toh(o->data.hash);
2470
2471 items[i] = (EntryItem) {
2472 .object_offset = p,
2473 .hash = le64toh(o->data.hash),
2474 };
2475 }
2476
2477 /* Order by the position on disk, in order to improve seek
2478 * times for rotating media. */
2479 typesafe_qsort(items, n_iovec, entry_item_cmp);
2480 n_iovec = remove_duplicate_entry_items(items, n_iovec);
2481
2482 r = journal_file_append_entry_internal(
2483 f,
2484 ts,
2485 boot_id,
2486 machine_id,
2487 xor_hash,
2488 items,
2489 n_iovec,
2490 seqnum,
2491 seqnum_id,
2492 ret_object,
2493 ret_offset);
2494
2495 /* If the memory mapping triggered a SIGBUS then we return an
2496 * IO error and ignore the error code passed down to us, since
2497 * it is very likely just an effect of a nullified replacement
2498 * mapping page */
2499
2500 if (mmap_cache_fd_got_sigbus(f->cache_fd))
2501 r = -EIO;
2502
2503 if (f->post_change_timer)
2504 schedule_post_change(f);
2505 else
2506 journal_file_post_change(f);
2507
2508 return r;
2509 }
2510
2511 typedef struct ChainCacheItem {
2512 uint64_t first; /* the array at the beginning of the chain */
2513 uint64_t array; /* the cached array */
2514 uint64_t begin; /* the first item in the cached array */
2515 uint64_t total; /* the total number of items in all arrays before this one in the chain */
2516 uint64_t last_index; /* the last index we looked at, to optimize locality when bisecting */
2517 } ChainCacheItem;
2518
2519 static void chain_cache_put(
2520 OrderedHashmap *h,
2521 ChainCacheItem *ci,
2522 uint64_t first,
2523 uint64_t array,
2524 uint64_t begin,
2525 uint64_t total,
2526 uint64_t last_index) {
2527
2528 assert(h);
2529
2530 if (!ci) {
2531 /* If the chain item to cache for this chain is the
2532 * first one it's not worth caching anything */
2533 if (array == first)
2534 return;
2535
2536 if (ordered_hashmap_size(h) >= CHAIN_CACHE_MAX) {
2537 ci = ordered_hashmap_steal_first(h);
2538 assert(ci);
2539 } else {
2540 ci = new(ChainCacheItem, 1);
2541 if (!ci)
2542 return;
2543 }
2544
2545 ci->first = first;
2546
2547 if (ordered_hashmap_put(h, &ci->first, ci) < 0) {
2548 free(ci);
2549 return;
2550 }
2551 } else
2552 assert(ci->first == first);
2553
2554 ci->array = array;
2555 ci->begin = begin;
2556 ci->total = total;
2557 ci->last_index = last_index;
2558 }
2559
2560 static int bump_array_index(uint64_t *i, direction_t direction, uint64_t n) {
2561 assert(i);
2562
2563 /* Increase or decrease the specified index, in the right direction. */
2564
2565 if (direction == DIRECTION_DOWN) {
2566 if (*i >= n - 1)
2567 return 0;
2568
2569 (*i)++;
2570 } else {
2571 if (*i <= 0)
2572 return 0;
2573
2574 (*i)--;
2575 }
2576
2577 return 1;
2578 }
2579
2580 static int bump_entry_array(
2581 JournalFile *f,
2582 Object *o,
2583 uint64_t offset,
2584 uint64_t first,
2585 direction_t direction,
2586 uint64_t *ret) {
2587
2588 uint64_t p, q = 0;
2589 int r;
2590
2591 assert(f);
2592 assert(offset);
2593 assert(ret);
2594
2595 if (direction == DIRECTION_DOWN) {
2596 assert(o);
2597 *ret = le64toh(o->entry_array.next_entry_array_offset);
2598 return 0;
2599 }
2600
2601 /* Entry array chains are a singly linked list, so to find the previous array in the chain, we have
2602 * to start iterating from the top. */
2603
2604 p = first;
2605
2606 while (p > 0 && p != offset) {
2607 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, p, &o);
2608 if (r < 0)
2609 return r;
2610
2611 q = p;
2612 p = le64toh(o->entry_array.next_entry_array_offset);
2613 }
2614
2615 /* If we can't find the previous entry array in the entry array chain, we're likely dealing with a
2616 * corrupted journal file. */
2617 if (p == 0)
2618 return -EBADMSG;
2619
2620 *ret = q;
2621
2622 return 0;
2623 }
2624
2625 static int generic_array_get(
2626 JournalFile *f,
2627 uint64_t first,
2628 uint64_t i,
2629 direction_t direction,
2630 Object **ret_object,
2631 uint64_t *ret_offset) {
2632
2633 uint64_t a, t = 0, k;
2634 ChainCacheItem *ci;
2635 Object *o;
2636 int r;
2637
2638 assert(f);
2639
2640 /* FIXME: fix return value assignment on success. */
2641
2642 a = first;
2643
2644 /* Try the chain cache first */
2645 ci = ordered_hashmap_get(f->chain_cache, &first);
2646 if (ci && i > ci->total) {
2647 a = ci->array;
2648 i -= ci->total;
2649 t = ci->total;
2650 }
2651
2652 while (a > 0) {
2653 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
2654 if (IN_SET(r, -EBADMSG, -EADDRNOTAVAIL)) {
2655 /* If there's corruption and we're going downwards, let's pretend we reached the
2656 * final entry in the entry array chain. */
2657
2658 if (direction == DIRECTION_DOWN)
2659 return 0;
2660
2661 /* If there's corruption and we're going upwards, move back to the previous entry
2662 * array and start iterating entries from there. */
2663
2664 r = bump_entry_array(f, NULL, a, first, DIRECTION_UP, &a);
2665 if (r < 0)
2666 return r;
2667
2668 i = UINT64_MAX;
2669
2670 break;
2671 }
2672 if (r < 0)
2673 return r;
2674
2675 k = journal_file_entry_array_n_items(f, o);
2676 if (i < k)
2677 break;
2678
2679 i -= k;
2680 t += k;
2681 a = le64toh(o->entry_array.next_entry_array_offset);
2682 }
2683
2684 /* If we've found the right location, now look for the first non-corrupt entry object (in the right
2685 * direction). */
2686
2687 while (a > 0) {
2688 /* In the first iteration of the while loop, we reuse i, k and o from the previous while
2689 * loop. */
2690 if (i == UINT64_MAX) {
2691 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
2692 if (r < 0)
2693 return r;
2694
2695 k = journal_file_entry_array_n_items(f, o);
2696 if (k == 0)
2697 break;
2698
2699 i = direction == DIRECTION_DOWN ? 0 : k - 1;
2700 }
2701
2702 do {
2703 uint64_t p;
2704
2705 p = journal_file_entry_array_item(f, o, i);
2706
2707 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, ret_object);
2708 if (r >= 0) {
2709 /* Let's cache this item for the next invocation */
2710 chain_cache_put(f->chain_cache, ci, first, a, journal_file_entry_array_item(f, o, 0), t, i);
2711
2712 if (ret_offset)
2713 *ret_offset = p;
2714
2715 return 1;
2716 }
2717 if (!IN_SET(r, -EADDRNOTAVAIL, -EBADMSG))
2718 return r;
2719
2720 /* OK, so this entry is borked. Most likely some entry didn't get synced to
2721 * disk properly, let's see if the next one might work for us instead. */
2722 log_debug_errno(r, "Entry item %" PRIu64 " is bad, skipping over it.", i);
2723
2724 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o);
2725 if (r < 0)
2726 return r;
2727
2728 } while (bump_array_index(&i, direction, k) > 0);
2729
2730 r = bump_entry_array(f, o, a, first, direction, &a);
2731 if (r < 0)
2732 return r;
2733
2734 t += k;
2735 i = UINT64_MAX;
2736 }
2737
2738 return 0;
2739 }
2740
2741 static int generic_array_get_plus_one(
2742 JournalFile *f,
2743 uint64_t extra,
2744 uint64_t first,
2745 uint64_t i,
2746 direction_t direction,
2747 Object **ret_object,
2748 uint64_t *ret_offset) {
2749
2750 int r;
2751
2752 assert(f);
2753
2754 /* FIXME: fix return value assignment on success. */
2755
2756 if (i == 0) {
2757 r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, ret_object);
2758 if (IN_SET(r, -EADDRNOTAVAIL, -EBADMSG))
2759 return generic_array_get(f, first, 0, direction, ret_object, ret_offset);
2760 if (r < 0)
2761 return r;
2762
2763 if (ret_offset)
2764 *ret_offset = extra;
2765
2766 return 1;
2767 }
2768
2769 return generic_array_get(f, first, i - 1, direction, ret_object, ret_offset);
2770 }
2771
2772 enum {
2773 TEST_FOUND,
2774 TEST_LEFT,
2775 TEST_RIGHT
2776 };
2777
2778 static int generic_array_bisect_one(
2779 JournalFile *f,
2780 uint64_t a, /* offset of entry array object. */
2781 uint64_t i, /* index of the entry item we will test. */
2782 uint64_t needle,
2783 int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
2784 direction_t direction,
2785 uint64_t *left,
2786 uint64_t *right,
2787 uint64_t *ret_offset) {
2788
2789 Object *array;
2790 uint64_t p;
2791 int r;
2792
2793 assert(f);
2794 assert(test_object);
2795 assert(left);
2796 assert(right);
2797 assert(*left <= i);
2798 assert(i <= *right);
2799
2800 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &array);
2801 if (r < 0)
2802 return r;
2803
2804 p = journal_file_entry_array_item(f, array, i);
2805 if (p <= 0)
2806 r = -EBADMSG;
2807 else
2808 r = test_object(f, p, needle);
2809 if (IN_SET(r, -EBADMSG, -EADDRNOTAVAIL)) {
2810 log_debug_errno(r, "Encountered invalid entry while bisecting, cutting algorithm short.");
2811 *right = i;
2812 return -ENOANO; /* recognizable error */
2813 }
2814 if (r < 0)
2815 return r;
2816
2817 if (r == TEST_FOUND)
2818 r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
2819
2820 if (r == TEST_RIGHT)
2821 *right = i;
2822 else
2823 *left = i + 1;
2824
2825 if (ret_offset)
2826 *ret_offset = p;
2827
2828 return r;
2829 }
2830
2831 static int generic_array_bisect(
2832 JournalFile *f,
2833 uint64_t first,
2834 uint64_t n,
2835 uint64_t needle,
2836 int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
2837 direction_t direction,
2838 Object **ret_object,
2839 uint64_t *ret_offset,
2840 uint64_t *ret_idx) {
2841
2842 /* Given an entry array chain, this function finds the object "closest" to the given needle in the
2843 * chain, taking into account the provided direction. A function can be provided to determine how
2844 * an object is matched against the given needle.
2845 *
2846 * Given a journal file, the offset of an object and the needle, the test_object() function should
2847 * return TEST_LEFT if the needle is located earlier in the entry array chain, TEST_LEFT if the
2848 * needle is located later in the entry array chain and TEST_FOUND if the object matches the needle.
2849 * If test_object() returns TEST_FOUND for a specific object, that object's information will be used
2850 * to populate the return values of this function. If test_object() never returns TEST_FOUND, the
2851 * return values are populated with the details of one of the objects closest to the needle. If the
2852 * direction is DIRECTION_UP, the earlier object is used. Otherwise, the later object is used.
2853 */
2854
2855 uint64_t a, p, t = 0, i = 0, last_p = 0, last_index = UINT64_MAX;
2856 bool subtract_one = false;
2857 ChainCacheItem *ci;
2858 Object *array;
2859 int r;
2860
2861 assert(f);
2862 assert(test_object);
2863
2864 /* Start with the first array in the chain */
2865 a = first;
2866
2867 ci = ordered_hashmap_get(f->chain_cache, &first);
2868 if (ci && n > ci->total && ci->begin != 0) {
2869 /* Ah, we have iterated this bisection array chain previously! Let's see if we can skip ahead
2870 * in the chain, as far as the last time. But we can't jump backwards in the chain, so let's
2871 * check that first. */
2872
2873 r = test_object(f, ci->begin, needle);
2874 if (r < 0)
2875 return r;
2876
2877 if (r == TEST_LEFT) {
2878 /* OK, what we are looking for is right of the begin of this EntryArray, so let's
2879 * jump straight to previously cached array in the chain */
2880
2881 a = ci->array;
2882 n -= ci->total;
2883 t = ci->total;
2884 last_index = ci->last_index;
2885 }
2886 }
2887
2888 while (a > 0) {
2889 uint64_t left = 0, right, k, lp;
2890
2891 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &array);
2892 if (r < 0)
2893 return r;
2894
2895 k = journal_file_entry_array_n_items(f, array);
2896 right = MIN(k, n);
2897 if (right <= 0)
2898 return 0;
2899
2900 right--;
2901 r = generic_array_bisect_one(f, a, right, needle, test_object, direction, &left, &right, &lp);
2902 if (r == -ENOANO) {
2903 n = right;
2904 continue;
2905 }
2906 if (r < 0)
2907 return r;
2908
2909 if (r == TEST_RIGHT) {
2910 /* If we cached the last index we looked at, let's try to not to jump too wildly
2911 * around and see if we can limit the range to look at early to the immediate
2912 * neighbors of the last index we looked at. */
2913
2914 if (last_index > 0 && last_index - 1 < right) {
2915 r = generic_array_bisect_one(f, a, last_index - 1, needle, test_object, direction, &left, &right, NULL);
2916 if (r < 0 && r != -ENOANO)
2917 return r;
2918 }
2919
2920 if (last_index < right) {
2921 r = generic_array_bisect_one(f, a, last_index + 1, needle, test_object, direction, &left, &right, NULL);
2922 if (r < 0 && r != -ENOANO)
2923 return r;
2924 }
2925
2926 for (;;) {
2927 if (left == right) {
2928 if (direction == DIRECTION_UP)
2929 subtract_one = true;
2930
2931 i = left;
2932 goto found;
2933 }
2934
2935 assert(left < right);
2936 i = (left + right) / 2;
2937
2938 r = generic_array_bisect_one(f, a, i, needle, test_object, direction, &left, &right, NULL);
2939 if (r < 0 && r != -ENOANO)
2940 return r;
2941 }
2942 }
2943
2944 if (k >= n) {
2945 if (direction == DIRECTION_UP) {
2946 i = n;
2947 subtract_one = true;
2948 goto found;
2949 }
2950
2951 return 0;
2952 }
2953
2954 last_p = lp;
2955
2956 n -= k;
2957 t += k;
2958 last_index = UINT64_MAX;
2959 a = le64toh(array->entry_array.next_entry_array_offset);
2960 }
2961
2962 return 0;
2963
2964 found:
2965 if (subtract_one && t == 0 && i == 0)
2966 return 0;
2967
2968 r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &array);
2969 if (r < 0)
2970 return r;
2971
2972 p = journal_file_entry_array_item(f, array, 0);
2973 if (p <= 0)
2974 return -EBADMSG;
2975
2976 /* Let's cache this item for the next invocation */
2977 chain_cache_put(f->chain_cache, ci, first, a, p, t, subtract_one ? (i > 0 ? i-1 : UINT64_MAX) : i);
2978
2979 if (subtract_one && i == 0)
2980 p = last_p;
2981 else if (subtract_one)
2982 p = journal_file_entry_array_item(f, array, i - 1);
2983 else
2984 p = journal_file_entry_array_item(f, array, i);
2985
2986 if (ret_object) {
2987 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, ret_object);
2988 if (r < 0)
2989 return r;
2990 }
2991
2992 if (ret_offset)
2993 *ret_offset = p;
2994
2995 if (ret_idx)
2996 *ret_idx = t + i + (subtract_one ? -1 : 0);
2997
2998 return 1;
2999 }
3000
3001 static int generic_array_bisect_plus_one(
3002 JournalFile *f,
3003 uint64_t extra,
3004 uint64_t first,
3005 uint64_t n,
3006 uint64_t needle,
3007 int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle),
3008 direction_t direction,
3009 Object **ret_object,
3010 uint64_t *ret_offset,
3011 uint64_t *ret_idx) {
3012
3013 int r;
3014 bool step_back = false;
3015
3016 assert(f);
3017 assert(test_object);
3018
3019 if (n <= 0)
3020 return 0;
3021
3022 /* This bisects the array in object 'first', but first checks
3023 * an extra */
3024 r = test_object(f, extra, needle);
3025 if (r < 0)
3026 return r;
3027
3028 if (r == TEST_FOUND)
3029 r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT;
3030
3031 /* if we are looking with DIRECTION_UP then we need to first
3032 see if in the actual array there is a matching entry, and
3033 return the last one of that. But if there isn't any we need
3034 to return this one. Hence remember this, and return it
3035 below. */
3036 if (r == TEST_LEFT)
3037 step_back = direction == DIRECTION_UP;
3038
3039 if (r == TEST_RIGHT) {
3040 if (direction == DIRECTION_DOWN)
3041 goto found;
3042 else
3043 return 0;
3044 }
3045
3046 r = generic_array_bisect(f, first, n-1, needle, test_object, direction, ret_object, ret_offset, ret_idx);
3047
3048 if (r == 0 && step_back)
3049 goto found;
3050
3051 if (r > 0 && ret_idx)
3052 (*ret_idx)++;
3053
3054 return r;
3055
3056 found:
3057 if (ret_object) {
3058 r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, ret_object);
3059 if (r < 0)
3060 return r;
3061 }
3062
3063 if (ret_offset)
3064 *ret_offset = extra;
3065
3066 if (ret_idx)
3067 *ret_idx = 0;
3068
3069 return 1;
3070 }
3071
3072 _pure_ static int test_object_offset(JournalFile *f, uint64_t p, uint64_t needle) {
3073 assert(f);
3074 assert(p > 0);
3075
3076 if (p == needle)
3077 return TEST_FOUND;
3078 else if (p < needle)
3079 return TEST_LEFT;
3080 else
3081 return TEST_RIGHT;
3082 }
3083
3084 int journal_file_move_to_entry_by_offset(
3085 JournalFile *f,
3086 uint64_t p,
3087 direction_t direction,
3088 Object **ret_object,
3089 uint64_t *ret_offset) {
3090
3091 assert(f);
3092 assert(f->header);
3093
3094 return generic_array_bisect(
3095 f,
3096 le64toh(f->header->entry_array_offset),
3097 le64toh(f->header->n_entries),
3098 p,
3099 test_object_offset,
3100 direction,
3101 ret_object, ret_offset, NULL);
3102 }
3103
3104 static int test_object_seqnum(JournalFile *f, uint64_t p, uint64_t needle) {
3105 uint64_t sq;
3106 Object *o;
3107 int r;
3108
3109 assert(f);
3110 assert(p > 0);
3111
3112 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
3113 if (r < 0)
3114 return r;
3115
3116 sq = le64toh(READ_NOW(o->entry.seqnum));
3117 if (sq == needle)
3118 return TEST_FOUND;
3119 else if (sq < needle)
3120 return TEST_LEFT;
3121 else
3122 return TEST_RIGHT;
3123 }
3124
3125 int journal_file_move_to_entry_by_seqnum(
3126 JournalFile *f,
3127 uint64_t seqnum,
3128 direction_t direction,
3129 Object **ret_object,
3130 uint64_t *ret_offset) {
3131
3132 assert(f);
3133 assert(f->header);
3134
3135 return generic_array_bisect(
3136 f,
3137 le64toh(f->header->entry_array_offset),
3138 le64toh(f->header->n_entries),
3139 seqnum,
3140 test_object_seqnum,
3141 direction,
3142 ret_object, ret_offset, NULL);
3143 }
3144
3145 static int test_object_realtime(JournalFile *f, uint64_t p, uint64_t needle) {
3146 Object *o;
3147 uint64_t rt;
3148 int r;
3149
3150 assert(f);
3151 assert(p > 0);
3152
3153 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
3154 if (r < 0)
3155 return r;
3156
3157 rt = le64toh(READ_NOW(o->entry.realtime));
3158 if (rt == needle)
3159 return TEST_FOUND;
3160 else if (rt < needle)
3161 return TEST_LEFT;
3162 else
3163 return TEST_RIGHT;
3164 }
3165
3166 int journal_file_move_to_entry_by_realtime(
3167 JournalFile *f,
3168 uint64_t realtime,
3169 direction_t direction,
3170 Object **ret_object,
3171 uint64_t *ret_offset) {
3172
3173 assert(f);
3174 assert(f->header);
3175
3176 return generic_array_bisect(
3177 f,
3178 le64toh(f->header->entry_array_offset),
3179 le64toh(f->header->n_entries),
3180 realtime,
3181 test_object_realtime,
3182 direction,
3183 ret_object, ret_offset, NULL);
3184 }
3185
3186 static int test_object_monotonic(JournalFile *f, uint64_t p, uint64_t needle) {
3187 Object *o;
3188 uint64_t m;
3189 int r;
3190
3191 assert(f);
3192 assert(p > 0);
3193
3194 r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o);
3195 if (r < 0)
3196 return r;
3197
3198 m = le64toh(READ_NOW(o->entry.monotonic));
3199 if (m == needle)
3200 return TEST_FOUND;
3201 else if (m < needle)
3202 return TEST_LEFT;
3203 else
3204 return TEST_RIGHT;
3205 }
3206
3207 static int find_data_object_by_boot_id(
3208 JournalFile *f,
3209 sd_id128_t boot_id,
3210 Object **ret_object,
3211 uint64_t *ret_offset) {
3212
3213 char t[STRLEN("_BOOT_ID=") + 32 + 1] = "_BOOT_ID=";
3214
3215 assert(f);
3216
3217 sd_id128_to_string(boot_id, t + 9);
3218 return journal_file_find_data_object(f, t, sizeof(t) - 1, ret_object, ret_offset);
3219 }
3220
3221 int journal_file_move_to_entry_by_monotonic(
3222 JournalFile *f,
3223 sd_id128_t boot_id,
3224 uint64_t monotonic,
3225 direction_t direction,
3226 Object **ret_object,
3227 uint64_t *ret_offset) {
3228
3229 Object *o;
3230 int r;
3231
3232 assert(f);
3233
3234 r = find_data_object_by_boot_id(f, boot_id, &o, NULL);
3235 if (r < 0)
3236 return r;
3237 if (r == 0)
3238 return -ENOENT;
3239
3240 return generic_array_bisect_plus_one(
3241 f,
3242 le64toh(o->data.entry_offset),
3243 le64toh(o->data.entry_array_offset),
3244 le64toh(o->data.n_entries),
3245 monotonic,
3246 test_object_monotonic,
3247 direction,
3248 ret_object, ret_offset, NULL);
3249 }
3250
3251 void journal_file_reset_location(JournalFile *f) {
3252 assert(f);
3253
3254 f->location_type = LOCATION_HEAD;
3255 f->current_offset = 0;
3256 f->current_seqnum = 0;
3257 f->current_realtime = 0;
3258 f->current_monotonic = 0;
3259 zero(f->current_boot_id);
3260 f->current_xor_hash = 0;
3261 }
3262
3263 void journal_file_save_location(JournalFile *f, Object *o, uint64_t offset) {
3264 assert(f);
3265 assert(o);
3266
3267 f->location_type = LOCATION_SEEK;
3268 f->current_offset = offset;
3269 f->current_seqnum = le64toh(o->entry.seqnum);
3270 f->current_realtime = le64toh(o->entry.realtime);
3271 f->current_monotonic = le64toh(o->entry.monotonic);
3272 f->current_boot_id = o->entry.boot_id;
3273 f->current_xor_hash = le64toh(o->entry.xor_hash);
3274 }
3275
3276 static bool check_properly_ordered(uint64_t new_offset, uint64_t old_offset, direction_t direction) {
3277
3278 /* Consider it an error if any of the two offsets is uninitialized */
3279 if (old_offset == 0 || new_offset == 0)
3280 return false;
3281
3282 /* If we go down, the new offset must be larger than the old one. */
3283 return direction == DIRECTION_DOWN ?
3284 new_offset > old_offset :
3285 new_offset < old_offset;
3286 }
3287
3288 int journal_file_next_entry(
3289 JournalFile *f,
3290 uint64_t p,
3291 direction_t direction,
3292 Object **ret_object,
3293 uint64_t *ret_offset) {
3294
3295 uint64_t i, n, ofs;
3296 int r;
3297
3298 assert(f);
3299 assert(f->header);
3300
3301 /* FIXME: fix return value assignment. */
3302
3303 n = le64toh(READ_NOW(f->header->n_entries));
3304 if (n <= 0)
3305 return 0;
3306
3307 if (p == 0)
3308 i = direction == DIRECTION_DOWN ? 0 : n - 1;
3309 else {
3310 r = generic_array_bisect(f,
3311 le64toh(f->header->entry_array_offset),
3312 le64toh(f->header->n_entries),
3313 p,
3314 test_object_offset,
3315 DIRECTION_DOWN,
3316 NULL, NULL,
3317 &i);
3318 if (r <= 0)
3319 return r;
3320
3321 r = bump_array_index(&i, direction, n);
3322 if (r <= 0)
3323 return r;
3324 }
3325
3326 /* And jump to it */
3327 r = generic_array_get(f, le64toh(f->header->entry_array_offset), i, direction, ret_object, &ofs);
3328 if (r <= 0)
3329 return r;
3330
3331 /* Ensure our array is properly ordered. */
3332 if (p > 0 && !check_properly_ordered(ofs, p, direction))
3333 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
3334 "%s: entry array not properly ordered at entry %" PRIu64,
3335 f->path, i);
3336
3337 if (ret_offset)
3338 *ret_offset = ofs;
3339
3340 return 1;
3341 }
3342
3343 int journal_file_next_entry_for_data(
3344 JournalFile *f,
3345 Object *d,
3346 direction_t direction,
3347 Object **ret_object,
3348 uint64_t *ret_offset) {
3349
3350 uint64_t i, n, ofs;
3351 int r;
3352
3353 assert(f);
3354 assert(d);
3355 assert(d->object.type == OBJECT_DATA);
3356
3357 /* FIXME: fix return value assignment. */
3358
3359 n = le64toh(READ_NOW(d->data.n_entries));
3360 if (n <= 0)
3361 return n;
3362
3363 i = direction == DIRECTION_DOWN ? 0 : n - 1;
3364
3365 r = generic_array_get_plus_one(f,
3366 le64toh(d->data.entry_offset),
3367 le64toh(d->data.entry_array_offset),
3368 i,
3369 direction,
3370 ret_object, &ofs);
3371 if (r <= 0)
3372 return r;
3373
3374 if (ret_offset)
3375 *ret_offset = ofs;
3376
3377 return 1;
3378 }
3379
3380 int journal_file_move_to_entry_by_offset_for_data(
3381 JournalFile *f,
3382 Object *d,
3383 uint64_t p,
3384 direction_t direction,
3385 Object **ret, uint64_t *ret_offset) {
3386
3387 assert(f);
3388 assert(d);
3389 assert(d->object.type == OBJECT_DATA);
3390
3391 return generic_array_bisect_plus_one(
3392 f,
3393 le64toh(d->data.entry_offset),
3394 le64toh(d->data.entry_array_offset),
3395 le64toh(d->data.n_entries),
3396 p,
3397 test_object_offset,
3398 direction,
3399 ret, ret_offset, NULL);
3400 }
3401
3402 int journal_file_move_to_entry_by_monotonic_for_data(
3403 JournalFile *f,
3404 Object *d,
3405 sd_id128_t boot_id,
3406 uint64_t monotonic,
3407 direction_t direction,
3408 Object **ret_object,
3409 uint64_t *ret_offset) {
3410
3411 uint64_t b, z, entry_offset, entry_array_offset, n_entries;
3412 Object *o;
3413 int r;
3414
3415 assert(f);
3416 assert(d);
3417 assert(d->object.type == OBJECT_DATA);
3418
3419 /* Save all the required data before the data object gets invalidated. */
3420 entry_offset = le64toh(READ_NOW(d->data.entry_offset));
3421 entry_array_offset = le64toh(READ_NOW(d->data.entry_array_offset));
3422 n_entries = le64toh(READ_NOW(d->data.n_entries));
3423
3424 /* First, seek by time */
3425 r = find_data_object_by_boot_id(f, boot_id, &o, &b);
3426 if (r < 0)
3427 return r;
3428 if (r == 0)
3429 return -ENOENT;
3430
3431 r = generic_array_bisect_plus_one(f,
3432 le64toh(o->data.entry_offset),
3433 le64toh(o->data.entry_array_offset),
3434 le64toh(o->data.n_entries),
3435 monotonic,
3436 test_object_monotonic,
3437 direction,
3438 NULL, &z, NULL);
3439 if (r <= 0)
3440 return r;
3441
3442 /* And now, continue seeking until we find an entry that
3443 * exists in both bisection arrays */
3444
3445 r = journal_file_move_to_object(f, OBJECT_DATA, b, &o);
3446 if (r < 0)
3447 return r;
3448
3449 for (;;) {
3450 uint64_t p, q;
3451
3452 r = generic_array_bisect_plus_one(f,
3453 entry_offset,
3454 entry_array_offset,
3455 n_entries,
3456 z,
3457 test_object_offset,
3458 direction,
3459 NULL, &p, NULL);
3460 if (r <= 0)
3461 return r;
3462
3463 r = generic_array_bisect_plus_one(f,
3464 le64toh(o->data.entry_offset),
3465 le64toh(o->data.entry_array_offset),
3466 le64toh(o->data.n_entries),
3467 p,
3468 test_object_offset,
3469 direction,
3470 NULL, &q, NULL);
3471
3472 if (r <= 0)
3473 return r;
3474
3475 if (p == q) {
3476 if (ret_object) {
3477 r = journal_file_move_to_object(f, OBJECT_ENTRY, q, ret_object);
3478 if (r < 0)
3479 return r;
3480 }
3481
3482 if (ret_offset)
3483 *ret_offset = q;
3484
3485 return 1;
3486 }
3487
3488 z = q;
3489 }
3490 }
3491
3492 int journal_file_move_to_entry_by_seqnum_for_data(
3493 JournalFile *f,
3494 Object *d,
3495 uint64_t seqnum,
3496 direction_t direction,
3497 Object **ret_object,
3498 uint64_t *ret_offset) {
3499
3500 assert(f);
3501 assert(d);
3502 assert(d->object.type == OBJECT_DATA);
3503
3504 return generic_array_bisect_plus_one(
3505 f,
3506 le64toh(d->data.entry_offset),
3507 le64toh(d->data.entry_array_offset),
3508 le64toh(d->data.n_entries),
3509 seqnum,
3510 test_object_seqnum,
3511 direction,
3512 ret_object, ret_offset, NULL);
3513 }
3514
3515 int journal_file_move_to_entry_by_realtime_for_data(
3516 JournalFile *f,
3517 Object *d,
3518 uint64_t realtime,
3519 direction_t direction,
3520 Object **ret, uint64_t *ret_offset) {
3521
3522 assert(f);
3523 assert(d);
3524 assert(d->object.type == OBJECT_DATA);
3525
3526 return generic_array_bisect_plus_one(
3527 f,
3528 le64toh(d->data.entry_offset),
3529 le64toh(d->data.entry_array_offset),
3530 le64toh(d->data.n_entries),
3531 realtime,
3532 test_object_realtime,
3533 direction,
3534 ret, ret_offset, NULL);
3535 }
3536
3537 void journal_file_dump(JournalFile *f) {
3538 Object *o;
3539 uint64_t p;
3540 int r;
3541
3542 assert(f);
3543 assert(f->header);
3544
3545 journal_file_print_header(f);
3546
3547 p = le64toh(READ_NOW(f->header->header_size));
3548 while (p != 0) {
3549 const char *s;
3550 Compression c;
3551
3552 r = journal_file_move_to_object(f, OBJECT_UNUSED, p, &o);
3553 if (r < 0)
3554 goto fail;
3555
3556 s = journal_object_type_to_string(o->object.type);
3557
3558 switch (o->object.type) {
3559
3560 case OBJECT_ENTRY:
3561 assert(s);
3562
3563 printf("Type: %s seqnum=%"PRIu64" monotonic=%"PRIu64" realtime=%"PRIu64"\n",
3564 s,
3565 le64toh(o->entry.seqnum),
3566 le64toh(o->entry.monotonic),
3567 le64toh(o->entry.realtime));
3568 break;
3569
3570 case OBJECT_TAG:
3571 assert(s);
3572
3573 printf("Type: %s seqnum=%"PRIu64" epoch=%"PRIu64"\n",
3574 s,
3575 le64toh(o->tag.seqnum),
3576 le64toh(o->tag.epoch));
3577 break;
3578
3579 default:
3580 if (s)
3581 printf("Type: %s \n", s);
3582 else
3583 printf("Type: unknown (%i)", o->object.type);
3584
3585 break;
3586 }
3587
3588 c = COMPRESSION_FROM_OBJECT(o);
3589 if (c > COMPRESSION_NONE)
3590 printf("Flags: %s\n",
3591 compression_to_string(c));
3592
3593 if (p == le64toh(f->header->tail_object_offset))
3594 p = 0;
3595 else
3596 p += ALIGN64(le64toh(o->object.size));
3597 }
3598
3599 return;
3600 fail:
3601 log_error("File corrupt");
3602 }
3603
3604 /* Note: the lifetime of the compound literal is the immediately surrounding block. */
3605 #define FORMAT_TIMESTAMP_SAFE(t) (FORMAT_TIMESTAMP(t) ?: " --- ")
3606
3607 void journal_file_print_header(JournalFile *f) {
3608 struct stat st;
3609
3610 assert(f);
3611 assert(f->header);
3612
3613 printf("File path: %s\n"
3614 "File ID: %s\n"
3615 "Machine ID: %s\n"
3616 "Boot ID: %s\n"
3617 "Sequential number ID: %s\n"
3618 "State: %s\n"
3619 "Compatible flags:%s%s%s\n"
3620 "Incompatible flags:%s%s%s%s%s%s\n"
3621 "Header size: %"PRIu64"\n"
3622 "Arena size: %"PRIu64"\n"
3623 "Data hash table size: %"PRIu64"\n"
3624 "Field hash table size: %"PRIu64"\n"
3625 "Rotate suggested: %s\n"
3626 "Head sequential number: %"PRIu64" (%"PRIx64")\n"
3627 "Tail sequential number: %"PRIu64" (%"PRIx64")\n"
3628 "Head realtime timestamp: %s (%"PRIx64")\n"
3629 "Tail realtime timestamp: %s (%"PRIx64")\n"
3630 "Tail monotonic timestamp: %s (%"PRIx64")\n"
3631 "Objects: %"PRIu64"\n"
3632 "Entry objects: %"PRIu64"\n",
3633 f->path,
3634 SD_ID128_TO_STRING(f->header->file_id),
3635 SD_ID128_TO_STRING(f->header->machine_id),
3636 SD_ID128_TO_STRING(f->header->tail_entry_boot_id),
3637 SD_ID128_TO_STRING(f->header->seqnum_id),
3638 f->header->state == STATE_OFFLINE ? "OFFLINE" :
3639 f->header->state == STATE_ONLINE ? "ONLINE" :
3640 f->header->state == STATE_ARCHIVED ? "ARCHIVED" : "UNKNOWN",
3641 JOURNAL_HEADER_SEALED(f->header) ? " SEALED" : "",
3642 JOURNAL_HEADER_TAIL_ENTRY_BOOT_ID(f->header) ? " TAIL_ENTRY_BOOT_ID" : "",
3643 (le32toh(f->header->compatible_flags) & ~HEADER_COMPATIBLE_ANY) ? " ???" : "",
3644 JOURNAL_HEADER_COMPRESSED_XZ(f->header) ? " COMPRESSED-XZ" : "",
3645 JOURNAL_HEADER_COMPRESSED_LZ4(f->header) ? " COMPRESSED-LZ4" : "",
3646 JOURNAL_HEADER_COMPRESSED_ZSTD(f->header) ? " COMPRESSED-ZSTD" : "",
3647 JOURNAL_HEADER_KEYED_HASH(f->header) ? " KEYED-HASH" : "",
3648 JOURNAL_HEADER_COMPACT(f->header) ? " COMPACT" : "",
3649 (le32toh(f->header->incompatible_flags) & ~HEADER_INCOMPATIBLE_ANY) ? " ???" : "",
3650 le64toh(f->header->header_size),
3651 le64toh(f->header->arena_size),
3652 le64toh(f->header->data_hash_table_size) / sizeof(HashItem),
3653 le64toh(f->header->field_hash_table_size) / sizeof(HashItem),
3654 yes_no(journal_file_rotate_suggested(f, 0, LOG_DEBUG)),
3655 le64toh(f->header->head_entry_seqnum), le64toh(f->header->head_entry_seqnum),
3656 le64toh(f->header->tail_entry_seqnum), le64toh(f->header->tail_entry_seqnum),
3657 FORMAT_TIMESTAMP_SAFE(le64toh(f->header->head_entry_realtime)), le64toh(f->header->head_entry_realtime),
3658 FORMAT_TIMESTAMP_SAFE(le64toh(f->header->tail_entry_realtime)), le64toh(f->header->tail_entry_realtime),
3659 FORMAT_TIMESPAN(le64toh(f->header->tail_entry_monotonic), USEC_PER_MSEC), le64toh(f->header->tail_entry_monotonic),
3660 le64toh(f->header->n_objects),
3661 le64toh(f->header->n_entries));
3662
3663 if (JOURNAL_HEADER_CONTAINS(f->header, n_data))
3664 printf("Data objects: %"PRIu64"\n"
3665 "Data hash table fill: %.1f%%\n",
3666 le64toh(f->header->n_data),
3667 100.0 * (double) le64toh(f->header->n_data) / ((double) (le64toh(f->header->data_hash_table_size) / sizeof(HashItem))));
3668
3669 if (JOURNAL_HEADER_CONTAINS(f->header, n_fields))
3670 printf("Field objects: %"PRIu64"\n"
3671 "Field hash table fill: %.1f%%\n",
3672 le64toh(f->header->n_fields),
3673 100.0 * (double) le64toh(f->header->n_fields) / ((double) (le64toh(f->header->field_hash_table_size) / sizeof(HashItem))));
3674
3675 if (JOURNAL_HEADER_CONTAINS(f->header, n_tags))
3676 printf("Tag objects: %"PRIu64"\n",
3677 le64toh(f->header->n_tags));
3678 if (JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays))
3679 printf("Entry array objects: %"PRIu64"\n",
3680 le64toh(f->header->n_entry_arrays));
3681
3682 if (JOURNAL_HEADER_CONTAINS(f->header, field_hash_chain_depth))
3683 printf("Deepest field hash chain: %" PRIu64"\n",
3684 f->header->field_hash_chain_depth);
3685
3686 if (JOURNAL_HEADER_CONTAINS(f->header, data_hash_chain_depth))
3687 printf("Deepest data hash chain: %" PRIu64"\n",
3688 f->header->data_hash_chain_depth);
3689
3690 if (fstat(f->fd, &st) >= 0)
3691 printf("Disk usage: %s\n", FORMAT_BYTES((uint64_t) st.st_blocks * 512ULL));
3692 }
3693
3694 static int journal_file_warn_btrfs(JournalFile *f) {
3695 unsigned attrs;
3696 int r;
3697
3698 assert(f);
3699
3700 /* Before we write anything, check if the COW logic is turned
3701 * off on btrfs. Given our write pattern that is quite
3702 * unfriendly to COW file systems this should greatly improve
3703 * performance on COW file systems, such as btrfs, at the
3704 * expense of data integrity features (which shouldn't be too
3705 * bad, given that we do our own checksumming). */
3706
3707 r = fd_is_fs_type(f->fd, BTRFS_SUPER_MAGIC);
3708 if (r < 0)
3709 return log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT, "Failed to determine if journal is on btrfs: %m");
3710 if (!r)
3711 return 0;
3712
3713 r = read_attr_fd(f->fd, &attrs);
3714 if (r < 0)
3715 return log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT, "Failed to read file attributes: %m");
3716
3717 if (attrs & FS_NOCOW_FL) {
3718 log_debug("Detected btrfs file system with copy-on-write disabled, all is good.");
3719 return 0;
3720 }
3721
3722 log_ratelimit_notice(JOURNAL_LOG_RATELIMIT,
3723 "Creating journal file %s on a btrfs file system, and copy-on-write is enabled. "
3724 "This is likely to slow down journal access substantially, please consider turning "
3725 "off the copy-on-write file attribute on the journal directory, using chattr +C.",
3726 f->path);
3727
3728 return 1;
3729 }
3730
3731 static void journal_default_metrics(JournalMetrics *m, int fd, bool compact) {
3732 struct statvfs ss;
3733 uint64_t fs_size = 0;
3734
3735 assert(m);
3736 assert(fd >= 0);
3737
3738 if (fstatvfs(fd, &ss) >= 0)
3739 fs_size = ss.f_frsize * ss.f_blocks;
3740 else
3741 log_debug_errno(errno, "Failed to determine disk size: %m");
3742
3743 if (m->max_use == UINT64_MAX) {
3744
3745 if (fs_size > 0)
3746 m->max_use = CLAMP(PAGE_ALIGN(fs_size / 10), /* 10% of file system size */
3747 MAX_USE_LOWER, MAX_USE_UPPER);
3748 else
3749 m->max_use = MAX_USE_LOWER;
3750 } else {
3751 m->max_use = PAGE_ALIGN(m->max_use);
3752
3753 if (m->max_use != 0 && m->max_use < JOURNAL_FILE_SIZE_MIN*2)
3754 m->max_use = JOURNAL_FILE_SIZE_MIN*2;
3755 }
3756
3757 if (m->min_use == UINT64_MAX) {
3758 if (fs_size > 0)
3759 m->min_use = CLAMP(PAGE_ALIGN(fs_size / 50), /* 2% of file system size */
3760 MIN_USE_LOW, MIN_USE_HIGH);
3761 else
3762 m->min_use = MIN_USE_LOW;
3763 }
3764
3765 if (m->min_use > m->max_use)
3766 m->min_use = m->max_use;
3767
3768 if (m->max_size == UINT64_MAX)
3769 m->max_size = MIN(PAGE_ALIGN(m->max_use / 8), /* 8 chunks */
3770 MAX_SIZE_UPPER);
3771 else
3772 m->max_size = PAGE_ALIGN(m->max_size);
3773
3774 if (compact && m->max_size > JOURNAL_COMPACT_SIZE_MAX)
3775 m->max_size = JOURNAL_COMPACT_SIZE_MAX;
3776
3777 if (m->max_size != 0) {
3778 if (m->max_size < JOURNAL_FILE_SIZE_MIN)
3779 m->max_size = JOURNAL_FILE_SIZE_MIN;
3780
3781 if (m->max_use != 0 && m->max_size*2 > m->max_use)
3782 m->max_use = m->max_size*2;
3783 }
3784
3785 if (m->min_size == UINT64_MAX)
3786 m->min_size = JOURNAL_FILE_SIZE_MIN;
3787 else
3788 m->min_size = CLAMP(PAGE_ALIGN(m->min_size),
3789 JOURNAL_FILE_SIZE_MIN,
3790 m->max_size ?: UINT64_MAX);
3791
3792 if (m->keep_free == UINT64_MAX) {
3793 if (fs_size > 0)
3794 m->keep_free = MIN(PAGE_ALIGN(fs_size / 20), /* 5% of file system size */
3795 KEEP_FREE_UPPER);
3796 else
3797 m->keep_free = DEFAULT_KEEP_FREE;
3798 }
3799
3800 if (m->n_max_files == UINT64_MAX)
3801 m->n_max_files = DEFAULT_N_MAX_FILES;
3802
3803 log_debug("Fixed min_use=%s max_use=%s max_size=%s min_size=%s keep_free=%s n_max_files=%" PRIu64,
3804 FORMAT_BYTES(m->min_use),
3805 FORMAT_BYTES(m->max_use),
3806 FORMAT_BYTES(m->max_size),
3807 FORMAT_BYTES(m->min_size),
3808 FORMAT_BYTES(m->keep_free),
3809 m->n_max_files);
3810 }
3811
3812 int journal_file_open(
3813 int fd,
3814 const char *fname,
3815 int open_flags,
3816 JournalFileFlags file_flags,
3817 mode_t mode,
3818 uint64_t compress_threshold_bytes,
3819 JournalMetrics *metrics,
3820 MMapCache *mmap_cache,
3821 JournalFile *template,
3822 JournalFile **ret) {
3823
3824 bool newly_created = false;
3825 JournalFile *f;
3826 void *h;
3827 int r;
3828
3829 assert(fd >= 0 || fname);
3830 assert(file_flags >= 0);
3831 assert(file_flags <= _JOURNAL_FILE_FLAGS_MAX);
3832 assert(mmap_cache);
3833 assert(ret);
3834
3835 if (!IN_SET((open_flags & O_ACCMODE), O_RDONLY, O_RDWR))
3836 return -EINVAL;
3837
3838 if ((open_flags & O_ACCMODE) == O_RDONLY && FLAGS_SET(open_flags, O_CREAT))
3839 return -EINVAL;
3840
3841 if (fname && (open_flags & O_CREAT) && !endswith(fname, ".journal"))
3842 return -EINVAL;
3843
3844 f = new(JournalFile, 1);
3845 if (!f)
3846 return -ENOMEM;
3847
3848 *f = (JournalFile) {
3849 .fd = fd,
3850 .mode = mode,
3851 .open_flags = open_flags,
3852 .compress_threshold_bytes = compress_threshold_bytes == UINT64_MAX ?
3853 DEFAULT_COMPRESS_THRESHOLD :
3854 MAX(MIN_COMPRESS_THRESHOLD, compress_threshold_bytes),
3855 .strict_order = FLAGS_SET(file_flags, JOURNAL_STRICT_ORDER),
3856 .newest_boot_id_prioq_idx = PRIOQ_IDX_NULL,
3857 };
3858
3859 if (fname) {
3860 f->path = strdup(fname);
3861 if (!f->path) {
3862 r = -ENOMEM;
3863 goto fail;
3864 }
3865 } else {
3866 assert(fd >= 0);
3867
3868 /* If we don't know the path, fill in something explanatory and vaguely useful */
3869 if (asprintf(&f->path, "/proc/self/%i", fd) < 0) {
3870 r = -ENOMEM;
3871 goto fail;
3872 }
3873 }
3874
3875 f->chain_cache = ordered_hashmap_new(&uint64_hash_ops);
3876 if (!f->chain_cache) {
3877 r = -ENOMEM;
3878 goto fail;
3879 }
3880
3881 if (f->fd < 0) {
3882 /* We pass O_NONBLOCK here, so that in case somebody pointed us to some character device node or FIFO
3883 * or so, we likely fail quickly than block for long. For regular files O_NONBLOCK has no effect, hence
3884 * it doesn't hurt in that case. */
3885
3886 f->fd = openat_report_new(AT_FDCWD, f->path, f->open_flags|O_CLOEXEC|O_NONBLOCK, f->mode, &newly_created);
3887 if (f->fd < 0) {
3888 r = f->fd;
3889 goto fail;
3890 }
3891
3892 /* fds we opened here by us should also be closed by us. */
3893 f->close_fd = true;
3894
3895 r = fd_nonblock(f->fd, false);
3896 if (r < 0)
3897 goto fail;
3898
3899 if (!newly_created) {
3900 r = journal_file_fstat(f);
3901 if (r < 0)
3902 goto fail;
3903 }
3904 } else {
3905 r = journal_file_fstat(f);
3906 if (r < 0)
3907 goto fail;
3908
3909 /* If we just got the fd passed in, we don't really know if we created the file anew */
3910 newly_created = f->last_stat.st_size == 0 && journal_file_writable(f);
3911 }
3912
3913 f->cache_fd = mmap_cache_add_fd(mmap_cache, f->fd, mmap_prot_from_open_flags(open_flags));
3914 if (!f->cache_fd) {
3915 r = -ENOMEM;
3916 goto fail;
3917 }
3918
3919 if (newly_created) {
3920 (void) journal_file_warn_btrfs(f);
3921
3922 /* Let's attach the creation time to the journal file, so that the vacuuming code knows the age of this
3923 * file even if the file might end up corrupted one day... Ideally we'd just use the creation time many
3924 * file systems maintain for each file, but the API to query this is very new, hence let's emulate this
3925 * via extended attributes. If extended attributes are not supported we'll just skip this, and rely
3926 * solely on mtime/atime/ctime of the file. */
3927 (void) fd_setcrtime(f->fd, 0);
3928
3929 r = journal_file_init_header(f, file_flags, template);
3930 if (r < 0)
3931 goto fail;
3932
3933 r = journal_file_fstat(f);
3934 if (r < 0)
3935 goto fail;
3936 }
3937
3938 if (f->last_stat.st_size < (off_t) HEADER_SIZE_MIN) {
3939 r = -ENODATA;
3940 goto fail;
3941 }
3942
3943 r = mmap_cache_fd_get(f->cache_fd, CONTEXT_HEADER, true, 0, PAGE_ALIGN(sizeof(Header)), &f->last_stat, &h);
3944 if (r == -EINVAL) {
3945 /* Some file systems (jffs2 or p9fs) don't support mmap() properly (or only read-only
3946 * mmap()), and return EINVAL in that case. Let's propagate that as a more recognizable error
3947 * code. */
3948 r = -EAFNOSUPPORT;
3949 goto fail;
3950 }
3951 if (r < 0)
3952 goto fail;
3953
3954 f->header = h;
3955
3956 if (!newly_created) {
3957 r = journal_file_verify_header(f);
3958 if (r < 0)
3959 goto fail;
3960 }
3961
3962 #if HAVE_GCRYPT
3963 if (!newly_created && journal_file_writable(f) && JOURNAL_HEADER_SEALED(f->header)) {
3964 r = journal_file_fss_load(f);
3965 if (r < 0)
3966 goto fail;
3967 }
3968 #endif
3969
3970 if (journal_file_writable(f)) {
3971 if (metrics) {
3972 journal_default_metrics(metrics, f->fd, JOURNAL_HEADER_COMPACT(f->header));
3973 f->metrics = *metrics;
3974 } else if (template)
3975 f->metrics = template->metrics;
3976
3977 r = journal_file_refresh_header(f);
3978 if (r < 0)
3979 goto fail;
3980 }
3981
3982 #if HAVE_GCRYPT
3983 r = journal_file_hmac_setup(f);
3984 if (r < 0)
3985 goto fail;
3986 #endif
3987
3988 if (newly_created) {
3989 r = journal_file_setup_field_hash_table(f);
3990 if (r < 0)
3991 goto fail;
3992
3993 r = journal_file_setup_data_hash_table(f);
3994 if (r < 0)
3995 goto fail;
3996
3997 #if HAVE_GCRYPT
3998 r = journal_file_append_first_tag(f);
3999 if (r < 0)
4000 goto fail;
4001 #endif
4002 }
4003
4004 if (mmap_cache_fd_got_sigbus(f->cache_fd)) {
4005 r = -EIO;
4006 goto fail;
4007 }
4008
4009 if (template && template->post_change_timer) {
4010 r = journal_file_enable_post_change_timer(
4011 f,
4012 sd_event_source_get_event(template->post_change_timer),
4013 template->post_change_timer_period);
4014
4015 if (r < 0)
4016 goto fail;
4017 }
4018
4019 /* The file is opened now successfully, thus we take possession of any passed in fd. */
4020 f->close_fd = true;
4021
4022 if (DEBUG_LOGGING) {
4023 static int last_seal = -1, last_keyed_hash = -1;
4024 static Compression last_compression = _COMPRESSION_INVALID;
4025 static uint64_t last_bytes = UINT64_MAX;
4026
4027 if (last_seal != JOURNAL_HEADER_SEALED(f->header) ||
4028 last_keyed_hash != JOURNAL_HEADER_KEYED_HASH(f->header) ||
4029 last_compression != JOURNAL_FILE_COMPRESSION(f) ||
4030 last_bytes != f->compress_threshold_bytes) {
4031
4032 log_debug("Journal effective settings seal=%s keyed_hash=%s compress=%s compress_threshold_bytes=%s",
4033 yes_no(JOURNAL_HEADER_SEALED(f->header)), yes_no(JOURNAL_HEADER_KEYED_HASH(f->header)),
4034 compression_to_string(JOURNAL_FILE_COMPRESSION(f)), FORMAT_BYTES(f->compress_threshold_bytes));
4035 last_seal = JOURNAL_HEADER_SEALED(f->header);
4036 last_keyed_hash = JOURNAL_HEADER_KEYED_HASH(f->header);
4037 last_compression = JOURNAL_FILE_COMPRESSION(f);
4038 last_bytes = f->compress_threshold_bytes;
4039 }
4040 }
4041
4042 *ret = f;
4043 return 0;
4044
4045 fail:
4046 if (f->cache_fd && mmap_cache_fd_got_sigbus(f->cache_fd))
4047 r = -EIO;
4048
4049 (void) journal_file_close(f);
4050
4051 if (newly_created && fd < 0)
4052 (void) unlink(fname);
4053
4054 return r;
4055 }
4056
4057 int journal_file_parse_uid_from_filename(const char *path, uid_t *ret_uid) {
4058 _cleanup_free_ char *buf = NULL, *p = NULL;
4059 const char *a, *b, *at;
4060 int r;
4061
4062 /* This helper returns -EREMOTE when the filename doesn't match user online/offline journal
4063 * pattern. Hence it currently doesn't parse archived or disposed user journals. */
4064
4065 assert(path);
4066 assert(ret_uid);
4067
4068 r = path_extract_filename(path, &p);
4069 if (r < 0)
4070 return r;
4071 if (r == O_DIRECTORY)
4072 return -EISDIR;
4073
4074 a = startswith(p, "user-");
4075 if (!a)
4076 return -EREMOTE;
4077 b = endswith(p, ".journal");
4078 if (!b)
4079 return -EREMOTE;
4080
4081 at = strchr(a, '@');
4082 if (at)
4083 return -EREMOTE;
4084
4085 buf = strndup(a, b-a);
4086 if (!buf)
4087 return -ENOMEM;
4088
4089 return parse_uid(buf, ret_uid);
4090 }
4091
4092 int journal_file_archive(JournalFile *f, char **ret_previous_path) {
4093 _cleanup_free_ char *p = NULL;
4094
4095 assert(f);
4096
4097 if (!journal_file_writable(f))
4098 return -EINVAL;
4099
4100 /* Is this a journal file that was passed to us as fd? If so, we synthesized a path name for it, and we refuse
4101 * rotation, since we don't know the actual path, and couldn't rename the file hence. */
4102 if (path_startswith(f->path, "/proc/self/fd"))
4103 return -EINVAL;
4104
4105 if (!endswith(f->path, ".journal"))
4106 return -EINVAL;
4107
4108 if (asprintf(&p, "%.*s@" SD_ID128_FORMAT_STR "-%016"PRIx64"-%016"PRIx64".journal",
4109 (int) strlen(f->path) - 8, f->path,
4110 SD_ID128_FORMAT_VAL(f->header->seqnum_id),
4111 le64toh(f->header->head_entry_seqnum),
4112 le64toh(f->header->head_entry_realtime)) < 0)
4113 return -ENOMEM;
4114
4115 /* Try to rename the file to the archived version. If the file already was deleted, we'll get ENOENT, let's
4116 * ignore that case. */
4117 if (rename(f->path, p) < 0 && errno != ENOENT)
4118 return -errno;
4119
4120 /* Sync the rename to disk */
4121 (void) fsync_directory_of_file(f->fd);
4122
4123 if (ret_previous_path)
4124 *ret_previous_path = f->path;
4125 else
4126 free(f->path);
4127
4128 f->path = TAKE_PTR(p);
4129
4130 /* Set as archive so offlining commits w/state=STATE_ARCHIVED. Previously we would set old_file->header->state
4131 * to STATE_ARCHIVED directly here, but journal_file_set_offline() short-circuits when state != STATE_ONLINE,
4132 * which would result in the rotated journal never getting fsync() called before closing. Now we simply queue
4133 * the archive state by setting an archive bit, leaving the state as STATE_ONLINE so proper offlining
4134 * occurs. */
4135 f->archive = true;
4136
4137 return 0;
4138 }
4139
4140 int journal_file_dispose(int dir_fd, const char *fname) {
4141 _cleanup_free_ char *p = NULL;
4142
4143 assert(fname);
4144
4145 /* Renames a journal file to *.journal~, i.e. to mark it as corrupted or otherwise uncleanly shutdown. Note that
4146 * this is done without looking into the file or changing any of its contents. The idea is that this is called
4147 * whenever something is suspicious and we want to move the file away and make clear that it is not accessed
4148 * for writing anymore. */
4149
4150 if (!endswith(fname, ".journal"))
4151 return -EINVAL;
4152
4153 if (asprintf(&p, "%.*s@%016" PRIx64 "-%016" PRIx64 ".journal~",
4154 (int) strlen(fname) - 8, fname,
4155 now(CLOCK_REALTIME),
4156 random_u64()) < 0)
4157 return -ENOMEM;
4158
4159 if (renameat(dir_fd, fname, dir_fd, p) < 0)
4160 return -errno;
4161
4162 return 0;
4163 }
4164
4165 int journal_file_copy_entry(
4166 JournalFile *from,
4167 JournalFile *to,
4168 Object *o,
4169 uint64_t p,
4170 uint64_t *seqnum,
4171 sd_id128_t *seqnum_id) {
4172
4173 _cleanup_free_ EntryItem *items_alloc = NULL;
4174 EntryItem *items;
4175 uint64_t n, m = 0, xor_hash = 0;
4176 sd_id128_t boot_id;
4177 dual_timestamp ts;
4178 int r;
4179
4180 assert(from);
4181 assert(to);
4182 assert(o);
4183 assert(p > 0);
4184
4185 if (!journal_file_writable(to))
4186 return -EPERM;
4187
4188 ts = (dual_timestamp) {
4189 .monotonic = le64toh(o->entry.monotonic),
4190 .realtime = le64toh(o->entry.realtime),
4191 };
4192 boot_id = o->entry.boot_id;
4193
4194 n = journal_file_entry_n_items(from, o);
4195 if (n == 0)
4196 return 0;
4197
4198 if (n < ALLOCA_MAX / sizeof(EntryItem) / 2)
4199 items = newa(EntryItem, n);
4200 else {
4201 items_alloc = new(EntryItem, n);
4202 if (!items_alloc)
4203 return -ENOMEM;
4204
4205 items = items_alloc;
4206 }
4207
4208 for (uint64_t i = 0; i < n; i++) {
4209 uint64_t h, q;
4210 void *data;
4211 size_t l;
4212 Object *u;
4213
4214 q = journal_file_entry_item_object_offset(from, o, i);
4215 r = journal_file_data_payload(from, NULL, q, NULL, 0, 0, &data, &l);
4216 if (IN_SET(r, -EADDRNOTAVAIL, -EBADMSG)) {
4217 log_debug_errno(r, "Entry item %"PRIu64" data object is bad, skipping over it: %m", i);
4218 goto next;
4219 }
4220 if (r < 0)
4221 return r;
4222 assert(r > 0);
4223
4224 if (l == 0)
4225 return -EBADMSG;
4226
4227 r = journal_file_append_data(to, data, l, &u, &h);
4228 if (r < 0)
4229 return r;
4230
4231 if (JOURNAL_HEADER_KEYED_HASH(to->header))
4232 xor_hash ^= jenkins_hash64(data, l);
4233 else
4234 xor_hash ^= le64toh(u->data.hash);
4235
4236 items[m++] = (EntryItem) {
4237 .object_offset = h,
4238 .hash = le64toh(u->data.hash),
4239 };
4240
4241 next:
4242 /* The above journal_file_data_payload() may clear or overwrite cached object. Hence, we need
4243 * to re-read the object from the cache. */
4244 r = journal_file_move_to_object(from, OBJECT_ENTRY, p, &o);
4245 if (r < 0)
4246 return r;
4247 }
4248
4249 if (m == 0)
4250 return 0;
4251
4252 r = journal_file_append_entry_internal(
4253 to,
4254 &ts,
4255 &boot_id,
4256 &from->header->machine_id,
4257 xor_hash,
4258 items,
4259 m,
4260 seqnum,
4261 seqnum_id,
4262 /* ret_object= */ NULL,
4263 /* ret_offset= */ NULL);
4264
4265 if (mmap_cache_fd_got_sigbus(to->cache_fd))
4266 return -EIO;
4267
4268 return r;
4269 }
4270
4271 void journal_reset_metrics(JournalMetrics *m) {
4272 assert(m);
4273
4274 /* Set everything to "pick automatic values". */
4275
4276 *m = (JournalMetrics) {
4277 .min_use = UINT64_MAX,
4278 .max_use = UINT64_MAX,
4279 .min_size = UINT64_MAX,
4280 .max_size = UINT64_MAX,
4281 .keep_free = UINT64_MAX,
4282 .n_max_files = UINT64_MAX,
4283 };
4284 }
4285
4286 int journal_file_get_cutoff_realtime_usec(JournalFile *f, usec_t *ret_from, usec_t *ret_to) {
4287 assert(f);
4288 assert(f->header);
4289 assert(ret_from || ret_to);
4290
4291 if (ret_from) {
4292 if (f->header->head_entry_realtime == 0)
4293 return -ENOENT;
4294
4295 *ret_from = le64toh(f->header->head_entry_realtime);
4296 }
4297
4298 if (ret_to) {
4299 if (f->header->tail_entry_realtime == 0)
4300 return -ENOENT;
4301
4302 *ret_to = le64toh(f->header->tail_entry_realtime);
4303 }
4304
4305 return 1;
4306 }
4307
4308 int journal_file_get_cutoff_monotonic_usec(JournalFile *f, sd_id128_t boot_id, usec_t *ret_from, usec_t *ret_to) {
4309 Object *o;
4310 uint64_t p;
4311 int r;
4312
4313 assert(f);
4314 assert(ret_from || ret_to);
4315
4316 /* FIXME: fix return value assignment on success with 0. */
4317
4318 r = find_data_object_by_boot_id(f, boot_id, &o, &p);
4319 if (r <= 0)
4320 return r;
4321
4322 if (le64toh(o->data.n_entries) <= 0)
4323 return 0;
4324
4325 if (ret_from) {
4326 r = journal_file_move_to_object(f, OBJECT_ENTRY, le64toh(o->data.entry_offset), &o);
4327 if (r < 0)
4328 return r;
4329
4330 *ret_from = le64toh(o->entry.monotonic);
4331 }
4332
4333 if (ret_to) {
4334 r = journal_file_move_to_object(f, OBJECT_DATA, p, &o);
4335 if (r < 0)
4336 return r;
4337
4338 r = generic_array_get_plus_one(f,
4339 le64toh(o->data.entry_offset),
4340 le64toh(o->data.entry_array_offset),
4341 le64toh(o->data.n_entries) - 1,
4342 DIRECTION_UP,
4343 &o, NULL);
4344 if (r <= 0)
4345 return r;
4346
4347 *ret_to = le64toh(o->entry.monotonic);
4348 }
4349
4350 return 1;
4351 }
4352
4353 bool journal_file_rotate_suggested(JournalFile *f, usec_t max_file_usec, int log_level) {
4354 assert(f);
4355 assert(f->header);
4356
4357 /* If we gained new header fields we gained new features,
4358 * hence suggest a rotation */
4359 if (le64toh(f->header->header_size) < sizeof(Header)) {
4360 log_ratelimit_full(log_level, JOURNAL_LOG_RATELIMIT,
4361 "%s uses an outdated header, suggesting rotation.", f->path);
4362 return true;
4363 }
4364
4365 /* Let's check if the hash tables grew over a certain fill level (75%, borrowing this value from
4366 * Java's hash table implementation), and if so suggest a rotation. To calculate the fill level we
4367 * need the n_data field, which only exists in newer versions. */
4368
4369 if (JOURNAL_HEADER_CONTAINS(f->header, n_data))
4370 if (le64toh(f->header->n_data) * 4ULL > (le64toh(f->header->data_hash_table_size) / sizeof(HashItem)) * 3ULL) {
4371 log_ratelimit_full(
4372 log_level, JOURNAL_LOG_RATELIMIT,
4373 "Data hash table of %s has a fill level at %.1f (%"PRIu64" of %"PRIu64" items, %"PRIu64" file size, %"PRIu64" bytes per hash table item), suggesting rotation.",
4374 f->path,
4375 100.0 * (double) le64toh(f->header->n_data) / ((double) (le64toh(f->header->data_hash_table_size) / sizeof(HashItem))),
4376 le64toh(f->header->n_data),
4377 le64toh(f->header->data_hash_table_size) / sizeof(HashItem),
4378 (uint64_t) f->last_stat.st_size,
4379 f->last_stat.st_size / le64toh(f->header->n_data));
4380 return true;
4381 }
4382
4383 if (JOURNAL_HEADER_CONTAINS(f->header, n_fields))
4384 if (le64toh(f->header->n_fields) * 4ULL > (le64toh(f->header->field_hash_table_size) / sizeof(HashItem)) * 3ULL) {
4385 log_ratelimit_full(
4386 log_level, JOURNAL_LOG_RATELIMIT,
4387 "Field hash table of %s has a fill level at %.1f (%"PRIu64" of %"PRIu64" items), suggesting rotation.",
4388 f->path,
4389 100.0 * (double) le64toh(f->header->n_fields) / ((double) (le64toh(f->header->field_hash_table_size) / sizeof(HashItem))),
4390 le64toh(f->header->n_fields),
4391 le64toh(f->header->field_hash_table_size) / sizeof(HashItem));
4392 return true;
4393 }
4394
4395 /* If there are too many hash collisions somebody is most likely playing games with us. Hence, if our
4396 * longest chain is longer than some threshold, let's suggest rotation. */
4397 if (JOURNAL_HEADER_CONTAINS(f->header, data_hash_chain_depth) &&
4398 le64toh(f->header->data_hash_chain_depth) > HASH_CHAIN_DEPTH_MAX) {
4399 log_ratelimit_full(
4400 log_level, JOURNAL_LOG_RATELIMIT,
4401 "Data hash table of %s has deepest hash chain of length %" PRIu64 ", suggesting rotation.",
4402 f->path, le64toh(f->header->data_hash_chain_depth));
4403 return true;
4404 }
4405
4406 if (JOURNAL_HEADER_CONTAINS(f->header, field_hash_chain_depth) &&
4407 le64toh(f->header->field_hash_chain_depth) > HASH_CHAIN_DEPTH_MAX) {
4408 log_ratelimit_full(
4409 log_level, JOURNAL_LOG_RATELIMIT,
4410 "Field hash table of %s has deepest hash chain of length at %" PRIu64 ", suggesting rotation.",
4411 f->path, le64toh(f->header->field_hash_chain_depth));
4412 return true;
4413 }
4414
4415 /* Are the data objects properly indexed by field objects? */
4416 if (JOURNAL_HEADER_CONTAINS(f->header, n_data) &&
4417 JOURNAL_HEADER_CONTAINS(f->header, n_fields) &&
4418 le64toh(f->header->n_data) > 0 &&
4419 le64toh(f->header->n_fields) == 0) {
4420 log_ratelimit_full(
4421 log_level, JOURNAL_LOG_RATELIMIT,
4422 "Data objects of %s are not indexed by field objects, suggesting rotation.",
4423 f->path);
4424 return true;
4425 }
4426
4427 if (max_file_usec > 0) {
4428 usec_t t, h;
4429
4430 h = le64toh(f->header->head_entry_realtime);
4431 t = now(CLOCK_REALTIME);
4432
4433 if (h > 0 && t > h + max_file_usec) {
4434 log_ratelimit_full(
4435 log_level, JOURNAL_LOG_RATELIMIT,
4436 "Oldest entry in %s is older than the configured file retention duration (%s), suggesting rotation.",
4437 f->path, FORMAT_TIMESPAN(max_file_usec, USEC_PER_SEC));
4438 return true;
4439 }
4440 }
4441
4442 return false;
4443 }
4444
4445 static const char * const journal_object_type_table[] = {
4446 [OBJECT_UNUSED] = "unused",
4447 [OBJECT_DATA] = "data",
4448 [OBJECT_FIELD] = "field",
4449 [OBJECT_ENTRY] = "entry",
4450 [OBJECT_DATA_HASH_TABLE] = "data hash table",
4451 [OBJECT_FIELD_HASH_TABLE] = "field hash table",
4452 [OBJECT_ENTRY_ARRAY] = "entry array",
4453 [OBJECT_TAG] = "tag",
4454 };
4455
4456 DEFINE_STRING_TABLE_LOOKUP_TO_STRING(journal_object_type, ObjectType);