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