Coverage Report

Created: 2026-09-03 06:30

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