Home | History | Annotate | Line # | Download | only in dns
journal.c revision 1.9
      1 /*	$NetBSD: journal.c,v 1.9 2021/08/19 11:50:17 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 static isc_result_t
    860 maybe_fixup_xhdr(dns_journal_t *j, journal_xhdr_t *xhdr, uint32_t serial,
    861 		 isc_offset_t offset) {
    862 	isc_result_t result = ISC_R_SUCCESS;
    863 
    864 	/*
    865 	 * Handle mixture of version 1 and version 2
    866 	 * transaction headers in a version 1 journal.
    867 	 */
    868 	if ((xhdr->serial0 != serial ||
    869 	     isc_serial_le(xhdr->serial1, xhdr->serial0))) {
    870 		if (j->xhdr_version == XHDR_VERSION1 && xhdr->serial1 == serial)
    871 		{
    872 			isc_log_write(
    873 				JOURNAL_COMMON_LOGARGS, ISC_LOG_DEBUG(3),
    874 				"%s: XHDR_VERSION1 -> XHDR_VERSION2 at %u",
    875 				j->filename, serial);
    876 			j->xhdr_version = XHDR_VERSION2;
    877 			CHECK(journal_seek(j, offset));
    878 			CHECK(journal_read_xhdr(j, xhdr));
    879 			j->recovered = true;
    880 		} else if (j->xhdr_version == XHDR_VERSION2 &&
    881 			   xhdr->count == serial) {
    882 			isc_log_write(
    883 				JOURNAL_COMMON_LOGARGS, ISC_LOG_DEBUG(3),
    884 				"%s: XHDR_VERSION2 -> XHDR_VERSION1 at %u",
    885 				j->filename, serial);
    886 			j->xhdr_version = XHDR_VERSION1;
    887 			CHECK(journal_seek(j, offset));
    888 			CHECK(journal_read_xhdr(j, xhdr));
    889 			j->recovered = true;
    890 		}
    891 	}
    892 
    893 	/*
    894 	 * Handle <size, serial0, serial1, 0> transaction header.
    895 	 */
    896 	if (j->xhdr_version == XHDR_VERSION1) {
    897 		uint32_t value;
    898 
    899 		CHECK(journal_read(j, &value, sizeof(value)));
    900 		if (value != 0L) {
    901 			CHECK(journal_seek(j, offset + 12));
    902 		} else {
    903 			isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_DEBUG(3),
    904 				      "%s: XHDR_VERSION1 count zero at %u",
    905 				      j->filename, serial);
    906 			j->xhdr_version = XHDR_VERSION2;
    907 			j->recovered = true;
    908 		}
    909 	} else if (j->xhdr_version == XHDR_VERSION2 && xhdr->count == serial &&
    910 		   xhdr->serial1 == 0U &&
    911 		   isc_serial_gt(xhdr->serial0, xhdr->count))
    912 	{
    913 		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_DEBUG(3),
    914 			      "%s: XHDR_VERSION2 count zero at %u", j->filename,
    915 			      serial);
    916 		xhdr->serial1 = xhdr->serial0;
    917 		xhdr->serial0 = xhdr->count;
    918 		xhdr->count = 0;
    919 		j->recovered = true;
    920 	}
    921 
    922 failure:
    923 	return (result);
    924 }
    925 
    926 /*
    927  * Advance '*pos' to the next journal transaction.
    928  *
    929  * Requires:
    930  *	*pos refers to a valid journal transaction.
    931  *
    932  * Ensures:
    933  *	When ISC_R_SUCCESS is returned,
    934  *	*pos refers to the next journal transaction.
    935  *
    936  * Returns one of:
    937  *
    938  *    ISC_R_SUCCESS
    939  *    ISC_R_NOMORE 	*pos pointed at the last transaction
    940  *    Other results due to file errors are possible.
    941  */
    942 static isc_result_t
    943 journal_next(dns_journal_t *j, journal_pos_t *pos) {
    944 	isc_result_t result;
    945 	journal_xhdr_t xhdr;
    946 	size_t hdrsize;
    947 
    948 	REQUIRE(DNS_JOURNAL_VALID(j));
    949 
    950 	result = journal_seek(j, pos->offset);
    951 	if (result != ISC_R_SUCCESS) {
    952 		return (result);
    953 	}
    954 
    955 	if (pos->serial == j->header.end.serial) {
    956 		return (ISC_R_NOMORE);
    957 	}
    958 
    959 	/*
    960 	 * Read the header of the current transaction.
    961 	 * This will return ISC_R_NOMORE if we are at EOF.
    962 	 */
    963 	result = journal_read_xhdr(j, &xhdr);
    964 	if (result != ISC_R_SUCCESS) {
    965 		return (result);
    966 	}
    967 
    968 	if (j->header_ver1) {
    969 		CHECK(maybe_fixup_xhdr(j, &xhdr, pos->serial, pos->offset));
    970 	}
    971 
    972 	/*
    973 	 * Check serial number consistency.
    974 	 */
    975 	if (xhdr.serial0 != pos->serial ||
    976 	    isc_serial_le(xhdr.serial1, xhdr.serial0)) {
    977 		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
    978 			      "%s: journal file corrupt: "
    979 			      "expected serial %u, got %u",
    980 			      j->filename, pos->serial, xhdr.serial0);
    981 		return (ISC_R_UNEXPECTED);
    982 	}
    983 
    984 	/*
    985 	 * Check for offset wraparound.
    986 	 */
    987 	hdrsize = (j->xhdr_version == XHDR_VERSION2)
    988 			  ? sizeof(journal_rawxhdr_t)
    989 			  : sizeof(journal_rawxhdr_ver1_t);
    990 
    991 	if ((isc_offset_t)(pos->offset + hdrsize + xhdr.size) < pos->offset) {
    992 		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
    993 			      "%s: offset too large", j->filename);
    994 		return (ISC_R_UNEXPECTED);
    995 	}
    996 
    997 	pos->offset += hdrsize + xhdr.size;
    998 	pos->serial = xhdr.serial1;
    999 	return (ISC_R_SUCCESS);
   1000 
   1001 failure:
   1002 	return (result);
   1003 }
   1004 
   1005 /*
   1006  * If the index of the journal 'j' contains an entry "better"
   1007  * than '*best_guess', replace '*best_guess' with it.
   1008  *
   1009  * "Better" means having a serial number closer to 'serial'
   1010  * but not greater than 'serial'.
   1011  */
   1012 static void
   1013 index_find(dns_journal_t *j, uint32_t serial, journal_pos_t *best_guess) {
   1014 	unsigned int i;
   1015 	if (j->index == NULL) {
   1016 		return;
   1017 	}
   1018 	for (i = 0; i < j->header.index_size; i++) {
   1019 		if (POS_VALID(j->index[i]) &&
   1020 		    DNS_SERIAL_GE(serial, j->index[i].serial) &&
   1021 		    DNS_SERIAL_GT(j->index[i].serial, best_guess->serial))
   1022 		{
   1023 			*best_guess = j->index[i];
   1024 		}
   1025 	}
   1026 }
   1027 
   1028 /*
   1029  * Add a new index entry.  If there is no room, make room by removing
   1030  * the odd-numbered entries and compacting the others into the first
   1031  * half of the index.  This decimates old index entries exponentially
   1032  * over time, so that the index always contains a much larger fraction
   1033  * of recent serial numbers than of old ones.  This is deliberate -
   1034  * most index searches are for outgoing IXFR, and IXFR tends to request
   1035  * recent versions more often than old ones.
   1036  */
   1037 static void
   1038 index_add(dns_journal_t *j, journal_pos_t *pos) {
   1039 	unsigned int i;
   1040 
   1041 	if (j->index == NULL) {
   1042 		return;
   1043 	}
   1044 
   1045 	/*
   1046 	 * Search for a vacant position.
   1047 	 */
   1048 	for (i = 0; i < j->header.index_size; i++) {
   1049 		if (!POS_VALID(j->index[i])) {
   1050 			break;
   1051 		}
   1052 	}
   1053 	if (i == j->header.index_size) {
   1054 		unsigned int k = 0;
   1055 		/*
   1056 		 * Found no vacant position.  Make some room.
   1057 		 */
   1058 		for (i = 0; i < j->header.index_size; i += 2) {
   1059 			j->index[k++] = j->index[i];
   1060 		}
   1061 		i = k; /* 'i' identifies the first vacant position. */
   1062 		while (k < j->header.index_size) {
   1063 			POS_INVALIDATE(j->index[k]);
   1064 			k++;
   1065 		}
   1066 	}
   1067 	INSIST(i < j->header.index_size);
   1068 	INSIST(!POS_VALID(j->index[i]));
   1069 
   1070 	/*
   1071 	 * Store the new index entry.
   1072 	 */
   1073 	j->index[i] = *pos;
   1074 }
   1075 
   1076 /*
   1077  * Invalidate any existing index entries that could become
   1078  * ambiguous when a new transaction with number 'serial' is added.
   1079  */
   1080 static void
   1081 index_invalidate(dns_journal_t *j, uint32_t serial) {
   1082 	unsigned int i;
   1083 	if (j->index == NULL) {
   1084 		return;
   1085 	}
   1086 	for (i = 0; i < j->header.index_size; i++) {
   1087 		if (!DNS_SERIAL_GT(serial, j->index[i].serial)) {
   1088 			POS_INVALIDATE(j->index[i]);
   1089 		}
   1090 	}
   1091 }
   1092 
   1093 /*
   1094  * Try to find a transaction with initial serial number 'serial'
   1095  * in the journal 'j'.
   1096  *
   1097  * If found, store its position at '*pos' and return ISC_R_SUCCESS.
   1098  *
   1099  * If 'serial' is current (= the ending serial number of the
   1100  * last transaction in the journal), set '*pos' to
   1101  * the position immediately following the last transaction and
   1102  * return ISC_R_SUCCESS.
   1103  *
   1104  * If 'serial' is within the range of addressable serial numbers
   1105  * covered by the journal but that particular serial number is missing
   1106  * (from the journal, not just from the index), return ISC_R_NOTFOUND.
   1107  *
   1108  * If 'serial' is outside the range of addressable serial numbers
   1109  * covered by the journal, return ISC_R_RANGE.
   1110  *
   1111  */
   1112 static isc_result_t
   1113 journal_find(dns_journal_t *j, uint32_t serial, journal_pos_t *pos) {
   1114 	isc_result_t result;
   1115 	journal_pos_t current_pos;
   1116 
   1117 	REQUIRE(DNS_JOURNAL_VALID(j));
   1118 
   1119 	if (DNS_SERIAL_GT(j->header.begin.serial, serial)) {
   1120 		return (ISC_R_RANGE);
   1121 	}
   1122 	if (DNS_SERIAL_GT(serial, j->header.end.serial)) {
   1123 		return (ISC_R_RANGE);
   1124 	}
   1125 	if (serial == j->header.end.serial) {
   1126 		*pos = j->header.end;
   1127 		return (ISC_R_SUCCESS);
   1128 	}
   1129 
   1130 	current_pos = j->header.begin;
   1131 	index_find(j, serial, &current_pos);
   1132 
   1133 	while (current_pos.serial != serial) {
   1134 		if (DNS_SERIAL_GT(current_pos.serial, serial)) {
   1135 			return (ISC_R_NOTFOUND);
   1136 		}
   1137 		result = journal_next(j, &current_pos);
   1138 		if (result != ISC_R_SUCCESS) {
   1139 			return (result);
   1140 		}
   1141 	}
   1142 	*pos = current_pos;
   1143 	return (ISC_R_SUCCESS);
   1144 }
   1145 
   1146 isc_result_t
   1147 dns_journal_begin_transaction(dns_journal_t *j) {
   1148 	uint32_t offset;
   1149 	isc_result_t result;
   1150 
   1151 	REQUIRE(DNS_JOURNAL_VALID(j));
   1152 	REQUIRE(j->state == JOURNAL_STATE_WRITE ||
   1153 		j->state == JOURNAL_STATE_INLINE);
   1154 
   1155 	/*
   1156 	 * Find the file offset where the new transaction should
   1157 	 * be written, and seek there.
   1158 	 */
   1159 	if (JOURNAL_EMPTY(&j->header)) {
   1160 		offset = sizeof(journal_rawheader_t) +
   1161 			 j->header.index_size * sizeof(journal_rawpos_t);
   1162 	} else {
   1163 		offset = j->header.end.offset;
   1164 	}
   1165 	j->x.pos[0].offset = offset;
   1166 	j->x.pos[1].offset = offset; /* Initial value, will be incremented. */
   1167 	j->x.n_soa = 0;
   1168 
   1169 	CHECK(journal_seek(j, offset));
   1170 
   1171 	/*
   1172 	 * Write a dummy transaction header of all zeroes to reserve
   1173 	 * space.  It will be filled in when the transaction is
   1174 	 * finished.
   1175 	 */
   1176 	CHECK(journal_write_xhdr(j, 0, 0, 0, 0));
   1177 	j->x.pos[1].offset = j->offset;
   1178 
   1179 	j->state = JOURNAL_STATE_TRANSACTION;
   1180 	result = ISC_R_SUCCESS;
   1181 failure:
   1182 	return (result);
   1183 }
   1184 
   1185 isc_result_t
   1186 dns_journal_writediff(dns_journal_t *j, dns_diff_t *diff) {
   1187 	dns_difftuple_t *t;
   1188 	isc_buffer_t buffer;
   1189 	void *mem = NULL;
   1190 	uint64_t size = 0;
   1191 	uint32_t rrcount = 0;
   1192 	isc_result_t result;
   1193 	isc_region_t used;
   1194 
   1195 	REQUIRE(DNS_DIFF_VALID(diff));
   1196 	REQUIRE(j->state == JOURNAL_STATE_TRANSACTION);
   1197 
   1198 	isc_log_write(JOURNAL_DEBUG_LOGARGS(3), "writing to journal");
   1199 	(void)dns_diff_print(diff, NULL);
   1200 
   1201 	/*
   1202 	 * Pass 1: determine the buffer size needed, and
   1203 	 * keep track of SOA serial numbers.
   1204 	 */
   1205 	for (t = ISC_LIST_HEAD(diff->tuples); t != NULL;
   1206 	     t = ISC_LIST_NEXT(t, link)) {
   1207 		if (t->rdata.type == dns_rdatatype_soa) {
   1208 			if (j->x.n_soa < 2) {
   1209 				j->x.pos[j->x.n_soa].serial =
   1210 					dns_soa_getserial(&t->rdata);
   1211 			}
   1212 			j->x.n_soa++;
   1213 		}
   1214 		size += sizeof(journal_rawrrhdr_t);
   1215 		size += t->name.length; /* XXX should have access macro? */
   1216 		size += 10;
   1217 		size += t->rdata.length;
   1218 	}
   1219 
   1220 	if (size >= DNS_JOURNAL_SIZE_MAX) {
   1221 		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
   1222 			      "dns_journal_writediff: %s: journal entry "
   1223 			      "too big to be stored: %" PRIu64 " bytes",
   1224 			      j->filename, size);
   1225 		return (ISC_R_NOSPACE);
   1226 	}
   1227 
   1228 	mem = isc_mem_get(j->mctx, size);
   1229 
   1230 	isc_buffer_init(&buffer, mem, size);
   1231 
   1232 	/*
   1233 	 * Pass 2.  Write RRs to buffer.
   1234 	 */
   1235 	for (t = ISC_LIST_HEAD(diff->tuples); t != NULL;
   1236 	     t = ISC_LIST_NEXT(t, link)) {
   1237 		/*
   1238 		 * Write the RR header.
   1239 		 */
   1240 		isc_buffer_putuint32(&buffer,
   1241 				     t->name.length + 10 + t->rdata.length);
   1242 		/*
   1243 		 * Write the owner name, RR header, and RR data.
   1244 		 */
   1245 		isc_buffer_putmem(&buffer, t->name.ndata, t->name.length);
   1246 		isc_buffer_putuint16(&buffer, t->rdata.type);
   1247 		isc_buffer_putuint16(&buffer, t->rdata.rdclass);
   1248 		isc_buffer_putuint32(&buffer, t->ttl);
   1249 		INSIST(t->rdata.length < 65536);
   1250 		isc_buffer_putuint16(&buffer, (uint16_t)t->rdata.length);
   1251 		INSIST(isc_buffer_availablelength(&buffer) >= t->rdata.length);
   1252 		isc_buffer_putmem(&buffer, t->rdata.data, t->rdata.length);
   1253 
   1254 		rrcount++;
   1255 	}
   1256 
   1257 	isc_buffer_usedregion(&buffer, &used);
   1258 	INSIST(used.length == size);
   1259 
   1260 	j->x.pos[1].offset += used.length;
   1261 	j->x.n_rr = rrcount;
   1262 
   1263 	/*
   1264 	 * Write the buffer contents to the journal file.
   1265 	 */
   1266 	CHECK(journal_write(j, used.base, used.length));
   1267 
   1268 	result = ISC_R_SUCCESS;
   1269 
   1270 failure:
   1271 	if (mem != NULL) {
   1272 		isc_mem_put(j->mctx, mem, size);
   1273 	}
   1274 	return (result);
   1275 }
   1276 
   1277 isc_result_t
   1278 dns_journal_commit(dns_journal_t *j) {
   1279 	isc_result_t result;
   1280 	journal_rawheader_t rawheader;
   1281 	uint64_t total;
   1282 
   1283 	REQUIRE(DNS_JOURNAL_VALID(j));
   1284 	REQUIRE(j->state == JOURNAL_STATE_TRANSACTION ||
   1285 		j->state == JOURNAL_STATE_INLINE);
   1286 
   1287 	/*
   1288 	 * Just write out a updated header.
   1289 	 */
   1290 	if (j->state == JOURNAL_STATE_INLINE) {
   1291 		CHECK(journal_fsync(j));
   1292 		journal_header_encode(&j->header, &rawheader);
   1293 		CHECK(journal_seek(j, 0));
   1294 		CHECK(journal_write(j, &rawheader, sizeof(rawheader)));
   1295 		CHECK(journal_fsync(j));
   1296 		j->state = JOURNAL_STATE_WRITE;
   1297 		return (ISC_R_SUCCESS);
   1298 	}
   1299 
   1300 	/*
   1301 	 * Perform some basic consistency checks.
   1302 	 */
   1303 	if (j->x.n_soa != 2) {
   1304 		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
   1305 			      "%s: malformed transaction: %d SOAs", j->filename,
   1306 			      j->x.n_soa);
   1307 		return (ISC_R_UNEXPECTED);
   1308 	}
   1309 	if (!DNS_SERIAL_GT(j->x.pos[1].serial, j->x.pos[0].serial)) {
   1310 		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
   1311 			      "%s: malformed transaction: serial number "
   1312 			      "did not increase",
   1313 			      j->filename);
   1314 		return (ISC_R_UNEXPECTED);
   1315 	}
   1316 	if (!JOURNAL_EMPTY(&j->header)) {
   1317 		if (j->x.pos[0].serial != j->header.end.serial) {
   1318 			isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
   1319 				      "malformed transaction: "
   1320 				      "%s last serial %u != "
   1321 				      "transaction first serial %u",
   1322 				      j->filename, j->header.end.serial,
   1323 				      j->x.pos[0].serial);
   1324 			return (ISC_R_UNEXPECTED);
   1325 		}
   1326 	}
   1327 
   1328 	/*
   1329 	 * We currently don't support huge journal entries.
   1330 	 */
   1331 	total = j->x.pos[1].offset - j->x.pos[0].offset;
   1332 	if (total >= DNS_JOURNAL_SIZE_MAX) {
   1333 		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
   1334 			      "transaction too big to be stored in journal: "
   1335 			      "%" PRIu64 "b (max is %" PRIu64 "b)",
   1336 			      total, (uint64_t)DNS_JOURNAL_SIZE_MAX);
   1337 		return (ISC_R_UNEXPECTED);
   1338 	}
   1339 
   1340 	/*
   1341 	 * Some old journal entries may become non-addressable
   1342 	 * when we increment the current serial number.  Purge them
   1343 	 * by stepping header.begin forward to the first addressable
   1344 	 * transaction.  Also purge them from the index.
   1345 	 */
   1346 	if (!JOURNAL_EMPTY(&j->header)) {
   1347 		while (!DNS_SERIAL_GT(j->x.pos[1].serial,
   1348 				      j->header.begin.serial)) {
   1349 			CHECK(journal_next(j, &j->header.begin));
   1350 		}
   1351 		index_invalidate(j, j->x.pos[1].serial);
   1352 	}
   1353 #ifdef notyet
   1354 	if (DNS_SERIAL_GT(last_dumped_serial, j->x.pos[1].serial)) {
   1355 		force_dump(...);
   1356 	}
   1357 #endif /* ifdef notyet */
   1358 
   1359 	/*
   1360 	 * Commit the transaction data to stable storage.
   1361 	 */
   1362 	CHECK(journal_fsync(j));
   1363 
   1364 	if (j->state == JOURNAL_STATE_TRANSACTION) {
   1365 		isc_offset_t offset;
   1366 		offset = (j->x.pos[1].offset - j->x.pos[0].offset) -
   1367 			 (j->header_ver1 ? sizeof(journal_rawxhdr_ver1_t)
   1368 					 : sizeof(journal_rawxhdr_t));
   1369 		/*
   1370 		 * Update the transaction header.
   1371 		 */
   1372 		CHECK(journal_seek(j, j->x.pos[0].offset));
   1373 		CHECK(journal_write_xhdr(j, offset, j->x.n_rr,
   1374 					 j->x.pos[0].serial,
   1375 					 j->x.pos[1].serial));
   1376 	}
   1377 
   1378 	/*
   1379 	 * Update the journal header.
   1380 	 */
   1381 	if (JOURNAL_EMPTY(&j->header)) {
   1382 		j->header.begin = j->x.pos[0];
   1383 	}
   1384 	j->header.end = j->x.pos[1];
   1385 	journal_header_encode(&j->header, &rawheader);
   1386 	CHECK(journal_seek(j, 0));
   1387 	CHECK(journal_write(j, &rawheader, sizeof(rawheader)));
   1388 
   1389 	/*
   1390 	 * Update the index.
   1391 	 */
   1392 	index_add(j, &j->x.pos[0]);
   1393 
   1394 	/*
   1395 	 * Convert the index into on-disk format and write
   1396 	 * it to disk.
   1397 	 */
   1398 	CHECK(index_to_disk(j));
   1399 
   1400 	/*
   1401 	 * Commit the header to stable storage.
   1402 	 */
   1403 	CHECK(journal_fsync(j));
   1404 
   1405 	/*
   1406 	 * We no longer have a transaction open.
   1407 	 */
   1408 	j->state = JOURNAL_STATE_WRITE;
   1409 
   1410 	result = ISC_R_SUCCESS;
   1411 
   1412 failure:
   1413 	return (result);
   1414 }
   1415 
   1416 isc_result_t
   1417 dns_journal_write_transaction(dns_journal_t *j, dns_diff_t *diff) {
   1418 	isc_result_t result;
   1419 
   1420 	CHECK(dns_diff_sort(diff, ixfr_order));
   1421 	CHECK(dns_journal_begin_transaction(j));
   1422 	CHECK(dns_journal_writediff(j, diff));
   1423 	CHECK(dns_journal_commit(j));
   1424 	result = ISC_R_SUCCESS;
   1425 failure:
   1426 	return (result);
   1427 }
   1428 
   1429 void
   1430 dns_journal_destroy(dns_journal_t **journalp) {
   1431 	dns_journal_t *j = NULL;
   1432 
   1433 	REQUIRE(journalp != NULL);
   1434 	REQUIRE(DNS_JOURNAL_VALID(*journalp));
   1435 
   1436 	j = *journalp;
   1437 	*journalp = NULL;
   1438 
   1439 	j->it.result = ISC_R_FAILURE;
   1440 	dns_name_invalidate(&j->it.name);
   1441 	dns_decompress_invalidate(&j->it.dctx);
   1442 	if (j->rawindex != NULL) {
   1443 		isc_mem_put(j->mctx, j->rawindex,
   1444 			    j->header.index_size * sizeof(journal_rawpos_t));
   1445 	}
   1446 	if (j->index != NULL) {
   1447 		isc_mem_put(j->mctx, j->index,
   1448 			    j->header.index_size * sizeof(journal_pos_t));
   1449 	}
   1450 	if (j->it.target.base != NULL) {
   1451 		isc_mem_put(j->mctx, j->it.target.base, j->it.target.length);
   1452 	}
   1453 	if (j->it.source.base != NULL) {
   1454 		isc_mem_put(j->mctx, j->it.source.base, j->it.source.length);
   1455 	}
   1456 	if (j->filename != NULL) {
   1457 		isc_mem_free(j->mctx, j->filename);
   1458 	}
   1459 	if (j->fp != NULL) {
   1460 		(void)isc_stdio_close(j->fp);
   1461 	}
   1462 	j->magic = 0;
   1463 	isc_mem_putanddetach(&j->mctx, j, sizeof(*j));
   1464 }
   1465 
   1466 /*
   1467  * Roll the open journal 'j' into the database 'db'.
   1468  * A new database version will be created.
   1469  */
   1470 
   1471 /* XXX Share code with incoming IXFR? */
   1472 
   1473 isc_result_t
   1474 dns_journal_rollforward(dns_journal_t *j, dns_db_t *db, unsigned int options) {
   1475 	isc_buffer_t source; /* Transaction data from disk */
   1476 	isc_buffer_t target; /* Ditto after _fromwire check */
   1477 	uint32_t db_serial;  /* Database SOA serial */
   1478 	uint32_t end_serial; /* Last journal SOA serial */
   1479 	isc_result_t result;
   1480 	dns_dbversion_t *ver = NULL;
   1481 	journal_pos_t pos;
   1482 	dns_diff_t diff;
   1483 	unsigned int n_soa = 0;
   1484 	unsigned int n_put = 0;
   1485 	dns_diffop_t op;
   1486 
   1487 	REQUIRE(DNS_JOURNAL_VALID(j));
   1488 	REQUIRE(DNS_DB_VALID(db));
   1489 
   1490 	dns_diff_init(j->mctx, &diff);
   1491 
   1492 	/*
   1493 	 * Set up empty initial buffers for unchecked and checked
   1494 	 * wire format transaction data.  They will be reallocated
   1495 	 * later.
   1496 	 */
   1497 	isc_buffer_init(&source, NULL, 0);
   1498 	isc_buffer_init(&target, NULL, 0);
   1499 
   1500 	/*
   1501 	 * Create the new database version.
   1502 	 */
   1503 	CHECK(dns_db_newversion(db, &ver));
   1504 
   1505 	/*
   1506 	 * Get the current database SOA serial number.
   1507 	 */
   1508 	CHECK(dns_db_getsoaserial(db, ver, &db_serial));
   1509 
   1510 	/*
   1511 	 * Locate a journal entry for the current database serial.
   1512 	 */
   1513 	CHECK(journal_find(j, db_serial, &pos));
   1514 
   1515 	end_serial = dns_journal_last_serial(j);
   1516 
   1517 	/*
   1518 	 * If we're reading a version 1 file, scan all the transactions
   1519 	 * to see if the journal needs rewriting: if any outdated
   1520 	 * transaction headers are found, j->recovered will be set.
   1521 	 */
   1522 	if (j->header_ver1) {
   1523 		uint32_t start_serial = dns_journal_first_serial(j);
   1524 
   1525 		CHECK(dns_journal_iter_init(j, start_serial, db_serial, NULL));
   1526 		for (result = dns_journal_first_rr(j); result == ISC_R_SUCCESS;
   1527 		     result = dns_journal_next_rr(j))
   1528 		{
   1529 			continue;
   1530 		}
   1531 	}
   1532 
   1533 	if (db_serial == end_serial) {
   1534 		CHECK(DNS_R_UPTODATE);
   1535 	}
   1536 
   1537 	CHECK(dns_journal_iter_init(j, db_serial, end_serial, NULL));
   1538 	for (result = dns_journal_first_rr(j); result == ISC_R_SUCCESS;
   1539 	     result = dns_journal_next_rr(j))
   1540 	{
   1541 		dns_name_t *name = NULL;
   1542 		dns_rdata_t *rdata = NULL;
   1543 		dns_difftuple_t *tuple = NULL;
   1544 		uint32_t ttl;
   1545 
   1546 		dns_journal_current_rr(j, &name, &ttl, &rdata);
   1547 
   1548 		if (rdata->type == dns_rdatatype_soa) {
   1549 			n_soa++;
   1550 			if (n_soa == 2) {
   1551 				db_serial = j->it.current_serial;
   1552 			}
   1553 		}
   1554 
   1555 		if (n_soa == 3) {
   1556 			n_soa = 1;
   1557 		}
   1558 		if (n_soa == 0) {
   1559 			isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
   1560 				      "%s: journal file corrupt: missing "
   1561 				      "initial SOA",
   1562 				      j->filename);
   1563 			FAIL(ISC_R_UNEXPECTED);
   1564 		}
   1565 		if ((options & DNS_JOURNALOPT_RESIGN) != 0) {
   1566 			op = (n_soa == 1) ? DNS_DIFFOP_DELRESIGN
   1567 					  : DNS_DIFFOP_ADDRESIGN;
   1568 		} else {
   1569 			op = (n_soa == 1) ? DNS_DIFFOP_DEL : DNS_DIFFOP_ADD;
   1570 		}
   1571 
   1572 		CHECK(dns_difftuple_create(diff.mctx, op, name, ttl, rdata,
   1573 					   &tuple));
   1574 		dns_diff_append(&diff, &tuple);
   1575 
   1576 		if (++n_put > 100) {
   1577 			isc_log_write(JOURNAL_DEBUG_LOGARGS(3),
   1578 				      "%s: applying diff to database (%u)",
   1579 				      j->filename, db_serial);
   1580 			(void)dns_diff_print(&diff, NULL);
   1581 			CHECK(dns_diff_apply(&diff, db, ver));
   1582 			dns_diff_clear(&diff);
   1583 			n_put = 0;
   1584 		}
   1585 	}
   1586 	if (result == ISC_R_NOMORE) {
   1587 		result = ISC_R_SUCCESS;
   1588 	}
   1589 	CHECK(result);
   1590 
   1591 	if (n_put != 0) {
   1592 		isc_log_write(JOURNAL_DEBUG_LOGARGS(3),
   1593 			      "%s: applying final diff to database (%u)",
   1594 			      j->filename, db_serial);
   1595 		(void)dns_diff_print(&diff, NULL);
   1596 		CHECK(dns_diff_apply(&diff, db, ver));
   1597 		dns_diff_clear(&diff);
   1598 	}
   1599 
   1600 failure:
   1601 	if (ver != NULL) {
   1602 		dns_db_closeversion(db, &ver,
   1603 				    result == ISC_R_SUCCESS ? true : false);
   1604 	}
   1605 
   1606 	if (source.base != NULL) {
   1607 		isc_mem_put(j->mctx, source.base, source.length);
   1608 	}
   1609 	if (target.base != NULL) {
   1610 		isc_mem_put(j->mctx, target.base, target.length);
   1611 	}
   1612 
   1613 	dns_diff_clear(&diff);
   1614 
   1615 	INSIST(ver == NULL);
   1616 
   1617 	return (result);
   1618 }
   1619 
   1620 isc_result_t
   1621 dns_journal_print(isc_mem_t *mctx, uint32_t flags, const char *filename,
   1622 		  FILE *file) {
   1623 	dns_journal_t *j = NULL;
   1624 	isc_buffer_t source;   /* Transaction data from disk */
   1625 	isc_buffer_t target;   /* Ditto after _fromwire check */
   1626 	uint32_t start_serial; /* Database SOA serial */
   1627 	uint32_t end_serial;   /* Last journal SOA serial */
   1628 	isc_result_t result;
   1629 	dns_diff_t diff;
   1630 	unsigned int n_soa = 0;
   1631 	unsigned int n_put = 0;
   1632 	bool printxhdr = ((flags & DNS_JOURNAL_PRINTXHDR) != 0);
   1633 
   1634 	REQUIRE(filename != NULL);
   1635 
   1636 	result = dns_journal_open(mctx, filename, DNS_JOURNAL_READ, &j);
   1637 	if (result == ISC_R_NOTFOUND) {
   1638 		isc_log_write(JOURNAL_DEBUG_LOGARGS(3), "no journal file");
   1639 		return (DNS_R_NOJOURNAL);
   1640 	} else if (result != ISC_R_SUCCESS) {
   1641 		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
   1642 			      "journal open failure: %s: %s",
   1643 			      isc_result_totext(result), filename);
   1644 		return (result);
   1645 	}
   1646 
   1647 	if (printxhdr) {
   1648 		fprintf(file, "Journal format = %sHeader version = %d\n",
   1649 			j->header.format + 1, j->header_ver1 ? 1 : 2);
   1650 		fprintf(file, "Start serial = %u\n", j->header.begin.serial);
   1651 		fprintf(file, "End serial = %u\n", j->header.end.serial);
   1652 		fprintf(file, "Index (size = %u):\n", j->header.index_size);
   1653 		for (uint32_t i = 0; i < j->header.index_size; i++) {
   1654 			if (j->index[i].offset == 0) {
   1655 				fputc('\n', file);
   1656 				break;
   1657 			}
   1658 			fprintf(file, "%lld", (long long)j->index[i].offset);
   1659 			fputc((i + 1) % 8 == 0 ? '\n' : ' ', file);
   1660 		}
   1661 	}
   1662 	if (j->header.serialset) {
   1663 		fprintf(file, "Source serial = %u\n", j->header.sourceserial);
   1664 	}
   1665 	dns_diff_init(j->mctx, &diff);
   1666 
   1667 	/*
   1668 	 * Set up empty initial buffers for unchecked and checked
   1669 	 * wire format transaction data.  They will be reallocated
   1670 	 * later.
   1671 	 */
   1672 	isc_buffer_init(&source, NULL, 0);
   1673 	isc_buffer_init(&target, NULL, 0);
   1674 
   1675 	start_serial = dns_journal_first_serial(j);
   1676 	end_serial = dns_journal_last_serial(j);
   1677 
   1678 	CHECK(dns_journal_iter_init(j, start_serial, end_serial, NULL));
   1679 
   1680 	for (result = dns_journal_first_rr(j); result == ISC_R_SUCCESS;
   1681 	     result = dns_journal_next_rr(j))
   1682 	{
   1683 		dns_name_t *name = NULL;
   1684 		dns_rdata_t *rdata = NULL;
   1685 		dns_difftuple_t *tuple = NULL;
   1686 		static uint32_t i = 0;
   1687 		bool print = false;
   1688 		uint32_t ttl;
   1689 
   1690 		dns_journal_current_rr(j, &name, &ttl, &rdata);
   1691 
   1692 		if (rdata->type == dns_rdatatype_soa) {
   1693 			n_soa++;
   1694 			if (n_soa == 3) {
   1695 				n_soa = 1;
   1696 			}
   1697 			if (n_soa == 1) {
   1698 				print = printxhdr;
   1699 			}
   1700 		}
   1701 		if (n_soa == 0) {
   1702 			isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
   1703 				      "%s: journal file corrupt: missing "
   1704 				      "initial SOA",
   1705 				      j->filename);
   1706 			FAIL(ISC_R_UNEXPECTED);
   1707 		}
   1708 
   1709 		if (print) {
   1710 			fprintf(file,
   1711 				"Transaction: version %d offset %lld size %u "
   1712 				"rrcount %u start %u end %u\n",
   1713 				j->xhdr_version, (long long)j->it.cpos.offset,
   1714 				j->curxhdr.size, j->curxhdr.count,
   1715 				j->curxhdr.serial0, j->curxhdr.serial1);
   1716 			if (j->it.cpos.offset > j->index[i].offset) {
   1717 				fprintf(file,
   1718 					"ERROR: Offset mismatch, "
   1719 					"expected %lld\n",
   1720 					(long long)j->index[i].offset);
   1721 			} else if (j->it.cpos.offset == j->index[i].offset) {
   1722 				i++;
   1723 			}
   1724 		}
   1725 		CHECK(dns_difftuple_create(
   1726 			diff.mctx, n_soa == 1 ? DNS_DIFFOP_DEL : DNS_DIFFOP_ADD,
   1727 			name, ttl, rdata, &tuple));
   1728 		dns_diff_append(&diff, &tuple);
   1729 
   1730 		if (++n_put > 100 || printxhdr) {
   1731 			result = dns_diff_print(&diff, file);
   1732 			dns_diff_clear(&diff);
   1733 			n_put = 0;
   1734 			if (result != ISC_R_SUCCESS) {
   1735 				break;
   1736 			}
   1737 		}
   1738 	}
   1739 	if (result == ISC_R_NOMORE) {
   1740 		result = ISC_R_SUCCESS;
   1741 	}
   1742 	CHECK(result);
   1743 
   1744 	if (n_put != 0) {
   1745 		result = dns_diff_print(&diff, file);
   1746 		dns_diff_clear(&diff);
   1747 	}
   1748 	goto cleanup;
   1749 
   1750 failure:
   1751 	isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
   1752 		      "%s: cannot print: journal file corrupt", j->filename);
   1753 
   1754 cleanup:
   1755 	if (source.base != NULL) {
   1756 		isc_mem_put(j->mctx, source.base, source.length);
   1757 	}
   1758 	if (target.base != NULL) {
   1759 		isc_mem_put(j->mctx, target.base, target.length);
   1760 	}
   1761 
   1762 	dns_diff_clear(&diff);
   1763 	dns_journal_destroy(&j);
   1764 
   1765 	return (result);
   1766 }
   1767 
   1768 /**************************************************************************/
   1769 /*
   1770  * Miscellaneous accessors.
   1771  */
   1772 bool
   1773 dns_journal_empty(dns_journal_t *j) {
   1774 	return (JOURNAL_EMPTY(&j->header));
   1775 }
   1776 
   1777 bool
   1778 dns_journal_recovered(dns_journal_t *j) {
   1779 	return (j->recovered);
   1780 }
   1781 
   1782 uint32_t
   1783 dns_journal_first_serial(dns_journal_t *j) {
   1784 	return (j->header.begin.serial);
   1785 }
   1786 
   1787 uint32_t
   1788 dns_journal_last_serial(dns_journal_t *j) {
   1789 	return (j->header.end.serial);
   1790 }
   1791 
   1792 void
   1793 dns_journal_set_sourceserial(dns_journal_t *j, uint32_t sourceserial) {
   1794 	REQUIRE(j->state == JOURNAL_STATE_WRITE ||
   1795 		j->state == JOURNAL_STATE_INLINE ||
   1796 		j->state == JOURNAL_STATE_TRANSACTION);
   1797 
   1798 	j->header.sourceserial = sourceserial;
   1799 	j->header.serialset = true;
   1800 	if (j->state == JOURNAL_STATE_WRITE) {
   1801 		j->state = JOURNAL_STATE_INLINE;
   1802 	}
   1803 }
   1804 
   1805 bool
   1806 dns_journal_get_sourceserial(dns_journal_t *j, uint32_t *sourceserial) {
   1807 	REQUIRE(sourceserial != NULL);
   1808 
   1809 	if (!j->header.serialset) {
   1810 		return (false);
   1811 	}
   1812 	*sourceserial = j->header.sourceserial;
   1813 	return (true);
   1814 }
   1815 
   1816 /**************************************************************************/
   1817 /*
   1818  * Iteration support.
   1819  *
   1820  * When serving an outgoing IXFR, we transmit a part the journal starting
   1821  * at the serial number in the IXFR request and ending at the serial
   1822  * number that is current when the IXFR request arrives.  The ending
   1823  * serial number is not necessarily at the end of the journal:
   1824  * the journal may grow while the IXFR is in progress, but we stop
   1825  * when we reach the serial number that was current when the IXFR started.
   1826  */
   1827 
   1828 static isc_result_t
   1829 read_one_rr(dns_journal_t *j);
   1830 
   1831 /*
   1832  * Make sure the buffer 'b' is has at least 'size' bytes
   1833  * allocated, and clear it.
   1834  *
   1835  * Requires:
   1836  *	Either b->base is NULL, or it points to b->length bytes of memory
   1837  *	previously allocated by isc_mem_get().
   1838  */
   1839 
   1840 static isc_result_t
   1841 size_buffer(isc_mem_t *mctx, isc_buffer_t *b, unsigned size) {
   1842 	if (b->length < size) {
   1843 		void *mem = isc_mem_get(mctx, size);
   1844 		if (mem == NULL) {
   1845 			return (ISC_R_NOMEMORY);
   1846 		}
   1847 		if (b->base != NULL) {
   1848 			isc_mem_put(mctx, b->base, b->length);
   1849 		}
   1850 		b->base = mem;
   1851 		b->length = size;
   1852 	}
   1853 	isc_buffer_clear(b);
   1854 	return (ISC_R_SUCCESS);
   1855 }
   1856 
   1857 isc_result_t
   1858 dns_journal_iter_init(dns_journal_t *j, uint32_t begin_serial,
   1859 		      uint32_t end_serial, size_t *xfrsizep) {
   1860 	isc_result_t result;
   1861 
   1862 	CHECK(journal_find(j, begin_serial, &j->it.bpos));
   1863 	INSIST(j->it.bpos.serial == begin_serial);
   1864 
   1865 	CHECK(journal_find(j, end_serial, &j->it.epos));
   1866 	INSIST(j->it.epos.serial == end_serial);
   1867 
   1868 	if (xfrsizep != NULL) {
   1869 		journal_pos_t pos = j->it.bpos;
   1870 		journal_xhdr_t xhdr;
   1871 		uint64_t size = 0;
   1872 		uint32_t count = 0;
   1873 
   1874 		/*
   1875 		 * We already know the beginning and ending serial
   1876 		 * numbers are in the journal. Scan through them,
   1877 		 * adding up sizes and RR counts so we can calculate
   1878 		 * the IXFR size.
   1879 		 */
   1880 		do {
   1881 			CHECK(journal_seek(j, pos.offset));
   1882 			CHECK(journal_read_xhdr(j, &xhdr));
   1883 
   1884 			if (j->header_ver1) {
   1885 				CHECK(maybe_fixup_xhdr(j, &xhdr, pos.serial,
   1886 						       pos.offset));
   1887 			}
   1888 
   1889 			/*
   1890 			 * Check that xhdr is consistent.
   1891 			 */
   1892 			if (xhdr.serial0 != pos.serial ||
   1893 			    isc_serial_le(xhdr.serial1, xhdr.serial0)) {
   1894 				CHECK(ISC_R_UNEXPECTED);
   1895 			}
   1896 
   1897 			size += xhdr.size;
   1898 			count += xhdr.count;
   1899 
   1900 			result = journal_next(j, &pos);
   1901 			if (result == ISC_R_NOMORE) {
   1902 				result = ISC_R_SUCCESS;
   1903 			}
   1904 			CHECK(result);
   1905 		} while (pos.serial != end_serial);
   1906 
   1907 		/*
   1908 		 * For each RR, subtract the length of the RR header,
   1909 		 * as this would not be present in IXFR messages.
   1910 		 * (We don't need to worry about the transaction header
   1911 		 * because that was already excluded from xdr.size.)
   1912 		 */
   1913 		*xfrsizep = size - (count * sizeof(journal_rawrrhdr_t));
   1914 	}
   1915 
   1916 	result = ISC_R_SUCCESS;
   1917 failure:
   1918 	j->it.result = result;
   1919 	return (j->it.result);
   1920 }
   1921 
   1922 isc_result_t
   1923 dns_journal_first_rr(dns_journal_t *j) {
   1924 	isc_result_t result;
   1925 
   1926 	/*
   1927 	 * Seek to the beginning of the first transaction we are
   1928 	 * interested in.
   1929 	 */
   1930 	CHECK(journal_seek(j, j->it.bpos.offset));
   1931 	j->it.current_serial = j->it.bpos.serial;
   1932 
   1933 	j->it.xsize = 0; /* We have no transaction data yet... */
   1934 	j->it.xpos = 0;	 /* ...and haven't used any of it. */
   1935 
   1936 	return (read_one_rr(j));
   1937 
   1938 failure:
   1939 	return (result);
   1940 }
   1941 
   1942 static isc_result_t
   1943 read_one_rr(dns_journal_t *j) {
   1944 	isc_result_t result;
   1945 	dns_rdatatype_t rdtype;
   1946 	dns_rdataclass_t rdclass;
   1947 	unsigned int rdlen;
   1948 	uint32_t ttl;
   1949 	journal_xhdr_t xhdr;
   1950 	journal_rrhdr_t rrhdr;
   1951 	dns_journal_t save = *j;
   1952 
   1953 	if (j->offset > j->it.epos.offset) {
   1954 		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
   1955 			      "%s: journal corrupt: possible integer overflow",
   1956 			      j->filename);
   1957 		return (ISC_R_UNEXPECTED);
   1958 	}
   1959 	if (j->offset == j->it.epos.offset) {
   1960 		return (ISC_R_NOMORE);
   1961 	}
   1962 	if (j->it.xpos == j->it.xsize) {
   1963 		/*
   1964 		 * We are at a transaction boundary.
   1965 		 * Read another transaction header.
   1966 		 */
   1967 		CHECK(journal_read_xhdr(j, &xhdr));
   1968 		if (xhdr.size == 0) {
   1969 			isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
   1970 				      "%s: journal corrupt: empty transaction",
   1971 				      j->filename);
   1972 			FAIL(ISC_R_UNEXPECTED);
   1973 		}
   1974 
   1975 		if (j->header_ver1) {
   1976 			CHECK(maybe_fixup_xhdr(j, &xhdr, j->it.current_serial,
   1977 					       save.offset));
   1978 		}
   1979 
   1980 		if (xhdr.serial0 != j->it.current_serial ||
   1981 		    isc_serial_le(xhdr.serial1, xhdr.serial0))
   1982 		{
   1983 			isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
   1984 				      "%s: journal file corrupt: "
   1985 				      "expected serial %u, got %u",
   1986 				      j->filename, j->it.current_serial,
   1987 				      xhdr.serial0);
   1988 			FAIL(ISC_R_UNEXPECTED);
   1989 		}
   1990 
   1991 		j->it.xsize = xhdr.size;
   1992 		j->it.xpos = 0;
   1993 	}
   1994 	/*
   1995 	 * Read an RR.
   1996 	 */
   1997 	CHECK(journal_read_rrhdr(j, &rrhdr));
   1998 	/*
   1999 	 * Perform a sanity check on the journal RR size.
   2000 	 * The smallest possible RR has a 1-byte owner name
   2001 	 * and a 10-byte header.  The largest possible
   2002 	 * RR has 65535 bytes of data, a header, and a maximum-
   2003 	 * size owner name, well below 70 k total.
   2004 	 */
   2005 	if (rrhdr.size < 1 + 10 || rrhdr.size > 70000) {
   2006 		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
   2007 			      "%s: journal corrupt: impossible RR size "
   2008 			      "(%d bytes)",
   2009 			      j->filename, rrhdr.size);
   2010 		FAIL(ISC_R_UNEXPECTED);
   2011 	}
   2012 
   2013 	CHECK(size_buffer(j->mctx, &j->it.source, rrhdr.size));
   2014 	CHECK(journal_read(j, j->it.source.base, rrhdr.size));
   2015 	isc_buffer_add(&j->it.source, rrhdr.size);
   2016 
   2017 	/*
   2018 	 * The target buffer is made the same size
   2019 	 * as the source buffer, with the assumption that when
   2020 	 * no compression in present, the output of dns_*_fromwire()
   2021 	 * is no larger than the input.
   2022 	 */
   2023 	CHECK(size_buffer(j->mctx, &j->it.target, rrhdr.size));
   2024 
   2025 	/*
   2026 	 * Parse the owner name.  We don't know where it
   2027 	 * ends yet, so we make the entire "remaining"
   2028 	 * part of the buffer "active".
   2029 	 */
   2030 	isc_buffer_setactive(&j->it.source,
   2031 			     j->it.source.used - j->it.source.current);
   2032 	CHECK(dns_name_fromwire(&j->it.name, &j->it.source, &j->it.dctx, 0,
   2033 				&j->it.target));
   2034 
   2035 	/*
   2036 	 * Check that the RR header is there, and parse it.
   2037 	 */
   2038 	if (isc_buffer_remaininglength(&j->it.source) < 10) {
   2039 		FAIL(DNS_R_FORMERR);
   2040 	}
   2041 
   2042 	rdtype = isc_buffer_getuint16(&j->it.source);
   2043 	rdclass = isc_buffer_getuint16(&j->it.source);
   2044 	ttl = isc_buffer_getuint32(&j->it.source);
   2045 	rdlen = isc_buffer_getuint16(&j->it.source);
   2046 
   2047 	if (rdlen > DNS_RDATA_MAXLENGTH) {
   2048 		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
   2049 			      "%s: journal corrupt: impossible rdlen "
   2050 			      "(%u bytes)",
   2051 			      j->filename, rdlen);
   2052 		FAIL(ISC_R_FAILURE);
   2053 	}
   2054 
   2055 	/*
   2056 	 * Parse the rdata.
   2057 	 */
   2058 	if (isc_buffer_remaininglength(&j->it.source) != rdlen) {
   2059 		FAIL(DNS_R_FORMERR);
   2060 	}
   2061 	isc_buffer_setactive(&j->it.source, rdlen);
   2062 	dns_rdata_reset(&j->it.rdata);
   2063 	CHECK(dns_rdata_fromwire(&j->it.rdata, rdclass, rdtype, &j->it.source,
   2064 				 &j->it.dctx, 0, &j->it.target));
   2065 	j->it.ttl = ttl;
   2066 
   2067 	j->it.xpos += sizeof(journal_rawrrhdr_t) + rrhdr.size;
   2068 	if (rdtype == dns_rdatatype_soa) {
   2069 		/* XXX could do additional consistency checks here */
   2070 		j->it.current_serial = dns_soa_getserial(&j->it.rdata);
   2071 	}
   2072 
   2073 	result = ISC_R_SUCCESS;
   2074 
   2075 failure:
   2076 	j->it.result = result;
   2077 	return (result);
   2078 }
   2079 
   2080 isc_result_t
   2081 dns_journal_next_rr(dns_journal_t *j) {
   2082 	j->it.result = read_one_rr(j);
   2083 	return (j->it.result);
   2084 }
   2085 
   2086 void
   2087 dns_journal_current_rr(dns_journal_t *j, dns_name_t **name, uint32_t *ttl,
   2088 		       dns_rdata_t **rdata) {
   2089 	REQUIRE(j->it.result == ISC_R_SUCCESS);
   2090 	*name = &j->it.name;
   2091 	*ttl = j->it.ttl;
   2092 	*rdata = &j->it.rdata;
   2093 }
   2094 
   2095 /**************************************************************************/
   2096 /*
   2097  * Generating diffs from databases
   2098  */
   2099 
   2100 /*
   2101  * Construct a diff containing all the RRs at the current name of the
   2102  * database iterator 'dbit' in database 'db', version 'ver'.
   2103  * Set '*name' to the current name, and append the diff to 'diff'.
   2104  * All new tuples will have the operation 'op'.
   2105  *
   2106  * Requires: 'name' must have buffer large enough to hold the name.
   2107  * Typically, a dns_fixedname_t would be used.
   2108  */
   2109 static isc_result_t
   2110 get_name_diff(dns_db_t *db, dns_dbversion_t *ver, isc_stdtime_t now,
   2111 	      dns_dbiterator_t *dbit, dns_name_t *name, dns_diffop_t op,
   2112 	      dns_diff_t *diff) {
   2113 	isc_result_t result;
   2114 	dns_dbnode_t *node = NULL;
   2115 	dns_rdatasetiter_t *rdsiter = NULL;
   2116 	dns_difftuple_t *tuple = NULL;
   2117 
   2118 	result = dns_dbiterator_current(dbit, &node, name);
   2119 	if (result != ISC_R_SUCCESS) {
   2120 		return (result);
   2121 	}
   2122 
   2123 	result = dns_db_allrdatasets(db, node, ver, now, &rdsiter);
   2124 	if (result != ISC_R_SUCCESS) {
   2125 		goto cleanup_node;
   2126 	}
   2127 
   2128 	for (result = dns_rdatasetiter_first(rdsiter); result == ISC_R_SUCCESS;
   2129 	     result = dns_rdatasetiter_next(rdsiter))
   2130 	{
   2131 		dns_rdataset_t rdataset;
   2132 
   2133 		dns_rdataset_init(&rdataset);
   2134 		dns_rdatasetiter_current(rdsiter, &rdataset);
   2135 
   2136 		for (result = dns_rdataset_first(&rdataset);
   2137 		     result == ISC_R_SUCCESS;
   2138 		     result = dns_rdataset_next(&rdataset))
   2139 		{
   2140 			dns_rdata_t rdata = DNS_RDATA_INIT;
   2141 			dns_rdataset_current(&rdataset, &rdata);
   2142 			result = dns_difftuple_create(diff->mctx, op, name,
   2143 						      rdataset.ttl, &rdata,
   2144 						      &tuple);
   2145 			if (result != ISC_R_SUCCESS) {
   2146 				dns_rdataset_disassociate(&rdataset);
   2147 				goto cleanup_iterator;
   2148 			}
   2149 			dns_diff_append(diff, &tuple);
   2150 		}
   2151 		dns_rdataset_disassociate(&rdataset);
   2152 		if (result != ISC_R_NOMORE) {
   2153 			goto cleanup_iterator;
   2154 		}
   2155 	}
   2156 	if (result != ISC_R_NOMORE) {
   2157 		goto cleanup_iterator;
   2158 	}
   2159 
   2160 	result = ISC_R_SUCCESS;
   2161 
   2162 cleanup_iterator:
   2163 	dns_rdatasetiter_destroy(&rdsiter);
   2164 
   2165 cleanup_node:
   2166 	dns_db_detachnode(db, &node);
   2167 
   2168 	return (result);
   2169 }
   2170 
   2171 /*
   2172  * Comparison function for use by dns_diff_subtract when sorting
   2173  * the diffs to be subtracted.  The sort keys are the rdata type
   2174  * and the rdata itself.  The owner name is ignored, because
   2175  * it is known to be the same for all tuples.
   2176  */
   2177 static int
   2178 rdata_order(const void *av, const void *bv) {
   2179 	dns_difftuple_t const *const *ap = av;
   2180 	dns_difftuple_t const *const *bp = bv;
   2181 	dns_difftuple_t const *a = *ap;
   2182 	dns_difftuple_t const *b = *bp;
   2183 	int r;
   2184 	r = (b->rdata.type - a->rdata.type);
   2185 	if (r != 0) {
   2186 		return (r);
   2187 	}
   2188 	r = dns_rdata_compare(&a->rdata, &b->rdata);
   2189 	return (r);
   2190 }
   2191 
   2192 static isc_result_t
   2193 dns_diff_subtract(dns_diff_t diff[2], dns_diff_t *r) {
   2194 	isc_result_t result;
   2195 	dns_difftuple_t *p[2];
   2196 	int i, t;
   2197 	bool append;
   2198 	dns_difftuplelist_t add, del;
   2199 
   2200 	CHECK(dns_diff_sort(&diff[0], rdata_order));
   2201 	CHECK(dns_diff_sort(&diff[1], rdata_order));
   2202 	ISC_LIST_INIT(add);
   2203 	ISC_LIST_INIT(del);
   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 				dns_difftuplelist_t *l = (i == 0) ? &add : &del;
   2215 				ISC_LIST_UNLINK(diff[i].tuples, p[i], link);
   2216 				ISC_LIST_APPEND(*l, p[i], link);
   2217 				goto next;
   2218 			}
   2219 		}
   2220 		t = rdata_order(&p[0], &p[1]);
   2221 		if (t < 0) {
   2222 			ISC_LIST_UNLINK(diff[0].tuples, p[0], link);
   2223 			ISC_LIST_APPEND(add, p[0], link);
   2224 			goto next;
   2225 		}
   2226 		if (t > 0) {
   2227 			ISC_LIST_UNLINK(diff[1].tuples, p[1], link);
   2228 			ISC_LIST_APPEND(del, p[1], link);
   2229 			goto next;
   2230 		}
   2231 		INSIST(t == 0);
   2232 		/*
   2233 		 * Identical RRs in both databases; skip them both
   2234 		 * if the ttl differs.
   2235 		 */
   2236 		append = (p[0]->ttl != p[1]->ttl);
   2237 		for (i = 0; i < 2; i++) {
   2238 			ISC_LIST_UNLINK(diff[i].tuples, p[i], link);
   2239 			if (append) {
   2240 				dns_difftuplelist_t *l = (i == 0) ? &add : &del;
   2241 				ISC_LIST_APPEND(*l, p[i], link);
   2242 			} else {
   2243 				dns_difftuple_free(&p[i]);
   2244 			}
   2245 		}
   2246 	next:;
   2247 	}
   2248 	ISC_LIST_APPENDLIST(r->tuples, del, link);
   2249 	ISC_LIST_APPENDLIST(r->tuples, add, link);
   2250 	result = ISC_R_SUCCESS;
   2251 failure:
   2252 	return (result);
   2253 }
   2254 
   2255 static isc_result_t
   2256 diff_namespace(dns_db_t *dba, dns_dbversion_t *dbvera, dns_db_t *dbb,
   2257 	       dns_dbversion_t *dbverb, unsigned int options,
   2258 	       dns_diff_t *resultdiff) {
   2259 	dns_db_t *db[2];
   2260 	dns_dbversion_t *ver[2];
   2261 	dns_dbiterator_t *dbit[2] = { NULL, NULL };
   2262 	bool have[2] = { false, false };
   2263 	dns_fixedname_t fixname[2];
   2264 	isc_result_t result, itresult[2];
   2265 	dns_diff_t diff[2];
   2266 	int i, t;
   2267 
   2268 	db[0] = dba, db[1] = dbb;
   2269 	ver[0] = dbvera, ver[1] = dbverb;
   2270 
   2271 	dns_diff_init(resultdiff->mctx, &diff[0]);
   2272 	dns_diff_init(resultdiff->mctx, &diff[1]);
   2273 
   2274 	dns_fixedname_init(&fixname[0]);
   2275 	dns_fixedname_init(&fixname[1]);
   2276 
   2277 	result = dns_db_createiterator(db[0], options, &dbit[0]);
   2278 	if (result != ISC_R_SUCCESS) {
   2279 		return (result);
   2280 	}
   2281 	result = dns_db_createiterator(db[1], options, &dbit[1]);
   2282 	if (result != ISC_R_SUCCESS) {
   2283 		goto cleanup_iterator;
   2284 	}
   2285 
   2286 	itresult[0] = dns_dbiterator_first(dbit[0]);
   2287 	itresult[1] = dns_dbiterator_first(dbit[1]);
   2288 
   2289 	for (;;) {
   2290 		for (i = 0; i < 2; i++) {
   2291 			if (!have[i] && itresult[i] == ISC_R_SUCCESS) {
   2292 				CHECK(get_name_diff(
   2293 					db[i], ver[i], 0, dbit[i],
   2294 					dns_fixedname_name(&fixname[i]),
   2295 					i == 0 ? DNS_DIFFOP_ADD
   2296 					       : DNS_DIFFOP_DEL,
   2297 					&diff[i]));
   2298 				itresult[i] = dns_dbiterator_next(dbit[i]);
   2299 				have[i] = true;
   2300 			}
   2301 		}
   2302 
   2303 		if (!have[0] && !have[1]) {
   2304 			INSIST(ISC_LIST_EMPTY(diff[0].tuples));
   2305 			INSIST(ISC_LIST_EMPTY(diff[1].tuples));
   2306 			break;
   2307 		}
   2308 
   2309 		for (i = 0; i < 2; i++) {
   2310 			if (!have[!i]) {
   2311 				ISC_LIST_APPENDLIST(resultdiff->tuples,
   2312 						    diff[i].tuples, link);
   2313 				INSIST(ISC_LIST_EMPTY(diff[i].tuples));
   2314 				have[i] = false;
   2315 				goto next;
   2316 			}
   2317 		}
   2318 
   2319 		t = dns_name_compare(dns_fixedname_name(&fixname[0]),
   2320 				     dns_fixedname_name(&fixname[1]));
   2321 		if (t < 0) {
   2322 			ISC_LIST_APPENDLIST(resultdiff->tuples, diff[0].tuples,
   2323 					    link);
   2324 			INSIST(ISC_LIST_EMPTY(diff[0].tuples));
   2325 			have[0] = false;
   2326 			continue;
   2327 		}
   2328 		if (t > 0) {
   2329 			ISC_LIST_APPENDLIST(resultdiff->tuples, diff[1].tuples,
   2330 					    link);
   2331 			INSIST(ISC_LIST_EMPTY(diff[1].tuples));
   2332 			have[1] = false;
   2333 			continue;
   2334 		}
   2335 		INSIST(t == 0);
   2336 		CHECK(dns_diff_subtract(diff, resultdiff));
   2337 		INSIST(ISC_LIST_EMPTY(diff[0].tuples));
   2338 		INSIST(ISC_LIST_EMPTY(diff[1].tuples));
   2339 		have[0] = have[1] = false;
   2340 	next:;
   2341 	}
   2342 	if (itresult[0] != ISC_R_NOMORE) {
   2343 		FAIL(itresult[0]);
   2344 	}
   2345 	if (itresult[1] != ISC_R_NOMORE) {
   2346 		FAIL(itresult[1]);
   2347 	}
   2348 
   2349 	INSIST(ISC_LIST_EMPTY(diff[0].tuples));
   2350 	INSIST(ISC_LIST_EMPTY(diff[1].tuples));
   2351 
   2352 failure:
   2353 	dns_dbiterator_destroy(&dbit[1]);
   2354 
   2355 cleanup_iterator:
   2356 	dns_dbiterator_destroy(&dbit[0]);
   2357 	dns_diff_clear(&diff[0]);
   2358 	dns_diff_clear(&diff[1]);
   2359 	return (result);
   2360 }
   2361 
   2362 /*
   2363  * Compare the databases 'dba' and 'dbb' and generate a journal
   2364  * entry containing the changes to make 'dba' from 'dbb' (note
   2365  * the order).  This journal entry will consist of a single,
   2366  * possibly very large transaction.
   2367  */
   2368 isc_result_t
   2369 dns_db_diff(isc_mem_t *mctx, dns_db_t *dba, dns_dbversion_t *dbvera,
   2370 	    dns_db_t *dbb, dns_dbversion_t *dbverb, const char *filename) {
   2371 	isc_result_t result;
   2372 	dns_diff_t diff;
   2373 
   2374 	dns_diff_init(mctx, &diff);
   2375 
   2376 	result = dns_db_diffx(&diff, dba, dbvera, dbb, dbverb, filename);
   2377 
   2378 	dns_diff_clear(&diff);
   2379 
   2380 	return (result);
   2381 }
   2382 
   2383 isc_result_t
   2384 dns_db_diffx(dns_diff_t *diff, dns_db_t *dba, dns_dbversion_t *dbvera,
   2385 	     dns_db_t *dbb, dns_dbversion_t *dbverb, const char *filename) {
   2386 	isc_result_t result;
   2387 	dns_journal_t *journal = NULL;
   2388 
   2389 	if (filename != NULL) {
   2390 		result = dns_journal_open(diff->mctx, filename,
   2391 					  DNS_JOURNAL_CREATE, &journal);
   2392 		if (result != ISC_R_SUCCESS) {
   2393 			return (result);
   2394 		}
   2395 	}
   2396 
   2397 	CHECK(diff_namespace(dba, dbvera, dbb, dbverb, DNS_DB_NONSEC3, diff));
   2398 	CHECK(diff_namespace(dba, dbvera, dbb, dbverb, DNS_DB_NSEC3ONLY, diff));
   2399 
   2400 	if (journal != NULL) {
   2401 		if (ISC_LIST_EMPTY(diff->tuples)) {
   2402 			isc_log_write(JOURNAL_DEBUG_LOGARGS(3), "no changes");
   2403 		} else {
   2404 			CHECK(dns_journal_write_transaction(journal, diff));
   2405 		}
   2406 	}
   2407 
   2408 failure:
   2409 	if (journal != NULL) {
   2410 		dns_journal_destroy(&journal);
   2411 	}
   2412 	return (result);
   2413 }
   2414 
   2415 static uint32_t
   2416 rrcount(unsigned char *buf, unsigned int size) {
   2417 	isc_buffer_t b;
   2418 	uint32_t rrsize, count = 0;
   2419 
   2420 	isc_buffer_init(&b, buf, size);
   2421 	isc_buffer_add(&b, size);
   2422 	while (isc_buffer_remaininglength(&b) > 0) {
   2423 		rrsize = isc_buffer_getuint32(&b);
   2424 		INSIST(isc_buffer_remaininglength(&b) >= rrsize);
   2425 		isc_buffer_forward(&b, rrsize);
   2426 		count++;
   2427 	}
   2428 
   2429 	return (count);
   2430 }
   2431 
   2432 static bool
   2433 check_delta(unsigned char *buf, size_t size) {
   2434 	isc_buffer_t b;
   2435 	uint32_t rrsize;
   2436 
   2437 	isc_buffer_init(&b, buf, size);
   2438 	isc_buffer_add(&b, size);
   2439 	while (isc_buffer_remaininglength(&b) > 0) {
   2440 		if (isc_buffer_remaininglength(&b) < 4) {
   2441 			return (false);
   2442 		}
   2443 		rrsize = isc_buffer_getuint32(&b);
   2444 		/* "." + type + class + ttl + rdlen => 11U */
   2445 		if (rrsize < 11U || isc_buffer_remaininglength(&b) < rrsize) {
   2446 			return (false);
   2447 		}
   2448 		isc_buffer_forward(&b, rrsize);
   2449 	}
   2450 
   2451 	return (true);
   2452 }
   2453 
   2454 isc_result_t
   2455 dns_journal_compact(isc_mem_t *mctx, char *filename, uint32_t serial,
   2456 		    uint32_t flags, uint32_t target_size) {
   2457 	unsigned int i;
   2458 	journal_pos_t best_guess;
   2459 	journal_pos_t current_pos;
   2460 	dns_journal_t *j1 = NULL;
   2461 	dns_journal_t *j2 = NULL;
   2462 	journal_rawheader_t rawheader;
   2463 	unsigned int len;
   2464 	size_t namelen;
   2465 	unsigned char *buf = NULL;
   2466 	unsigned int size = 0;
   2467 	isc_result_t result;
   2468 	unsigned int indexend;
   2469 	char newname[PATH_MAX];
   2470 	char backup[PATH_MAX];
   2471 	bool is_backup = false;
   2472 	bool rewrite = false;
   2473 	bool downgrade = false;
   2474 
   2475 	REQUIRE(filename != NULL);
   2476 
   2477 	namelen = strlen(filename);
   2478 	if (namelen > 4U && strcmp(filename + namelen - 4, ".jnl") == 0) {
   2479 		namelen -= 4;
   2480 	}
   2481 
   2482 	result = snprintf(newname, sizeof(newname), "%.*s.jnw", (int)namelen,
   2483 			  filename);
   2484 	RUNTIME_CHECK(result < sizeof(newname));
   2485 
   2486 	result = snprintf(backup, sizeof(backup), "%.*s.jbk", (int)namelen,
   2487 			  filename);
   2488 	RUNTIME_CHECK(result < sizeof(backup));
   2489 
   2490 	result = journal_open(mctx, filename, false, false, false, &j1);
   2491 	if (result == ISC_R_NOTFOUND) {
   2492 		is_backup = true;
   2493 		result = journal_open(mctx, backup, false, false, false, &j1);
   2494 	}
   2495 	if (result != ISC_R_SUCCESS) {
   2496 		return (result);
   2497 	}
   2498 
   2499 	/*
   2500 	 * Always perform a re-write when processing a version 1 journal.
   2501 	 */
   2502 	rewrite = j1->header_ver1;
   2503 
   2504 	/*
   2505 	 * Check whether we need to rewrite the whole journal
   2506 	 * file (for example, to upversion it).
   2507 	 */
   2508 	if ((flags & DNS_JOURNAL_COMPACTALL) != 0) {
   2509 		if ((flags & DNS_JOURNAL_VERSION1) != 0) {
   2510 			downgrade = true;
   2511 		}
   2512 		rewrite = true;
   2513 		serial = dns_journal_first_serial(j1);
   2514 	} else if (JOURNAL_EMPTY(&j1->header)) {
   2515 		dns_journal_destroy(&j1);
   2516 		return (ISC_R_SUCCESS);
   2517 	}
   2518 
   2519 	if (DNS_SERIAL_GT(j1->header.begin.serial, serial) ||
   2520 	    DNS_SERIAL_GT(serial, j1->header.end.serial))
   2521 	{
   2522 		dns_journal_destroy(&j1);
   2523 		return (ISC_R_RANGE);
   2524 	}
   2525 
   2526 	/*
   2527 	 * Cope with very small target sizes.
   2528 	 */
   2529 	indexend = sizeof(journal_rawheader_t) +
   2530 		   j1->header.index_size * sizeof(journal_rawpos_t);
   2531 	if (target_size < DNS_JOURNAL_SIZE_MIN) {
   2532 		target_size = DNS_JOURNAL_SIZE_MIN;
   2533 	}
   2534 	if (target_size < indexend * 2) {
   2535 		target_size = target_size / 2 + indexend;
   2536 	}
   2537 
   2538 	/*
   2539 	 * See if there is any work to do.
   2540 	 */
   2541 	if (!rewrite && (uint32_t)j1->header.end.offset < target_size) {
   2542 		dns_journal_destroy(&j1);
   2543 		return (ISC_R_SUCCESS);
   2544 	}
   2545 
   2546 	CHECK(journal_open(mctx, newname, true, true, downgrade, &j2));
   2547 	CHECK(journal_seek(j2, indexend));
   2548 
   2549 	/*
   2550 	 * Remove overhead so space test below can succeed.
   2551 	 */
   2552 	if (target_size >= indexend) {
   2553 		target_size -= indexend;
   2554 	}
   2555 
   2556 	/*
   2557 	 * Find if we can create enough free space.
   2558 	 */
   2559 	best_guess = j1->header.begin;
   2560 	for (i = 0; i < j1->header.index_size; i++) {
   2561 		if (POS_VALID(j1->index[i]) &&
   2562 		    DNS_SERIAL_GE(serial, j1->index[i].serial) &&
   2563 		    ((uint32_t)(j1->header.end.offset - j1->index[i].offset) >=
   2564 		     target_size / 2) &&
   2565 		    j1->index[i].offset > best_guess.offset)
   2566 		{
   2567 			best_guess = j1->index[i];
   2568 		}
   2569 	}
   2570 
   2571 	current_pos = best_guess;
   2572 	while (current_pos.serial != serial) {
   2573 		CHECK(journal_next(j1, &current_pos));
   2574 		if (current_pos.serial == j1->header.end.serial) {
   2575 			break;
   2576 		}
   2577 
   2578 		if (DNS_SERIAL_GE(serial, current_pos.serial) &&
   2579 		    ((uint32_t)(j1->header.end.offset - current_pos.offset) >=
   2580 		     (target_size / 2)) &&
   2581 		    current_pos.offset > best_guess.offset)
   2582 		{
   2583 			best_guess = current_pos;
   2584 		} else {
   2585 			break;
   2586 		}
   2587 	}
   2588 
   2589 	INSIST(best_guess.serial != j1->header.end.serial);
   2590 	if (best_guess.serial != serial) {
   2591 		CHECK(journal_next(j1, &best_guess));
   2592 		serial = best_guess.serial;
   2593 	}
   2594 
   2595 	/*
   2596 	 * We should now be roughly half target_size provided
   2597 	 * we did not reach 'serial'.  If not we will just copy
   2598 	 * all uncommitted deltas regardless of the size.
   2599 	 */
   2600 	len = j1->header.end.offset - best_guess.offset;
   2601 	if (len != 0) {
   2602 		CHECK(journal_seek(j1, best_guess.offset));
   2603 
   2604 		/* Prepare new header */
   2605 		j2->header.begin.serial = best_guess.serial;
   2606 		j2->header.begin.offset = indexend;
   2607 		j2->header.sourceserial = j1->header.sourceserial;
   2608 		j2->header.serialset = j1->header.serialset;
   2609 		j2->header.end.serial = j1->header.end.serial;
   2610 
   2611 		/*
   2612 		 * Only use this method if we're rewriting the
   2613 		 * journal to fix outdated transaction headers;
   2614 		 * otherwise we'll copy the whole journal without
   2615 		 * parsing individual deltas below.
   2616 		 */
   2617 		while (rewrite && len > 0) {
   2618 			journal_xhdr_t xhdr;
   2619 			isc_offset_t offset = j1->offset;
   2620 			uint32_t count;
   2621 
   2622 			result = journal_read_xhdr(j1, &xhdr);
   2623 			if (rewrite && result == ISC_R_NOMORE) {
   2624 				break;
   2625 			}
   2626 			CHECK(result);
   2627 
   2628 			size = xhdr.size;
   2629 			if (size > len) {
   2630 				isc_log_write(JOURNAL_COMMON_LOGARGS,
   2631 					      ISC_LOG_ERROR,
   2632 					      "%s: journal file corrupt, "
   2633 					      "transaction too large",
   2634 					      j1->filename);
   2635 				CHECK(ISC_R_FAILURE);
   2636 			}
   2637 			buf = isc_mem_get(mctx, size);
   2638 			result = journal_read(j1, buf, size);
   2639 
   2640 			/*
   2641 			 * If we're repairing an outdated journal, the
   2642 			 * xhdr format may be wrong.
   2643 			 */
   2644 			if (rewrite && (result != ISC_R_SUCCESS ||
   2645 					!check_delta(buf, size))) {
   2646 				if (j1->xhdr_version == XHDR_VERSION2) {
   2647 					/* XHDR_VERSION2 -> XHDR_VERSION1 */
   2648 					j1->xhdr_version = XHDR_VERSION1;
   2649 					CHECK(journal_seek(j1, offset));
   2650 					CHECK(journal_read_xhdr(j1, &xhdr));
   2651 				} else if (j1->xhdr_version == XHDR_VERSION1) {
   2652 					/* XHDR_VERSION1 -> XHDR_VERSION2 */
   2653 					j1->xhdr_version = XHDR_VERSION2;
   2654 					CHECK(journal_seek(j1, offset));
   2655 					CHECK(journal_read_xhdr(j1, &xhdr));
   2656 				}
   2657 
   2658 				/* Check again */
   2659 				isc_mem_put(mctx, buf, size);
   2660 				size = xhdr.size;
   2661 				if (size > len) {
   2662 					isc_log_write(
   2663 						JOURNAL_COMMON_LOGARGS,
   2664 						ISC_LOG_ERROR,
   2665 						"%s: journal file corrupt, "
   2666 						"transaction too large",
   2667 						j1->filename);
   2668 					CHECK(ISC_R_FAILURE);
   2669 				}
   2670 				buf = isc_mem_get(mctx, size);
   2671 				CHECK(journal_read(j1, buf, size));
   2672 
   2673 				if (!check_delta(buf, size)) {
   2674 					CHECK(ISC_R_UNEXPECTED);
   2675 				}
   2676 			} else {
   2677 				CHECK(result);
   2678 			}
   2679 
   2680 			/*
   2681 			 * Recover from incorrectly written transaction header.
   2682 			 * The incorrect header was written as size, serial0,
   2683 			 * serial1, and 0.  XHDR_VERSION2 is expecting size,
   2684 			 * count, serial0, and serial1.
   2685 			 */
   2686 			if (j1->xhdr_version == XHDR_VERSION2 &&
   2687 			    xhdr.count == serial && xhdr.serial1 == 0U &&
   2688 			    isc_serial_gt(xhdr.serial0, xhdr.count))
   2689 			{
   2690 				xhdr.serial1 = xhdr.serial0;
   2691 				xhdr.serial0 = xhdr.count;
   2692 				xhdr.count = 0;
   2693 			}
   2694 
   2695 			/*
   2696 			 * Check that xhdr is consistent.
   2697 			 */
   2698 			if (xhdr.serial0 != serial ||
   2699 			    isc_serial_le(xhdr.serial1, xhdr.serial0)) {
   2700 				CHECK(ISC_R_UNEXPECTED);
   2701 			}
   2702 
   2703 			/*
   2704 			 * Extract record count from the transaction.  This
   2705 			 * is needed when converting from XHDR_VERSION1 to
   2706 			 * XHDR_VERSION2, and when recovering from an
   2707 			 * incorrectly written XHDR_VERSION2.
   2708 			 */
   2709 			count = rrcount(buf, size);
   2710 			CHECK(journal_write_xhdr(j2, xhdr.size, count,
   2711 						 xhdr.serial0, xhdr.serial1));
   2712 			CHECK(journal_write(j2, buf, size));
   2713 
   2714 			j2->header.end.offset = j2->offset;
   2715 
   2716 			serial = xhdr.serial1;
   2717 
   2718 			len = j1->header.end.offset - j1->offset;
   2719 			isc_mem_put(mctx, buf, size);
   2720 		}
   2721 
   2722 		/*
   2723 		 * If we're not rewriting transaction headers, we can use
   2724 		 * this faster method instead.
   2725 		 */
   2726 		if (!rewrite) {
   2727 			size = ISC_MIN(64 * 1024, len);
   2728 			buf = isc_mem_get(mctx, size);
   2729 			for (i = 0; i < len; i += size) {
   2730 				unsigned int blob = ISC_MIN(size, len - i);
   2731 				CHECK(journal_read(j1, buf, blob));
   2732 				CHECK(journal_write(j2, buf, blob));
   2733 			}
   2734 
   2735 			j2->header.end.offset = indexend + len;
   2736 		}
   2737 
   2738 		CHECK(journal_fsync(j2));
   2739 
   2740 		/*
   2741 		 * Update the journal header.
   2742 		 */
   2743 		journal_header_encode(&j2->header, &rawheader);
   2744 		CHECK(journal_seek(j2, 0));
   2745 		CHECK(journal_write(j2, &rawheader, sizeof(rawheader)));
   2746 		CHECK(journal_fsync(j2));
   2747 
   2748 		/*
   2749 		 * Build new index.
   2750 		 */
   2751 		current_pos = j2->header.begin;
   2752 		while (current_pos.serial != j2->header.end.serial) {
   2753 			index_add(j2, &current_pos);
   2754 			CHECK(journal_next(j2, &current_pos));
   2755 		}
   2756 
   2757 		/*
   2758 		 * Write index.
   2759 		 */
   2760 		CHECK(index_to_disk(j2));
   2761 		CHECK(journal_fsync(j2));
   2762 
   2763 		indexend = j2->header.end.offset;
   2764 		POST(indexend);
   2765 	}
   2766 
   2767 	/*
   2768 	 * Close both journals before trying to rename files (this is
   2769 	 * necessary on WIN32).
   2770 	 */
   2771 	dns_journal_destroy(&j1);
   2772 	dns_journal_destroy(&j2);
   2773 
   2774 	/*
   2775 	 * With a UFS file system this should just succeed and be atomic.
   2776 	 * Any IXFR outs will just continue and the old journal will be
   2777 	 * removed on final close.
   2778 	 *
   2779 	 * With MSDOS / NTFS we need to do a two stage rename, triggered
   2780 	 * by EEXIST.  (If any IXFR's are running in other threads, however,
   2781 	 * this will fail, and the journal will not be compacted.  But
   2782 	 * if so, hopefully they'll be finished by the next time we
   2783 	 * compact.)
   2784 	 */
   2785 	if (rename(newname, filename) == -1) {
   2786 		if (errno == EEXIST && !is_backup) {
   2787 			result = isc_file_remove(backup);
   2788 			if (result != ISC_R_SUCCESS &&
   2789 			    result != ISC_R_FILENOTFOUND) {
   2790 				goto failure;
   2791 			}
   2792 			if (rename(filename, backup) == -1) {
   2793 				goto maperrno;
   2794 			}
   2795 			if (rename(newname, filename) == -1) {
   2796 				goto maperrno;
   2797 			}
   2798 			(void)isc_file_remove(backup);
   2799 		} else {
   2800 		maperrno:
   2801 			result = ISC_R_FAILURE;
   2802 			goto failure;
   2803 		}
   2804 	}
   2805 
   2806 	result = ISC_R_SUCCESS;
   2807 
   2808 failure:
   2809 	(void)isc_file_remove(newname);
   2810 	if (buf != NULL) {
   2811 		isc_mem_put(mctx, buf, size);
   2812 	}
   2813 	if (j1 != NULL) {
   2814 		dns_journal_destroy(&j1);
   2815 	}
   2816 	if (j2 != NULL) {
   2817 		dns_journal_destroy(&j2);
   2818 	}
   2819 	return (result);
   2820 }
   2821 
   2822 static isc_result_t
   2823 index_to_disk(dns_journal_t *j) {
   2824 	isc_result_t result = ISC_R_SUCCESS;
   2825 
   2826 	if (j->header.index_size != 0) {
   2827 		unsigned int i;
   2828 		unsigned char *p;
   2829 		unsigned int rawbytes;
   2830 
   2831 		rawbytes = j->header.index_size * sizeof(journal_rawpos_t);
   2832 
   2833 		p = j->rawindex;
   2834 		for (i = 0; i < j->header.index_size; i++) {
   2835 			encode_uint32(j->index[i].serial, p);
   2836 			p += 4;
   2837 			encode_uint32(j->index[i].offset, p);
   2838 			p += 4;
   2839 		}
   2840 		INSIST(p == j->rawindex + rawbytes);
   2841 
   2842 		CHECK(journal_seek(j, sizeof(journal_rawheader_t)));
   2843 		CHECK(journal_write(j, j->rawindex, rawbytes));
   2844 	}
   2845 failure:
   2846 	return (result);
   2847 }
   2848