journal.c revision 193149
1/*
2 * Copyright (C) 2004, 2005, 2007-2009  Internet Systems Consortium, Inc. ("ISC")
3 * Copyright (C) 1999-2002  Internet Software Consortium.
4 *
5 * Permission to use, copy, modify, and/or distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11 * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15 * PERFORMANCE OF THIS SOFTWARE.
16 */
17
18/* $Id: journal.c,v 1.103.48.2 2009/01/18 23:47:37 tbox Exp $ */
19
20#include <config.h>
21
22#include <stdlib.h>
23#include <unistd.h>
24#include <errno.h>
25
26#include <isc/file.h>
27#include <isc/mem.h>
28#include <isc/stdio.h>
29#include <isc/string.h>
30#include <isc/util.h>
31
32#include <dns/compress.h>
33#include <dns/db.h>
34#include <dns/dbiterator.h>
35#include <dns/diff.h>
36#include <dns/fixedname.h>
37#include <dns/journal.h>
38#include <dns/log.h>
39#include <dns/rdataset.h>
40#include <dns/rdatasetiter.h>
41#include <dns/result.h>
42#include <dns/soa.h>
43
44/*! \file
45 * \brief Journaling.
46 *
47 * A journal file consists of
48 *
49 *   \li A fixed-size header of type journal_rawheader_t.
50 *
51 *   \li The index.  This is an unordered array of index entries
52 *     of type journal_rawpos_t giving the locations
53 *     of some arbitrary subset of the journal's addressable
54 *     transactions.  The index entries are used as hints to
55 *     speed up the process of locating a transaction with a given
56 *     serial number.  Unused index entries have an "offset"
57 *     field of zero.  The size of the index can vary between
58 *     journal files, but does not change during the lifetime
59 *     of a file.  The size can be zero.
60 *
61 *   \li The journal data.  This  consists of one or more transactions.
62 *     Each transaction begins with a transaction header of type
63 *     journal_rawxhdr_t.  The transaction header is followed by a
64 *     sequence of RRs, similar in structure to an IXFR difference
65 *     sequence (RFC1995).  That is, the pre-transaction SOA,
66 *     zero or more other deleted RRs, the post-transaction SOA,
67 *     and zero or more other added RRs.  Unlike in IXFR, each RR
68 *     is prefixed with a 32-bit length.
69 *
70 *     The journal data part grows as new transactions are
71 *     appended to the file.  Only those transactions
72 *     whose serial number is current-(2^31-1) to current
73 *     are considered "addressable" and may be pointed
74 *     to from the header or index.  They may be preceded
75 *     by old transactions that are no longer addressable,
76 *     and they may be followed by transactions that were
77 *     appended to the journal but never committed by updating
78 *     the "end" position in the header.  The latter will
79 *     be overwritten when new transactions are added.
80 */
81/*%
82 * When true, accept IXFR difference sequences where the
83 * SOA serial number does not change (BIND 8 sends such
84 * sequences).
85 */
86static isc_boolean_t bind8_compat = ISC_TRUE; /* XXX config */
87
88/**************************************************************************/
89/*
90 * Miscellaneous utilities.
91 */
92
93#define JOURNAL_COMMON_LOGARGS \
94	dns_lctx, DNS_LOGCATEGORY_GENERAL, DNS_LOGMODULE_JOURNAL
95
96#define JOURNAL_DEBUG_LOGARGS(n) \
97	JOURNAL_COMMON_LOGARGS, ISC_LOG_DEBUG(n)
98
99/*%
100 * It would be non-sensical (or at least obtuse) to use FAIL() with an
101 * ISC_R_SUCCESS code, but the test is there to keep the Solaris compiler
102 * from complaining about "end-of-loop code not reached".
103 */
104#define FAIL(code) \
105	do { result = (code);					\
106		if (result != ISC_R_SUCCESS) goto failure;	\
107	} while (0)
108
109#define CHECK(op) \
110	do { result = (op); 					\
111		if (result != ISC_R_SUCCESS) goto failure; 	\
112	} while (0)
113
114static isc_result_t index_to_disk(dns_journal_t *);
115
116static inline isc_uint32_t
117decode_uint32(unsigned char *p) {
118	return ((p[0] << 24) +
119		(p[1] << 16) +
120		(p[2] <<  8) +
121		(p[3] <<  0));
122}
123
124static inline void
125encode_uint32(isc_uint32_t val, unsigned char *p) {
126	p[0] = (isc_uint8_t)(val >> 24);
127	p[1] = (isc_uint8_t)(val >> 16);
128	p[2] = (isc_uint8_t)(val >>  8);
129	p[3] = (isc_uint8_t)(val >>  0);
130}
131
132isc_result_t
133dns_db_createsoatuple(dns_db_t *db, dns_dbversion_t *ver, isc_mem_t *mctx,
134		      dns_diffop_t op, dns_difftuple_t **tp)
135{
136	isc_result_t result;
137	dns_dbnode_t *node;
138	dns_rdataset_t rdataset;
139	dns_rdata_t rdata = DNS_RDATA_INIT;
140	dns_name_t *zonename;
141
142	zonename = dns_db_origin(db);
143
144	node = NULL;
145	result = dns_db_findnode(db, zonename, ISC_FALSE, &node);
146	if (result != ISC_R_SUCCESS)
147		goto nonode;
148
149	dns_rdataset_init(&rdataset);
150	result = dns_db_findrdataset(db, node, ver, dns_rdatatype_soa, 0,
151				     (isc_stdtime_t)0, &rdataset, NULL);
152	if (result != ISC_R_SUCCESS)
153		goto freenode;
154
155	result = dns_rdataset_first(&rdataset);
156	if (result != ISC_R_SUCCESS)
157		goto freenode;
158
159	dns_rdataset_current(&rdataset, &rdata);
160
161	result = dns_difftuple_create(mctx, op, zonename, rdataset.ttl,
162				      &rdata, tp);
163
164	dns_rdataset_disassociate(&rdataset);
165	dns_db_detachnode(db, &node);
166	return (ISC_R_SUCCESS);
167
168 freenode:
169	dns_db_detachnode(db, &node);
170 nonode:
171	UNEXPECTED_ERROR(__FILE__, __LINE__, "missing SOA");
172	return (result);
173}
174
175/* Journaling */
176
177/*%
178 * On-disk representation of a "pointer" to a journal entry.
179 * These are used in the journal header to locate the beginning
180 * and end of the journal, and in the journal index to locate
181 * other transactions.
182 */
183typedef struct {
184	unsigned char	serial[4];  /*%< SOA serial before update. */
185	/*
186	 * XXXRTH  Should offset be 8 bytes?
187	 * XXXDCL ... probably, since isc_offset_t is 8 bytes on many OSs.
188	 * XXXAG  ... but we will not be able to seek >2G anyway on many
189	 *            platforms as long as we are using fseek() rather
190	 *            than lseek().
191	 */
192	unsigned char	offset[4];  /*%< Offset from beginning of file. */
193} journal_rawpos_t;
194
195
196/*%
197 * The header is of a fixed size, with some spare room for future
198 * extensions.
199 */
200#define JOURNAL_HEADER_SIZE 64 /* Bytes. */
201
202/*%
203 * The on-disk representation of the journal header.
204 * All numbers are stored in big-endian order.
205 */
206typedef union {
207	struct {
208		/*% File format version ID. */
209		unsigned char 		format[16];
210		/*% Position of the first addressable transaction */
211		journal_rawpos_t 	begin;
212		/*% Position of the next (yet nonexistent) transaction. */
213		journal_rawpos_t 	end;
214		/*% Number of index entries following the header. */
215		unsigned char 		index_size[4];
216	} h;
217	/* Pad the header to a fixed size. */
218	unsigned char pad[JOURNAL_HEADER_SIZE];
219} journal_rawheader_t;
220
221/*%
222 * The on-disk representation of the transaction header.
223 * There is one of these at the beginning of each transaction.
224 */
225typedef struct {
226	unsigned char	size[4]; 	/*%< In bytes, excluding header. */
227	unsigned char	serial0[4];	/*%< SOA serial before update. */
228	unsigned char	serial1[4];	/*%< SOA serial after update. */
229} journal_rawxhdr_t;
230
231/*%
232 * The on-disk representation of the RR header.
233 * There is one of these at the beginning of each RR.
234 */
235typedef struct {
236	unsigned char	size[4]; 	/*%< In bytes, excluding header. */
237} journal_rawrrhdr_t;
238
239/*%
240 * The in-core representation of the journal header.
241 */
242typedef struct {
243	isc_uint32_t	serial;
244	isc_offset_t	offset;
245} journal_pos_t;
246
247#define POS_VALID(pos) 		((pos).offset != 0)
248#define POS_INVALIDATE(pos) 	((pos).offset = 0, (pos).serial = 0)
249
250typedef struct {
251	unsigned char 	format[16];
252	journal_pos_t 	begin;
253	journal_pos_t 	end;
254	isc_uint32_t	index_size;
255} journal_header_t;
256
257/*%
258 * The in-core representation of the transaction header.
259 */
260
261typedef struct {
262	isc_uint32_t	size;
263	isc_uint32_t	serial0;
264	isc_uint32_t	serial1;
265} journal_xhdr_t;
266
267/*%
268 * The in-core representation of the RR header.
269 */
270typedef struct {
271	isc_uint32_t	size;
272} journal_rrhdr_t;
273
274
275/*%
276 * Initial contents to store in the header of a newly created
277 * journal file.
278 *
279 * The header starts with the magic string ";BIND LOG V9\n"
280 * to identify the file as a BIND 9 journal file.  An ASCII
281 * identification string is used rather than a binary magic
282 * number to be consistent with BIND 8 (BIND 8 journal files
283 * are ASCII text files).
284 */
285
286static journal_header_t
287initial_journal_header = { ";BIND LOG V9\n", { 0, 0 }, { 0, 0 }, 0 };
288
289#define JOURNAL_EMPTY(h) ((h)->begin.offset == (h)->end.offset)
290
291typedef enum {
292	JOURNAL_STATE_INVALID,
293	JOURNAL_STATE_READ,
294	JOURNAL_STATE_WRITE,
295	JOURNAL_STATE_TRANSACTION
296} journal_state_t;
297
298struct dns_journal {
299	unsigned int		magic;		/*%< JOUR */
300	isc_mem_t		*mctx;		/*%< Memory context */
301	journal_state_t		state;
302	const char 		*filename;	/*%< Journal file name */
303	FILE *			fp;		/*%< File handle */
304	isc_offset_t		offset;		/*%< Current file offset */
305	journal_header_t 	header;		/*%< In-core journal header */
306	unsigned char		*rawindex;	/*%< In-core buffer for journal index in on-disk format */
307	journal_pos_t		*index;		/*%< In-core journal index */
308
309	/*% Current transaction state (when writing). */
310	struct {
311		unsigned int	n_soa;		/*%< Number of SOAs seen */
312		journal_pos_t	pos[2];		/*%< Begin/end position */
313	} x;
314
315	/*% Iteration state (when reading). */
316	struct {
317		/* These define the part of the journal we iterate over. */
318		journal_pos_t bpos;		/*%< Position before first, */
319		journal_pos_t epos;		/*%< and after last transaction */
320		/* The rest is iterator state. */
321		isc_uint32_t current_serial;	/*%< Current SOA serial */
322		isc_buffer_t source;		/*%< Data from disk */
323		isc_buffer_t target;		/*%< Data from _fromwire check */
324		dns_decompress_t dctx;		/*%< Dummy decompression ctx */
325		dns_name_t name;		/*%< Current domain name */
326		dns_rdata_t rdata;		/*%< Current rdata */
327		isc_uint32_t ttl;		/*%< Current TTL */
328		unsigned int xsize;		/*%< Size of transaction data */
329		unsigned int xpos;		/*%< Current position in it */
330		isc_result_t result;		/*%< Result of last call */
331	} it;
332};
333
334#define DNS_JOURNAL_MAGIC	ISC_MAGIC('J', 'O', 'U', 'R')
335#define DNS_JOURNAL_VALID(t)	ISC_MAGIC_VALID(t, DNS_JOURNAL_MAGIC)
336
337static void
338journal_pos_decode(journal_rawpos_t *raw, journal_pos_t *cooked) {
339	cooked->serial = decode_uint32(raw->serial);
340	cooked->offset = decode_uint32(raw->offset);
341}
342
343static void
344journal_pos_encode(journal_rawpos_t *raw, journal_pos_t *cooked) {
345	encode_uint32(cooked->serial, raw->serial);
346	encode_uint32(cooked->offset, raw->offset);
347}
348
349static void
350journal_header_decode(journal_rawheader_t *raw, journal_header_t *cooked) {
351	INSIST(sizeof(cooked->format) == sizeof(raw->h.format));
352	memcpy(cooked->format, raw->h.format, sizeof(cooked->format));
353	journal_pos_decode(&raw->h.begin, &cooked->begin);
354	journal_pos_decode(&raw->h.end, &cooked->end);
355	cooked->index_size = decode_uint32(raw->h.index_size);
356}
357
358static void
359journal_header_encode(journal_header_t *cooked, journal_rawheader_t *raw) {
360	INSIST(sizeof(cooked->format) == sizeof(raw->h.format));
361	memset(raw->pad, 0, sizeof(raw->pad));
362	memcpy(raw->h.format, cooked->format, sizeof(raw->h.format));
363	journal_pos_encode(&raw->h.begin, &cooked->begin);
364	journal_pos_encode(&raw->h.end, &cooked->end);
365	encode_uint32(cooked->index_size, raw->h.index_size);
366}
367
368/*
369 * Journal file I/O subroutines, with error checking and reporting.
370 */
371static isc_result_t
372journal_seek(dns_journal_t *j, isc_uint32_t offset) {
373	isc_result_t result;
374	result = isc_stdio_seek(j->fp, (long)offset, SEEK_SET);
375	if (result != ISC_R_SUCCESS) {
376		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
377			      "%s: seek: %s", j->filename,
378			      isc_result_totext(result));
379		return (ISC_R_UNEXPECTED);
380	}
381	j->offset = offset;
382	return (ISC_R_SUCCESS);
383}
384
385static isc_result_t
386journal_read(dns_journal_t *j, void *mem, size_t nbytes) {
387	isc_result_t result;
388
389	result = isc_stdio_read(mem, 1, nbytes, j->fp, NULL);
390	if (result != ISC_R_SUCCESS) {
391		if (result == ISC_R_EOF)
392			return (ISC_R_NOMORE);
393		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
394			      "%s: read: %s",
395			      j->filename, isc_result_totext(result));
396		return (ISC_R_UNEXPECTED);
397	}
398	j->offset += nbytes;
399	return (ISC_R_SUCCESS);
400}
401
402static isc_result_t
403journal_write(dns_journal_t *j, void *mem, size_t nbytes) {
404	isc_result_t result;
405
406	result = isc_stdio_write(mem, 1, nbytes, j->fp, NULL);
407	if (result != ISC_R_SUCCESS) {
408		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
409			      "%s: write: %s",
410			      j->filename, isc_result_totext(result));
411		return (ISC_R_UNEXPECTED);
412	}
413	j->offset += nbytes;
414	return (ISC_R_SUCCESS);
415}
416
417static isc_result_t
418journal_fsync(dns_journal_t *j) {
419	isc_result_t result;
420	result = isc_stdio_flush(j->fp);
421	if (result != ISC_R_SUCCESS) {
422		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
423			      "%s: flush: %s",
424			      j->filename, isc_result_totext(result));
425		return (ISC_R_UNEXPECTED);
426	}
427	result = isc_stdio_sync(j->fp);
428	if (result != ISC_R_SUCCESS) {
429		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
430			      "%s: fsync: %s",
431			      j->filename, isc_result_totext(result));
432		return (ISC_R_UNEXPECTED);
433	}
434	return (ISC_R_SUCCESS);
435}
436
437/*
438 * Read/write a transaction header at the current file position.
439 */
440
441static isc_result_t
442journal_read_xhdr(dns_journal_t *j, journal_xhdr_t *xhdr) {
443	journal_rawxhdr_t raw;
444	isc_result_t result;
445	result = journal_read(j, &raw, sizeof(raw));
446	if (result != ISC_R_SUCCESS)
447		return (result);
448	xhdr->size = decode_uint32(raw.size);
449	xhdr->serial0 = decode_uint32(raw.serial0);
450	xhdr->serial1 = decode_uint32(raw.serial1);
451	return (ISC_R_SUCCESS);
452}
453
454static isc_result_t
455journal_write_xhdr(dns_journal_t *j, isc_uint32_t size,
456		   isc_uint32_t serial0, isc_uint32_t serial1)
457{
458	journal_rawxhdr_t raw;
459	encode_uint32(size, raw.size);
460	encode_uint32(serial0, raw.serial0);
461	encode_uint32(serial1, raw.serial1);
462	return (journal_write(j, &raw, sizeof(raw)));
463}
464
465
466/*
467 * Read an RR header at the current file position.
468 */
469
470static isc_result_t
471journal_read_rrhdr(dns_journal_t *j, journal_rrhdr_t *rrhdr) {
472	journal_rawrrhdr_t raw;
473	isc_result_t result;
474	result = journal_read(j, &raw, sizeof(raw));
475	if (result != ISC_R_SUCCESS)
476		return (result);
477	rrhdr->size = decode_uint32(raw.size);
478	return (ISC_R_SUCCESS);
479}
480
481static isc_result_t
482journal_file_create(isc_mem_t *mctx, const char *filename) {
483	FILE *fp = NULL;
484	isc_result_t result;
485	journal_header_t header;
486	journal_rawheader_t rawheader;
487	int index_size = 56; /* XXX configurable */
488	int size;
489	void *mem; /* Memory for temporary index image. */
490
491	INSIST(sizeof(journal_rawheader_t) == JOURNAL_HEADER_SIZE);
492
493	result = isc_stdio_open(filename, "wb", &fp);
494	if (result != ISC_R_SUCCESS) {
495		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
496			      "%s: create: %s",
497			      filename, isc_result_totext(result));
498		return (ISC_R_UNEXPECTED);
499	}
500
501	header = initial_journal_header;
502	header.index_size = index_size;
503	journal_header_encode(&header, &rawheader);
504
505	size = sizeof(journal_rawheader_t) +
506		index_size * sizeof(journal_rawpos_t);
507
508	mem = isc_mem_get(mctx, size);
509	if (mem == NULL) {
510		(void)isc_stdio_close(fp);
511		(void)isc_file_remove(filename);
512		return (ISC_R_NOMEMORY);
513	}
514	memset(mem, 0, size);
515	memcpy(mem, &rawheader, sizeof(rawheader));
516
517	result = isc_stdio_write(mem, 1, (size_t) size, fp, NULL);
518	if (result != ISC_R_SUCCESS) {
519		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
520				 "%s: write: %s",
521				 filename, isc_result_totext(result));
522		(void)isc_stdio_close(fp);
523		(void)isc_file_remove(filename);
524		isc_mem_put(mctx, mem, size);
525		return (ISC_R_UNEXPECTED);
526	}
527	isc_mem_put(mctx, mem, size);
528
529	result = isc_stdio_close(fp);
530	if (result != ISC_R_SUCCESS) {
531		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
532				 "%s: close: %s",
533				 filename, isc_result_totext(result));
534		(void)isc_file_remove(filename);
535		return (ISC_R_UNEXPECTED);
536	}
537
538	return (ISC_R_SUCCESS);
539}
540
541static isc_result_t
542journal_open(isc_mem_t *mctx, const char *filename, isc_boolean_t write,
543	     isc_boolean_t create, dns_journal_t **journalp) {
544	FILE *fp = NULL;
545	isc_result_t result;
546	journal_rawheader_t rawheader;
547	dns_journal_t *j;
548
549	INSIST(journalp != NULL && *journalp == NULL);
550	j = isc_mem_get(mctx, sizeof(*j));
551	if (j == NULL)
552		return (ISC_R_NOMEMORY);
553
554	j->mctx = mctx;
555	j->state = JOURNAL_STATE_INVALID;
556	j->fp = NULL;
557	j->filename = filename;
558	j->index = NULL;
559	j->rawindex = NULL;
560
561	result = isc_stdio_open(j->filename, write ? "rb+" : "rb", &fp);
562
563	if (result == ISC_R_FILENOTFOUND) {
564		if (create) {
565			isc_log_write(JOURNAL_COMMON_LOGARGS,
566				      ISC_LOG_INFO,
567				      "journal file %s does not exist, "
568				      "creating it",
569				      j->filename);
570			CHECK(journal_file_create(mctx, filename));
571			/*
572			 * Retry.
573			 */
574			result = isc_stdio_open(j->filename, "rb+", &fp);
575		} else {
576			FAIL(ISC_R_NOTFOUND);
577		}
578	}
579	if (result != ISC_R_SUCCESS) {
580		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
581			      "%s: open: %s",
582			      j->filename, isc_result_totext(result));
583		FAIL(ISC_R_UNEXPECTED);
584	}
585
586	j->fp = fp;
587
588	/*
589	 * Set magic early so that seek/read can succeed.
590	 */
591	j->magic = DNS_JOURNAL_MAGIC;
592
593	CHECK(journal_seek(j, 0));
594	CHECK(journal_read(j, &rawheader, sizeof(rawheader)));
595
596	if (memcmp(rawheader.h.format, initial_journal_header.format,
597		   sizeof(initial_journal_header.format)) != 0) {
598		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
599				 "%s: journal format not recognized",
600				 j->filename);
601		FAIL(ISC_R_UNEXPECTED);
602	}
603	journal_header_decode(&rawheader, &j->header);
604
605	/*
606	 * If there is an index, read the raw index into a dynamically
607	 * allocated buffer and then convert it into a cooked index.
608	 */
609	if (j->header.index_size != 0) {
610		unsigned int i;
611		unsigned int rawbytes;
612		unsigned char *p;
613
614		rawbytes = j->header.index_size * sizeof(journal_rawpos_t);
615		j->rawindex = isc_mem_get(mctx, rawbytes);
616		if (j->rawindex == NULL)
617			FAIL(ISC_R_NOMEMORY);
618
619		CHECK(journal_read(j, j->rawindex, rawbytes));
620
621		j->index = isc_mem_get(mctx, j->header.index_size *
622				       sizeof(journal_pos_t));
623		if (j->index == NULL)
624			FAIL(ISC_R_NOMEMORY);
625
626		p = j->rawindex;
627		for (i = 0; i < j->header.index_size; i++) {
628			j->index[i].serial = decode_uint32(p);
629			p += 4;
630			j->index[i].offset = decode_uint32(p);
631			p += 4;
632		}
633		INSIST(p == j->rawindex + rawbytes);
634	}
635	j->offset = -1; /* Invalid, must seek explicitly. */
636
637	/*
638	 * Initialize the iterator.
639	 */
640	dns_name_init(&j->it.name, NULL);
641	dns_rdata_init(&j->it.rdata);
642
643	/*
644	 * Set up empty initial buffers for unchecked and checked
645	 * wire format RR data.  They will be reallocated
646	 * later.
647	 */
648	isc_buffer_init(&j->it.source, NULL, 0);
649	isc_buffer_init(&j->it.target, NULL, 0);
650	dns_decompress_init(&j->it.dctx, -1, DNS_DECOMPRESS_NONE);
651
652	j->state =
653		write ? JOURNAL_STATE_WRITE : JOURNAL_STATE_READ;
654
655	*journalp = j;
656	return (ISC_R_SUCCESS);
657
658 failure:
659	j->magic = 0;
660	if (j->index != NULL) {
661		isc_mem_put(j->mctx, j->index, j->header.index_size *
662			    sizeof(journal_rawpos_t));
663		j->index = NULL;
664	}
665	if (j->fp != NULL)
666		(void)isc_stdio_close(j->fp);
667	isc_mem_put(j->mctx, j, sizeof(*j));
668	return (result);
669}
670
671isc_result_t
672dns_journal_open(isc_mem_t *mctx, const char *filename, isc_boolean_t write,
673		 dns_journal_t **journalp) {
674	isc_result_t result;
675	int namelen;
676	char backup[1024];
677
678	result = journal_open(mctx, filename, write, write, journalp);
679	if (result == ISC_R_NOTFOUND) {
680		namelen = strlen(filename);
681		if (namelen > 4 && strcmp(filename + namelen - 4, ".jnl") == 0)
682			namelen -= 4;
683
684		result = isc_string_printf(backup, sizeof(backup), "%.*s.jbk",
685					   namelen, filename);
686		if (result != ISC_R_SUCCESS)
687			return (result);
688		result = journal_open(mctx, backup, write, write, journalp);
689	}
690	return (result);
691}
692
693/*
694 * A comparison function defining the sorting order for
695 * entries in the IXFR-style journal file.
696 *
697 * The IXFR format requires that deletions are sorted before
698 * additions, and within either one, SOA records are sorted
699 * before others.
700 *
701 * Also sort the non-SOA records by type as a courtesy to the
702 * server receiving the IXFR - it may help reduce the amount of
703 * rdataset merging it has to do.
704 */
705static int
706ixfr_order(const void *av, const void *bv) {
707	dns_difftuple_t const * const *ap = av;
708	dns_difftuple_t const * const *bp = bv;
709	dns_difftuple_t const *a = *ap;
710	dns_difftuple_t const *b = *bp;
711	int r;
712	int bop = 0, aop = 0;
713
714	switch (a->op) {
715	case DNS_DIFFOP_DEL:
716	case DNS_DIFFOP_DELRESIGN:
717		aop = 1;
718		break;
719	case DNS_DIFFOP_ADD:
720	case DNS_DIFFOP_ADDRESIGN:
721		aop = 0;
722		break;
723	default:
724		INSIST(0);
725	}
726
727	switch (b->op) {
728	case DNS_DIFFOP_DEL:
729	case DNS_DIFFOP_DELRESIGN:
730		bop = 1;
731		break;
732	case DNS_DIFFOP_ADD:
733	case DNS_DIFFOP_ADDRESIGN:
734		bop = 0;
735		break;
736	default:
737		INSIST(0);
738	}
739
740	r = bop - aop;
741	if (r != 0)
742		return (r);
743
744	r = (b->rdata.type == dns_rdatatype_soa) -
745		(a->rdata.type == dns_rdatatype_soa);
746	if (r != 0)
747		return (r);
748
749	r = (a->rdata.type - b->rdata.type);
750	return (r);
751}
752
753/*
754 * Advance '*pos' to the next journal transaction.
755 *
756 * Requires:
757 *	*pos refers to a valid journal transaction.
758 *
759 * Ensures:
760 *	When ISC_R_SUCCESS is returned,
761 *	*pos refers to the next journal transaction.
762 *
763 * Returns one of:
764 *
765 *    ISC_R_SUCCESS
766 *    ISC_R_NOMORE 	*pos pointed at the last transaction
767 *    Other results due to file errors are possible.
768 */
769static isc_result_t
770journal_next(dns_journal_t *j, journal_pos_t *pos) {
771	isc_result_t result;
772	journal_xhdr_t xhdr;
773	REQUIRE(DNS_JOURNAL_VALID(j));
774
775	result = journal_seek(j, pos->offset);
776	if (result != ISC_R_SUCCESS)
777		return (result);
778
779	if (pos->serial == j->header.end.serial)
780		return (ISC_R_NOMORE);
781	/*
782	 * Read the header of the current transaction.
783	 * This will return ISC_R_NOMORE if we are at EOF.
784	 */
785	result = journal_read_xhdr(j, &xhdr);
786	if (result != ISC_R_SUCCESS)
787		return (result);
788
789	/*
790	 * Check serial number consistency.
791	 */
792	if (xhdr.serial0 != pos->serial) {
793		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
794			      "%s: journal file corrupt: "
795			      "expected serial %u, got %u",
796			      j->filename, pos->serial, xhdr.serial0);
797		return (ISC_R_UNEXPECTED);
798	}
799
800	/*
801	 * Check for offset wraparound.
802	 */
803	if ((isc_offset_t)(pos->offset + sizeof(journal_rawxhdr_t) + xhdr.size)
804	    < pos->offset) {
805		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
806			      "%s: offset too large", j->filename);
807		return (ISC_R_UNEXPECTED);
808	}
809
810	pos->offset += sizeof(journal_rawxhdr_t) + xhdr.size;
811	pos->serial = xhdr.serial1;
812	return (ISC_R_SUCCESS);
813}
814
815/*
816 * If the index of the journal 'j' contains an entry "better"
817 * than '*best_guess', replace '*best_guess' with it.
818 *
819 * "Better" means having a serial number closer to 'serial'
820 * but not greater than 'serial'.
821 */
822static void
823index_find(dns_journal_t *j, isc_uint32_t serial, journal_pos_t *best_guess) {
824	unsigned int i;
825	if (j->index == NULL)
826		return;
827	for (i = 0; i < j->header.index_size; i++) {
828		if (POS_VALID(j->index[i]) &&
829		    DNS_SERIAL_GE(serial, j->index[i].serial) &&
830		    DNS_SERIAL_GT(j->index[i].serial, best_guess->serial))
831			*best_guess = j->index[i];
832	}
833}
834
835/*
836 * Add a new index entry.  If there is no room, make room by removing
837 * the odd-numbered entries and compacting the others into the first
838 * half of the index.  This decimates old index entries exponentially
839 * over time, so that the index always contains a much larger fraction
840 * of recent serial numbers than of old ones.  This is deliberate -
841 * most index searches are for outgoing IXFR, and IXFR tends to request
842 * recent versions more often than old ones.
843 */
844static void
845index_add(dns_journal_t *j, journal_pos_t *pos) {
846	unsigned int i;
847	if (j->index == NULL)
848		return;
849	/*
850	 * Search for a vacant position.
851	 */
852	for (i = 0; i < j->header.index_size; i++) {
853		if (! POS_VALID(j->index[i]))
854			break;
855	}
856	if (i == j->header.index_size) {
857		unsigned int k = 0;
858		/*
859		 * Found no vacant position.  Make some room.
860		 */
861		for (i = 0; i < j->header.index_size; i += 2) {
862			j->index[k++] = j->index[i];
863		}
864		i = k; /* 'i' identifies the first vacant position. */
865		while (k < j->header.index_size) {
866			POS_INVALIDATE(j->index[k]);
867			k++;
868		}
869	}
870	INSIST(i < j->header.index_size);
871	INSIST(! POS_VALID(j->index[i]));
872
873	/*
874	 * Store the new index entry.
875	 */
876	j->index[i] = *pos;
877}
878
879/*
880 * Invalidate any existing index entries that could become
881 * ambiguous when a new transaction with number 'serial' is added.
882 */
883static void
884index_invalidate(dns_journal_t *j, isc_uint32_t serial) {
885	unsigned int i;
886	if (j->index == NULL)
887		return;
888	for (i = 0; i < j->header.index_size; i++) {
889		if (! DNS_SERIAL_GT(serial, j->index[i].serial))
890			POS_INVALIDATE(j->index[i]);
891	}
892}
893
894/*
895 * Try to find a transaction with initial serial number 'serial'
896 * in the journal 'j'.
897 *
898 * If found, store its position at '*pos' and return ISC_R_SUCCESS.
899 *
900 * If 'serial' is current (= the ending serial number of the
901 * last transaction in the journal), set '*pos' to
902 * the position immediately following the last transaction and
903 * return ISC_R_SUCCESS.
904 *
905 * If 'serial' is within the range of addressable serial numbers
906 * covered by the journal but that particular serial number is missing
907 * (from the journal, not just from the index), return ISC_R_NOTFOUND.
908 *
909 * If 'serial' is outside the range of addressable serial numbers
910 * covered by the journal, return ISC_R_RANGE.
911 *
912 */
913static isc_result_t
914journal_find(dns_journal_t *j, isc_uint32_t serial, journal_pos_t *pos) {
915	isc_result_t result;
916	journal_pos_t current_pos;
917	REQUIRE(DNS_JOURNAL_VALID(j));
918
919	if (DNS_SERIAL_GT(j->header.begin.serial, serial))
920		return (ISC_R_RANGE);
921	if (DNS_SERIAL_GT(serial, j->header.end.serial))
922		return (ISC_R_RANGE);
923	if (serial == j->header.end.serial) {
924		*pos = j->header.end;
925		return (ISC_R_SUCCESS);
926	}
927
928	current_pos = j->header.begin;
929	index_find(j, serial, &current_pos);
930
931	while (current_pos.serial != serial) {
932		if (DNS_SERIAL_GT(current_pos.serial, serial))
933			return (ISC_R_NOTFOUND);
934		result = journal_next(j, &current_pos);
935		if (result != ISC_R_SUCCESS)
936			return (result);
937	}
938	*pos = current_pos;
939	return (ISC_R_SUCCESS);
940}
941
942isc_result_t
943dns_journal_begin_transaction(dns_journal_t *j) {
944	isc_uint32_t offset;
945	isc_result_t result;
946	journal_rawxhdr_t hdr;
947
948	REQUIRE(DNS_JOURNAL_VALID(j));
949	REQUIRE(j->state == JOURNAL_STATE_WRITE);
950
951	/*
952	 * Find the file offset where the new transaction should
953	 * be written, and seek there.
954	 */
955	if (JOURNAL_EMPTY(&j->header)) {
956		offset = sizeof(journal_rawheader_t) +
957			j->header.index_size * sizeof(journal_rawpos_t);
958	} else {
959		offset = j->header.end.offset;
960	}
961	j->x.pos[0].offset = offset;
962	j->x.pos[1].offset = offset; /* Initial value, will be incremented. */
963	j->x.n_soa = 0;
964
965	CHECK(journal_seek(j, offset));
966
967	/*
968	 * Write a dummy transaction header of all zeroes to reserve
969	 * space.  It will be filled in when the transaction is
970	 * finished.
971	 */
972	memset(&hdr, 0, sizeof(hdr));
973	CHECK(journal_write(j, &hdr, sizeof(hdr)));
974	j->x.pos[1].offset = j->offset;
975
976	j->state = JOURNAL_STATE_TRANSACTION;
977	result = ISC_R_SUCCESS;
978 failure:
979	return (result);
980}
981
982isc_result_t
983dns_journal_writediff(dns_journal_t *j, dns_diff_t *diff) {
984	dns_difftuple_t *t;
985	isc_buffer_t buffer;
986	void *mem = NULL;
987	unsigned int size;
988	isc_result_t result;
989	isc_region_t used;
990
991	REQUIRE(DNS_DIFF_VALID(diff));
992	REQUIRE(j->state == JOURNAL_STATE_TRANSACTION);
993
994	isc_log_write(JOURNAL_DEBUG_LOGARGS(3), "writing to journal");
995	(void)dns_diff_print(diff, NULL);
996
997	/*
998	 * Pass 1: determine the buffer size needed, and
999	 * keep track of SOA serial numbers.
1000	 */
1001	size = 0;
1002	for (t = ISC_LIST_HEAD(diff->tuples); t != NULL;
1003	     t = ISC_LIST_NEXT(t, link))
1004	{
1005		if (t->rdata.type == dns_rdatatype_soa) {
1006			if (j->x.n_soa < 2)
1007				j->x.pos[j->x.n_soa].serial =
1008					dns_soa_getserial(&t->rdata);
1009			j->x.n_soa++;
1010		}
1011		size += sizeof(journal_rawrrhdr_t);
1012		size += t->name.length; /* XXX should have access macro? */
1013		size += 10;
1014		size += t->rdata.length;
1015	}
1016
1017	mem = isc_mem_get(j->mctx, size);
1018	if (mem == NULL)
1019		return (ISC_R_NOMEMORY);
1020
1021	isc_buffer_init(&buffer, mem, size);
1022
1023	/*
1024	 * Pass 2.  Write RRs to buffer.
1025	 */
1026	for (t = ISC_LIST_HEAD(diff->tuples); t != NULL;
1027	     t = ISC_LIST_NEXT(t, link))
1028	{
1029		/*
1030		 * Write the RR header.
1031		 */
1032		isc_buffer_putuint32(&buffer, t->name.length + 10 +
1033				     t->rdata.length);
1034		/*
1035		 * Write the owner name, RR header, and RR data.
1036		 */
1037		isc_buffer_putmem(&buffer, t->name.ndata, t->name.length);
1038		isc_buffer_putuint16(&buffer, t->rdata.type);
1039		isc_buffer_putuint16(&buffer, t->rdata.rdclass);
1040		isc_buffer_putuint32(&buffer, t->ttl);
1041		INSIST(t->rdata.length < 65536);
1042		isc_buffer_putuint16(&buffer, (isc_uint16_t)t->rdata.length);
1043		INSIST(isc_buffer_availablelength(&buffer) >= t->rdata.length);
1044		isc_buffer_putmem(&buffer, t->rdata.data, t->rdata.length);
1045	}
1046
1047	isc_buffer_usedregion(&buffer, &used);
1048	INSIST(used.length == size);
1049
1050	j->x.pos[1].offset += used.length;
1051
1052	/*
1053	 * Write the buffer contents to the journal file.
1054	 */
1055	CHECK(journal_write(j, used.base, used.length));
1056
1057	result = ISC_R_SUCCESS;
1058
1059 failure:
1060	if (mem != NULL)
1061		isc_mem_put(j->mctx, mem, size);
1062	return (result);
1063
1064}
1065
1066isc_result_t
1067dns_journal_commit(dns_journal_t *j) {
1068	isc_result_t result;
1069	journal_rawheader_t rawheader;
1070
1071	REQUIRE(DNS_JOURNAL_VALID(j));
1072	REQUIRE(j->state == JOURNAL_STATE_TRANSACTION);
1073
1074	/*
1075	 * Perform some basic consistency checks.
1076	 */
1077	if (j->x.n_soa != 2) {
1078		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1079			      "%s: malformed transaction: %d SOAs",
1080			      j->filename, j->x.n_soa);
1081		return (ISC_R_UNEXPECTED);
1082	}
1083	if (! (DNS_SERIAL_GT(j->x.pos[1].serial, j->x.pos[0].serial) ||
1084	       (bind8_compat &&
1085		j->x.pos[1].serial == j->x.pos[0].serial)))
1086	{
1087		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1088			      "%s: malformed transaction: serial number "
1089			      "would decrease", j->filename);
1090		return (ISC_R_UNEXPECTED);
1091	}
1092	if (! JOURNAL_EMPTY(&j->header)) {
1093		if (j->x.pos[0].serial != j->header.end.serial) {
1094			isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1095					 "malformed transaction: "
1096					 "%s last serial %u != "
1097					 "transaction first serial %u",
1098					 j->filename,
1099					 j->header.end.serial,
1100					 j->x.pos[0].serial);
1101			return (ISC_R_UNEXPECTED);
1102		}
1103	}
1104
1105	/*
1106	 * Some old journal entries may become non-addressable
1107	 * when we increment the current serial number.  Purge them
1108	 * by stepping header.begin forward to the first addressable
1109	 * transaction.  Also purge them from the index.
1110	 */
1111	if (! JOURNAL_EMPTY(&j->header)) {
1112		while (! DNS_SERIAL_GT(j->x.pos[1].serial,
1113				       j->header.begin.serial)) {
1114			CHECK(journal_next(j, &j->header.begin));
1115		}
1116		index_invalidate(j, j->x.pos[1].serial);
1117	}
1118#ifdef notyet
1119	if (DNS_SERIAL_GT(last_dumped_serial, j->x.pos[1].serial)) {
1120		force_dump(...);
1121	}
1122#endif
1123
1124	/*
1125	 * Commit the transaction data to stable storage.
1126	 */
1127	CHECK(journal_fsync(j));
1128
1129	/*
1130	 * Update the transaction header.
1131	 */
1132	CHECK(journal_seek(j, j->x.pos[0].offset));
1133	CHECK(journal_write_xhdr(j, (j->x.pos[1].offset - j->x.pos[0].offset) -
1134				 sizeof(journal_rawxhdr_t),
1135				 j->x.pos[0].serial, j->x.pos[1].serial));
1136
1137	/*
1138	 * Update the journal header.
1139	 */
1140	if (JOURNAL_EMPTY(&j->header)) {
1141		j->header.begin = j->x.pos[0];
1142	}
1143	j->header.end = j->x.pos[1];
1144	journal_header_encode(&j->header, &rawheader);
1145	CHECK(journal_seek(j, 0));
1146	CHECK(journal_write(j, &rawheader, sizeof(rawheader)));
1147
1148	/*
1149	 * Update the index.
1150	 */
1151	index_add(j, &j->x.pos[0]);
1152
1153	/*
1154	 * Convert the index into on-disk format and write
1155	 * it to disk.
1156	 */
1157	CHECK(index_to_disk(j));
1158
1159	/*
1160	 * Commit the header to stable storage.
1161	 */
1162	CHECK(journal_fsync(j));
1163
1164	/*
1165	 * We no longer have a transaction open.
1166	 */
1167	j->state = JOURNAL_STATE_WRITE;
1168
1169	result = ISC_R_SUCCESS;
1170
1171 failure:
1172	return (result);
1173}
1174
1175isc_result_t
1176dns_journal_write_transaction(dns_journal_t *j, dns_diff_t *diff) {
1177	isc_result_t result;
1178	CHECK(dns_diff_sort(diff, ixfr_order));
1179	CHECK(dns_journal_begin_transaction(j));
1180	CHECK(dns_journal_writediff(j, diff));
1181	CHECK(dns_journal_commit(j));
1182	result = ISC_R_SUCCESS;
1183 failure:
1184	return (result);
1185}
1186
1187void
1188dns_journal_destroy(dns_journal_t **journalp) {
1189	dns_journal_t *j = *journalp;
1190	REQUIRE(DNS_JOURNAL_VALID(j));
1191
1192	j->it.result = ISC_R_FAILURE;
1193	dns_name_invalidate(&j->it.name);
1194	dns_decompress_invalidate(&j->it.dctx);
1195	if (j->rawindex != NULL)
1196		isc_mem_put(j->mctx, j->rawindex, j->header.index_size *
1197			    sizeof(journal_rawpos_t));
1198	if (j->index != NULL)
1199		isc_mem_put(j->mctx, j->index, j->header.index_size *
1200			    sizeof(journal_pos_t));
1201	if (j->it.target.base != NULL)
1202		isc_mem_put(j->mctx, j->it.target.base, j->it.target.length);
1203	if (j->it.source.base != NULL)
1204		isc_mem_put(j->mctx, j->it.source.base, j->it.source.length);
1205
1206	if (j->fp != NULL)
1207		(void)isc_stdio_close(j->fp);
1208	j->magic = 0;
1209	isc_mem_put(j->mctx, j, sizeof(*j));
1210	*journalp = NULL;
1211}
1212
1213/*
1214 * Roll the open journal 'j' into the database 'db'.
1215 * A new database version will be created.
1216 */
1217
1218/* XXX Share code with incoming IXFR? */
1219
1220static isc_result_t
1221roll_forward(dns_journal_t *j, dns_db_t *db, unsigned int options) {
1222	isc_buffer_t source;		/* Transaction data from disk */
1223	isc_buffer_t target;		/* Ditto after _fromwire check */
1224	isc_uint32_t db_serial;		/* Database SOA serial */
1225	isc_uint32_t end_serial;	/* Last journal SOA serial */
1226	isc_result_t result;
1227	dns_dbversion_t *ver = NULL;
1228	journal_pos_t pos;
1229	dns_diff_t diff;
1230	unsigned int n_soa = 0;
1231	unsigned int n_put = 0;
1232	dns_diffop_t op;
1233
1234	REQUIRE(DNS_JOURNAL_VALID(j));
1235	REQUIRE(DNS_DB_VALID(db));
1236
1237	dns_diff_init(j->mctx, &diff);
1238
1239	/*
1240	 * Set up empty initial buffers for unchecked and checked
1241	 * wire format transaction data.  They will be reallocated
1242	 * later.
1243	 */
1244	isc_buffer_init(&source, NULL, 0);
1245	isc_buffer_init(&target, NULL, 0);
1246
1247	/*
1248	 * Create the new database version.
1249	 */
1250	CHECK(dns_db_newversion(db, &ver));
1251
1252	/*
1253	 * Get the current database SOA serial number.
1254	 */
1255	CHECK(dns_db_getsoaserial(db, ver, &db_serial));
1256
1257	/*
1258	 * Locate a journal entry for the current database serial.
1259	 */
1260	CHECK(journal_find(j, db_serial, &pos));
1261	/*
1262	 * XXX do more drastic things, like marking zone stale,
1263	 * if this fails?
1264	 */
1265	/*
1266	 * XXXRTH  The zone code should probably mark the zone as bad and
1267	 *         scream loudly into the log if this is a dynamic update
1268	 *	   log reply that failed.
1269	 */
1270
1271	end_serial = dns_journal_last_serial(j);
1272	if (db_serial == end_serial)
1273		CHECK(DNS_R_UPTODATE);
1274
1275	CHECK(dns_journal_iter_init(j, db_serial, end_serial));
1276
1277	for (result = dns_journal_first_rr(j);
1278	     result == ISC_R_SUCCESS;
1279	     result = dns_journal_next_rr(j))
1280	{
1281		dns_name_t *name;
1282		isc_uint32_t ttl;
1283		dns_rdata_t *rdata;
1284		dns_difftuple_t *tuple = NULL;
1285
1286		name = NULL;
1287		rdata = NULL;
1288		dns_journal_current_rr(j, &name, &ttl, &rdata);
1289
1290		if (rdata->type == dns_rdatatype_soa) {
1291			n_soa++;
1292			if (n_soa == 2)
1293				db_serial = j->it.current_serial;
1294		}
1295
1296		if (n_soa == 3)
1297			n_soa = 1;
1298		if (n_soa == 0) {
1299			isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1300					 "%s: journal file corrupt: missing "
1301					 "initial SOA", j->filename);
1302			FAIL(ISC_R_UNEXPECTED);
1303		}
1304		if ((options & DNS_JOURNALOPT_RESIGN) != 0)
1305			op = (n_soa == 1) ? DNS_DIFFOP_DELRESIGN :
1306					    DNS_DIFFOP_ADDRESIGN;
1307		else
1308			op = (n_soa == 1) ? DNS_DIFFOP_DEL : DNS_DIFFOP_ADD;
1309
1310		CHECK(dns_difftuple_create(diff.mctx, op, name, ttl, rdata,
1311					   &tuple));
1312		dns_diff_append(&diff, &tuple);
1313
1314		if (++n_put > 100)  {
1315			isc_log_write(JOURNAL_DEBUG_LOGARGS(3),
1316				      "%s: applying diff to database (%u)",
1317				      j->filename, db_serial);
1318			(void)dns_diff_print(&diff, NULL);
1319			CHECK(dns_diff_apply(&diff, db, ver));
1320			dns_diff_clear(&diff);
1321			n_put = 0;
1322		}
1323	}
1324	if (result == ISC_R_NOMORE)
1325		result = ISC_R_SUCCESS;
1326	CHECK(result);
1327
1328	if (n_put != 0) {
1329		isc_log_write(JOURNAL_DEBUG_LOGARGS(3),
1330			      "%s: applying final diff to database (%u)",
1331			      j->filename, db_serial);
1332		(void)dns_diff_print(&diff, NULL);
1333		CHECK(dns_diff_apply(&diff, db, ver));
1334		dns_diff_clear(&diff);
1335	}
1336
1337 failure:
1338	if (ver != NULL)
1339		dns_db_closeversion(db, &ver, result == ISC_R_SUCCESS ?
1340				    ISC_TRUE : ISC_FALSE);
1341
1342	if (source.base != NULL)
1343		isc_mem_put(j->mctx, source.base, source.length);
1344	if (target.base != NULL)
1345		isc_mem_put(j->mctx, target.base, target.length);
1346
1347	dns_diff_clear(&diff);
1348
1349	return (result);
1350}
1351
1352isc_result_t
1353dns_journal_rollforward(isc_mem_t *mctx, dns_db_t *db,
1354			unsigned int options, const char *filename)
1355{
1356	dns_journal_t *j;
1357	isc_result_t result;
1358
1359	REQUIRE(DNS_DB_VALID(db));
1360	REQUIRE(filename != NULL);
1361
1362	j = NULL;
1363	result = dns_journal_open(mctx, filename, ISC_FALSE, &j);
1364	if (result == ISC_R_NOTFOUND) {
1365		isc_log_write(JOURNAL_DEBUG_LOGARGS(3),
1366			      "no journal file, but that's OK");
1367		return (DNS_R_NOJOURNAL);
1368	}
1369	if (result != ISC_R_SUCCESS)
1370		return (result);
1371	if (JOURNAL_EMPTY(&j->header))
1372		result = DNS_R_UPTODATE;
1373	else
1374		result = roll_forward(j, db, options);
1375
1376	dns_journal_destroy(&j);
1377
1378	return (result);
1379}
1380
1381isc_result_t
1382dns_journal_print(isc_mem_t *mctx, const char *filename, FILE *file) {
1383	dns_journal_t *j;
1384	isc_buffer_t source;		/* Transaction data from disk */
1385	isc_buffer_t target;		/* Ditto after _fromwire check */
1386	isc_uint32_t start_serial;		/* Database SOA serial */
1387	isc_uint32_t end_serial;	/* Last journal SOA serial */
1388	isc_result_t result;
1389	dns_diff_t diff;
1390	unsigned int n_soa = 0;
1391	unsigned int n_put = 0;
1392
1393	REQUIRE(filename != NULL);
1394
1395	j = NULL;
1396	result = dns_journal_open(mctx, filename, ISC_FALSE, &j);
1397	if (result == ISC_R_NOTFOUND) {
1398		isc_log_write(JOURNAL_DEBUG_LOGARGS(3), "no journal file");
1399		return (DNS_R_NOJOURNAL);
1400	}
1401
1402	if (result != ISC_R_SUCCESS) {
1403		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1404			      "journal open failure: %s: %s",
1405			      isc_result_totext(result), filename);
1406		return (result);
1407	}
1408
1409	dns_diff_init(j->mctx, &diff);
1410
1411	/*
1412	 * Set up empty initial buffers for unchecked and checked
1413	 * wire format transaction data.  They will be reallocated
1414	 * later.
1415	 */
1416	isc_buffer_init(&source, NULL, 0);
1417	isc_buffer_init(&target, NULL, 0);
1418
1419	start_serial = dns_journal_first_serial(j);
1420	end_serial = dns_journal_last_serial(j);
1421
1422	CHECK(dns_journal_iter_init(j, start_serial, end_serial));
1423
1424	for (result = dns_journal_first_rr(j);
1425	     result == ISC_R_SUCCESS;
1426	     result = dns_journal_next_rr(j))
1427	{
1428		dns_name_t *name;
1429		isc_uint32_t ttl;
1430		dns_rdata_t *rdata;
1431		dns_difftuple_t *tuple = NULL;
1432
1433		name = NULL;
1434		rdata = NULL;
1435		dns_journal_current_rr(j, &name, &ttl, &rdata);
1436
1437		if (rdata->type == dns_rdatatype_soa)
1438			n_soa++;
1439
1440		if (n_soa == 3)
1441			n_soa = 1;
1442		if (n_soa == 0) {
1443			isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1444				      "%s: journal file corrupt: missing "
1445				      "initial SOA", j->filename);
1446			FAIL(ISC_R_UNEXPECTED);
1447		}
1448		CHECK(dns_difftuple_create(diff.mctx, n_soa == 1 ?
1449					   DNS_DIFFOP_DEL : DNS_DIFFOP_ADD,
1450					   name, ttl, rdata, &tuple));
1451		dns_diff_append(&diff, &tuple);
1452
1453		if (++n_put > 100)  {
1454			result = dns_diff_print(&diff, file);
1455			dns_diff_clear(&diff);
1456			n_put = 0;
1457			if (result != ISC_R_SUCCESS)
1458				break;
1459		}
1460	}
1461	if (result == ISC_R_NOMORE)
1462		result = ISC_R_SUCCESS;
1463	CHECK(result);
1464
1465	if (n_put != 0) {
1466		result = dns_diff_print(&diff, file);
1467		dns_diff_clear(&diff);
1468	}
1469	goto cleanup;
1470
1471 failure:
1472	isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1473		      "%s: cannot print: journal file corrupt", j->filename);
1474
1475 cleanup:
1476	if (source.base != NULL)
1477		isc_mem_put(j->mctx, source.base, source.length);
1478	if (target.base != NULL)
1479		isc_mem_put(j->mctx, target.base, target.length);
1480
1481	dns_diff_clear(&diff);
1482	dns_journal_destroy(&j);
1483
1484	return (result);
1485}
1486
1487/**************************************************************************/
1488/*
1489 * Miscellaneous accessors.
1490 */
1491isc_uint32_t dns_journal_first_serial(dns_journal_t *j) {
1492	return (j->header.begin.serial);
1493}
1494
1495isc_uint32_t dns_journal_last_serial(dns_journal_t *j) {
1496	return (j->header.end.serial);
1497}
1498
1499/**************************************************************************/
1500/*
1501 * Iteration support.
1502 *
1503 * When serving an outgoing IXFR, we transmit a part the journal starting
1504 * at the serial number in the IXFR request and ending at the serial
1505 * number that is current when the IXFR request arrives.  The ending
1506 * serial number is not necessarily at the end of the journal:
1507 * the journal may grow while the IXFR is in progress, but we stop
1508 * when we reach the serial number that was current when the IXFR started.
1509 */
1510
1511static isc_result_t read_one_rr(dns_journal_t *j);
1512
1513/*
1514 * Make sure the buffer 'b' is has at least 'size' bytes
1515 * allocated, and clear it.
1516 *
1517 * Requires:
1518 *	Either b->base is NULL, or it points to b->length bytes of memory
1519 *	previously allocated by isc_mem_get().
1520 */
1521
1522static isc_result_t
1523size_buffer(isc_mem_t *mctx, isc_buffer_t *b, unsigned size) {
1524	if (b->length < size) {
1525		void *mem = isc_mem_get(mctx, size);
1526		if (mem == NULL)
1527			return (ISC_R_NOMEMORY);
1528		if (b->base != NULL)
1529			isc_mem_put(mctx, b->base, b->length);
1530		b->base = mem;
1531		b->length = size;
1532	}
1533	isc_buffer_clear(b);
1534	return (ISC_R_SUCCESS);
1535}
1536
1537isc_result_t
1538dns_journal_iter_init(dns_journal_t *j,
1539		      isc_uint32_t begin_serial, isc_uint32_t end_serial)
1540{
1541	isc_result_t result;
1542
1543	CHECK(journal_find(j, begin_serial, &j->it.bpos));
1544	INSIST(j->it.bpos.serial == begin_serial);
1545
1546	CHECK(journal_find(j, end_serial, &j->it.epos));
1547	INSIST(j->it.epos.serial == end_serial);
1548
1549	result = ISC_R_SUCCESS;
1550 failure:
1551	j->it.result = result;
1552	return (j->it.result);
1553}
1554
1555
1556isc_result_t
1557dns_journal_first_rr(dns_journal_t *j) {
1558	isc_result_t result;
1559
1560	/*
1561	 * Seek to the beginning of the first transaction we are
1562	 * interested in.
1563	 */
1564	CHECK(journal_seek(j, j->it.bpos.offset));
1565	j->it.current_serial = j->it.bpos.serial;
1566
1567	j->it.xsize = 0;  /* We have no transaction data yet... */
1568	j->it.xpos = 0;	  /* ...and haven't used any of it. */
1569
1570	return (read_one_rr(j));
1571
1572 failure:
1573	return (result);
1574}
1575
1576static isc_result_t
1577read_one_rr(dns_journal_t *j) {
1578	isc_result_t result;
1579
1580	dns_rdatatype_t rdtype;
1581	dns_rdataclass_t rdclass;
1582	unsigned int rdlen;
1583	isc_uint32_t ttl;
1584	journal_xhdr_t xhdr;
1585	journal_rrhdr_t rrhdr;
1586
1587	INSIST(j->offset <= j->it.epos.offset);
1588	if (j->offset == j->it.epos.offset)
1589		return (ISC_R_NOMORE);
1590	if (j->it.xpos == j->it.xsize) {
1591		/*
1592		 * We are at a transaction boundary.
1593		 * Read another transaction header.
1594		 */
1595		CHECK(journal_read_xhdr(j, &xhdr));
1596		if (xhdr.size == 0) {
1597			isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1598				      "%s: journal corrupt: empty transaction",
1599				      j->filename);
1600			FAIL(ISC_R_UNEXPECTED);
1601		}
1602		if (xhdr.serial0 != j->it.current_serial) {
1603			isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1604					 "%s: journal file corrupt: "
1605					 "expected serial %u, got %u",
1606					 j->filename,
1607					 j->it.current_serial, xhdr.serial0);
1608			FAIL(ISC_R_UNEXPECTED);
1609		}
1610		j->it.xsize = xhdr.size;
1611		j->it.xpos = 0;
1612	}
1613	/*
1614	 * Read an RR.
1615	 */
1616	CHECK(journal_read_rrhdr(j, &rrhdr));
1617	/*
1618	 * Perform a sanity check on the journal RR size.
1619	 * The smallest possible RR has a 1-byte owner name
1620	 * and a 10-byte header.  The largest possible
1621	 * RR has 65535 bytes of data, a header, and a maximum-
1622	 * size owner name, well below 70 k total.
1623	 */
1624	if (rrhdr.size < 1+10 || rrhdr.size > 70000) {
1625		isc_log_write(JOURNAL_COMMON_LOGARGS, ISC_LOG_ERROR,
1626				 "%s: journal corrupt: impossible RR size "
1627				 "(%d bytes)", j->filename, rrhdr.size);
1628		FAIL(ISC_R_UNEXPECTED);
1629	}
1630
1631	CHECK(size_buffer(j->mctx, &j->it.source, rrhdr.size));
1632	CHECK(journal_read(j, j->it.source.base, rrhdr.size));
1633	isc_buffer_add(&j->it.source, rrhdr.size);
1634
1635	/*
1636	 * The target buffer is made the same size
1637	 * as the source buffer, with the assumption that when
1638	 * no compression in present, the output of dns_*_fromwire()
1639	 * is no larger than the input.
1640	 */
1641	CHECK(size_buffer(j->mctx, &j->it.target, rrhdr.size));
1642
1643	/*
1644	 * Parse the owner name.  We don't know where it
1645	 * ends yet, so we make the entire "remaining"
1646	 * part of the buffer "active".
1647	 */
1648	isc_buffer_setactive(&j->it.source,
1649			     j->it.source.used - j->it.source.current);
1650	CHECK(dns_name_fromwire(&j->it.name, &j->it.source,
1651				&j->it.dctx, 0, &j->it.target));
1652
1653	/*
1654	 * Check that the RR header is there, and parse it.
1655	 */
1656	if (isc_buffer_remaininglength(&j->it.source) < 10)
1657		FAIL(DNS_R_FORMERR);
1658
1659	rdtype = isc_buffer_getuint16(&j->it.source);
1660	rdclass = isc_buffer_getuint16(&j->it.source);
1661	ttl = isc_buffer_getuint32(&j->it.source);
1662	rdlen = isc_buffer_getuint16(&j->it.source);
1663
1664	/*
1665	 * Parse the rdata.
1666	 */
1667	if (isc_buffer_remaininglength(&j->it.source) != rdlen)
1668		FAIL(DNS_R_FORMERR);
1669	isc_buffer_setactive(&j->it.source, rdlen);
1670	dns_rdata_reset(&j->it.rdata);
1671	CHECK(dns_rdata_fromwire(&j->it.rdata, rdclass,
1672				 rdtype, &j->it.source, &j->it.dctx,
1673				 0, &j->it.target));
1674	j->it.ttl = ttl;
1675
1676	j->it.xpos += sizeof(journal_rawrrhdr_t) + rrhdr.size;
1677	if (rdtype == dns_rdatatype_soa) {
1678		/* XXX could do additional consistency checks here */
1679		j->it.current_serial = dns_soa_getserial(&j->it.rdata);
1680	}
1681
1682	result = ISC_R_SUCCESS;
1683
1684 failure:
1685	j->it.result = result;
1686	return (result);
1687}
1688
1689isc_result_t
1690dns_journal_next_rr(dns_journal_t *j) {
1691	j->it.result = read_one_rr(j);
1692	return (j->it.result);
1693}
1694
1695void
1696dns_journal_current_rr(dns_journal_t *j, dns_name_t **name, isc_uint32_t *ttl,
1697		   dns_rdata_t **rdata)
1698{
1699	REQUIRE(j->it.result == ISC_R_SUCCESS);
1700	*name = &j->it.name;
1701	*ttl = j->it.ttl;
1702	*rdata = &j->it.rdata;
1703}
1704
1705/**************************************************************************/
1706/*
1707 * Generating diffs from databases
1708 */
1709
1710/*
1711 * Construct a diff containing all the RRs at the current name of the
1712 * database iterator 'dbit' in database 'db', version 'ver'.
1713 * Set '*name' to the current name, and append the diff to 'diff'.
1714 * All new tuples will have the operation 'op'.
1715 *
1716 * Requires: 'name' must have buffer large enough to hold the name.
1717 * Typically, a dns_fixedname_t would be used.
1718 */
1719static isc_result_t
1720get_name_diff(dns_db_t *db, dns_dbversion_t *ver, isc_stdtime_t now,
1721	      dns_dbiterator_t *dbit, dns_name_t *name, dns_diffop_t op,
1722	      dns_diff_t *diff)
1723{
1724	isc_result_t result;
1725	dns_dbnode_t *node = NULL;
1726	dns_rdatasetiter_t *rdsiter = NULL;
1727	dns_difftuple_t *tuple = NULL;
1728
1729	result = dns_dbiterator_current(dbit, &node, name);
1730	if (result != ISC_R_SUCCESS)
1731		return (result);
1732
1733	result = dns_db_allrdatasets(db, node, ver, now, &rdsiter);
1734	if (result != ISC_R_SUCCESS)
1735		goto cleanup_node;
1736
1737	for (result = dns_rdatasetiter_first(rdsiter);
1738	     result == ISC_R_SUCCESS;
1739	     result = dns_rdatasetiter_next(rdsiter))
1740	{
1741		dns_rdataset_t rdataset;
1742
1743		dns_rdataset_init(&rdataset);
1744		dns_rdatasetiter_current(rdsiter, &rdataset);
1745
1746		for (result = dns_rdataset_first(&rdataset);
1747		     result == ISC_R_SUCCESS;
1748		     result = dns_rdataset_next(&rdataset))
1749		{
1750			dns_rdata_t rdata = DNS_RDATA_INIT;
1751			dns_rdataset_current(&rdataset, &rdata);
1752			result = dns_difftuple_create(diff->mctx, op, name,
1753						      rdataset.ttl, &rdata,
1754						      &tuple);
1755			if (result != ISC_R_SUCCESS) {
1756				dns_rdataset_disassociate(&rdataset);
1757				goto cleanup_iterator;
1758			}
1759			dns_diff_append(diff, &tuple);
1760		}
1761		dns_rdataset_disassociate(&rdataset);
1762		if (result != ISC_R_NOMORE)
1763			goto cleanup_iterator;
1764	}
1765	if (result != ISC_R_NOMORE)
1766		goto cleanup_iterator;
1767
1768	result = ISC_R_SUCCESS;
1769
1770 cleanup_iterator:
1771	dns_rdatasetiter_destroy(&rdsiter);
1772
1773 cleanup_node:
1774	dns_db_detachnode(db, &node);
1775
1776	return (result);
1777}
1778
1779/*
1780 * Comparison function for use by dns_diff_subtract when sorting
1781 * the diffs to be subtracted.  The sort keys are the rdata type
1782 * and the rdata itself.  The owner name is ignored, because
1783 * it is known to be the same for all tuples.
1784 */
1785static int
1786rdata_order(const void *av, const void *bv) {
1787	dns_difftuple_t const * const *ap = av;
1788	dns_difftuple_t const * const *bp = bv;
1789	dns_difftuple_t const *a = *ap;
1790	dns_difftuple_t const *b = *bp;
1791	int r;
1792	r = (b->rdata.type - a->rdata.type);
1793	if (r != 0)
1794		return (r);
1795	r = dns_rdata_compare(&a->rdata, &b->rdata);
1796	return (r);
1797}
1798
1799static isc_result_t
1800dns_diff_subtract(dns_diff_t diff[2], dns_diff_t *r) {
1801	isc_result_t result;
1802	dns_difftuple_t *p[2];
1803	int i, t;
1804	isc_boolean_t append;
1805
1806	CHECK(dns_diff_sort(&diff[0], rdata_order));
1807	CHECK(dns_diff_sort(&diff[1], rdata_order));
1808
1809	for (;;) {
1810		p[0] = ISC_LIST_HEAD(diff[0].tuples);
1811		p[1] = ISC_LIST_HEAD(diff[1].tuples);
1812		if (p[0] == NULL && p[1] == NULL)
1813			break;
1814
1815		for (i = 0; i < 2; i++)
1816			if (p[!i] == NULL) {
1817				ISC_LIST_UNLINK(diff[i].tuples, p[i], link);
1818				ISC_LIST_APPEND(r->tuples, p[i], link);
1819				goto next;
1820			}
1821		t = rdata_order(&p[0], &p[1]);
1822		if (t < 0) {
1823			ISC_LIST_UNLINK(diff[0].tuples, p[0], link);
1824			ISC_LIST_APPEND(r->tuples, p[0], link);
1825			goto next;
1826		}
1827		if (t > 0) {
1828			ISC_LIST_UNLINK(diff[1].tuples, p[1], link);
1829			ISC_LIST_APPEND(r->tuples, p[1], link);
1830			goto next;
1831		}
1832		INSIST(t == 0);
1833		/*
1834		 * Identical RRs in both databases; skip them both
1835		 * if the ttl differs.
1836		 */
1837		append = ISC_TF(p[0]->ttl != p[1]->ttl);
1838		for (i = 0; i < 2; i++) {
1839			ISC_LIST_UNLINK(diff[i].tuples, p[i], link);
1840			if (append) {
1841				ISC_LIST_APPEND(r->tuples, p[i], link);
1842			} else {
1843				dns_difftuple_free(&p[i]);
1844			}
1845		}
1846	next: ;
1847	}
1848	result = ISC_R_SUCCESS;
1849 failure:
1850	return (result);
1851}
1852
1853/*
1854 * Compare the databases 'dba' and 'dbb' and generate a journal
1855 * entry containing the changes to make 'dba' from 'dbb' (note
1856 * the order).  This journal entry will consist of a single,
1857 * possibly very large transaction.
1858 */
1859
1860isc_result_t
1861dns_db_diff(isc_mem_t *mctx,
1862	    dns_db_t *dba, dns_dbversion_t *dbvera,
1863	    dns_db_t *dbb, dns_dbversion_t *dbverb,
1864	    const char *journal_filename)
1865{
1866	dns_db_t *db[2];
1867	dns_dbversion_t *ver[2];
1868	dns_dbiterator_t *dbit[2] = { NULL, NULL };
1869	isc_boolean_t have[2] = { ISC_FALSE, ISC_FALSE };
1870	dns_fixedname_t fixname[2];
1871	isc_result_t result, itresult[2];
1872	dns_diff_t diff[2], resultdiff;
1873	int i, t;
1874	dns_journal_t *journal = NULL;
1875
1876	db[0] = dba, db[1] = dbb;
1877	ver[0] = dbvera, ver[1] = dbverb;
1878
1879	dns_diff_init(mctx, &diff[0]);
1880	dns_diff_init(mctx, &diff[1]);
1881	dns_diff_init(mctx, &resultdiff);
1882
1883	dns_fixedname_init(&fixname[0]);
1884	dns_fixedname_init(&fixname[1]);
1885
1886	result = dns_journal_open(mctx, journal_filename, ISC_TRUE, &journal);
1887	if (result != ISC_R_SUCCESS)
1888		return (result);
1889
1890	result = dns_db_createiterator(db[0], 0, &dbit[0]);
1891	if (result != ISC_R_SUCCESS)
1892		goto cleanup_journal;
1893	result = dns_db_createiterator(db[1], 0, &dbit[1]);
1894	if (result != ISC_R_SUCCESS)
1895		goto cleanup_interator0;
1896
1897	itresult[0] = dns_dbiterator_first(dbit[0]);
1898	itresult[1] = dns_dbiterator_first(dbit[1]);
1899
1900	for (;;) {
1901		for (i = 0; i < 2; i++) {
1902			if (! have[i] && itresult[i] == ISC_R_SUCCESS) {
1903				CHECK(get_name_diff(db[i], ver[i], 0, dbit[i],
1904					    dns_fixedname_name(&fixname[i]),
1905					    i == 0 ?
1906					    DNS_DIFFOP_ADD :
1907					    DNS_DIFFOP_DEL,
1908					    &diff[i]));
1909				itresult[i] = dns_dbiterator_next(dbit[i]);
1910				have[i] = ISC_TRUE;
1911			}
1912		}
1913
1914		if (! have[0] && ! have[1]) {
1915			INSIST(ISC_LIST_EMPTY(diff[0].tuples));
1916			INSIST(ISC_LIST_EMPTY(diff[1].tuples));
1917			break;
1918		}
1919
1920		for (i = 0; i < 2; i++) {
1921			if (! have[!i]) {
1922				ISC_LIST_APPENDLIST(resultdiff.tuples,
1923						    diff[i].tuples, link);
1924				INSIST(ISC_LIST_EMPTY(diff[i].tuples));
1925				have[i] = ISC_FALSE;
1926				goto next;
1927			}
1928		}
1929
1930		t = dns_name_compare(dns_fixedname_name(&fixname[0]),
1931				     dns_fixedname_name(&fixname[1]));
1932		if (t < 0) {
1933			ISC_LIST_APPENDLIST(resultdiff.tuples,
1934					    diff[0].tuples, link);
1935			INSIST(ISC_LIST_EMPTY(diff[0].tuples));
1936			have[0] = ISC_FALSE;
1937			continue;
1938		}
1939		if (t > 0) {
1940			ISC_LIST_APPENDLIST(resultdiff.tuples,
1941					    diff[1].tuples, link);
1942			INSIST(ISC_LIST_EMPTY(diff[1].tuples));
1943			have[1] = ISC_FALSE;
1944			continue;
1945		}
1946		INSIST(t == 0);
1947		CHECK(dns_diff_subtract(diff, &resultdiff));
1948		INSIST(ISC_LIST_EMPTY(diff[0].tuples));
1949		INSIST(ISC_LIST_EMPTY(diff[1].tuples));
1950		have[0] = have[1] = ISC_FALSE;
1951	next: ;
1952	}
1953	if (itresult[0] != ISC_R_NOMORE)
1954		FAIL(itresult[0]);
1955	if (itresult[1] != ISC_R_NOMORE)
1956		FAIL(itresult[1]);
1957
1958	if (ISC_LIST_EMPTY(resultdiff.tuples)) {
1959		isc_log_write(JOURNAL_DEBUG_LOGARGS(3), "no changes");
1960	} else {
1961		CHECK(dns_journal_write_transaction(journal, &resultdiff));
1962	}
1963	INSIST(ISC_LIST_EMPTY(diff[0].tuples));
1964	INSIST(ISC_LIST_EMPTY(diff[1].tuples));
1965
1966 failure:
1967	dns_diff_clear(&resultdiff);
1968	dns_dbiterator_destroy(&dbit[1]);
1969 cleanup_interator0:
1970	dns_dbiterator_destroy(&dbit[0]);
1971 cleanup_journal:
1972	dns_journal_destroy(&journal);
1973	return (result);
1974}
1975
1976isc_result_t
1977dns_journal_compact(isc_mem_t *mctx, char *filename, isc_uint32_t serial,
1978		    isc_uint32_t target_size)
1979{
1980	unsigned int i;
1981	journal_pos_t best_guess;
1982	journal_pos_t current_pos;
1983	dns_journal_t *j = NULL;
1984	dns_journal_t *new = NULL;
1985	journal_rawheader_t rawheader;
1986	unsigned int copy_length;
1987	int namelen;
1988	char *buf = NULL;
1989	unsigned int size = 0;
1990	isc_result_t result;
1991	unsigned int indexend;
1992	char newname[1024];
1993	char backup[1024];
1994	isc_boolean_t is_backup = ISC_FALSE;
1995
1996	namelen = strlen(filename);
1997	if (namelen > 4 && strcmp(filename + namelen - 4, ".jnl") == 0)
1998		namelen -= 4;
1999
2000	result = isc_string_printf(newname, sizeof(newname), "%.*s.jnw",
2001				   namelen, filename);
2002	if (result != ISC_R_SUCCESS)
2003		return (result);
2004
2005	result = isc_string_printf(backup, sizeof(backup), "%.*s.jbk",
2006				   namelen, filename);
2007	if (result != ISC_R_SUCCESS)
2008		return (result);
2009
2010	result = journal_open(mctx, filename, ISC_FALSE, ISC_FALSE, &j);
2011	if (result == ISC_R_NOTFOUND) {
2012		is_backup = ISC_TRUE;
2013		result = journal_open(mctx, backup, ISC_FALSE, ISC_FALSE, &j);
2014	}
2015	if (result != ISC_R_SUCCESS)
2016		return (result);
2017
2018	if (JOURNAL_EMPTY(&j->header)) {
2019		dns_journal_destroy(&j);
2020		return (ISC_R_SUCCESS);
2021	}
2022
2023	if (DNS_SERIAL_GT(j->header.begin.serial, serial) ||
2024	    DNS_SERIAL_GT(serial, j->header.end.serial)) {
2025		dns_journal_destroy(&j);
2026		return (ISC_R_RANGE);
2027	}
2028
2029	/*
2030	 * Cope with very small target sizes.
2031	 */
2032	indexend = sizeof(journal_rawheader_t) +
2033		   j->header.index_size * sizeof(journal_rawpos_t);
2034	if (target_size < indexend * 2)
2035		target_size = target_size/2 + indexend;
2036
2037	/*
2038	 * See if there is any work to do.
2039	 */
2040	if ((isc_uint32_t) j->header.end.offset < target_size) {
2041		dns_journal_destroy(&j);
2042		return (ISC_R_SUCCESS);
2043	}
2044
2045	CHECK(journal_open(mctx, newname, ISC_TRUE, ISC_TRUE, &new));
2046
2047	/*
2048	 * Remove overhead so space test below can succeed.
2049	 */
2050	if (target_size >= indexend)
2051		target_size -= indexend;
2052
2053	/*
2054	 * Find if we can create enough free space.
2055	 */
2056	best_guess = j->header.begin;
2057	for (i = 0; i < j->header.index_size; i++) {
2058		if (POS_VALID(j->index[i]) &&
2059		    DNS_SERIAL_GE(serial, j->index[i].serial) &&
2060		    ((isc_uint32_t)(j->header.end.offset - j->index[i].offset)
2061		     >= target_size / 2) &&
2062		    j->index[i].offset > best_guess.offset)
2063			best_guess = j->index[i];
2064	}
2065
2066	current_pos = best_guess;
2067	while (current_pos.serial != serial) {
2068		CHECK(journal_next(j, &current_pos));
2069		if (current_pos.serial == j->header.end.serial)
2070			break;
2071
2072		if (DNS_SERIAL_GE(serial, current_pos.serial) &&
2073		   ((isc_uint32_t)(j->header.end.offset - current_pos.offset)
2074		     >= (target_size / 2)) &&
2075		    current_pos.offset > best_guess.offset)
2076			best_guess = current_pos;
2077		else
2078			break;
2079	}
2080
2081	INSIST(best_guess.serial != j->header.end.serial);
2082	if (best_guess.serial != serial)
2083		CHECK(journal_next(j, &best_guess));
2084
2085	/*
2086	 * We should now be roughly half target_size provided
2087	 * we did not reach 'serial'.  If not we will just copy
2088	 * all uncommitted deltas regardless of the size.
2089	 */
2090	copy_length = j->header.end.offset - best_guess.offset;
2091
2092	if (copy_length != 0) {
2093		/*
2094		 * Copy best_guess to end into space just freed.
2095		 */
2096		size = 64*1024;
2097		if (copy_length < size)
2098			size = copy_length;
2099		buf = isc_mem_get(mctx, size);
2100		if (buf == NULL) {
2101			result = ISC_R_NOMEMORY;
2102			goto failure;
2103		}
2104
2105		CHECK(journal_seek(j, best_guess.offset));
2106		CHECK(journal_seek(new, indexend));
2107		for (i = 0; i < copy_length; i += size) {
2108			unsigned int len = (copy_length - i) > size ? size :
2109							 (copy_length - i);
2110			CHECK(journal_read(j, buf, len));
2111			CHECK(journal_write(new, buf, len));
2112		}
2113
2114		CHECK(journal_fsync(new));
2115
2116		/*
2117		 * Compute new header.
2118		 */
2119		new->header.begin.serial = best_guess.serial;
2120		new->header.begin.offset = indexend;
2121		new->header.end.serial = j->header.end.serial;
2122		new->header.end.offset = indexend + copy_length;
2123
2124		/*
2125		 * Update the journal header.
2126		 */
2127		journal_header_encode(&new->header, &rawheader);
2128		CHECK(journal_seek(new, 0));
2129		CHECK(journal_write(new, &rawheader, sizeof(rawheader)));
2130		CHECK(journal_fsync(new));
2131
2132		/*
2133		 * Build new index.
2134		 */
2135		current_pos = new->header.begin;
2136		while (current_pos.serial != new->header.end.serial) {
2137			index_add(new, &current_pos);
2138			CHECK(journal_next(new, &current_pos));
2139		}
2140
2141		/*
2142		 * Write index.
2143		 */
2144		CHECK(index_to_disk(new));
2145		CHECK(journal_fsync(new));
2146
2147		indexend = new->header.end.offset;
2148	}
2149	dns_journal_destroy(&new);
2150
2151	/*
2152	 * With a UFS file system this should just succeed and be atomic.
2153	 * Any IXFR outs will just continue and the old journal will be
2154	 * removed on final close.
2155	 *
2156	 * With MSDOS / NTFS we need to do a two stage rename triggered
2157	 * bu EEXISTS.  Hopefully all IXFR's that were active at the last
2158	 * rename are now complete.
2159	 */
2160	if (rename(newname, filename) == -1) {
2161		if (errno == EACCES && !is_backup) {
2162			result = isc_file_remove(backup);
2163			if (result != ISC_R_SUCCESS &&
2164			    result != ISC_R_FILENOTFOUND)
2165				goto failure;
2166			if (rename(filename, backup) == -1)
2167				goto maperrno;
2168			if (rename(newname, filename) == -1)
2169				goto maperrno;
2170			(void)isc_file_remove(backup);
2171		} else {
2172 maperrno:
2173			result = ISC_R_FAILURE;
2174			goto failure;
2175		}
2176	}
2177
2178	dns_journal_destroy(&j);
2179	result = ISC_R_SUCCESS;
2180
2181 failure:
2182	(void)isc_file_remove(newname);
2183	if (buf != NULL)
2184		isc_mem_put(mctx, buf, size);
2185	if (j != NULL)
2186		dns_journal_destroy(&j);
2187	if (new != NULL)
2188		dns_journal_destroy(&new);
2189	return (result);
2190}
2191
2192static isc_result_t
2193index_to_disk(dns_journal_t *j) {
2194	isc_result_t result = ISC_R_SUCCESS;
2195
2196	if (j->header.index_size != 0) {
2197		unsigned int i;
2198		unsigned char *p;
2199		unsigned int rawbytes;
2200
2201		rawbytes = j->header.index_size * sizeof(journal_rawpos_t);
2202
2203		p = j->rawindex;
2204		for (i = 0; i < j->header.index_size; i++) {
2205			encode_uint32(j->index[i].serial, p);
2206			p += 4;
2207			encode_uint32(j->index[i].offset, p);
2208			p += 4;
2209		}
2210		INSIST(p == j->rawindex + rawbytes);
2211
2212		CHECK(journal_seek(j, sizeof(journal_rawheader_t)));
2213		CHECK(journal_write(j, j->rawindex, rawbytes));
2214	}
2215failure:
2216	return (result);
2217}
2218