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