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