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