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