journal.c revision 1.8 1 /* $NetBSD: journal.c,v 1.8 2021/04/29 17:26:11 christos Exp $ */
2
3 /*
4 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
5 *
6 * This Source Code Form is subject to the terms of the Mozilla Public
7 * License, v. 2.0. If a copy of the MPL was not distributed with this
8 * file, you can obtain one at https://mozilla.org/MPL/2.0/.
9 *
10 * See the COPYRIGHT file distributed with this work for additional
11 * information regarding copyright ownership.
12 */
13
14 #include <errno.h>
15 #include <inttypes.h>
16 #include <stdbool.h>
17 #include <stdlib.h>
18 #include <unistd.h>
19
20 #include <isc/file.h>
21 #include <isc/mem.h>
22 #include <isc/print.h>
23 #include <isc/serial.h>
24 #include <isc/stdio.h>
25 #include <isc/string.h>
26 #include <isc/util.h>
27
28 #include <dns/compress.h>
29 #include <dns/db.h>
30 #include <dns/dbiterator.h>
31 #include <dns/diff.h>
32 #include <dns/fixedname.h>
33 #include <dns/journal.h>
34 #include <dns/log.h>
35 #include <dns/rdataset.h>
36 #include <dns/rdatasetiter.h>
37 #include <dns/result.h>
38 #include <dns/soa.h>
39
40 /*! \file
41 * \brief Journaling.
42 *
43 * A journal file consists of
44 *
45 * \li A fixed-size header of type journal_rawheader_t.
46 *
47 * \li The index. This is an unordered array of index entries
48 * of type journal_rawpos_t giving the locations
49 * of some arbitrary subset of the journal's addressable
50 * transactions. The index entries are used as hints to
51 * speed up the process of locating a transaction with a given
52 * serial number. Unused index entries have an "offset"
53 * field of zero. The size of the index can vary between
54 * journal files, but does not change during the lifetime
55 * of a file. The size can be zero.
56 *
57 * \li The journal data. This consists of one or more transactions.
58 * Each transaction begins with a transaction header of type
59 * journal_rawxhdr_t. The transaction header is followed by a
60 * sequence of RRs, similar in structure to an IXFR difference
61 * sequence (RFC1995). That is, the pre-transaction SOA,
62 * zero or more other deleted RRs, the post-transaction SOA,
63 * and zero or more other added RRs. Unlike in IXFR, each RR
64 * is prefixed with a 32-bit length.
65 *
66 * The journal data part grows as new transactions are
67 * appended to the file. Only those transactions
68 * whose serial number is current-(2^31-1) to current
69 * are considered "addressable" and may be pointed
70 * to from the header or index. They may be preceded
71 * by old transactions that are no longer addressable,
72 * and they may be followed by transactions that were
73 * appended to the journal but never committed by updating
74 * the "end" position in the header. The latter will
75 * be overwritten when new transactions are added.
76 */
77
78 /**************************************************************************/
79 /*
80 * Miscellaneous utilities.
81 */
82
83 #define JOURNAL_COMMON_LOGARGS \
84 dns_lctx, DNS_LOGCATEGORY_GENERAL, DNS_LOGMODULE_JOURNAL
85
86 #define JOURNAL_DEBUG_LOGARGS(n) JOURNAL_COMMON_LOGARGS, ISC_LOG_DEBUG(n)
87
88 /*%
89 * It would be non-sensical (or at least obtuse) to use FAIL() with an
90 * ISC_R_SUCCESS code, but the test is there to keep the Solaris compiler
91 * from complaining about "end-of-loop code not reached".
92 */
93 #define FAIL(code) \
94 do { \
95 result = (code); \
96 if (result != ISC_R_SUCCESS) \
97 goto failure; \
98 } while (0)
99
100 #define CHECK(op) \
101 do { \
102 result = (op); \
103 if (result != ISC_R_SUCCESS) \
104 goto failure; \
105 } while (0)
106
107 #define JOURNAL_SERIALSET 0x01U
108
109 static isc_result_t
110 index_to_disk(dns_journal_t *);
111
112 static inline uint32_t
113 decode_uint32(unsigned char *p) {
114 return ((p[0] << 24) + (p[1] << 16) + (p[2] << 8) + (p[3] << 0));
115 }
116
117 static inline void
118 encode_uint32(uint32_t val, unsigned char *p) {
119 p[0] = (uint8_t)(val >> 24);
120 p[1] = (uint8_t)(val >> 16);
121 p[2] = (uint8_t)(val >> 8);
122 p[3] = (uint8_t)(val >> 0);
123 }
124
125 isc_result_t
126 dns_db_createsoatuple(dns_db_t *db, dns_dbversion_t *ver, isc_mem_t *mctx,
127 dns_diffop_t op, dns_difftuple_t **tp) {
128 isc_result_t result;
129 dns_dbnode_t *node;
130 dns_rdataset_t rdataset;
131 dns_rdata_t rdata = DNS_RDATA_INIT;
132 dns_fixedname_t fixed;
133 dns_name_t *zonename;
134
135 zonename = dns_fixedname_initname(&fixed);
136 dns_name_copynf(dns_db_origin(db), zonename);
137
138 node = NULL;
139 result = dns_db_findnode(db, zonename, false, &node);
140 if (result != ISC_R_SUCCESS) {
141 goto nonode;
142 }
143
144 dns_rdataset_init(&rdataset);
145 result = dns_db_findrdataset(db, node, ver, dns_rdatatype_soa, 0,
146 (isc_stdtime_t)0, &rdataset, NULL);
147 if (result != ISC_R_SUCCESS) {
148 goto freenode;
149 }
150
151 result = dns_rdataset_first(&rdataset);
152 if (result != ISC_R_SUCCESS) {
153 goto freenode;
154 }
155
156 dns_rdataset_current(&rdataset, &rdata);
157 dns_rdataset_getownercase(&rdataset, zonename);
158
159 result = dns_difftuple_create(mctx, op, zonename, rdataset.ttl, &rdata,
160 tp);
161
162 dns_rdataset_disassociate(&rdataset);
163 dns_db_detachnode(db, &node);
164 return (result);
165
166 freenode:
167 dns_db_detachnode(db, &node);
168 nonode:
169 UNEXPECTED_ERROR(__FILE__, __LINE__, "missing SOA");
170 return (result);
171 }
172
173 /* Journaling */
174
175 /*%
176 * On-disk representation of a "pointer" to a journal entry.
177 * These are used in the journal header to locate the beginning
178 * and end of the journal, and in the journal index to locate
179 * other transactions.
180 */
181 typedef struct {
182 unsigned char serial[4]; /*%< SOA serial before update. */
183 /*
184 * XXXRTH Should offset be 8 bytes?
185 * XXXDCL ... probably, since isc_offset_t is 8 bytes on many OSs.
186 * XXXAG ... but we will not be able to seek >2G anyway on many
187 * platforms as long as we are using fseek() rather
188 * than lseek().
189 */
190 unsigned char offset[4]; /*%< Offset from beginning of file. */
191 } journal_rawpos_t;
192
193 /*%
194 * The header is of a fixed size, with some spare room for future
195 * extensions.
196 */
197 #define JOURNAL_HEADER_SIZE 64 /* Bytes. */
198
199 typedef enum {
200 XHDR_VERSION1 = 1,
201 XHDR_VERSION2 = 2,
202 } xhdr_version_t;
203
204 /*%
205 * The on-disk representation of the journal header.
206 * All numbers are stored in big-endian order.
207 */
208 typedef union {
209 struct {
210 /*% File format version ID. */
211 unsigned char format[16];
212 /*% Position of the first addressable transaction */
213 journal_rawpos_t begin;
214 /*% Position of the next (yet nonexistent) transaction. */
215 journal_rawpos_t end;
216 /*% Number of index entries following the header. */
217 unsigned char index_size[4];
218 /*% Source serial number. */
219 unsigned char sourceserial[4];
220 unsigned char flags;
221 } h;
222 /* Pad the header to a fixed size. */
223 unsigned char pad[JOURNAL_HEADER_SIZE];
224 } journal_rawheader_t;
225
226 /*%
227 * The on-disk representation of the transaction header, version 2.
228 * There is one of these at the beginning of each transaction.
229 */
230 typedef struct {
231 unsigned char size[4]; /*%< In bytes, excluding header. */
232 unsigned char count[4]; /*%< Number of records in transaction */
233 unsigned char serial0[4]; /*%< SOA serial before update. */
234 unsigned char serial1[4]; /*%< SOA serial after update. */
235 } journal_rawxhdr_t;
236
237 /*%
238 * Old-style raw transaction header, version 1, used for backward
239 * compatibility mode.
240 */
241 typedef struct {
242 unsigned char size[4];
243 unsigned char serial0[4];
244 unsigned char serial1[4];
245 } journal_rawxhdr_ver1_t;
246
247 /*%
248 * The on-disk representation of the RR header.
249 * There is one of these at the beginning of each RR.
250 */
251 typedef struct {
252 unsigned char size[4]; /*%< In bytes, excluding header. */
253 } journal_rawrrhdr_t;
254
255 /*%
256 * The in-core representation of the journal header.
257 */
258 typedef struct {
259 uint32_t serial;
260 isc_offset_t offset;
261 } journal_pos_t;
262
263 #define POS_VALID(pos) ((pos).offset != 0)
264 #define POS_INVALIDATE(pos) ((pos).offset = 0, (pos).serial = 0)
265
266 typedef struct {
267 unsigned char format[16];
268 journal_pos_t begin;
269 journal_pos_t end;
270 uint32_t index_size;
271 uint32_t sourceserial;
272 bool serialset;
273 } journal_header_t;
274
275 /*%
276 * The in-core representation of the transaction header.
277 */
278 typedef struct {
279 uint32_t size;
280 uint32_t count;
281 uint32_t serial0;
282 uint32_t serial1;
283 } journal_xhdr_t;
284
285 /*%
286 * The in-core representation of the RR header.
287 */
288 typedef struct {
289 uint32_t size;
290 } journal_rrhdr_t;
291
292 /*%
293 * Initial contents to store in the header of a newly created
294 * journal file.
295 *
296 * The header starts with the magic string ";BIND LOG V9.2\n"
297 * to identify the file as a BIND 9 journal file. An ASCII
298 * identification string is used rather than a binary magic
299 * number to be consistent with BIND 8 (BIND 8 journal files
300 * are ASCII text files).
301 */
302
303 static journal_header_t journal_header_ver1 = {
304 ";BIND LOG V9\n", { 0, 0 }, { 0, 0 }, 0, 0, 0
305 };
306 static journal_header_t initial_journal_header = {
307 ";BIND LOG V9.2\n", { 0, 0 }, { 0, 0 }, 0, 0, 0
308 };
309
310 #define JOURNAL_EMPTY(h) ((h)->begin.offset == (h)->end.offset)
311
312 typedef enum {
313 JOURNAL_STATE_INVALID,
314 JOURNAL_STATE_READ,
315 JOURNAL_STATE_WRITE,
316 JOURNAL_STATE_TRANSACTION,
317 JOURNAL_STATE_INLINE
318 } journal_state_t;
319
320 struct dns_journal {
321 unsigned int magic; /*%< JOUR */
322 isc_mem_t *mctx; /*%< Memory context */
323 journal_state_t state;
324 xhdr_version_t xhdr_version; /*%< Expected transaction header version */
325 bool header_ver1; /*%< Transaction header compatibility
326 * mode is allowed */
327 bool recovered; /*%< A recoverable error was found
328 * while reading the journal */
329 char *filename; /*%< Journal file name */
330 FILE *fp; /*%< File handle */
331 isc_offset_t offset; /*%< Current file offset */
332 journal_xhdr_t curxhdr; /*%< Current transaction header */
333 journal_header_t header; /*%< In-core journal header */
334 unsigned char *rawindex; /*%< In-core buffer for journal index
335 * in on-disk format */
336 journal_pos_t *index; /*%< In-core journal index */
337
338 /*% Current transaction state (when writing). */
339 struct {
340 unsigned int n_soa; /*%< Number of SOAs seen */
341 unsigned int n_rr; /*%< Number of RRs to write */
342 journal_pos_t pos[2]; /*%< Begin/end position */
343 } x;
344
345 /*% Iteration state (when reading). */
346 struct {
347 /* These define the part of the journal we iterate over. */
348 journal_pos_t bpos; /*%< Position before first, */
349 journal_pos_t cpos; /*%< before current, */
350 journal_pos_t epos; /*%< and after last transaction */
351 /* The rest is iterator state. */
352 uint32_t current_serial; /*%< Current SOA serial */
353 isc_buffer_t source; /*%< Data from disk */
354 isc_buffer_t target; /*%< Data from _fromwire check */
355 dns_decompress_t dctx; /*%< Dummy decompression ctx */
356 dns_name_t name; /*%< Current domain name */
357 dns_rdata_t rdata; /*%< Current rdata */
358 uint32_t ttl; /*%< Current TTL */
359 unsigned int xsize; /*%< Size of transaction data */
360 unsigned int xpos; /*%< Current position in it */
361 isc_result_t result; /*%< Result of last call */
362 } it;
363 };
364
365 #define DNS_JOURNAL_MAGIC ISC_MAGIC('J', 'O', 'U', 'R')
366 #define DNS_JOURNAL_VALID(t) ISC_MAGIC_VALID(t, DNS_JOURNAL_MAGIC)
367
368 static void
369 journal_pos_decode(journal_rawpos_t *raw, journal_pos_t *cooked) {
370 cooked->serial = decode_uint32(raw->serial);
371 cooked->offset = decode_uint32(raw->offset);
372 }
373
374 static void
375 journal_pos_encode(journal_rawpos_t *raw, journal_pos_t *cooked) {
376 encode_uint32(cooked->serial, raw->serial);
377 encode_uint32(cooked->offset, raw->offset);
378 }
379
380 static void
381 journal_header_decode(journal_rawheader_t *raw, journal_header_t *cooked) {
382 INSIST(sizeof(cooked->format) == sizeof(raw->h.format));
383
384 memmove(cooked->format, raw->h.format, sizeof(cooked->format));
385 journal_pos_decode(&raw->h.begin, &cooked->begin);
386 journal_pos_decode(&raw->h.end, &cooked->end);
387 cooked->index_size = decode_uint32(raw->h.index_size);
388 cooked->sourceserial = decode_uint32(raw->h.sourceserial);
389 cooked->serialset = ((raw->h.flags & JOURNAL_SERIALSET) != 0);
390 }
391
392 static void
393 journal_header_encode(journal_header_t *cooked, journal_rawheader_t *raw) {
394 unsigned char flags = 0;
395
396 INSIST(sizeof(cooked->format) == sizeof(raw->h.format));
397
398 memset(raw->pad, 0, sizeof(raw->pad));
399 memmove(raw->h.format, cooked->format, sizeof(raw->h.format));
400 journal_pos_encode(&raw->h.begin, &cooked->begin);
401 journal_pos_encode(&raw->h.end, &cooked->end);
402 encode_uint32(cooked->index_size, raw->h.index_size);
403 encode_uint32(cooked->sourceserial, raw->h.sourceserial);
404 if (cooked->serialset) {
405 flags |= JOURNAL_SERIALSET;
406 }
407 raw->h.flags = flags;
408 }
409
410 /*
411 * Journal file I/O subroutines, with error checking and reporting.
412 */
413 static isc_result_t
414 journal_seek(dns_journal_t *j, uint32_t offset) {
415 isc_result_t result;
416
417 result = isc_stdio_seek(j->fp, (off_t)offset, SEEK_SET);
418 if (result != ISC_R_SUCCESS) {
419 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
420 "%s: seek: %s", j->filename,
421 isc_result_totext(result));
422 return (ISC_R_UNEXPECTED);
423 }
424 j->offset = offset;
425 return (ISC_R_SUCCESS);
426 }
427
428 static isc_result_t
429 journal_read(dns_journal_t *j, void *mem, size_t nbytes) {
430 isc_result_t result;
431
432 result = isc_stdio_read(mem, 1, nbytes, j->fp, NULL);
433 if (result != ISC_R_SUCCESS) {
434 if (result == ISC_R_EOF) {
435 return (ISC_R_NOMORE);
436 }
437 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
438 "%s: read: %s", j->filename,
439 isc_result_totext(result));
440 return (ISC_R_UNEXPECTED);
441 }
442 j->offset += (isc_offset_t)nbytes;
443 return (ISC_R_SUCCESS);
444 }
445
446 static isc_result_t
447 journal_write(dns_journal_t *j, void *mem, size_t nbytes) {
448 isc_result_t result;
449
450 result = isc_stdio_write(mem, 1, nbytes, j->fp, NULL);
451 if (result != ISC_R_SUCCESS) {
452 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
453 "%s: write: %s", j->filename,
454 isc_result_totext(result));
455 return (ISC_R_UNEXPECTED);
456 }
457 j->offset += (isc_offset_t)nbytes;
458 return (ISC_R_SUCCESS);
459 }
460
461 static isc_result_t
462 journal_fsync(dns_journal_t *j) {
463 isc_result_t result;
464
465 result = isc_stdio_flush(j->fp);
466 if (result != ISC_R_SUCCESS) {
467 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
468 "%s: flush: %s", j->filename,
469 isc_result_totext(result));
470 return (ISC_R_UNEXPECTED);
471 }
472 result = isc_stdio_sync(j->fp);
473 if (result != ISC_R_SUCCESS) {
474 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
475 "%s: fsync: %s", j->filename,
476 isc_result_totext(result));
477 return (ISC_R_UNEXPECTED);
478 }
479 return (ISC_R_SUCCESS);
480 }
481
482 /*
483 * Read/write a transaction header at the current file position.
484 */
485 static isc_result_t
486 journal_read_xhdr(dns_journal_t *j, journal_xhdr_t *xhdr) {
487 isc_result_t result;
488
489 j->it.cpos.offset = j->offset;
490
491 switch (j->xhdr_version) {
492 case XHDR_VERSION1: {
493 journal_rawxhdr_ver1_t raw;
494 result = journal_read(j, &raw, sizeof(raw));
495 if (result != ISC_R_SUCCESS) {
496 return (result);
497 }
498 xhdr->size = decode_uint32(raw.size);
499 xhdr->count = 0;
500 xhdr->serial0 = decode_uint32(raw.serial0);
501 xhdr->serial1 = decode_uint32(raw.serial1);
502 j->curxhdr = *xhdr;
503 return (ISC_R_SUCCESS);
504 }
505
506 case XHDR_VERSION2: {
507 journal_rawxhdr_t raw;
508 result = journal_read(j, &raw, sizeof(raw));
509 if (result != ISC_R_SUCCESS) {
510 return (result);
511 }
512 xhdr->size = decode_uint32(raw.size);
513 xhdr->count = decode_uint32(raw.count);
514 xhdr->serial0 = decode_uint32(raw.serial0);
515 xhdr->serial1 = decode_uint32(raw.serial1);
516 j->curxhdr = *xhdr;
517 return (ISC_R_SUCCESS);
518 }
519
520 default:
521 return (ISC_R_NOTIMPLEMENTED);
522 }
523 }
524
525 static isc_result_t
526 journal_write_xhdr(dns_journal_t *j, uint32_t size, uint32_t count,
527 uint32_t serial0, uint32_t serial1) {
528 if (j->header_ver1) {
529 journal_rawxhdr_ver1_t raw;
530 encode_uint32(size, raw.size);
531 encode_uint32(serial0, raw.serial0);
532 encode_uint32(serial1, raw.serial1);
533 return (journal_write(j, &raw, sizeof(raw)));
534 } else {
535 journal_rawxhdr_t raw;
536 encode_uint32(size, raw.size);
537 encode_uint32(count, raw.count);
538 encode_uint32(serial0, raw.serial0);
539 encode_uint32(serial1, raw.serial1);
540 return (journal_write(j, &raw, sizeof(raw)));
541 }
542 }
543
544 /*
545 * Read an RR header at the current file position.
546 */
547
548 static isc_result_t
549 journal_read_rrhdr(dns_journal_t *j, journal_rrhdr_t *rrhdr) {
550 journal_rawrrhdr_t raw;
551 isc_result_t result;
552
553 result = journal_read(j, &raw, sizeof(raw));
554 if (result != ISC_R_SUCCESS) {
555 return (result);
556 }
557 rrhdr->size = decode_uint32(raw.size);
558 return (ISC_R_SUCCESS);
559 }
560
561 static isc_result_t
562 journal_file_create(isc_mem_t *mctx, bool downgrade, const char *filename) {
563 FILE *fp = NULL;
564 isc_result_t result;
565 journal_header_t header;
566 journal_rawheader_t rawheader;
567 int index_size = 56; /* XXX configurable */
568 int size;
569 void *mem = NULL; /* Memory for temporary index image. */
570
571 INSIST(sizeof(journal_rawheader_t) == JOURNAL_HEADER_SIZE);
572
573 result = isc_stdio_open(filename, "wb", &fp);
574 if (result != ISC_R_SUCCESS) {
575 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
576 "%s: create: %s", filename,
577 isc_result_totext(result));
578 return (ISC_R_UNEXPECTED);
579 }
580
581 if (downgrade) {
582 header = journal_header_ver1;
583 } else {
584 header = initial_journal_header;
585 }
586 header.index_size = index_size;
587 journal_header_encode(&header, &rawheader);
588
589 size = sizeof(journal_rawheader_t) +
590 index_size * sizeof(journal_rawpos_t);
591
592 mem = isc_mem_get(mctx, size);
593 memset(mem, 0, size);
594 memmove(mem, &rawheader, sizeof(rawheader));
595
596 result = isc_stdio_write(mem, 1, (size_t)size, fp, NULL);
597 if (result != ISC_R_SUCCESS) {
598 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
599 "%s: write: %s", filename,
600 isc_result_totext(result));
601 (void)isc_stdio_close(fp);
602 (void)isc_file_remove(filename);
603 isc_mem_put(mctx, mem, size);
604 return (ISC_R_UNEXPECTED);
605 }
606 isc_mem_put(mctx, mem, size);
607
608 result = isc_stdio_close(fp);
609 if (result != ISC_R_SUCCESS) {
610 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
611 "%s: close: %s", filename,
612 isc_result_totext(result));
613 (void)isc_file_remove(filename);
614 return (ISC_R_UNEXPECTED);
615 }
616
617 return (ISC_R_SUCCESS);
618 }
619
620 static isc_result_t
621 journal_open(isc_mem_t *mctx, const char *filename, bool writable, bool create,
622 bool downgrade, dns_journal_t **journalp) {
623 FILE *fp = NULL;
624 isc_result_t result;
625 journal_rawheader_t rawheader;
626 dns_journal_t *j;
627
628 REQUIRE(journalp != NULL && *journalp == NULL);
629
630 j = isc_mem_get(mctx, sizeof(*j));
631 *j = (dns_journal_t){ .state = JOURNAL_STATE_INVALID,
632 .filename = isc_mem_strdup(mctx, filename),
633 .xhdr_version = XHDR_VERSION2 };
634 isc_mem_attach(mctx, &j->mctx);
635
636 result = isc_stdio_open(j->filename, writable ? "rb+" : "rb", &fp);
637 if (result == ISC_R_FILENOTFOUND) {
638 if (create) {
639 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_DEBUG(1),
640 "journal file %s does not exist, "
641 "creating it",
642 j->filename);
643 CHECK(journal_file_create(mctx, downgrade, filename));
644 /*
645 * Retry.
646 */
647 result = isc_stdio_open(j->filename, "rb+", &fp);
648 } else {
649 FAIL(ISC_R_NOTFOUND);
650 }
651 }
652 if (result != ISC_R_SUCCESS) {
653 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
654 "%s: open: %s", j->filename,
655 isc_result_totext(result));
656 FAIL(ISC_R_UNEXPECTED);
657 }
658
659 j->fp = fp;
660
661 /*
662 * Set magic early so that seek/read can succeed.
663 */
664 j->magic = DNS_JOURNAL_MAGIC;
665
666 CHECK(journal_seek(j, 0));
667 CHECK(journal_read(j, &rawheader, sizeof(rawheader)));
668
669 if (memcmp(rawheader.h.format, journal_header_ver1.format,
670 sizeof(journal_header_ver1.format)) == 0)
671 {
672 /*
673 * The file header says it's the old format, but it
674 * still might have the new xhdr format because we
675 * forgot to change the format string when we introduced
676 * the new xhdr. When we first try to read it, we assume
677 * it uses the new xhdr format. If that fails, we'll be
678 * called a second time with compat set to true, in which
679 * case we can lower xhdr_version to 1 if we find a
680 * corrupt transaction.
681 */
682 j->header_ver1 = true;
683 } else if (memcmp(rawheader.h.format, initial_journal_header.format,
684 sizeof(initial_journal_header.format)) == 0)
685 {
686 /*
687 * File header says this is format version 2; all
688 * transactions have to match.
689 */
690 j->header_ver1 = false;
691 } else {
692 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
693 "%s: journal format not recognized", j->filename);
694 FAIL(ISC_R_UNEXPECTED);
695 }
696 journal_header_decode(&rawheader, &j->header);
697
698 /*
699 * If there is an index, read the raw index into a dynamically
700 * allocated buffer and then convert it into a cooked index.
701 */
702 if (j->header.index_size != 0) {
703 unsigned int i;
704 unsigned int rawbytes;
705 unsigned char *p;
706
707 rawbytes = j->header.index_size * sizeof(journal_rawpos_t);
708 j->rawindex = isc_mem_get(mctx, rawbytes);
709
710 CHECK(journal_read(j, j->rawindex, rawbytes));
711
712 j->index = isc_mem_get(mctx, j->header.index_size *
713 sizeof(journal_pos_t));
714
715 p = j->rawindex;
716 for (i = 0; i < j->header.index_size; i++) {
717 j->index[i].serial = decode_uint32(p);
718 p += 4;
719 j->index[i].offset = decode_uint32(p);
720 p += 4;
721 }
722 INSIST(p == j->rawindex + rawbytes);
723 }
724 j->offset = -1; /* Invalid, must seek explicitly. */
725
726 /*
727 * Initialize the iterator.
728 */
729 dns_name_init(&j->it.name, NULL);
730 dns_rdata_init(&j->it.rdata);
731
732 /*
733 * Set up empty initial buffers for unchecked and checked
734 * wire format RR data. They will be reallocated
735 * later.
736 */
737 isc_buffer_init(&j->it.source, NULL, 0);
738 isc_buffer_init(&j->it.target, NULL, 0);
739 dns_decompress_init(&j->it.dctx, -1, DNS_DECOMPRESS_NONE);
740
741 j->state = writable ? JOURNAL_STATE_WRITE : JOURNAL_STATE_READ;
742
743 *journalp = j;
744 return (ISC_R_SUCCESS);
745
746 failure:
747 j->magic = 0;
748 if (j->rawindex != NULL) {
749 isc_mem_put(j->mctx, j->rawindex,
750 j->header.index_size * sizeof(journal_rawpos_t));
751 }
752 if (j->index != NULL) {
753 isc_mem_put(j->mctx, j->index,
754 j->header.index_size * sizeof(journal_pos_t));
755 }
756 isc_mem_free(j->mctx, j->filename);
757 if (j->fp != NULL) {
758 (void)isc_stdio_close(j->fp);
759 }
760 isc_mem_putanddetach(&j->mctx, j, sizeof(*j));
761 return (result);
762 }
763
764 isc_result_t
765 dns_journal_open(isc_mem_t *mctx, const char *filename, unsigned int mode,
766 dns_journal_t **journalp) {
767 isc_result_t result;
768 size_t namelen;
769 char backup[1024];
770 bool writable, create;
771
772 create = ((mode & DNS_JOURNAL_CREATE) != 0);
773 writable = ((mode & (DNS_JOURNAL_WRITE | DNS_JOURNAL_CREATE)) != 0);
774
775 result = journal_open(mctx, filename, writable, create, false,
776 journalp);
777 if (result == ISC_R_NOTFOUND) {
778 namelen = strlen(filename);
779 if (namelen > 4U && strcmp(filename + namelen - 4, ".jnl") == 0)
780 {
781 namelen -= 4;
782 }
783
784 result = snprintf(backup, sizeof(backup), "%.*s.jbk",
785 (int)namelen, filename);
786 if (result >= sizeof(backup)) {
787 return (ISC_R_NOSPACE);
788 }
789 result = journal_open(mctx, backup, writable, writable, false,
790 journalp);
791 }
792 return (result);
793 }
794
795 /*
796 * A comparison function defining the sorting order for
797 * entries in the IXFR-style journal file.
798 *
799 * The IXFR format requires that deletions are sorted before
800 * additions, and within either one, SOA records are sorted
801 * before others.
802 *
803 * Also sort the non-SOA records by type as a courtesy to the
804 * server receiving the IXFR - it may help reduce the amount of
805 * rdataset merging it has to do.
806 */
807 static int
808 ixfr_order(const void *av, const void *bv) {
809 dns_difftuple_t const *const *ap = av;
810 dns_difftuple_t const *const *bp = bv;
811 dns_difftuple_t const *a = *ap;
812 dns_difftuple_t const *b = *bp;
813 int r;
814 int bop = 0, aop = 0;
815
816 switch (a->op) {
817 case DNS_DIFFOP_DEL:
818 case DNS_DIFFOP_DELRESIGN:
819 aop = 1;
820 break;
821 case DNS_DIFFOP_ADD:
822 case DNS_DIFFOP_ADDRESIGN:
823 aop = 0;
824 break;
825 default:
826 INSIST(0);
827 ISC_UNREACHABLE();
828 }
829
830 switch (b->op) {
831 case DNS_DIFFOP_DEL:
832 case DNS_DIFFOP_DELRESIGN:
833 bop = 1;
834 break;
835 case DNS_DIFFOP_ADD:
836 case DNS_DIFFOP_ADDRESIGN:
837 bop = 0;
838 break;
839 default:
840 INSIST(0);
841 ISC_UNREACHABLE();
842 }
843
844 r = bop - aop;
845 if (r != 0) {
846 return (r);
847 }
848
849 r = (b->rdata.type == dns_rdatatype_soa) -
850 (a->rdata.type == dns_rdatatype_soa);
851 if (r != 0) {
852 return (r);
853 }
854
855 r = (a->rdata.type - b->rdata.type);
856 return (r);
857 }
858
859 /*
860 * Advance '*pos' to the next journal transaction.
861 *
862 * Requires:
863 * *pos refers to a valid journal transaction.
864 *
865 * Ensures:
866 * When ISC_R_SUCCESS is returned,
867 * *pos refers to the next journal transaction.
868 *
869 * Returns one of:
870 *
871 * ISC_R_SUCCESS
872 * ISC_R_NOMORE *pos pointed at the last transaction
873 * Other results due to file errors are possible.
874 */
875 static isc_result_t
876 journal_next(dns_journal_t *j, journal_pos_t *pos, bool retry) {
877 isc_result_t result;
878 journal_xhdr_t xhdr;
879 size_t hdrsize;
880
881 REQUIRE(DNS_JOURNAL_VALID(j));
882
883 result = journal_seek(j, pos->offset);
884 if (result != ISC_R_SUCCESS) {
885 return (result);
886 }
887
888 if (pos->serial == j->header.end.serial) {
889 return (ISC_R_NOMORE);
890 }
891
892 /*
893 * Read the header of the current transaction.
894 * This will return ISC_R_NOMORE if we are at EOF.
895 */
896 result = journal_read_xhdr(j, &xhdr);
897 if (result != ISC_R_SUCCESS) {
898 return (result);
899 }
900
901 /*
902 * Check serial number consistency.
903 */
904 if (xhdr.serial0 != pos->serial ||
905 isc_serial_le(xhdr.serial1, xhdr.serial0)) {
906 if (j->header_ver1 && j->xhdr_version == XHDR_VERSION1 &&
907 xhdr.serial1 == pos->serial && !retry)
908 {
909 /* XHDR_VERSION1 -> XHDR_VERSION2 */
910 isc_log_write(
911 JOURNAL_COMMON_LOGARGS, ISC_LOG_DEBUG(3),
912 "%s: XHDR_VERSION1 -> XHDR_VERSION2 at %u",
913 j->filename, pos->serial);
914 j->xhdr_version = XHDR_VERSION2;
915 result = journal_next(j, pos, true);
916 if (result == ISC_R_SUCCESS) {
917 j->recovered = true;
918 }
919 return (result);
920 } else if (j->header_ver1 && j->xhdr_version == XHDR_VERSION2 &&
921 xhdr.count == pos->serial && !retry)
922 {
923 /* XHDR_VERSION2 -> XHDR_VERSION1 */
924 isc_log_write(
925 JOURNAL_COMMON_LOGARGS, ISC_LOG_DEBUG(3),
926 "%s: XHDR_VERSION2 -> XHDR_VERSION1 at %u",
927 j->filename, pos->serial);
928 j->xhdr_version = XHDR_VERSION1;
929 result = journal_next(j, pos, true);
930 if (result == ISC_R_SUCCESS) {
931 j->recovered = true;
932 }
933 return (result);
934 } else {
935 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
936 "%s: journal file corrupt: "
937 "expected serial %u, got %u",
938 j->filename, pos->serial, xhdr.serial0);
939 return (ISC_R_UNEXPECTED);
940 }
941 }
942
943 /*
944 * Check for offset wraparound.
945 */
946 hdrsize = (j->xhdr_version == XHDR_VERSION2)
947 ? sizeof(journal_rawxhdr_t)
948 : sizeof(journal_rawxhdr_ver1_t);
949
950 /*
951 * Handle <size, serial0, serial1, 0> transaction header.
952 */
953 if (j->header_ver1 && j->xhdr_version == XHDR_VERSION1) {
954 uint32_t value;
955
956 CHECK(journal_read(j, &value, sizeof(value)));
957 if (value != 0L) {
958 CHECK(journal_seek(j, pos->offset + 12));
959 } else {
960 j->recovered = true;
961 hdrsize += 4;
962 }
963 } else if (j->header_ver1 && j->xhdr_version == XHDR_VERSION2 &&
964 xhdr.count == pos->serial && xhdr.serial1 == 0U &&
965 isc_serial_ge(xhdr.serial0, xhdr.count))
966 {
967 xhdr.serial1 = xhdr.serial0;
968 xhdr.serial0 = xhdr.count;
969 xhdr.count = 0;
970 j->recovered = true;
971 }
972
973 if ((isc_offset_t)(pos->offset + hdrsize + xhdr.size) < pos->offset) {
974 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
975 "%s: offset too large", j->filename);
976 return (ISC_R_UNEXPECTED);
977 }
978
979 pos->offset += hdrsize + xhdr.size;
980 pos->serial = xhdr.serial1;
981 return (ISC_R_SUCCESS);
982
983 failure:
984 return (result);
985 }
986
987 /*
988 * If the index of the journal 'j' contains an entry "better"
989 * than '*best_guess', replace '*best_guess' with it.
990 *
991 * "Better" means having a serial number closer to 'serial'
992 * but not greater than 'serial'.
993 */
994 static void
995 index_find(dns_journal_t *j, uint32_t serial, journal_pos_t *best_guess) {
996 unsigned int i;
997 if (j->index == NULL) {
998 return;
999 }
1000 for (i = 0; i < j->header.index_size; i++) {
1001 if (POS_VALID(j->index[i]) &&
1002 DNS_SERIAL_GE(serial, j->index[i].serial) &&
1003 DNS_SERIAL_GT(j->index[i].serial, best_guess->serial))
1004 {
1005 *best_guess = j->index[i];
1006 }
1007 }
1008 }
1009
1010 /*
1011 * Add a new index entry. If there is no room, make room by removing
1012 * the odd-numbered entries and compacting the others into the first
1013 * half of the index. This decimates old index entries exponentially
1014 * over time, so that the index always contains a much larger fraction
1015 * of recent serial numbers than of old ones. This is deliberate -
1016 * most index searches are for outgoing IXFR, and IXFR tends to request
1017 * recent versions more often than old ones.
1018 */
1019 static void
1020 index_add(dns_journal_t *j, journal_pos_t *pos) {
1021 unsigned int i;
1022
1023 if (j->index == NULL) {
1024 return;
1025 }
1026
1027 /*
1028 * Search for a vacant position.
1029 */
1030 for (i = 0; i < j->header.index_size; i++) {
1031 if (!POS_VALID(j->index[i])) {
1032 break;
1033 }
1034 }
1035 if (i == j->header.index_size) {
1036 unsigned int k = 0;
1037 /*
1038 * Found no vacant position. Make some room.
1039 */
1040 for (i = 0; i < j->header.index_size; i += 2) {
1041 j->index[k++] = j->index[i];
1042 }
1043 i = k; /* 'i' identifies the first vacant position. */
1044 while (k < j->header.index_size) {
1045 POS_INVALIDATE(j->index[k]);
1046 k++;
1047 }
1048 }
1049 INSIST(i < j->header.index_size);
1050 INSIST(!POS_VALID(j->index[i]));
1051
1052 /*
1053 * Store the new index entry.
1054 */
1055 j->index[i] = *pos;
1056 }
1057
1058 /*
1059 * Invalidate any existing index entries that could become
1060 * ambiguous when a new transaction with number 'serial' is added.
1061 */
1062 static void
1063 index_invalidate(dns_journal_t *j, uint32_t serial) {
1064 unsigned int i;
1065 if (j->index == NULL) {
1066 return;
1067 }
1068 for (i = 0; i < j->header.index_size; i++) {
1069 if (!DNS_SERIAL_GT(serial, j->index[i].serial)) {
1070 POS_INVALIDATE(j->index[i]);
1071 }
1072 }
1073 }
1074
1075 /*
1076 * Try to find a transaction with initial serial number 'serial'
1077 * in the journal 'j'.
1078 *
1079 * If found, store its position at '*pos' and return ISC_R_SUCCESS.
1080 *
1081 * If 'serial' is current (= the ending serial number of the
1082 * last transaction in the journal), set '*pos' to
1083 * the position immediately following the last transaction and
1084 * return ISC_R_SUCCESS.
1085 *
1086 * If 'serial' is within the range of addressable serial numbers
1087 * covered by the journal but that particular serial number is missing
1088 * (from the journal, not just from the index), return ISC_R_NOTFOUND.
1089 *
1090 * If 'serial' is outside the range of addressable serial numbers
1091 * covered by the journal, return ISC_R_RANGE.
1092 *
1093 */
1094 static isc_result_t
1095 journal_find(dns_journal_t *j, uint32_t serial, journal_pos_t *pos) {
1096 isc_result_t result;
1097 journal_pos_t current_pos;
1098
1099 REQUIRE(DNS_JOURNAL_VALID(j));
1100
1101 if (DNS_SERIAL_GT(j->header.begin.serial, serial)) {
1102 return (ISC_R_RANGE);
1103 }
1104 if (DNS_SERIAL_GT(serial, j->header.end.serial)) {
1105 return (ISC_R_RANGE);
1106 }
1107 if (serial == j->header.end.serial) {
1108 *pos = j->header.end;
1109 return (ISC_R_SUCCESS);
1110 }
1111
1112 current_pos = j->header.begin;
1113 index_find(j, serial, ¤t_pos);
1114
1115 while (current_pos.serial != serial) {
1116 if (DNS_SERIAL_GT(current_pos.serial, serial)) {
1117 return (ISC_R_NOTFOUND);
1118 }
1119 result = journal_next(j, ¤t_pos, false);
1120 if (result != ISC_R_SUCCESS) {
1121 return (result);
1122 }
1123 }
1124 *pos = current_pos;
1125 return (ISC_R_SUCCESS);
1126 }
1127
1128 isc_result_t
1129 dns_journal_begin_transaction(dns_journal_t *j) {
1130 uint32_t offset;
1131 isc_result_t result;
1132
1133 REQUIRE(DNS_JOURNAL_VALID(j));
1134 REQUIRE(j->state == JOURNAL_STATE_WRITE ||
1135 j->state == JOURNAL_STATE_INLINE);
1136
1137 /*
1138 * Find the file offset where the new transaction should
1139 * be written, and seek there.
1140 */
1141 if (JOURNAL_EMPTY(&j->header)) {
1142 offset = sizeof(journal_rawheader_t) +
1143 j->header.index_size * sizeof(journal_rawpos_t);
1144 } else {
1145 offset = j->header.end.offset;
1146 }
1147 j->x.pos[0].offset = offset;
1148 j->x.pos[1].offset = offset; /* Initial value, will be incremented. */
1149 j->x.n_soa = 0;
1150
1151 CHECK(journal_seek(j, offset));
1152
1153 /*
1154 * Write a dummy transaction header of all zeroes to reserve
1155 * space. It will be filled in when the transaction is
1156 * finished.
1157 */
1158 CHECK(journal_write_xhdr(j, 0, 0, 0, 0));
1159 j->x.pos[1].offset = j->offset;
1160
1161 j->state = JOURNAL_STATE_TRANSACTION;
1162 result = ISC_R_SUCCESS;
1163 failure:
1164 return (result);
1165 }
1166
1167 isc_result_t
1168 dns_journal_writediff(dns_journal_t *j, dns_diff_t *diff) {
1169 dns_difftuple_t *t;
1170 isc_buffer_t buffer;
1171 void *mem = NULL;
1172 uint64_t size = 0;
1173 uint32_t rrcount = 0;
1174 isc_result_t result;
1175 isc_region_t used;
1176
1177 REQUIRE(DNS_DIFF_VALID(diff));
1178 REQUIRE(j->state == JOURNAL_STATE_TRANSACTION);
1179
1180 isc_log_write(JOURNAL_DEBUG_LOGARGS(3), "writing to journal");
1181 (void)dns_diff_print(diff, NULL);
1182
1183 /*
1184 * Pass 1: determine the buffer size needed, and
1185 * keep track of SOA serial numbers.
1186 */
1187 for (t = ISC_LIST_HEAD(diff->tuples); t != NULL;
1188 t = ISC_LIST_NEXT(t, link)) {
1189 if (t->rdata.type == dns_rdatatype_soa) {
1190 if (j->x.n_soa < 2) {
1191 j->x.pos[j->x.n_soa].serial =
1192 dns_soa_getserial(&t->rdata);
1193 }
1194 j->x.n_soa++;
1195 }
1196 size += sizeof(journal_rawrrhdr_t);
1197 size += t->name.length; /* XXX should have access macro? */
1198 size += 10;
1199 size += t->rdata.length;
1200 }
1201
1202 if (size >= DNS_JOURNAL_SIZE_MAX) {
1203 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1204 "dns_journal_writediff: %s: journal entry "
1205 "too big to be stored: %" PRIu64 " bytes",
1206 j->filename, size);
1207 return (ISC_R_NOSPACE);
1208 }
1209
1210 mem = isc_mem_get(j->mctx, size);
1211
1212 isc_buffer_init(&buffer, mem, size);
1213
1214 /*
1215 * Pass 2. Write RRs to buffer.
1216 */
1217 for (t = ISC_LIST_HEAD(diff->tuples); t != NULL;
1218 t = ISC_LIST_NEXT(t, link)) {
1219 /*
1220 * Write the RR header.
1221 */
1222 isc_buffer_putuint32(&buffer,
1223 t->name.length + 10 + t->rdata.length);
1224 /*
1225 * Write the owner name, RR header, and RR data.
1226 */
1227 isc_buffer_putmem(&buffer, t->name.ndata, t->name.length);
1228 isc_buffer_putuint16(&buffer, t->rdata.type);
1229 isc_buffer_putuint16(&buffer, t->rdata.rdclass);
1230 isc_buffer_putuint32(&buffer, t->ttl);
1231 INSIST(t->rdata.length < 65536);
1232 isc_buffer_putuint16(&buffer, (uint16_t)t->rdata.length);
1233 INSIST(isc_buffer_availablelength(&buffer) >= t->rdata.length);
1234 isc_buffer_putmem(&buffer, t->rdata.data, t->rdata.length);
1235
1236 rrcount++;
1237 }
1238
1239 isc_buffer_usedregion(&buffer, &used);
1240 INSIST(used.length == size);
1241
1242 j->x.pos[1].offset += used.length;
1243 j->x.n_rr = rrcount;
1244
1245 /*
1246 * Write the buffer contents to the journal file.
1247 */
1248 CHECK(journal_write(j, used.base, used.length));
1249
1250 result = ISC_R_SUCCESS;
1251
1252 failure:
1253 if (mem != NULL) {
1254 isc_mem_put(j->mctx, mem, size);
1255 }
1256 return (result);
1257 }
1258
1259 isc_result_t
1260 dns_journal_commit(dns_journal_t *j) {
1261 isc_result_t result;
1262 journal_rawheader_t rawheader;
1263 uint64_t total;
1264
1265 REQUIRE(DNS_JOURNAL_VALID(j));
1266 REQUIRE(j->state == JOURNAL_STATE_TRANSACTION ||
1267 j->state == JOURNAL_STATE_INLINE);
1268
1269 /*
1270 * Just write out a updated header.
1271 */
1272 if (j->state == JOURNAL_STATE_INLINE) {
1273 CHECK(journal_fsync(j));
1274 journal_header_encode(&j->header, &rawheader);
1275 CHECK(journal_seek(j, 0));
1276 CHECK(journal_write(j, &rawheader, sizeof(rawheader)));
1277 CHECK(journal_fsync(j));
1278 j->state = JOURNAL_STATE_WRITE;
1279 return (ISC_R_SUCCESS);
1280 }
1281
1282 /*
1283 * Perform some basic consistency checks.
1284 */
1285 if (j->x.n_soa != 2) {
1286 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1287 "%s: malformed transaction: %d SOAs", j->filename,
1288 j->x.n_soa);
1289 return (ISC_R_UNEXPECTED);
1290 }
1291 if (!DNS_SERIAL_GT(j->x.pos[1].serial, j->x.pos[0].serial)) {
1292 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1293 "%s: malformed transaction: serial number "
1294 "did not increase",
1295 j->filename);
1296 return (ISC_R_UNEXPECTED);
1297 }
1298 if (!JOURNAL_EMPTY(&j->header)) {
1299 if (j->x.pos[0].serial != j->header.end.serial) {
1300 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1301 "malformed transaction: "
1302 "%s last serial %u != "
1303 "transaction first serial %u",
1304 j->filename, j->header.end.serial,
1305 j->x.pos[0].serial);
1306 return (ISC_R_UNEXPECTED);
1307 }
1308 }
1309
1310 /*
1311 * We currently don't support huge journal entries.
1312 */
1313 total = j->x.pos[1].offset - j->x.pos[0].offset;
1314 if (total >= DNS_JOURNAL_SIZE_MAX) {
1315 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1316 "transaction too big to be stored in journal: "
1317 "%" PRIu64 "b (max is %" PRIu64 "b)",
1318 total, (uint64_t)DNS_JOURNAL_SIZE_MAX);
1319 return (ISC_R_UNEXPECTED);
1320 }
1321
1322 /*
1323 * Some old journal entries may become non-addressable
1324 * when we increment the current serial number. Purge them
1325 * by stepping header.begin forward to the first addressable
1326 * transaction. Also purge them from the index.
1327 */
1328 if (!JOURNAL_EMPTY(&j->header)) {
1329 while (!DNS_SERIAL_GT(j->x.pos[1].serial,
1330 j->header.begin.serial)) {
1331 CHECK(journal_next(j, &j->header.begin, false));
1332 }
1333 index_invalidate(j, j->x.pos[1].serial);
1334 }
1335 #ifdef notyet
1336 if (DNS_SERIAL_GT(last_dumped_serial, j->x.pos[1].serial)) {
1337 force_dump(...);
1338 }
1339 #endif /* ifdef notyet */
1340
1341 /*
1342 * Commit the transaction data to stable storage.
1343 */
1344 CHECK(journal_fsync(j));
1345
1346 if (j->state == JOURNAL_STATE_TRANSACTION) {
1347 isc_offset_t offset;
1348 offset = (j->x.pos[1].offset - j->x.pos[0].offset) -
1349 (j->header_ver1 ? sizeof(journal_rawxhdr_ver1_t)
1350 : sizeof(journal_rawxhdr_t));
1351 /*
1352 * Update the transaction header.
1353 */
1354 CHECK(journal_seek(j, j->x.pos[0].offset));
1355 CHECK(journal_write_xhdr(j, offset, j->x.n_rr,
1356 j->x.pos[0].serial,
1357 j->x.pos[1].serial));
1358 }
1359
1360 /*
1361 * Update the journal header.
1362 */
1363 if (JOURNAL_EMPTY(&j->header)) {
1364 j->header.begin = j->x.pos[0];
1365 }
1366 j->header.end = j->x.pos[1];
1367 journal_header_encode(&j->header, &rawheader);
1368 CHECK(journal_seek(j, 0));
1369 CHECK(journal_write(j, &rawheader, sizeof(rawheader)));
1370
1371 /*
1372 * Update the index.
1373 */
1374 index_add(j, &j->x.pos[0]);
1375
1376 /*
1377 * Convert the index into on-disk format and write
1378 * it to disk.
1379 */
1380 CHECK(index_to_disk(j));
1381
1382 /*
1383 * Commit the header to stable storage.
1384 */
1385 CHECK(journal_fsync(j));
1386
1387 /*
1388 * We no longer have a transaction open.
1389 */
1390 j->state = JOURNAL_STATE_WRITE;
1391
1392 result = ISC_R_SUCCESS;
1393
1394 failure:
1395 return (result);
1396 }
1397
1398 isc_result_t
1399 dns_journal_write_transaction(dns_journal_t *j, dns_diff_t *diff) {
1400 isc_result_t result;
1401
1402 CHECK(dns_diff_sort(diff, ixfr_order));
1403 CHECK(dns_journal_begin_transaction(j));
1404 CHECK(dns_journal_writediff(j, diff));
1405 CHECK(dns_journal_commit(j));
1406 result = ISC_R_SUCCESS;
1407 failure:
1408 return (result);
1409 }
1410
1411 void
1412 dns_journal_destroy(dns_journal_t **journalp) {
1413 dns_journal_t *j = NULL;
1414
1415 REQUIRE(journalp != NULL);
1416 REQUIRE(DNS_JOURNAL_VALID(*journalp));
1417
1418 j = *journalp;
1419 *journalp = NULL;
1420
1421 j->it.result = ISC_R_FAILURE;
1422 dns_name_invalidate(&j->it.name);
1423 dns_decompress_invalidate(&j->it.dctx);
1424 if (j->rawindex != NULL) {
1425 isc_mem_put(j->mctx, j->rawindex,
1426 j->header.index_size * sizeof(journal_rawpos_t));
1427 }
1428 if (j->index != NULL) {
1429 isc_mem_put(j->mctx, j->index,
1430 j->header.index_size * sizeof(journal_pos_t));
1431 }
1432 if (j->it.target.base != NULL) {
1433 isc_mem_put(j->mctx, j->it.target.base, j->it.target.length);
1434 }
1435 if (j->it.source.base != NULL) {
1436 isc_mem_put(j->mctx, j->it.source.base, j->it.source.length);
1437 }
1438 if (j->filename != NULL) {
1439 isc_mem_free(j->mctx, j->filename);
1440 }
1441 if (j->fp != NULL) {
1442 (void)isc_stdio_close(j->fp);
1443 }
1444 j->magic = 0;
1445 isc_mem_putanddetach(&j->mctx, j, sizeof(*j));
1446 }
1447
1448 /*
1449 * Roll the open journal 'j' into the database 'db'.
1450 * A new database version will be created.
1451 */
1452
1453 /* XXX Share code with incoming IXFR? */
1454
1455 isc_result_t
1456 dns_journal_rollforward(dns_journal_t *j, dns_db_t *db, unsigned int options) {
1457 isc_buffer_t source; /* Transaction data from disk */
1458 isc_buffer_t target; /* Ditto after _fromwire check */
1459 uint32_t db_serial; /* Database SOA serial */
1460 uint32_t end_serial; /* Last journal SOA serial */
1461 isc_result_t result;
1462 dns_dbversion_t *ver = NULL;
1463 journal_pos_t pos;
1464 dns_diff_t diff;
1465 unsigned int n_soa = 0;
1466 unsigned int n_put = 0;
1467 dns_diffop_t op;
1468
1469 REQUIRE(DNS_JOURNAL_VALID(j));
1470 REQUIRE(DNS_DB_VALID(db));
1471
1472 dns_diff_init(j->mctx, &diff);
1473
1474 /*
1475 * Set up empty initial buffers for unchecked and checked
1476 * wire format transaction data. They will be reallocated
1477 * later.
1478 */
1479 isc_buffer_init(&source, NULL, 0);
1480 isc_buffer_init(&target, NULL, 0);
1481
1482 /*
1483 * Create the new database version.
1484 */
1485 CHECK(dns_db_newversion(db, &ver));
1486
1487 /*
1488 * Get the current database SOA serial number.
1489 */
1490 CHECK(dns_db_getsoaserial(db, ver, &db_serial));
1491
1492 /*
1493 * Locate a journal entry for the current database serial.
1494 */
1495 CHECK(journal_find(j, db_serial, &pos));
1496
1497 end_serial = dns_journal_last_serial(j);
1498
1499 /*
1500 * If we're reading a version 1 file, scan all the transactions
1501 * to see if the journal needs rewriting: if any outdated
1502 * transaction headers are found, j->recovered will be set.
1503 */
1504 if (j->header_ver1) {
1505 uint32_t start_serial = dns_journal_first_serial(j);
1506
1507 CHECK(dns_journal_iter_init(j, start_serial, db_serial, NULL));
1508 for (result = dns_journal_first_rr(j); result == ISC_R_SUCCESS;
1509 result = dns_journal_next_rr(j))
1510 {
1511 continue;
1512 }
1513 }
1514
1515 if (db_serial == end_serial) {
1516 CHECK(DNS_R_UPTODATE);
1517 }
1518
1519 CHECK(dns_journal_iter_init(j, db_serial, end_serial, NULL));
1520 for (result = dns_journal_first_rr(j); result == ISC_R_SUCCESS;
1521 result = dns_journal_next_rr(j))
1522 {
1523 dns_name_t *name = NULL;
1524 dns_rdata_t *rdata = NULL;
1525 dns_difftuple_t *tuple = NULL;
1526 uint32_t ttl;
1527
1528 dns_journal_current_rr(j, &name, &ttl, &rdata);
1529
1530 if (rdata->type == dns_rdatatype_soa) {
1531 n_soa++;
1532 if (n_soa == 2) {
1533 db_serial = j->it.current_serial;
1534 }
1535 }
1536
1537 if (n_soa == 3) {
1538 n_soa = 1;
1539 }
1540 if (n_soa == 0) {
1541 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1542 "%s: journal file corrupt: missing "
1543 "initial SOA",
1544 j->filename);
1545 FAIL(ISC_R_UNEXPECTED);
1546 }
1547 if ((options & DNS_JOURNALOPT_RESIGN) != 0) {
1548 op = (n_soa == 1) ? DNS_DIFFOP_DELRESIGN
1549 : DNS_DIFFOP_ADDRESIGN;
1550 } else {
1551 op = (n_soa == 1) ? DNS_DIFFOP_DEL : DNS_DIFFOP_ADD;
1552 }
1553
1554 CHECK(dns_difftuple_create(diff.mctx, op, name, ttl, rdata,
1555 &tuple));
1556 dns_diff_append(&diff, &tuple);
1557
1558 if (++n_put > 100) {
1559 isc_log_write(JOURNAL_DEBUG_LOGARGS(3),
1560 "%s: applying diff to database (%u)",
1561 j->filename, db_serial);
1562 (void)dns_diff_print(&diff, NULL);
1563 CHECK(dns_diff_apply(&diff, db, ver));
1564 dns_diff_clear(&diff);
1565 n_put = 0;
1566 }
1567 }
1568 if (result == ISC_R_NOMORE) {
1569 result = ISC_R_SUCCESS;
1570 }
1571 CHECK(result);
1572
1573 if (n_put != 0) {
1574 isc_log_write(JOURNAL_DEBUG_LOGARGS(3),
1575 "%s: applying final diff to database (%u)",
1576 j->filename, db_serial);
1577 (void)dns_diff_print(&diff, NULL);
1578 CHECK(dns_diff_apply(&diff, db, ver));
1579 dns_diff_clear(&diff);
1580 }
1581
1582 failure:
1583 if (ver != NULL) {
1584 dns_db_closeversion(db, &ver,
1585 result == ISC_R_SUCCESS ? true : false);
1586 }
1587
1588 if (source.base != NULL) {
1589 isc_mem_put(j->mctx, source.base, source.length);
1590 }
1591 if (target.base != NULL) {
1592 isc_mem_put(j->mctx, target.base, target.length);
1593 }
1594
1595 dns_diff_clear(&diff);
1596
1597 INSIST(ver == NULL);
1598
1599 return (result);
1600 }
1601
1602 isc_result_t
1603 dns_journal_print(isc_mem_t *mctx, uint32_t flags, const char *filename,
1604 FILE *file) {
1605 dns_journal_t *j = NULL;
1606 isc_buffer_t source; /* Transaction data from disk */
1607 isc_buffer_t target; /* Ditto after _fromwire check */
1608 uint32_t start_serial; /* Database SOA serial */
1609 uint32_t end_serial; /* Last journal SOA serial */
1610 isc_result_t result;
1611 dns_diff_t diff;
1612 unsigned int n_soa = 0;
1613 unsigned int n_put = 0;
1614 bool printxhdr = ((flags & DNS_JOURNAL_PRINTXHDR) != 0);
1615
1616 REQUIRE(filename != NULL);
1617
1618 result = dns_journal_open(mctx, filename, DNS_JOURNAL_READ, &j);
1619 if (result == ISC_R_NOTFOUND) {
1620 isc_log_write(JOURNAL_DEBUG_LOGARGS(3), "no journal file");
1621 return (DNS_R_NOJOURNAL);
1622 } else if (result != ISC_R_SUCCESS) {
1623 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1624 "journal open failure: %s: %s",
1625 isc_result_totext(result), filename);
1626 return (result);
1627 }
1628
1629 if (printxhdr) {
1630 fprintf(file, "Journal format = %sHeader version = %d\n",
1631 j->header.format + 1, j->header_ver1 ? 1 : 2);
1632 fprintf(file, "Start serial = %u\n", j->header.begin.serial);
1633 fprintf(file, "End serial = %u\n", j->header.end.serial);
1634 fprintf(file, "Index (size = %u):\n", j->header.index_size);
1635 for (uint32_t i = 0; i < j->header.index_size; i++) {
1636 if (j->index[i].offset == 0) {
1637 fputc('\n', file);
1638 break;
1639 }
1640 fprintf(file, "%lld", (long long)j->index[i].offset);
1641 fputc((i + 1) % 8 == 0 ? '\n' : ' ', file);
1642 }
1643 }
1644 if (j->header.serialset) {
1645 fprintf(file, "Source serial = %u\n", j->header.sourceserial);
1646 }
1647 dns_diff_init(j->mctx, &diff);
1648
1649 /*
1650 * Set up empty initial buffers for unchecked and checked
1651 * wire format transaction data. They will be reallocated
1652 * later.
1653 */
1654 isc_buffer_init(&source, NULL, 0);
1655 isc_buffer_init(&target, NULL, 0);
1656
1657 start_serial = dns_journal_first_serial(j);
1658 end_serial = dns_journal_last_serial(j);
1659
1660 CHECK(dns_journal_iter_init(j, start_serial, end_serial, NULL));
1661
1662 for (result = dns_journal_first_rr(j); result == ISC_R_SUCCESS;
1663 result = dns_journal_next_rr(j))
1664 {
1665 dns_name_t *name = NULL;
1666 dns_rdata_t *rdata = NULL;
1667 dns_difftuple_t *tuple = NULL;
1668 static uint32_t i = 0;
1669 bool print = false;
1670 uint32_t ttl;
1671
1672 dns_journal_current_rr(j, &name, &ttl, &rdata);
1673
1674 if (rdata->type == dns_rdatatype_soa) {
1675 n_soa++;
1676 if (n_soa == 3) {
1677 n_soa = 1;
1678 }
1679 if (n_soa == 1) {
1680 print = printxhdr;
1681 }
1682 }
1683 if (n_soa == 0) {
1684 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1685 "%s: journal file corrupt: missing "
1686 "initial SOA",
1687 j->filename);
1688 FAIL(ISC_R_UNEXPECTED);
1689 }
1690
1691 if (print) {
1692 fprintf(file,
1693 "Transaction: version %d offset %lld size %u "
1694 "rrcount %u start %u end %u\n",
1695 j->xhdr_version, (long long)j->it.cpos.offset,
1696 j->curxhdr.size, j->curxhdr.count,
1697 j->curxhdr.serial0, j->curxhdr.serial1);
1698 if (j->it.cpos.offset > j->index[i].offset) {
1699 fprintf(file,
1700 "ERROR: Offset mismatch, "
1701 "expected %lld\n",
1702 (long long)j->index[i].offset);
1703 } else if (j->it.cpos.offset == j->index[i].offset) {
1704 i++;
1705 }
1706 }
1707 CHECK(dns_difftuple_create(
1708 diff.mctx, n_soa == 1 ? DNS_DIFFOP_DEL : DNS_DIFFOP_ADD,
1709 name, ttl, rdata, &tuple));
1710 dns_diff_append(&diff, &tuple);
1711
1712 if (++n_put > 100 || printxhdr) {
1713 result = dns_diff_print(&diff, file);
1714 dns_diff_clear(&diff);
1715 n_put = 0;
1716 if (result != ISC_R_SUCCESS) {
1717 break;
1718 }
1719 }
1720 }
1721 if (result == ISC_R_NOMORE) {
1722 result = ISC_R_SUCCESS;
1723 }
1724 CHECK(result);
1725
1726 if (n_put != 0) {
1727 result = dns_diff_print(&diff, file);
1728 dns_diff_clear(&diff);
1729 }
1730 goto cleanup;
1731
1732 failure:
1733 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1734 "%s: cannot print: journal file corrupt", j->filename);
1735
1736 cleanup:
1737 if (source.base != NULL) {
1738 isc_mem_put(j->mctx, source.base, source.length);
1739 }
1740 if (target.base != NULL) {
1741 isc_mem_put(j->mctx, target.base, target.length);
1742 }
1743
1744 dns_diff_clear(&diff);
1745 dns_journal_destroy(&j);
1746
1747 return (result);
1748 }
1749
1750 /**************************************************************************/
1751 /*
1752 * Miscellaneous accessors.
1753 */
1754 bool
1755 dns_journal_empty(dns_journal_t *j) {
1756 return (JOURNAL_EMPTY(&j->header));
1757 }
1758
1759 bool
1760 dns_journal_recovered(dns_journal_t *j) {
1761 return (j->recovered);
1762 }
1763
1764 uint32_t
1765 dns_journal_first_serial(dns_journal_t *j) {
1766 return (j->header.begin.serial);
1767 }
1768
1769 uint32_t
1770 dns_journal_last_serial(dns_journal_t *j) {
1771 return (j->header.end.serial);
1772 }
1773
1774 void
1775 dns_journal_set_sourceserial(dns_journal_t *j, uint32_t sourceserial) {
1776 REQUIRE(j->state == JOURNAL_STATE_WRITE ||
1777 j->state == JOURNAL_STATE_INLINE ||
1778 j->state == JOURNAL_STATE_TRANSACTION);
1779
1780 j->header.sourceserial = sourceserial;
1781 j->header.serialset = true;
1782 if (j->state == JOURNAL_STATE_WRITE) {
1783 j->state = JOURNAL_STATE_INLINE;
1784 }
1785 }
1786
1787 bool
1788 dns_journal_get_sourceserial(dns_journal_t *j, uint32_t *sourceserial) {
1789 REQUIRE(sourceserial != NULL);
1790
1791 if (!j->header.serialset) {
1792 return (false);
1793 }
1794 *sourceserial = j->header.sourceserial;
1795 return (true);
1796 }
1797
1798 /**************************************************************************/
1799 /*
1800 * Iteration support.
1801 *
1802 * When serving an outgoing IXFR, we transmit a part the journal starting
1803 * at the serial number in the IXFR request and ending at the serial
1804 * number that is current when the IXFR request arrives. The ending
1805 * serial number is not necessarily at the end of the journal:
1806 * the journal may grow while the IXFR is in progress, but we stop
1807 * when we reach the serial number that was current when the IXFR started.
1808 */
1809
1810 static isc_result_t
1811 read_one_rr(dns_journal_t *j, bool retry);
1812
1813 /*
1814 * Make sure the buffer 'b' is has at least 'size' bytes
1815 * allocated, and clear it.
1816 *
1817 * Requires:
1818 * Either b->base is NULL, or it points to b->length bytes of memory
1819 * previously allocated by isc_mem_get().
1820 */
1821
1822 static isc_result_t
1823 size_buffer(isc_mem_t *mctx, isc_buffer_t *b, unsigned size) {
1824 if (b->length < size) {
1825 void *mem = isc_mem_get(mctx, size);
1826 if (mem == NULL) {
1827 return (ISC_R_NOMEMORY);
1828 }
1829 if (b->base != NULL) {
1830 isc_mem_put(mctx, b->base, b->length);
1831 }
1832 b->base = mem;
1833 b->length = size;
1834 }
1835 isc_buffer_clear(b);
1836 return (ISC_R_SUCCESS);
1837 }
1838
1839 isc_result_t
1840 dns_journal_iter_init(dns_journal_t *j, uint32_t begin_serial,
1841 uint32_t end_serial, size_t *xfrsizep) {
1842 isc_result_t result;
1843
1844 CHECK(journal_find(j, begin_serial, &j->it.bpos));
1845 INSIST(j->it.bpos.serial == begin_serial);
1846
1847 CHECK(journal_find(j, end_serial, &j->it.epos));
1848 INSIST(j->it.epos.serial == end_serial);
1849
1850 if (xfrsizep != NULL) {
1851 journal_pos_t pos = j->it.bpos;
1852 journal_xhdr_t xhdr;
1853 uint64_t size = 0;
1854 uint32_t count = 0;
1855
1856 /*
1857 * We already know the beginning and ending serial
1858 * numbers are in the journal. Scan through them,
1859 * adding up sizes and RR counts so we can calculate
1860 * the IXFR size.
1861 */
1862 CHECK(journal_seek(j, pos.offset));
1863 do {
1864 CHECK(journal_read_xhdr(j, &xhdr));
1865
1866 size += xhdr.size;
1867 count += xhdr.count;
1868
1869 result = journal_next(j, &pos, false);
1870 if (result == ISC_R_NOMORE) {
1871 result = ISC_R_SUCCESS;
1872 }
1873 CHECK(result);
1874 } while (pos.serial != end_serial);
1875
1876 /*
1877 * For each RR, subtract the length of the RR header,
1878 * as this would not be present in IXFR messages.
1879 * (We don't need to worry about the transaction header
1880 * because that was already excluded from xdr.size.)
1881 */
1882 *xfrsizep = size - (count * sizeof(journal_rawrrhdr_t));
1883 }
1884
1885 result = ISC_R_SUCCESS;
1886 failure:
1887 j->it.result = result;
1888 return (j->it.result);
1889 }
1890
1891 isc_result_t
1892 dns_journal_first_rr(dns_journal_t *j) {
1893 isc_result_t result;
1894
1895 /*
1896 * Seek to the beginning of the first transaction we are
1897 * interested in.
1898 */
1899 CHECK(journal_seek(j, j->it.bpos.offset));
1900 j->it.current_serial = j->it.bpos.serial;
1901
1902 j->it.xsize = 0; /* We have no transaction data yet... */
1903 j->it.xpos = 0; /* ...and haven't used any of it. */
1904
1905 return (read_one_rr(j, false));
1906
1907 failure:
1908 return (result);
1909 }
1910
1911 static isc_result_t
1912 read_one_rr(dns_journal_t *j, bool retry) {
1913 isc_result_t result;
1914 dns_rdatatype_t rdtype;
1915 dns_rdataclass_t rdclass;
1916 unsigned int rdlen;
1917 uint32_t ttl;
1918 journal_xhdr_t xhdr;
1919 journal_rrhdr_t rrhdr;
1920 dns_journal_t save = *j;
1921
1922 if (j->offset > j->it.epos.offset) {
1923 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1924 "%s: journal corrupt: possible integer overflow",
1925 j->filename);
1926 return (ISC_R_UNEXPECTED);
1927 }
1928 if (j->offset == j->it.epos.offset) {
1929 return (ISC_R_NOMORE);
1930 }
1931 if (j->it.xpos == j->it.xsize) {
1932 /*
1933 * We are at a transaction boundary.
1934 * Read another transaction header.
1935 */
1936 CHECK(journal_read_xhdr(j, &xhdr));
1937 if (xhdr.size == 0) {
1938 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1939 "%s: journal corrupt: empty transaction",
1940 j->filename);
1941 FAIL(ISC_R_UNEXPECTED);
1942 }
1943 if (xhdr.serial0 != j->it.current_serial ||
1944 isc_serial_le(xhdr.serial1, xhdr.serial0))
1945 {
1946 if (!retry && j->header_ver1 &&
1947 j->xhdr_version == XHDR_VERSION2 &&
1948 xhdr.count == j->it.current_serial)
1949 {
1950 /* XHDR_VERSION2 -> XHDR_VERSION1 */
1951 j->xhdr_version = XHDR_VERSION1;
1952 CHECK(journal_seek(j, save.offset));
1953 result = read_one_rr(j, true);
1954 if (result == ISC_R_SUCCESS) {
1955 j->recovered = true;
1956 }
1957 return (result);
1958 } else if (!retry && j->header_ver1 &&
1959 j->xhdr_version == XHDR_VERSION1 &&
1960 xhdr.serial1 == j->it.current_serial)
1961 {
1962 /* XHDR_VERSION1 -> XHDR_VERSION2 */
1963 j->xhdr_version = XHDR_VERSION2;
1964 CHECK(journal_seek(j, save.offset));
1965 result = read_one_rr(j, true);
1966 if (result == ISC_R_SUCCESS) {
1967 j->recovered = true;
1968 }
1969 return (result);
1970 }
1971 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1972 "%s: journal file corrupt: "
1973 "expected serial %u, got %u",
1974 j->filename, j->it.current_serial,
1975 xhdr.serial0);
1976 FAIL(ISC_R_UNEXPECTED);
1977 }
1978
1979 /*
1980 * Handle <size, serial0, serial1, 0> transaction header.
1981 */
1982 if (j->header_ver1 && j->xhdr_version == XHDR_VERSION1) {
1983 uint32_t value;
1984
1985 CHECK(journal_read(j, &value, sizeof(value)));
1986 if (value != 0L) {
1987 CHECK(journal_seek(j, save.offset + 12));
1988 } else {
1989 j->recovered = true;
1990 }
1991 } else if (j->header_ver1 && j->xhdr_version == XHDR_VERSION2 &&
1992 xhdr.count == j->it.current_serial &&
1993 xhdr.serial1 == 0U &&
1994 isc_serial_ge(xhdr.serial0, xhdr.count))
1995 {
1996 xhdr.serial1 = xhdr.serial0;
1997 xhdr.serial0 = xhdr.count;
1998 xhdr.count = 0;
1999 j->recovered = true;
2000 }
2001
2002 j->it.xsize = xhdr.size;
2003 j->it.xpos = 0;
2004 }
2005 /*
2006 * Read an RR.
2007 */
2008 CHECK(journal_read_rrhdr(j, &rrhdr));
2009 /*
2010 * Perform a sanity check on the journal RR size.
2011 * The smallest possible RR has a 1-byte owner name
2012 * and a 10-byte header. The largest possible
2013 * RR has 65535 bytes of data, a header, and a maximum-
2014 * size owner name, well below 70 k total.
2015 */
2016 if (rrhdr.size < 1 + 10 || rrhdr.size > 70000) {
2017 isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
2018 "%s: journal corrupt: impossible RR size "
2019 "(%d bytes)",
2020 j->filename, rrhdr.size);
2021 FAIL(ISC_R_UNEXPECTED);
2022 }
2023
2024 CHECK(size_buffer(j->mctx, &j->it.source, rrhdr.size));
2025 CHECK(journal_read(j, j->it.source.base, rrhdr.size));
2026 isc_buffer_add(&j->it.source, rrhdr.size);
2027
2028 /*
2029 * The target buffer is made the same size
2030 * as the source buffer, with the assumption that when
2031 * no compression in present, the output of dns_*_fromwire()
2032 * is no larger than the input.
2033 */
2034 CHECK(size_buffer(j->mctx, &j->it.target, rrhdr.size));
2035
2036 /*
2037 * Parse the owner name. We don't know where it
2038 * ends yet, so we make the entire "remaining"
2039 * part of the buffer "active".
2040 */
2041 isc_buffer_setactive(&j->it.source,
2042 j->it.source.used - j->it.source.current);
2043 CHECK(dns_name_fromwire(&j->it.name, &j->it.source, &j->it.dctx, 0,
2044 &j->it.target));
2045
2046 /*
2047 * Check that the RR header is there, and parse it.
2048 */
2049 if (isc_buffer_remaininglength(&j->it.source) < 10) {
2050 FAIL(DNS_R_FORMERR);
2051 }
2052
2053 rdtype = isc_buffer_getuint16(&j->it.source);
2054 rdclass = isc_buffer_getuint16(&j->it.source);
2055 ttl = isc_buffer_getuint32(&j->it.source);
2056 rdlen = isc_buffer_getuint16(&j->it.source);
2057
2058 /*
2059 * Parse the rdata.
2060 */
2061 if (isc_buffer_remaininglength(&j->it.source) != rdlen) {
2062 FAIL(DNS_R_FORMERR);
2063 }
2064 isc_buffer_setactive(&j->it.source, rdlen);
2065 dns_rdata_reset(&j->it.rdata);
2066 CHECK(dns_rdata_fromwire(&j->it.rdata, rdclass, rdtype, &j->it.source,
2067 &j->it.dctx, 0, &j->it.target));
2068 j->it.ttl = ttl;
2069
2070 j->it.xpos += sizeof(journal_rawrrhdr_t) + rrhdr.size;
2071 if (rdtype == dns_rdatatype_soa) {
2072 /* XXX could do additional consistency checks here */
2073 j->it.current_serial = dns_soa_getserial(&j->it.rdata);
2074 }
2075
2076 result = ISC_R_SUCCESS;
2077
2078 failure:
2079 j->it.result = result;
2080 return (result);
2081 }
2082
2083 isc_result_t
2084 dns_journal_next_rr(dns_journal_t *j) {
2085 j->it.result = read_one_rr(j, false);
2086 return (j->it.result);
2087 }
2088
2089 void
2090 dns_journal_current_rr(dns_journal_t *j, dns_name_t **name, uint32_t *ttl,
2091 dns_rdata_t **rdata) {
2092 REQUIRE(j->it.result == ISC_R_SUCCESS);
2093 *name = &j->it.name;
2094 *ttl = j->it.ttl;
2095 *rdata = &j->it.rdata;
2096 }
2097
2098 /**************************************************************************/
2099 /*
2100 * Generating diffs from databases
2101 */
2102
2103 /*
2104 * Construct a diff containing all the RRs at the current name of the
2105 * database iterator 'dbit' in database 'db', version 'ver'.
2106 * Set '*name' to the current name, and append the diff to 'diff'.
2107 * All new tuples will have the operation 'op'.
2108 *
2109 * Requires: 'name' must have buffer large enough to hold the name.
2110 * Typically, a dns_fixedname_t would be used.
2111 */
2112 static isc_result_t
2113 get_name_diff(dns_db_t *db, dns_dbversion_t *ver, isc_stdtime_t now,
2114 dns_dbiterator_t *dbit, dns_name_t *name, dns_diffop_t op,
2115 dns_diff_t *diff) {
2116 isc_result_t result;
2117 dns_dbnode_t *node = NULL;
2118 dns_rdatasetiter_t *rdsiter = NULL;
2119 dns_difftuple_t *tuple = NULL;
2120
2121 result = dns_dbiterator_current(dbit, &node, name);
2122 if (result != ISC_R_SUCCESS) {
2123 return (result);
2124 }
2125
2126 result = dns_db_allrdatasets(db, node, ver, now, &rdsiter);
2127 if (result != ISC_R_SUCCESS) {
2128 goto cleanup_node;
2129 }
2130
2131 for (result = dns_rdatasetiter_first(rdsiter); result == ISC_R_SUCCESS;
2132 result = dns_rdatasetiter_next(rdsiter))
2133 {
2134 dns_rdataset_t rdataset;
2135
2136 dns_rdataset_init(&rdataset);
2137 dns_rdatasetiter_current(rdsiter, &rdataset);
2138
2139 for (result = dns_rdataset_first(&rdataset);
2140 result == ISC_R_SUCCESS;
2141 result = dns_rdataset_next(&rdataset))
2142 {
2143 dns_rdata_t rdata = DNS_RDATA_INIT;
2144 dns_rdataset_current(&rdataset, &rdata);
2145 result = dns_difftuple_create(diff->mctx, op, name,
2146 rdataset.ttl, &rdata,
2147 &tuple);
2148 if (result != ISC_R_SUCCESS) {
2149 dns_rdataset_disassociate(&rdataset);
2150 goto cleanup_iterator;
2151 }
2152 dns_diff_append(diff, &tuple);
2153 }
2154 dns_rdataset_disassociate(&rdataset);
2155 if (result != ISC_R_NOMORE) {
2156 goto cleanup_iterator;
2157 }
2158 }
2159 if (result != ISC_R_NOMORE) {
2160 goto cleanup_iterator;
2161 }
2162
2163 result = ISC_R_SUCCESS;
2164
2165 cleanup_iterator:
2166 dns_rdatasetiter_destroy(&rdsiter);
2167
2168 cleanup_node:
2169 dns_db_detachnode(db, &node);
2170
2171 return (result);
2172 }
2173
2174 /*
2175 * Comparison function for use by dns_diff_subtract when sorting
2176 * the diffs to be subtracted. The sort keys are the rdata type
2177 * and the rdata itself. The owner name is ignored, because
2178 * it is known to be the same for all tuples.
2179 */
2180 static int
2181 rdata_order(const void *av, const void *bv) {
2182 dns_difftuple_t const *const *ap = av;
2183 dns_difftuple_t const *const *bp = bv;
2184 dns_difftuple_t const *a = *ap;
2185 dns_difftuple_t const *b = *bp;
2186 int r;
2187 r = (b->rdata.type - a->rdata.type);
2188 if (r != 0) {
2189 return (r);
2190 }
2191 r = dns_rdata_compare(&a->rdata, &b->rdata);
2192 return (r);
2193 }
2194
2195 static isc_result_t
2196 dns_diff_subtract(dns_diff_t diff[2], dns_diff_t *r) {
2197 isc_result_t result;
2198 dns_difftuple_t *p[2];
2199 int i, t;
2200 bool append;
2201
2202 CHECK(dns_diff_sort(&diff[0], rdata_order));
2203 CHECK(dns_diff_sort(&diff[1], rdata_order));
2204
2205 for (;;) {
2206 p[0] = ISC_LIST_HEAD(diff[0].tuples);
2207 p[1] = ISC_LIST_HEAD(diff[1].tuples);
2208 if (p[0] == NULL && p[1] == NULL) {
2209 break;
2210 }
2211
2212 for (i = 0; i < 2; i++) {
2213 if (p[!i] == NULL) {
2214 {
2215 ISC_LIST_UNLINK(diff[i].tuples, p[i],
2216 link);
2217 ISC_LIST_APPEND(r->tuples, p[i], link);
2218 goto next;
2219 }
2220 }
2221 }
2222 t = rdata_order(&p[0], &p[1]);
2223 if (t < 0) {
2224 ISC_LIST_UNLINK(diff[0].tuples, p[0], link);
2225 ISC_LIST_APPEND(r->tuples, p[0], link);
2226 goto next;
2227 }
2228 if (t > 0) {
2229 ISC_LIST_UNLINK(diff[1].tuples, p[1], link);
2230 ISC_LIST_APPEND(r->tuples, p[1], link);
2231 goto next;
2232 }
2233 INSIST(t == 0);
2234 /*
2235 * Identical RRs in both databases; skip them both
2236 * if the ttl differs.
2237 */
2238 append = (p[0]->ttl != p[1]->ttl);
2239 for (i = 0; i < 2; i++) {
2240 ISC_LIST_UNLINK(diff[i].tuples, p[i], link);
2241 if (append) {
2242 ISC_LIST_APPEND(r->tuples, p[i], link);
2243 } else {
2244 dns_difftuple_free(&p[i]);
2245 }
2246 }
2247 next:;
2248 }
2249 result = ISC_R_SUCCESS;
2250 failure:
2251 return (result);
2252 }
2253
2254 static isc_result_t
2255 diff_namespace(dns_db_t *dba, dns_dbversion_t *dbvera, dns_db_t *dbb,
2256 dns_dbversion_t *dbverb, unsigned int options,
2257 dns_diff_t *resultdiff) {
2258 dns_db_t *db[2];
2259 dns_dbversion_t *ver[2];
2260 dns_dbiterator_t *dbit[2] = { NULL, NULL };
2261 bool have[2] = { false, false };
2262 dns_fixedname_t fixname[2];
2263 isc_result_t result, itresult[2];
2264 dns_diff_t diff[2];
2265 int i, t;
2266
2267 db[0] = dba, db[1] = dbb;
2268 ver[0] = dbvera, ver[1] = dbverb;
2269
2270 dns_diff_init(resultdiff->mctx, &diff[0]);
2271 dns_diff_init(resultdiff->mctx, &diff[1]);
2272
2273 dns_fixedname_init(&fixname[0]);
2274 dns_fixedname_init(&fixname[1]);
2275
2276 result = dns_db_createiterator(db[0], options, &dbit[0]);
2277 if (result != ISC_R_SUCCESS) {
2278 return (result);
2279 }
2280 result = dns_db_createiterator(db[1], options, &dbit[1]);
2281 if (result != ISC_R_SUCCESS) {
2282 goto cleanup_iterator;
2283 }
2284
2285 itresult[0] = dns_dbiterator_first(dbit[0]);
2286 itresult[1] = dns_dbiterator_first(dbit[1]);
2287
2288 for (;;) {
2289 for (i = 0; i < 2; i++) {
2290 if (!have[i] && itresult[i] == ISC_R_SUCCESS) {
2291 CHECK(get_name_diff(
2292 db[i], ver[i], 0, dbit[i],
2293 dns_fixedname_name(&fixname[i]),
2294 i == 0 ? DNS_DIFFOP_ADD
2295 : DNS_DIFFOP_DEL,
2296 &diff[i]));
2297 itresult[i] = dns_dbiterator_next(dbit[i]);
2298 have[i] = true;
2299 }
2300 }
2301
2302 if (!have[0] && !have[1]) {
2303 INSIST(ISC_LIST_EMPTY(diff[0].tuples));
2304 INSIST(ISC_LIST_EMPTY(diff[1].tuples));
2305 break;
2306 }
2307
2308 for (i = 0; i < 2; i++) {
2309 if (!have[!i]) {
2310 ISC_LIST_APPENDLIST(resultdiff->tuples,
2311 diff[i].tuples, link);
2312 INSIST(ISC_LIST_EMPTY(diff[i].tuples));
2313 have[i] = false;
2314 goto next;
2315 }
2316 }
2317
2318 t = dns_name_compare(dns_fixedname_name(&fixname[0]),
2319 dns_fixedname_name(&fixname[1]));
2320 if (t < 0) {
2321 ISC_LIST_APPENDLIST(resultdiff->tuples, diff[0].tuples,
2322 link);
2323 INSIST(ISC_LIST_EMPTY(diff[0].tuples));
2324 have[0] = false;
2325 continue;
2326 }
2327 if (t > 0) {
2328 ISC_LIST_APPENDLIST(resultdiff->tuples, diff[1].tuples,
2329 link);
2330 INSIST(ISC_LIST_EMPTY(diff[1].tuples));
2331 have[1] = false;
2332 continue;
2333 }
2334 INSIST(t == 0);
2335 CHECK(dns_diff_subtract(diff, resultdiff));
2336 INSIST(ISC_LIST_EMPTY(diff[0].tuples));
2337 INSIST(ISC_LIST_EMPTY(diff[1].tuples));
2338 have[0] = have[1] = false;
2339 next:;
2340 }
2341 if (itresult[0] != ISC_R_NOMORE) {
2342 FAIL(itresult[0]);
2343 }
2344 if (itresult[1] != ISC_R_NOMORE) {
2345 FAIL(itresult[1]);
2346 }
2347
2348 INSIST(ISC_LIST_EMPTY(diff[0].tuples));
2349 INSIST(ISC_LIST_EMPTY(diff[1].tuples));
2350
2351 failure:
2352 dns_dbiterator_destroy(&dbit[1]);
2353
2354 cleanup_iterator:
2355 dns_dbiterator_destroy(&dbit[0]);
2356 dns_diff_clear(&diff[0]);
2357 dns_diff_clear(&diff[1]);
2358 return (result);
2359 }
2360
2361 /*
2362 * Compare the databases 'dba' and 'dbb' and generate a journal
2363 * entry containing the changes to make 'dba' from 'dbb' (note
2364 * the order). This journal entry will consist of a single,
2365 * possibly very large transaction.
2366 */
2367 isc_result_t
2368 dns_db_diff(isc_mem_t *mctx, dns_db_t *dba, dns_dbversion_t *dbvera,
2369 dns_db_t *dbb, dns_dbversion_t *dbverb, const char *filename) {
2370 isc_result_t result;
2371 dns_diff_t diff;
2372
2373 dns_diff_init(mctx, &diff);
2374
2375 result = dns_db_diffx(&diff, dba, dbvera, dbb, dbverb, filename);
2376
2377 dns_diff_clear(&diff);
2378
2379 return (result);
2380 }
2381
2382 isc_result_t
2383 dns_db_diffx(dns_diff_t *diff, dns_db_t *dba, dns_dbversion_t *dbvera,
2384 dns_db_t *dbb, dns_dbversion_t *dbverb, const char *filename) {
2385 isc_result_t result;
2386 dns_journal_t *journal = NULL;
2387
2388 if (filename != NULL) {
2389 result = dns_journal_open(diff->mctx, filename,
2390 DNS_JOURNAL_CREATE, &journal);
2391 if (result != ISC_R_SUCCESS) {
2392 return (result);
2393 }
2394 }
2395
2396 CHECK(diff_namespace(dba, dbvera, dbb, dbverb, DNS_DB_NONSEC3, diff));
2397 CHECK(diff_namespace(dba, dbvera, dbb, dbverb, DNS_DB_NSEC3ONLY, diff));
2398
2399 if (journal != NULL) {
2400 if (ISC_LIST_EMPTY(diff->tuples)) {
2401 isc_log_write(JOURNAL_DEBUG_LOGARGS(3), "no changes");
2402 } else {
2403 CHECK(dns_journal_write_transaction(journal, diff));
2404 }
2405 }
2406
2407 failure:
2408 if (journal != NULL) {
2409 dns_journal_destroy(&journal);
2410 }
2411 return (result);
2412 }
2413
2414 static uint32_t
2415 rrcount(unsigned char *buf, unsigned int size) {
2416 isc_buffer_t b;
2417 uint32_t rrsize, count = 0;
2418
2419 isc_buffer_init(&b, buf, size);
2420 isc_buffer_add(&b, size);
2421 while (isc_buffer_remaininglength(&b) > 0) {
2422 rrsize = isc_buffer_getuint32(&b);
2423 INSIST(isc_buffer_remaininglength(&b) >= rrsize);
2424 isc_buffer_forward(&b, rrsize);
2425 count++;
2426 }
2427
2428 return (count);
2429 }
2430
2431 static bool
2432 check_delta(unsigned char *buf, size_t size) {
2433 isc_buffer_t b;
2434 uint32_t rrsize;
2435
2436 isc_buffer_init(&b, buf, size);
2437 isc_buffer_add(&b, size);
2438 while (isc_buffer_remaininglength(&b) > 0) {
2439 if (isc_buffer_remaininglength(&b) < 4) {
2440 return (false);
2441 }
2442 rrsize = isc_buffer_getuint32(&b);
2443 /* "." + type + class + ttl + rdlen => 11U */
2444 if (rrsize < 11U || isc_buffer_remaininglength(&b) < rrsize) {
2445 return (false);
2446 }
2447 isc_buffer_forward(&b, rrsize);
2448 }
2449
2450 return (true);
2451 }
2452
2453 isc_result_t
2454 dns_journal_compact(isc_mem_t *mctx, char *filename, uint32_t serial,
2455 uint32_t flags, uint32_t target_size) {
2456 unsigned int i;
2457 journal_pos_t best_guess;
2458 journal_pos_t current_pos;
2459 dns_journal_t *j1 = NULL;
2460 dns_journal_t *j2 = NULL;
2461 journal_rawheader_t rawheader;
2462 unsigned int len;
2463 size_t namelen;
2464 unsigned char *buf = NULL;
2465 unsigned int size = 0;
2466 isc_result_t result;
2467 unsigned int indexend;
2468 char newname[PATH_MAX];
2469 char backup[PATH_MAX];
2470 bool is_backup = false;
2471 bool rewrite = false;
2472 bool downgrade = false;
2473
2474 REQUIRE(filename != NULL);
2475
2476 namelen = strlen(filename);
2477 if (namelen > 4U && strcmp(filename + namelen - 4, ".jnl") == 0) {
2478 namelen -= 4;
2479 }
2480
2481 result = snprintf(newname, sizeof(newname), "%.*s.jnw", (int)namelen,
2482 filename);
2483 RUNTIME_CHECK(result < sizeof(newname));
2484
2485 result = snprintf(backup, sizeof(backup), "%.*s.jbk", (int)namelen,
2486 filename);
2487 RUNTIME_CHECK(result < sizeof(backup));
2488
2489 result = journal_open(mctx, filename, false, false, false, &j1);
2490 if (result == ISC_R_NOTFOUND) {
2491 is_backup = true;
2492 result = journal_open(mctx, backup, false, false, false, &j1);
2493 }
2494 if (result != ISC_R_SUCCESS) {
2495 return (result);
2496 }
2497
2498 /*
2499 * Check whether we need to rewrite the whole journal
2500 * file (for example, to upversion it).
2501 */
2502 if ((flags & DNS_JOURNAL_COMPACTALL) != 0) {
2503 if ((flags & DNS_JOURNAL_VERSION1) != 0) {
2504 downgrade = true;
2505 }
2506 rewrite = true;
2507 serial = dns_journal_first_serial(j1);
2508 } else if (JOURNAL_EMPTY(&j1->header)) {
2509 dns_journal_destroy(&j1);
2510 return (ISC_R_SUCCESS);
2511 }
2512
2513 if (DNS_SERIAL_GT(j1->header.begin.serial, serial) ||
2514 DNS_SERIAL_GT(serial, j1->header.end.serial))
2515 {
2516 dns_journal_destroy(&j1);
2517 return (ISC_R_RANGE);
2518 }
2519
2520 /*
2521 * Cope with very small target sizes.
2522 */
2523 indexend = sizeof(journal_rawheader_t) +
2524 j1->header.index_size * sizeof(journal_rawpos_t);
2525 if (target_size < DNS_JOURNAL_SIZE_MIN) {
2526 target_size = DNS_JOURNAL_SIZE_MIN;
2527 }
2528 if (target_size < indexend * 2) {
2529 target_size = target_size / 2 + indexend;
2530 }
2531
2532 /*
2533 * See if there is any work to do.
2534 */
2535 if (!rewrite && (uint32_t)j1->header.end.offset < target_size) {
2536 dns_journal_destroy(&j1);
2537 return (ISC_R_SUCCESS);
2538 }
2539
2540 CHECK(journal_open(mctx, newname, true, true, downgrade, &j2));
2541 CHECK(journal_seek(j2, indexend));
2542
2543 /*
2544 * Remove overhead so space test below can succeed.
2545 */
2546 if (target_size >= indexend) {
2547 target_size -= indexend;
2548 }
2549
2550 /*
2551 * Find if we can create enough free space.
2552 */
2553 best_guess = j1->header.begin;
2554 for (i = 0; i < j1->header.index_size; i++) {
2555 if (POS_VALID(j1->index[i]) &&
2556 DNS_SERIAL_GE(serial, j1->index[i].serial) &&
2557 ((uint32_t)(j1->header.end.offset - j1->index[i].offset) >=
2558 target_size / 2) &&
2559 j1->index[i].offset > best_guess.offset)
2560 {
2561 best_guess = j1->index[i];
2562 }
2563 }
2564
2565 current_pos = best_guess;
2566 while (current_pos.serial != serial) {
2567 CHECK(journal_next(j1, ¤t_pos, false));
2568 if (current_pos.serial == j1->header.end.serial) {
2569 break;
2570 }
2571
2572 if (DNS_SERIAL_GE(serial, current_pos.serial) &&
2573 ((uint32_t)(j1->header.end.offset - current_pos.offset) >=
2574 (target_size / 2)) &&
2575 current_pos.offset > best_guess.offset)
2576 {
2577 best_guess = current_pos;
2578 } else {
2579 break;
2580 }
2581 }
2582
2583 INSIST(best_guess.serial != j1->header.end.serial);
2584 if (best_guess.serial != serial) {
2585 CHECK(journal_next(j1, &best_guess, false));
2586 }
2587
2588 /*
2589 * We should now be roughly half target_size provided
2590 * we did not reach 'serial'. If not we will just copy
2591 * all uncommitted deltas regardless of the size.
2592 */
2593 len = j1->header.end.offset - best_guess.offset;
2594 if (len != 0) {
2595 CHECK(journal_seek(j1, best_guess.offset));
2596
2597 /* Prepare new header */
2598 j2->header.begin.serial = best_guess.serial;
2599 j2->header.begin.offset = indexend;
2600 j2->header.sourceserial = j1->header.sourceserial;
2601 j2->header.serialset = j1->header.serialset;
2602 j2->header.end.serial = j1->header.end.serial;
2603
2604 /*
2605 * Only use this method if we're rewriting the
2606 * journal to fix outdated transaction headers;
2607 * otherwise we'll copy the whole journal without
2608 * parsing individual deltas below.
2609 */
2610 while (rewrite && len > 0) {
2611 journal_xhdr_t xhdr;
2612 isc_offset_t offset = j1->offset;
2613 uint32_t count;
2614
2615 result = journal_read_xhdr(j1, &xhdr);
2616 if (rewrite && result == ISC_R_NOMORE) {
2617 break;
2618 }
2619 CHECK(result);
2620
2621 size = xhdr.size;
2622 buf = isc_mem_get(mctx, size);
2623 result = journal_read(j1, buf, size);
2624
2625 /*
2626 * If we're repairing an outdated journal, the
2627 * xhdr format may be wrong.
2628 */
2629 if (rewrite && (result != ISC_R_SUCCESS ||
2630 !check_delta(buf, size))) {
2631 if (j1->xhdr_version == XHDR_VERSION2) {
2632 /* XHDR_VERSION2 -> XHDR_VERSION1 */
2633 j1->xhdr_version = XHDR_VERSION1;
2634 CHECK(journal_seek(j1, offset));
2635 CHECK(journal_read_xhdr(j1, &xhdr));
2636 } else if (j1->xhdr_version == XHDR_VERSION1) {
2637 /* XHDR_VERSION1 -> XHDR_VERSION2 */
2638 j1->xhdr_version = XHDR_VERSION2;
2639 CHECK(journal_seek(j1, offset));
2640 CHECK(journal_read_xhdr(j1, &xhdr));
2641 }
2642
2643 /* Check again */
2644 isc_mem_put(mctx, buf, size);
2645 size = xhdr.size;
2646 buf = isc_mem_get(mctx, size);
2647 CHECK(journal_read(j1, buf, size));
2648
2649 if (!check_delta(buf, size)) {
2650 CHECK(ISC_R_UNEXPECTED);
2651 }
2652 } else {
2653 CHECK(result);
2654 }
2655
2656 /*
2657 * Recover from incorrectly written transaction header.
2658 * The incorrect header was written as size, serial0,
2659 * serial1, and 0. XHDR_VERSION2 is expecting size,
2660 * count, serial0, and serial1.
2661 */
2662 if (j1->xhdr_version == XHDR_VERSION2 &&
2663 xhdr.count == serial && xhdr.serial1 == 0U &&
2664 isc_serial_ge(xhdr.serial0, xhdr.count))
2665 {
2666 xhdr.serial1 = xhdr.serial0;
2667 xhdr.serial0 = xhdr.count;
2668 xhdr.count = 0;
2669 }
2670
2671 /*
2672 * Check that xhdr is consistent.
2673 */
2674 if (xhdr.serial0 != serial ||
2675 isc_serial_le(xhdr.serial1, xhdr.serial0)) {
2676 CHECK(ISC_R_UNEXPECTED);
2677 }
2678
2679 /*
2680 * Extract record count from the transaction. This
2681 * is needed when converting from XHDR_VERSION1 to
2682 * XHDR_VERSION2, and when recovering from an
2683 * incorrectly written XHDR_VERSION2.
2684 */
2685 count = rrcount(buf, size);
2686 CHECK(journal_write_xhdr(j2, xhdr.size, count,
2687 xhdr.serial0, xhdr.serial1));
2688 CHECK(journal_write(j2, buf, size));
2689
2690 j2->header.end.offset = j2->offset;
2691
2692 serial = xhdr.serial1;
2693
2694 len = j1->header.end.offset - j1->offset;
2695 isc_mem_put(mctx, buf, size);
2696 }
2697
2698 /*
2699 * If we're not rewriting transaction headers, we can use
2700 * this faster method instead.
2701 */
2702 if (!rewrite) {
2703 size = ISC_MIN(64 * 1024, len);
2704 buf = isc_mem_get(mctx, size);
2705 for (i = 0; i < len; i += size) {
2706 unsigned int blob = ISC_MIN(size, len - i);
2707 CHECK(journal_read(j1, buf, blob));
2708 CHECK(journal_write(j2, buf, blob));
2709 }
2710
2711 j2->header.end.offset = indexend + len;
2712 }
2713
2714 CHECK(journal_fsync(j2));
2715
2716 /*
2717 * Update the journal header.
2718 */
2719 journal_header_encode(&j2->header, &rawheader);
2720 CHECK(journal_seek(j2, 0));
2721 CHECK(journal_write(j2, &rawheader, sizeof(rawheader)));
2722 CHECK(journal_fsync(j2));
2723
2724 /*
2725 * Build new index.
2726 */
2727 current_pos = j2->header.begin;
2728 while (current_pos.serial != j2->header.end.serial) {
2729 index_add(j2, ¤t_pos);
2730 CHECK(journal_next(j2, ¤t_pos, false));
2731 }
2732
2733 /*
2734 * Write index.
2735 */
2736 CHECK(index_to_disk(j2));
2737 CHECK(journal_fsync(j2));
2738
2739 indexend = j2->header.end.offset;
2740 POST(indexend);
2741 }
2742
2743 /*
2744 * Close both journals before trying to rename files (this is
2745 * necessary on WIN32).
2746 */
2747 dns_journal_destroy(&j1);
2748 dns_journal_destroy(&j2);
2749
2750 /*
2751 * With a UFS file system this should just succeed and be atomic.
2752 * Any IXFR outs will just continue and the old journal will be
2753 * removed on final close.
2754 *
2755 * With MSDOS / NTFS we need to do a two stage rename, triggered
2756 * by EEXIST. (If any IXFR's are running in other threads, however,
2757 * this will fail, and the journal will not be compacted. But
2758 * if so, hopefully they'll be finished by the next time we
2759 * compact.)
2760 */
2761 if (rename(newname, filename) == -1) {
2762 if (errno == EEXIST && !is_backup) {
2763 result = isc_file_remove(backup);
2764 if (result != ISC_R_SUCCESS &&
2765 result != ISC_R_FILENOTFOUND) {
2766 goto failure;
2767 }
2768 if (rename(filename, backup) == -1) {
2769 goto maperrno;
2770 }
2771 if (rename(newname, filename) == -1) {
2772 goto maperrno;
2773 }
2774 (void)isc_file_remove(backup);
2775 } else {
2776 maperrno:
2777 result = ISC_R_FAILURE;
2778 goto failure;
2779 }
2780 }
2781
2782 result = ISC_R_SUCCESS;
2783
2784 failure:
2785 (void)isc_file_remove(newname);
2786 if (buf != NULL) {
2787 isc_mem_put(mctx, buf, size);
2788 }
2789 if (j1 != NULL) {
2790 dns_journal_destroy(&j1);
2791 }
2792 if (j2 != NULL) {
2793 dns_journal_destroy(&j2);
2794 }
2795 return (result);
2796 }
2797
2798 static isc_result_t
2799 index_to_disk(dns_journal_t *j) {
2800 isc_result_t result = ISC_R_SUCCESS;
2801
2802 if (j->header.index_size != 0) {
2803 unsigned int i;
2804 unsigned char *p;
2805 unsigned int rawbytes;
2806
2807 rawbytes = j->header.index_size * sizeof(journal_rawpos_t);
2808
2809 p = j->rawindex;
2810 for (i = 0; i < j->header.index_size; i++) {
2811 encode_uint32(j->index[i].serial, p);
2812 p += 4;
2813 encode_uint32(j->index[i].offset, p);
2814 p += 4;
2815 }
2816 INSIST(p == j->rawindex + rawbytes);
2817
2818 CHECK(journal_seek(j, sizeof(journal_rawheader_t)));
2819 CHECK(journal_write(j, j->rawindex, rawbytes));
2820 }
2821 failure:
2822 return (result);
2823 }
2824