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