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