Home | History | Annotate | Line # | Download | only in dist
ixfr.c revision 1.1
      1 /*
      2  * ixfr.c -- generating IXFR responses.
      3  *
      4  * Copyright (c) 2021, NLnet Labs. All rights reserved.
      5  *
      6  * See LICENSE for the license.
      7  *
      8  */
      9 
     10 #include "config.h"
     11 
     12 #include <errno.h>
     13 #include <string.h>
     14 #include <ctype.h>
     15 #ifdef HAVE_SYS_TYPES_H
     16 #  include <sys/types.h>
     17 #endif
     18 #ifdef HAVE_SYS_STAT_H
     19 #  include <sys/stat.h>
     20 #endif
     21 #include <unistd.h>
     22 
     23 #include "ixfr.h"
     24 #include "packet.h"
     25 #include "rdata.h"
     26 #include "axfr.h"
     27 #include "options.h"
     28 #include "zonec.h"
     29 
     30 /*
     31  * For optimal compression IXFR response packets are limited in size
     32  * to MAX_COMPRESSION_OFFSET.
     33  */
     34 #define IXFR_MAX_MESSAGE_LEN MAX_COMPRESSION_OFFSET
     35 
     36 /* draft-ietf-dnsop-rfc2845bis-06, section 5.3.1 says to sign every packet */
     37 #define IXFR_TSIG_SIGN_EVERY_NTH	0	/* tsig sign every N packets. */
     38 
     39 /* initial space in rrs data for storing records */
     40 #define IXFR_STORE_INITIAL_SIZE 4096
     41 
     42 /* store compression for one name */
     43 struct rrcompress_entry {
     44 	/* rbtree node, key is this struct */
     45 	struct rbnode node;
     46 	/* the uncompressed domain name */
     47 	const uint8_t* dname;
     48 	/* the length of the dname, includes terminating 0 label */
     49 	uint16_t len;
     50 	/* the offset of the dname in the packet */
     51 	uint16_t offset;
     52 };
     53 
     54 /* structure to store compression data for the packet */
     55 struct pktcompression {
     56 	/* rbtree of rrcompress_entry. sorted by dname */
     57 	struct rbtree tree;
     58 	/* allocation information, how many bytes allocated now */
     59 	size_t alloc_now;
     60 	/* allocation information, total size in block */
     61 	size_t alloc_max;
     62 	/* region to use if block full, this is NULL if unused */
     63 	struct region* region;
     64 	/* block of temp data for allocation */
     65 	uint8_t block[sizeof(struct rrcompress_entry)*1024];
     66 };
     67 
     68 /* compare two elements in the compression tree. Returns -1, 0, or 1. */
     69 static int compression_cmp(const void* a, const void* b)
     70 {
     71 	struct rrcompress_entry* rra = (struct rrcompress_entry*)a;
     72 	struct rrcompress_entry* rrb = (struct rrcompress_entry*)b;
     73 	if(rra->len != rrb->len) {
     74 		if(rra->len < rrb->len)
     75 			return -1;
     76 		return 1;
     77 	}
     78 	return memcmp(rra->dname, rrb->dname, rra->len);
     79 }
     80 
     81 /* init the pktcompression to a new packet */
     82 static void pktcompression_init(struct pktcompression* pcomp)
     83 {
     84 	pcomp->alloc_now = 0;
     85 	pcomp->alloc_max = sizeof(pcomp->block);
     86 	pcomp->region = NULL;
     87 	pcomp->tree.root = RBTREE_NULL;
     88 	pcomp->tree.count = 0;
     89 	pcomp->tree.region = NULL;
     90 	pcomp->tree.cmp = &compression_cmp;
     91 }
     92 
     93 /* freeup the pktcompression data */
     94 static void pktcompression_freeup(struct pktcompression* pcomp)
     95 {
     96 	if(pcomp->region) {
     97 		region_destroy(pcomp->region);
     98 		pcomp->region = NULL;
     99 	}
    100 	pcomp->alloc_now = 0;
    101 	pcomp->tree.root = RBTREE_NULL;
    102 	pcomp->tree.count = 0;
    103 }
    104 
    105 /* alloc data in pktcompression */
    106 static void* pktcompression_alloc(struct pktcompression* pcomp, size_t s)
    107 {
    108 	/* first attempt to allocate in the fixed block,
    109 	 * that is very fast and on the stack in the pcomp struct */
    110 	if(pcomp->alloc_now + s <= pcomp->alloc_max) {
    111 		void* ret = pcomp->block + pcomp->alloc_now;
    112 		pcomp->alloc_now += s;
    113 		return ret;
    114 	}
    115 
    116 	/* if that fails, create a region to allocate in,
    117 	 * it is freed in the freeup */
    118 	if(!pcomp->region) {
    119 		pcomp->region = region_create(xalloc, free);
    120 		if(!pcomp->region)
    121 			return NULL;
    122 	}
    123 	return region_alloc(pcomp->region, s);
    124 }
    125 
    126 /* find a pktcompression name, return offset if found */
    127 static uint16_t pktcompression_find(struct pktcompression* pcomp,
    128 	const uint8_t* dname, size_t len)
    129 {
    130 	struct rrcompress_entry key, *found;
    131 	key.node.key = &key;
    132 	key.dname = dname;
    133 	key.len = len;
    134 	found = (struct rrcompress_entry*)rbtree_search(&pcomp->tree, &key);
    135 	if(found) return found->offset;
    136 	return 0;
    137 }
    138 
    139 /* insert a new domain name into the compression tree.
    140  * it fails silently, no need to compress then. */
    141 static void pktcompression_insert(struct pktcompression* pcomp,
    142 	const uint8_t* dname, size_t len, uint16_t offset)
    143 {
    144 	struct rrcompress_entry* entry;
    145 	if(len > 65535)
    146 		return;
    147 	if(offset > MAX_COMPRESSION_OFFSET)
    148 		return; /* too far for a compression pointer */
    149 	entry = pktcompression_alloc(pcomp, sizeof(*entry));
    150 	if(!entry)
    151 		return;
    152 	memset(&entry->node, 0, sizeof(entry->node));
    153 	entry->node.key = entry;
    154 	entry->dname = dname;
    155 	entry->len = len;
    156 	entry->offset = offset;
    157 	(void)rbtree_insert(&pcomp->tree, &entry->node);
    158 }
    159 
    160 /* insert all the labels of a domain name */
    161 static void pktcompression_insert_with_labels(struct pktcompression* pcomp,
    162 	uint8_t* dname, size_t len, uint16_t offset)
    163 {
    164 	if(!dname)
    165 		return;
    166 	if(offset > MAX_COMPRESSION_OFFSET)
    167 		return;
    168 
    169 	/* while we have not seen the end root label */
    170 	while(len > 0 && dname[0] != 0) {
    171 		size_t lablen;
    172 		pktcompression_insert(pcomp, dname, len, offset);
    173 		lablen = (size_t)(dname[0]);
    174 		if( (lablen&0xc0) )
    175 			return; /* the dname should be uncompressed */
    176 		if(lablen+1 > len)
    177 			return; /* len should be uncompressed wireformat len */
    178 		if(offset > MAX_COMPRESSION_OFFSET - lablen - 1)
    179 			return; /* offset moves too far for compression */
    180 		/* skip label */
    181 		len -= lablen+1;
    182 		dname += lablen+1;
    183 		offset += lablen+1;
    184 	}
    185 }
    186 
    187 /* calculate length of dname in uncompressed wireformat in buffer */
    188 static size_t dname_length(const uint8_t* buf, size_t len)
    189 {
    190 	size_t l = 0;
    191 	if(!buf || len == 0)
    192 		return l;
    193 	while(len > 0 && buf[0] != 0) {
    194 		size_t lablen = (size_t)(buf[0]);
    195 		if( (lablen&0xc0) )
    196 			return 0; /* the name should be uncompressed */
    197 		if(lablen+1 > len)
    198 			return 0; /* should fit in the buffer */
    199 		l += lablen+1;
    200 		len -= lablen+1;
    201 		buf += lablen+1;
    202 	}
    203 	if(len == 0)
    204 		return 0; /* end label should fit in buffer */
    205 	if(buf[0] != 0)
    206 		return 0; /* must end in root label */
    207 	l += 1; /* for the end root label */
    208 	return l;
    209 }
    210 
    211 /* write a compressed domain name into the packet,
    212  * returns uncompressed wireformat length,
    213  * 0 if it does not fit and -1 on failure, bad dname. */
    214 static int pktcompression_write_dname(struct buffer* packet,
    215 	struct pktcompression* pcomp, const uint8_t* rr, size_t rrlen)
    216 {
    217 	size_t wirelen = 0;
    218 	size_t dname_len = dname_length(rr, rrlen);
    219 	if(!rr || rrlen == 0 || dname_len == 0)
    220 		return 0;
    221 	while(rrlen > 0 && rr[0] != 0) {
    222 		size_t lablen = (size_t)(rr[0]);
    223 		uint16_t offset;
    224 		if( (lablen&0xc0) )
    225 			return -1; /* name should be uncompressed */
    226 		if(lablen+1 > rrlen)
    227 			return -1; /* name should fit */
    228 
    229 		/* see if the domain name has a compression pointer */
    230 		if((offset=pktcompression_find(pcomp, rr, dname_len))!=0) {
    231 			if(!buffer_available(packet, 2))
    232 				return 0;
    233 			buffer_write_u16(packet, (uint16_t)(0xc000 | offset));
    234 			wirelen += dname_len;
    235 			return wirelen;
    236 		} else {
    237 			if(!buffer_available(packet, lablen+1))
    238 				return 0;
    239 			/* insert the domain name at this position */
    240 			pktcompression_insert(pcomp, rr, dname_len,
    241 				buffer_position(packet));
    242 			/* write it */
    243 			buffer_write(packet, rr, lablen+1);
    244 		}
    245 
    246 		wirelen += lablen+1;
    247 		rr += lablen+1;
    248 		rrlen -= lablen+1;
    249 		dname_len -= lablen+1;
    250 	}
    251 	if(rrlen > 0 && rr[0] == 0) {
    252 		/* write end root label */
    253 		if(!buffer_available(packet, 1))
    254 			return 0;
    255 		buffer_write_u8(packet, 0);
    256 		wirelen += 1;
    257 	}
    258 	return wirelen;
    259 }
    260 
    261 /* write an RR into the packet with compression for domain names,
    262  * return 0 and resets position if it does not fit in the packet. */
    263 static int ixfr_write_rr_pkt(struct query* query, struct buffer* packet,
    264 	struct pktcompression* pcomp, const uint8_t* rr, size_t rrlen)
    265 {
    266 	size_t oldpos = buffer_position(packet);
    267 	size_t rdpos;
    268 	uint16_t tp;
    269 	int dname_len;
    270 	size_t rdlen;
    271 	size_t i;
    272 	rrtype_descriptor_type* descriptor;
    273 
    274 	if(buffer_position(packet) > MAX_COMPRESSION_OFFSET
    275 		|| query_overflow(query)) {
    276 		/* we are past the maximum length */
    277 		return 0;
    278 	}
    279 
    280 	/* write owner */
    281 	dname_len = pktcompression_write_dname(packet, pcomp, rr, rrlen);
    282 	if(dname_len == -1)
    283 		return 1; /* attempt to skip this malformed rr, could assert */
    284 	if(dname_len == 0) {
    285 		buffer_set_position(packet, oldpos);
    286 		return 0;
    287 	}
    288 	rr += dname_len;
    289 	rrlen -= dname_len;
    290 
    291 	/* type, class, ttl, rdatalen */
    292 	if(!buffer_available(packet, 10)) {
    293 		buffer_set_position(packet, oldpos);
    294 		return 0;
    295 	}
    296 	if(10 > rrlen)
    297 		return 1; /* attempt to skip this malformed rr, could assert */
    298 	tp = read_uint16(rr);
    299 	buffer_write(packet, rr, 8);
    300 	rr += 8;
    301 	rrlen -= 8;
    302 	rdlen = read_uint16(rr);
    303 	rr += 2;
    304 	rrlen -= 2;
    305 	rdpos = buffer_position(packet);
    306 	buffer_write_u16(packet, 0);
    307 	if(rdlen > rrlen)
    308 		return 1; /* attempt to skip this malformed rr, could assert */
    309 
    310 	/* rdata */
    311 	descriptor = rrtype_descriptor_by_type(tp);
    312 	for(i=0; i<descriptor->maximum; i++) {
    313 		size_t copy_len = 0;
    314 		if(rdlen == 0)
    315 			break;
    316 
    317 		switch(rdata_atom_wireformat_type(tp, i)) {
    318 		case RDATA_WF_COMPRESSED_DNAME:
    319 			dname_len = pktcompression_write_dname(packet, pcomp,
    320 				rr, rdlen);
    321 			if(dname_len == -1)
    322 				return 1; /* attempt to skip malformed rr */
    323 			if(dname_len == 0) {
    324 				buffer_set_position(packet, oldpos);
    325 				return 0;
    326 			}
    327 			rr += dname_len;
    328 			rdlen -= dname_len;
    329 			break;
    330 		case RDATA_WF_UNCOMPRESSED_DNAME:
    331 		case RDATA_WF_LITERAL_DNAME:
    332 			copy_len = rdlen;
    333 			break;
    334 		case RDATA_WF_BYTE:
    335 			copy_len = 1;
    336 			break;
    337 		case RDATA_WF_SHORT:
    338 			copy_len = 2;
    339 			break;
    340 		case RDATA_WF_LONG:
    341 			copy_len = 4;
    342 			break;
    343 		case RDATA_WF_TEXTS:
    344 		case RDATA_WF_LONG_TEXT:
    345 			copy_len = rdlen;
    346 			break;
    347 		case RDATA_WF_TEXT:
    348 		case RDATA_WF_BINARYWITHLENGTH:
    349 			copy_len = 1;
    350 			if(rdlen > copy_len)
    351 				copy_len += rr[0];
    352 			break;
    353 		case RDATA_WF_A:
    354 			copy_len = 4;
    355 			break;
    356 		case RDATA_WF_AAAA:
    357 			copy_len = 16;
    358 			break;
    359 		case RDATA_WF_ILNP64:
    360 			copy_len = 8;
    361 			break;
    362 		case RDATA_WF_EUI48:
    363 			copy_len = EUI48ADDRLEN;
    364 			break;
    365 		case RDATA_WF_EUI64:
    366 			copy_len = EUI64ADDRLEN;
    367 			break;
    368 		case RDATA_WF_BINARY:
    369 			copy_len = rdlen;
    370 			break;
    371 		case RDATA_WF_APL:
    372 			copy_len = (sizeof(uint16_t)    /* address family */
    373                                   + sizeof(uint8_t)   /* prefix */
    374                                   + sizeof(uint8_t)); /* length */
    375 			if(copy_len <= rdlen)
    376 				copy_len += (rr[copy_len-1]&APL_LENGTH_MASK);
    377 			break;
    378 		case RDATA_WF_IPSECGATEWAY:
    379 			copy_len = rdlen;
    380 			break;
    381 		case RDATA_WF_SVCPARAM:
    382 			copy_len = 4;
    383 			if(copy_len <= rdlen)
    384 				copy_len += read_uint16(rr+2);
    385 			break;
    386 		default:
    387 			copy_len = rdlen;
    388 			break;
    389 		}
    390 		if(copy_len) {
    391 			if(!buffer_available(packet, copy_len)) {
    392 				buffer_set_position(packet, oldpos);
    393 				return 0;
    394 			}
    395 			if(copy_len > rdlen)
    396 				return 1; /* assert of skip malformed */
    397 			buffer_write(packet, rr, copy_len);
    398 			rr += copy_len;
    399 			rdlen -= copy_len;
    400 		}
    401 	}
    402 	/* write compressed rdata length */
    403 	buffer_write_u16_at(packet, rdpos, buffer_position(packet)-rdpos-2);
    404 	if(query_overflow(query)) {
    405 		/* we are past the maximum length */
    406 		buffer_set_position(packet, oldpos);
    407 		return 0;
    408 	}
    409 	return 1;
    410 }
    411 
    412 /* parse the serial number from the IXFR query */
    413 static int parse_qserial(struct buffer* packet, uint32_t* qserial,
    414 	size_t* snip_pos)
    415 {
    416 	unsigned int i;
    417 	uint16_t type, rdlen;
    418 	/* we must have a SOA in the authority section */
    419 	if(NSCOUNT(packet) == 0)
    420 		return 0;
    421 	/* skip over the question section, we want only one */
    422 	buffer_set_position(packet, QHEADERSZ);
    423 	if(QDCOUNT(packet) != 1)
    424 		return 0;
    425 	if(!packet_skip_rr(packet, 1))
    426 		return 0;
    427 	/* set position to snip off the authority section */
    428 	*snip_pos = buffer_position(packet);
    429 	/* skip over the authority section RRs until we find the SOA */
    430 	for(i=0; i<NSCOUNT(packet); i++) {
    431 		/* is this the SOA record? */
    432 		if(!packet_skip_dname(packet))
    433 			return 0; /* malformed name */
    434 		if(!buffer_available(packet, 10))
    435 			return 0; /* no type,class,ttl,rdatalen */
    436 		type = buffer_read_u16(packet);
    437 		buffer_skip(packet, 6);
    438 		rdlen = buffer_read_u16(packet);
    439 		if(!buffer_available(packet, rdlen))
    440 			return 0;
    441 		if(type == TYPE_SOA) {
    442 			/* read serial from rdata, skip two dnames, then
    443 			 * read the 32bit value */
    444 			if(!packet_skip_dname(packet))
    445 				return 0; /* malformed nsname */
    446 			if(!packet_skip_dname(packet))
    447 				return 0; /* malformed rname */
    448 			if(!buffer_available(packet, 4))
    449 				return 0;
    450 			*qserial = buffer_read_u32(packet);
    451 			return 1;
    452 		}
    453 		buffer_skip(packet, rdlen);
    454 	}
    455 	return 0;
    456 }
    457 
    458 /* get serial from SOA RR */
    459 static uint32_t soa_rr_get_serial(struct rr* rr)
    460 {
    461 	if(rr->rdata_count < 3)
    462 		return 0;
    463 	if(rr->rdatas[2].data[0] < 4)
    464 		return 0;
    465 	return read_uint32(&rr->rdatas[2].data[1]);
    466 }
    467 
    468 /* get the current serial from the zone */
    469 uint32_t zone_get_current_serial(struct zone* zone)
    470 {
    471 	if(!zone || !zone->soa_rrset)
    472 		return 0;
    473 	if(zone->soa_rrset->rr_count == 0)
    474 		return 0;
    475 	if(zone->soa_rrset->rrs[0].rdata_count < 3)
    476 		return 0;
    477 	if(zone->soa_rrset->rrs[0].rdatas[2].data[0] < 4)
    478 		return 0;
    479 	return read_uint32(&zone->soa_rrset->rrs[0].rdatas[2].data[1]);
    480 }
    481 
    482 /* iterator over ixfr data. find first element, eg. oldest zone version
    483  * change.
    484  * The iterator can be started with the ixfr_data_first, but also with
    485  * ixfr_data_last, or with an existing ixfr_data element to start from.
    486  * Continue by using ixfr_data_next or ixfr_data_prev to ask for more elements
    487  * until that returns NULL. NULL because end of list or loop was detected.
    488  * The ixfr_data_prev uses a counter, start it at 0, it returns NULL when
    489  * a loop is detected.
    490  */
    491 static struct ixfr_data* ixfr_data_first(struct zone_ixfr* ixfr)
    492 {
    493 	struct ixfr_data* n;
    494 	if(!ixfr || !ixfr->data || ixfr->data->count==0)
    495 		return NULL;
    496 	n = (struct ixfr_data*)rbtree_search(ixfr->data, &ixfr->oldest_serial);
    497 	if(!n || n == (struct ixfr_data*)RBTREE_NULL)
    498 		return NULL;
    499 	return n;
    500 }
    501 
    502 /* iterator over ixfr data. find last element, eg. newest zone version
    503  * change. */
    504 static struct ixfr_data* ixfr_data_last(struct zone_ixfr* ixfr)
    505 {
    506 	struct ixfr_data* n;
    507 	if(!ixfr || !ixfr->data || ixfr->data->count==0)
    508 		return NULL;
    509 	n = (struct ixfr_data*)rbtree_search(ixfr->data, &ixfr->newest_serial);
    510 	if(!n || n == (struct ixfr_data*)RBTREE_NULL)
    511 		return NULL;
    512 	return n;
    513 }
    514 
    515 /* iterator over ixfr data. fetch next item. If loop or nothing, NULL */
    516 static struct ixfr_data* ixfr_data_next(struct zone_ixfr* ixfr,
    517 	struct ixfr_data* cur)
    518 {
    519 	struct ixfr_data* n;
    520 	if(!cur || cur == (struct ixfr_data*)RBTREE_NULL)
    521 		return NULL;
    522 	if(cur->oldserial == ixfr->newest_serial)
    523 		return NULL; /* that was the last element */
    524 	n = (struct ixfr_data*)rbtree_next(&cur->node);
    525 	if(n && n != (struct ixfr_data*)RBTREE_NULL &&
    526 		cur->newserial == n->oldserial) {
    527 		/* the next rbtree item is the next ixfr data item */
    528 		return n;
    529 	}
    530 	/* If the next item is last of tree, and we have to loop around,
    531 	 * the search performs the lookup for the next item we need.
    532 	 * If the next item exists, but also is not connected, the search
    533 	 * finds the correct connected ixfr in the sorted tree. */
    534 	/* try searching for the correct ixfr data item */
    535 	n = (struct ixfr_data*)rbtree_search(ixfr->data, &cur->newserial);
    536 	if(!n || n == (struct ixfr_data*)RBTREE_NULL)
    537 		return NULL;
    538 	return n;
    539 }
    540 
    541 /* iterator over ixfr data. fetch the previous item. If loop or nothing NULL.*/
    542 static struct ixfr_data* ixfr_data_prev(struct zone_ixfr* ixfr,
    543 	struct ixfr_data* cur, size_t* prevcount)
    544 {
    545 	struct ixfr_data* prev;
    546 	if(!cur || cur == (struct ixfr_data*)RBTREE_NULL)
    547 		return NULL;
    548 	if(cur->oldserial == ixfr->oldest_serial)
    549 		return NULL; /* this was the first element */
    550 	prev = (struct ixfr_data*)rbtree_previous(&cur->node);
    551 	if(!prev || prev == (struct ixfr_data*)RBTREE_NULL) {
    552 		/* We hit the first element in the tree, go again
    553 		 * at the last one. Wrap around. */
    554 		prev = (struct ixfr_data*)rbtree_last(ixfr->data);
    555 	}
    556 	while(prev && prev != (struct ixfr_data*)RBTREE_NULL) {
    557 		if(prev->newserial == cur->oldserial) {
    558 			/* This is the correct matching previous ixfr data */
    559 			/* Increase the prevcounter every time the routine
    560 			 * returns an item, and if that becomes too large, we
    561 			 * are in a loop. in that case, stop. */
    562 			if(prevcount) {
    563 				(*prevcount)++;
    564 				if(*prevcount > ixfr->data->count + 12) {
    565 					/* Larger than the max number of items
    566 					 * plus a small margin. The longest
    567 					 * chain is all the ixfr elements in
    568 					 * the tree. It loops. */
    569 					return NULL;
    570 				}
    571 			}
    572 			return prev;
    573 		}
    574 		prev = (struct ixfr_data*)rbtree_previous(&prev->node);
    575 		if(!prev || prev == (struct ixfr_data*)RBTREE_NULL) {
    576 			/* We hit the first element in the tree, go again
    577 			 * at the last one. Wrap around. */
    578 			prev = (struct ixfr_data*)rbtree_last(ixfr->data);
    579 		}
    580 	}
    581 	/* no elements in list */
    582 	return NULL;
    583 }
    584 
    585 /* connect IXFRs, return true if connected, false if not. Return last serial */
    586 static int connect_ixfrs(struct zone_ixfr* ixfr, struct ixfr_data* data,
    587 	uint32_t* end_serial)
    588 {
    589 	struct ixfr_data* p = data;
    590 	while(p != NULL) {
    591 		struct ixfr_data* next = ixfr_data_next(ixfr, p);
    592 		if(next) {
    593 			if(p->newserial != next->oldserial) {
    594 				/* These ixfrs are not connected,
    595 				 * during IXFR processing that could already
    596 				 * have been deleted, but we check here
    597 				 * in any case */
    598 				return 0;
    599 			}
    600 		} else {
    601 			/* the chain of IXFRs ends in this serial number */
    602 			*end_serial = p->newserial;
    603 		}
    604 		p = next;
    605 	}
    606 	return 1;
    607 }
    608 
    609 /* Count length of next record in data */
    610 static size_t count_rr_length(const uint8_t* data, size_t data_len,
    611 	size_t current)
    612 {
    613 	uint8_t label_size;
    614 	uint16_t rdlen;
    615 	size_t i = current;
    616 	if(current >= data_len)
    617 		return 0;
    618 	/* pass the owner dname */
    619 	while(1) {
    620 		if(i+1 > data_len)
    621 			return 0;
    622 		label_size = data[i++];
    623 		if(label_size == 0) {
    624 			break;
    625 		} else if((label_size &0xc0) != 0) {
    626 			return 0; /* uncompressed dnames in IXFR store */
    627 		} else if(i+label_size > data_len) {
    628 			return 0;
    629 		} else {
    630 			i += label_size;
    631 		}
    632 	}
    633 	/* after dname, we pass type, class, ttl, rdatalen */
    634 	if(i+10 > data_len)
    635 		return 0;
    636 	i += 8;
    637 	rdlen = read_uint16(data+i);
    638 	i += 2;
    639 	/* pass over the rdata */
    640 	if(i+((size_t)rdlen) > data_len)
    641 		return 0;
    642 	i += ((size_t)rdlen);
    643 	return i-current;
    644 }
    645 
    646 /* Copy RRs into packet until packet full, return number RRs added */
    647 static uint16_t ixfr_copy_rrs_into_packet(struct query* query,
    648 	struct pktcompression* pcomp)
    649 {
    650 	uint16_t total_added = 0;
    651 
    652 	/* Copy RRs into the packet until the answer is full,
    653 	 * when an RR does not fit, we return and add no more. */
    654 
    655 	/* Add first SOA */
    656 	if(query->ixfr_count_newsoa < query->ixfr_end_data->newsoa_len) {
    657 		/* the new SOA is added from the end_data segment, it is
    658 		 * the final SOA of the result of the IXFR */
    659 		if(ixfr_write_rr_pkt(query, query->packet, pcomp,
    660 			query->ixfr_end_data->newsoa,
    661 			query->ixfr_end_data->newsoa_len)) {
    662 			query->ixfr_count_newsoa = query->ixfr_end_data->newsoa_len;
    663 			total_added++;
    664 			query->ixfr_pos_of_newsoa = buffer_position(query->packet);
    665 		} else {
    666 			/* cannot add another RR, so return */
    667 			return total_added;
    668 		}
    669 	}
    670 
    671 	/* Add second SOA */
    672 	if(query->ixfr_count_oldsoa < query->ixfr_data->oldsoa_len) {
    673 		if(ixfr_write_rr_pkt(query, query->packet, pcomp,
    674 			query->ixfr_data->oldsoa,
    675 			query->ixfr_data->oldsoa_len)) {
    676 			query->ixfr_count_oldsoa = query->ixfr_data->oldsoa_len;
    677 			total_added++;
    678 		} else {
    679 			/* cannot add another RR, so return */
    680 			return total_added;
    681 		}
    682 	}
    683 
    684 	/* Add del data, with deleted RRs and a SOA */
    685 	while(query->ixfr_count_del < query->ixfr_data->del_len) {
    686 		size_t rrlen = count_rr_length(query->ixfr_data->del,
    687 			query->ixfr_data->del_len, query->ixfr_count_del);
    688 		if(rrlen && ixfr_write_rr_pkt(query, query->packet, pcomp,
    689 			query->ixfr_data->del + query->ixfr_count_del,
    690 			rrlen)) {
    691 			query->ixfr_count_del += rrlen;
    692 			total_added++;
    693 		} else {
    694 			/* the next record does not fit in the remaining
    695 			 * space of the packet */
    696 			return total_added;
    697 		}
    698 	}
    699 
    700 	/* Add add data, with added RRs and a SOA */
    701 	while(query->ixfr_count_add < query->ixfr_data->add_len) {
    702 		size_t rrlen = count_rr_length(query->ixfr_data->add,
    703 			query->ixfr_data->add_len, query->ixfr_count_add);
    704 		if(rrlen && ixfr_write_rr_pkt(query, query->packet, pcomp,
    705 			query->ixfr_data->add + query->ixfr_count_add,
    706 			rrlen)) {
    707 			query->ixfr_count_add += rrlen;
    708 			total_added++;
    709 		} else {
    710 			/* the next record does not fit in the remaining
    711 			 * space of the packet */
    712 			return total_added;
    713 		}
    714 	}
    715 	return total_added;
    716 }
    717 
    718 query_state_type query_ixfr(struct nsd *nsd, struct query *query)
    719 {
    720 	uint16_t total_added = 0;
    721 	struct pktcompression pcomp;
    722 
    723 	if (query->ixfr_is_done)
    724 		return QUERY_PROCESSED;
    725 
    726 	pktcompression_init(&pcomp);
    727 	if (query->maxlen > IXFR_MAX_MESSAGE_LEN)
    728 		query->maxlen = IXFR_MAX_MESSAGE_LEN;
    729 
    730 	assert(!query_overflow(query));
    731 	/* only keep running values for most packets */
    732 	query->tsig_prepare_it = 0;
    733 	query->tsig_update_it = 1;
    734 	if(query->tsig_sign_it) {
    735 		/* prepare for next updates */
    736 		query->tsig_prepare_it = 1;
    737 		query->tsig_sign_it = 0;
    738 	}
    739 
    740 	if (query->ixfr_data == NULL) {
    741 		/* This is the first packet, process the query further */
    742 		uint32_t qserial = 0, current_serial = 0, end_serial = 0;
    743 		struct zone* zone;
    744 		struct ixfr_data* ixfr_data;
    745 		size_t oldpos;
    746 
    747 		STATUP(nsd, rixfr);
    748 		/* parse the serial number from the IXFR request */
    749 		oldpos = QHEADERSZ;
    750 		if(!parse_qserial(query->packet, &qserial, &oldpos)) {
    751 			NSCOUNT_SET(query->packet, 0);
    752 			ARCOUNT_SET(query->packet, 0);
    753 			buffer_set_position(query->packet, oldpos);
    754 			RCODE_SET(query->packet, RCODE_FORMAT);
    755 			return QUERY_PROCESSED;
    756 		}
    757 		NSCOUNT_SET(query->packet, 0);
    758 		ARCOUNT_SET(query->packet, 0);
    759 		buffer_set_position(query->packet, oldpos);
    760 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "ixfr query routine, %s IXFR=%u",
    761 			dname_to_string(query->qname, NULL), (unsigned)qserial));
    762 
    763 		/* do we have an IXFR with this serial number? If not, serve AXFR */
    764 		zone = namedb_find_zone(nsd->db, query->qname);
    765 		if(!zone) {
    766 			/* no zone is present */
    767 			RCODE_SET(query->packet, RCODE_NOTAUTH);
    768 			return QUERY_PROCESSED;
    769 		}
    770 		ZTATUP(nsd, zone, rixfr);
    771 
    772 		/* if the query is for same or newer serial than our current
    773 		 * serial, then serve a single SOA with our current serial */
    774 		current_serial = zone_get_current_serial(zone);
    775 		if(compare_serial(qserial, current_serial) >= 0) {
    776 			if(!zone->soa_rrset || zone->soa_rrset->rr_count != 1){
    777 				RCODE_SET(query->packet, RCODE_SERVFAIL);
    778 				return QUERY_PROCESSED;
    779 			}
    780 			query_add_compression_domain(query, zone->apex,
    781 				QHEADERSZ);
    782 			if(packet_encode_rr(query, zone->apex,
    783 				&zone->soa_rrset->rrs[0],
    784 				zone->soa_rrset->rrs[0].ttl)) {
    785 				ANCOUNT_SET(query->packet, 1);
    786 			} else {
    787 				RCODE_SET(query->packet, RCODE_SERVFAIL);
    788 			}
    789 			AA_SET(query->packet);
    790 			query_clear_compression_tables(query);
    791 			if(query->tsig.status == TSIG_OK)
    792 				query->tsig_sign_it = 1;
    793 			return QUERY_PROCESSED;
    794 		}
    795 
    796 		if(!zone->ixfr) {
    797 			/* we have no ixfr information for the zone, make an AXFR */
    798 			if(query->tsig_prepare_it)
    799 				query->tsig_sign_it = 1;
    800 			return query_axfr(nsd, query, 0);
    801 		}
    802 		ixfr_data = zone_ixfr_find_serial(zone->ixfr, qserial);
    803 		if(!ixfr_data) {
    804 			/* the specific version is not available, make an AXFR */
    805 			if(query->tsig_prepare_it)
    806 				query->tsig_sign_it = 1;
    807 			return query_axfr(nsd, query, 0);
    808 		}
    809 		/* see if the IXFRs connect to the next IXFR, and if it ends
    810 		 * at the current served zone, if not, AXFR */
    811 		if(!connect_ixfrs(zone->ixfr, ixfr_data, &end_serial) ||
    812 			end_serial != current_serial) {
    813 			if(query->tsig_prepare_it)
    814 				query->tsig_sign_it = 1;
    815 			return query_axfr(nsd, query, 0);
    816 		}
    817 
    818 		query->zone = zone;
    819 		query->ixfr_data = ixfr_data;
    820 		query->ixfr_is_done = 0;
    821 		/* set up to copy the last version's SOA as first SOA */
    822 		query->ixfr_end_data = ixfr_data_last(zone->ixfr);
    823 		query->ixfr_count_newsoa = 0;
    824 		query->ixfr_count_oldsoa = 0;
    825 		query->ixfr_count_del = 0;
    826 		query->ixfr_count_add = 0;
    827 		query->ixfr_pos_of_newsoa = 0;
    828 		/* the query name can be compressed to */
    829 		pktcompression_insert_with_labels(&pcomp,
    830 			buffer_at(query->packet, QHEADERSZ),
    831 			query->qname->name_size, QHEADERSZ);
    832 		if(query->tsig.status == TSIG_OK) {
    833 			query->tsig_sign_it = 1; /* sign first packet in stream */
    834 		}
    835 	} else {
    836 		/*
    837 		 * Query name need not be repeated after the
    838 		 * first response packet.
    839 		 */
    840 		buffer_set_limit(query->packet, QHEADERSZ);
    841 		QDCOUNT_SET(query->packet, 0);
    842 		query_prepare_response(query);
    843 	}
    844 
    845 	total_added = ixfr_copy_rrs_into_packet(query, &pcomp);
    846 
    847 	while(query->ixfr_count_add >= query->ixfr_data->add_len) {
    848 		struct ixfr_data* next = ixfr_data_next(query->zone->ixfr,
    849 			query->ixfr_data);
    850 		/* finished the ixfr_data */
    851 		if(next) {
    852 			/* move to the next IXFR */
    853 			query->ixfr_data = next;
    854 			/* we need to skip the SOA records, set len to done*/
    855 			/* the newsoa count is already done, at end_data len */
    856 			query->ixfr_count_oldsoa = next->oldsoa_len;
    857 			/* and then set up to copy the del and add sections */
    858 			query->ixfr_count_del = 0;
    859 			query->ixfr_count_add = 0;
    860 			total_added += ixfr_copy_rrs_into_packet(query, &pcomp);
    861 		} else {
    862 			/* we finished the IXFR */
    863 			/* sign the last packet */
    864 			query->tsig_sign_it = 1;
    865 			query->ixfr_is_done = 1;
    866 			break;
    867 		}
    868 	}
    869 
    870 	/* return the answer */
    871 	AA_SET(query->packet);
    872 	ANCOUNT_SET(query->packet, total_added);
    873 	NSCOUNT_SET(query->packet, 0);
    874 	ARCOUNT_SET(query->packet, 0);
    875 
    876 	if(!query->tcp && !query->ixfr_is_done) {
    877 		TC_SET(query->packet);
    878 		if(query->ixfr_pos_of_newsoa) {
    879 			/* if we recorded the newsoa in the result, snip off
    880 			 * the rest of the response, the RFC1995 response for
    881 			 * when it does not fit is only the latest SOA */
    882 			buffer_set_position(query->packet, query->ixfr_pos_of_newsoa);
    883 			ANCOUNT_SET(query->packet, 1);
    884 		}
    885 		query->ixfr_is_done = 1;
    886 	}
    887 
    888 	/* check if it needs tsig signatures */
    889 	if(query->tsig.status == TSIG_OK) {
    890 #if IXFR_TSIG_SIGN_EVERY_NTH > 0
    891 		if(query->tsig.updates_since_last_prepare >= IXFR_TSIG_SIGN_EVERY_NTH) {
    892 #endif
    893 			query->tsig_sign_it = 1;
    894 #if IXFR_TSIG_SIGN_EVERY_NTH > 0
    895 		}
    896 #endif
    897 	}
    898 	pktcompression_freeup(&pcomp);
    899 	return QUERY_IN_IXFR;
    900 }
    901 
    902 /* free ixfr_data structure */
    903 static void ixfr_data_free(struct ixfr_data* data)
    904 {
    905 	if(!data)
    906 		return;
    907 	free(data->newsoa);
    908 	free(data->oldsoa);
    909 	free(data->del);
    910 	free(data->add);
    911 	free(data->log_str);
    912 	free(data);
    913 }
    914 
    915 size_t ixfr_data_size(struct ixfr_data* data)
    916 {
    917 	return sizeof(struct ixfr_data) + data->newsoa_len + data->oldsoa_len
    918 		+ data->del_len + data->add_len;
    919 }
    920 
    921 struct ixfr_store* ixfr_store_start(struct zone* zone,
    922 	struct ixfr_store* ixfr_store_mem, uint32_t old_serial,
    923 	uint32_t new_serial)
    924 {
    925 	struct ixfr_store* ixfr_store = ixfr_store_mem;
    926 	memset(ixfr_store, 0, sizeof(*ixfr_store));
    927 	ixfr_store->zone = zone;
    928 	ixfr_store->data = xalloc_zero(sizeof(*ixfr_store->data));
    929 	ixfr_store->data->oldserial = old_serial;
    930 	ixfr_store->data->newserial = new_serial;
    931 	return ixfr_store;
    932 }
    933 
    934 void ixfr_store_cancel(struct ixfr_store* ixfr_store)
    935 {
    936 	ixfr_store->cancelled = 1;
    937 	ixfr_data_free(ixfr_store->data);
    938 	ixfr_store->data = NULL;
    939 }
    940 
    941 void ixfr_store_free(struct ixfr_store* ixfr_store)
    942 {
    943 	if(!ixfr_store)
    944 		return;
    945 	ixfr_data_free(ixfr_store->data);
    946 }
    947 
    948 /* make space in record data for the new size, grows the allocation */
    949 static void ixfr_rrs_make_space(uint8_t** rrs, size_t* len, size_t* capacity,
    950 	size_t added)
    951 {
    952 	size_t newsize = 0;
    953 	if(*rrs == NULL) {
    954 		newsize = IXFR_STORE_INITIAL_SIZE;
    955 	} else {
    956 		if(*len + added <= *capacity)
    957 			return; /* already enough space */
    958 		newsize = (*capacity)*2;
    959 	}
    960 	if(*len + added > newsize)
    961 		newsize = *len + added;
    962 	if(*rrs == NULL) {
    963 		*rrs = xalloc(newsize);
    964 	} else {
    965 		*rrs = xrealloc(*rrs, newsize);
    966 	}
    967 	*capacity = newsize;
    968 }
    969 
    970 /* put new SOA record after delrrs and addrrs */
    971 static void ixfr_put_newsoa(struct ixfr_store* ixfr_store, uint8_t** rrs,
    972 	size_t* len, size_t* capacity)
    973 {
    974 	uint8_t* soa;
    975 	size_t soa_len;
    976 	if(!ixfr_store->data)
    977 		return; /* data should be nonNULL, we are not cancelled */
    978 	soa = ixfr_store->data->newsoa;
    979 	soa_len= ixfr_store->data->newsoa_len;
    980 	ixfr_rrs_make_space(rrs, len, capacity, soa_len);
    981 	if(!*rrs || *len + soa_len > *capacity) {
    982 		log_msg(LOG_ERR, "ixfr_store addrr: cannot allocate space");
    983 		ixfr_store_cancel(ixfr_store);
    984 		return;
    985 	}
    986 	memmove(*rrs + *len, soa, soa_len);
    987 	*len += soa_len;
    988 }
    989 
    990 /* trim unused storage from the rrs data */
    991 static void ixfr_trim_capacity(uint8_t** rrs, size_t* len, size_t* capacity)
    992 {
    993 	if(*rrs == NULL)
    994 		return;
    995 	if(*capacity == *len)
    996 		return;
    997 	*rrs = xrealloc(*rrs, *len);
    998 	*capacity = *len;
    999 }
   1000 
   1001 void ixfr_store_finish_data(struct ixfr_store* ixfr_store)
   1002 {
   1003 	if(ixfr_store->data_trimmed)
   1004 		return;
   1005 	ixfr_store->data_trimmed = 1;
   1006 
   1007 	/* put new serial SOA record after delrrs and addrrs */
   1008 	ixfr_put_newsoa(ixfr_store, &ixfr_store->data->del,
   1009 		&ixfr_store->data->del_len, &ixfr_store->del_capacity);
   1010 	ixfr_put_newsoa(ixfr_store, &ixfr_store->data->add,
   1011 		&ixfr_store->data->add_len, &ixfr_store->add_capacity);
   1012 
   1013 	/* trim the data in the store, the overhead from capacity is
   1014 	 * removed */
   1015 	if(!ixfr_store->data)
   1016 		return; /* data should be nonNULL, we are not cancelled */
   1017 	ixfr_trim_capacity(&ixfr_store->data->del,
   1018 		&ixfr_store->data->del_len, &ixfr_store->del_capacity);
   1019 	ixfr_trim_capacity(&ixfr_store->data->add,
   1020 		&ixfr_store->data->add_len, &ixfr_store->add_capacity);
   1021 }
   1022 
   1023 void ixfr_store_finish(struct ixfr_store* ixfr_store, struct nsd* nsd,
   1024 	char* log_buf)
   1025 {
   1026 	if(ixfr_store->cancelled) {
   1027 		ixfr_store_free(ixfr_store);
   1028 		return;
   1029 	}
   1030 
   1031 	ixfr_store_finish_data(ixfr_store);
   1032 
   1033 	if(ixfr_store->cancelled) {
   1034 		ixfr_store_free(ixfr_store);
   1035 		return;
   1036 	}
   1037 
   1038 	if(log_buf && !ixfr_store->data->log_str)
   1039 		ixfr_store->data->log_str = strdup(log_buf);
   1040 
   1041 	/* store the data in the zone */
   1042 	if(!ixfr_store->zone->ixfr)
   1043 		ixfr_store->zone->ixfr = zone_ixfr_create(nsd);
   1044 	zone_ixfr_make_space(ixfr_store->zone->ixfr, ixfr_store->zone,
   1045 		ixfr_store->data, ixfr_store);
   1046 	if(ixfr_store->cancelled) {
   1047 		ixfr_store_free(ixfr_store);
   1048 		return;
   1049 	}
   1050 	zone_ixfr_add(ixfr_store->zone->ixfr, ixfr_store->data, 1);
   1051 	ixfr_store->data = NULL;
   1052 
   1053 	/* free structure */
   1054 	ixfr_store_free(ixfr_store);
   1055 }
   1056 
   1057 /* read SOA rdata section for SOA storage */
   1058 static int read_soa_rdata(struct buffer* packet, uint8_t* primns,
   1059 	int* primns_len, uint8_t* email, int* email_len,
   1060 	uint32_t* serial, uint32_t* refresh, uint32_t* retry,
   1061 	uint32_t* expire, uint32_t* minimum, size_t* sz)
   1062 {
   1063 	if(!(*primns_len = dname_make_wire_from_packet(primns, packet, 1))) {
   1064 		log_msg(LOG_ERR, "ixfr_store: cannot parse soa nsname in packet");
   1065 		return 0;
   1066 	}
   1067 	*sz += *primns_len;
   1068 	if(!(*email_len = dname_make_wire_from_packet(email, packet, 1))) {
   1069 		log_msg(LOG_ERR, "ixfr_store: cannot parse soa maintname in packet");
   1070 		return 0;
   1071 	}
   1072 	*sz += *email_len;
   1073 	*serial = buffer_read_u32(packet);
   1074 	*sz += 4;
   1075 	*refresh = buffer_read_u32(packet);
   1076 	*sz += 4;
   1077 	*retry = buffer_read_u32(packet);
   1078 	*sz += 4;
   1079 	*expire = buffer_read_u32(packet);
   1080 	*sz += 4;
   1081 	*minimum = buffer_read_u32(packet);
   1082 	*sz += 4;
   1083 	return 1;
   1084 }
   1085 
   1086 /* store SOA record data in memory buffer */
   1087 static void store_soa(uint8_t* soa, struct zone* zone, uint32_t ttl,
   1088 	uint16_t rdlen_uncompressed, uint8_t* primns, int primns_len,
   1089 	uint8_t* email, int email_len, uint32_t serial, uint32_t refresh,
   1090 	uint32_t retry, uint32_t expire, uint32_t minimum)
   1091 {
   1092 	uint8_t* sp = soa;
   1093 	memmove(sp, dname_name(domain_dname(zone->apex)),
   1094 		domain_dname(zone->apex)->name_size);
   1095 	sp += domain_dname(zone->apex)->name_size;
   1096 	write_uint16(sp, TYPE_SOA);
   1097 	sp += 2;
   1098 	write_uint16(sp, CLASS_IN);
   1099 	sp += 2;
   1100 	write_uint32(sp, ttl);
   1101 	sp += 4;
   1102 	write_uint16(sp, rdlen_uncompressed);
   1103 	sp += 2;
   1104 	memmove(sp, primns, primns_len);
   1105 	sp += primns_len;
   1106 	memmove(sp, email, email_len);
   1107 	sp += email_len;
   1108 	write_uint32(sp, serial);
   1109 	sp += 4;
   1110 	write_uint32(sp, refresh);
   1111 	sp += 4;
   1112 	write_uint32(sp, retry);
   1113 	sp += 4;
   1114 	write_uint32(sp, expire);
   1115 	sp += 4;
   1116 	write_uint32(sp, minimum);
   1117 }
   1118 
   1119 void ixfr_store_add_newsoa(struct ixfr_store* ixfr_store,
   1120 	struct buffer* packet, size_t ttlpos)
   1121 {
   1122 	size_t oldpos, sz = 0;
   1123 	uint32_t ttl, serial, refresh, retry, expire, minimum;
   1124 	uint16_t rdlen_uncompressed, rdlen_wire;
   1125 	int primns_len = 0, email_len = 0;
   1126 	uint8_t primns[MAXDOMAINLEN + 1], email[MAXDOMAINLEN + 1];
   1127 
   1128 	if(ixfr_store->cancelled)
   1129 		return;
   1130 	if(ixfr_store->data->newsoa) {
   1131 		free(ixfr_store->data->newsoa);
   1132 		ixfr_store->data->newsoa = NULL;
   1133 		ixfr_store->data->newsoa_len = 0;
   1134 	}
   1135 	oldpos = buffer_position(packet);
   1136 	buffer_set_position(packet, ttlpos);
   1137 
   1138 	/* calculate the length */
   1139 	sz = domain_dname(ixfr_store->zone->apex)->name_size;
   1140 	sz += 2 /* type */ + 2 /* class */;
   1141 	/* read ttl */
   1142 	if(!buffer_available(packet, 4/*ttl*/+2/*rdlen*/)) {
   1143 		/* not possible already parsed, but fail nicely anyway */
   1144 		log_msg(LOG_ERR, "ixfr_store: not enough space in packet");
   1145 		ixfr_store_cancel(ixfr_store);
   1146 		buffer_set_position(packet, oldpos);
   1147 		return;
   1148 	}
   1149 	ttl = buffer_read_u32(packet);
   1150 	sz += 4;
   1151 	rdlen_wire = buffer_read_u16(packet);
   1152 	sz += 2;
   1153 	if(!buffer_available(packet, rdlen_wire)) {
   1154 		/* not possible already parsed, but fail nicely anyway */
   1155 		log_msg(LOG_ERR, "ixfr_store: not enough rdata space in packet");
   1156 		ixfr_store_cancel(ixfr_store);
   1157 		buffer_set_position(packet, oldpos);
   1158 		return;
   1159 	}
   1160 	if(!read_soa_rdata(packet, primns, &primns_len, email, &email_len,
   1161 		&serial, &refresh, &retry, &expire, &minimum, &sz)) {
   1162 		log_msg(LOG_ERR, "ixfr_store newsoa: cannot parse packet");
   1163 		ixfr_store_cancel(ixfr_store);
   1164 		buffer_set_position(packet, oldpos);
   1165 		return;
   1166 	}
   1167 	rdlen_uncompressed = primns_len + email_len + 4 + 4 + 4 + 4 + 4;
   1168 
   1169 	/* store the soa record */
   1170 	ixfr_store->data->newsoa = xalloc(sz);
   1171 	ixfr_store->data->newsoa_len = sz;
   1172 	store_soa(ixfr_store->data->newsoa, ixfr_store->zone, ttl,
   1173 		rdlen_uncompressed, primns, primns_len, email, email_len,
   1174 		serial, refresh, retry, expire, minimum);
   1175 
   1176 	buffer_set_position(packet, oldpos);
   1177 }
   1178 
   1179 void ixfr_store_add_oldsoa(struct ixfr_store* ixfr_store, uint32_t ttl,
   1180 	struct buffer* packet, size_t rrlen)
   1181 {
   1182 	size_t oldpos, sz = 0;
   1183 	uint32_t serial, refresh, retry, expire, minimum;
   1184 	uint16_t rdlen_uncompressed;
   1185 	int primns_len = 0, email_len = 0;
   1186 	uint8_t primns[MAXDOMAINLEN + 1], email[MAXDOMAINLEN + 1];
   1187 
   1188 	if(ixfr_store->cancelled)
   1189 		return;
   1190 	if(ixfr_store->data->oldsoa) {
   1191 		free(ixfr_store->data->oldsoa);
   1192 		ixfr_store->data->oldsoa = NULL;
   1193 		ixfr_store->data->oldsoa_len = 0;
   1194 	}
   1195 	/* we have the old SOA and thus we are sure it is an IXFR, make space*/
   1196 	zone_ixfr_make_space(ixfr_store->zone->ixfr, ixfr_store->zone,
   1197 		ixfr_store->data, ixfr_store);
   1198 	if(ixfr_store->cancelled)
   1199 		return;
   1200 	oldpos = buffer_position(packet);
   1201 
   1202 	/* calculate the length */
   1203 	sz = domain_dname(ixfr_store->zone->apex)->name_size;
   1204 	sz += 2 /*type*/ + 2 /*class*/ + 4 /*ttl*/ + 2 /*rdlen*/;
   1205 	if(!buffer_available(packet, rrlen)) {
   1206 		/* not possible already parsed, but fail nicely anyway */
   1207 		log_msg(LOG_ERR, "ixfr_store oldsoa: not enough rdata space in packet");
   1208 		ixfr_store_cancel(ixfr_store);
   1209 		buffer_set_position(packet, oldpos);
   1210 		return;
   1211 	}
   1212 	if(!read_soa_rdata(packet, primns, &primns_len, email, &email_len,
   1213 		&serial, &refresh, &retry, &expire, &minimum, &sz)) {
   1214 		log_msg(LOG_ERR, "ixfr_store oldsoa: cannot parse packet");
   1215 		ixfr_store_cancel(ixfr_store);
   1216 		buffer_set_position(packet, oldpos);
   1217 		return;
   1218 	}
   1219 	rdlen_uncompressed = primns_len + email_len + 4 + 4 + 4 + 4 + 4;
   1220 
   1221 	/* store the soa record */
   1222 	ixfr_store->data->oldsoa = xalloc(sz);
   1223 	ixfr_store->data->oldsoa_len = sz;
   1224 	store_soa(ixfr_store->data->oldsoa, ixfr_store->zone, ttl,
   1225 		rdlen_uncompressed, primns, primns_len, email, email_len,
   1226 		serial, refresh, retry, expire, minimum);
   1227 
   1228 	buffer_set_position(packet, oldpos);
   1229 }
   1230 
   1231 /* store RR in data segment */
   1232 static int ixfr_putrr(const struct dname* dname, uint16_t type, uint16_t klass,
   1233 	uint32_t ttl, rdata_atom_type* rdatas, ssize_t rdata_num,
   1234 	uint8_t** rrs, size_t* rrs_len, size_t* rrs_capacity)
   1235 {
   1236 	size_t rdlen_uncompressed, sz;
   1237 	uint8_t* sp;
   1238 	int i;
   1239 
   1240 	/* find rdatalen */
   1241 	rdlen_uncompressed = 0;
   1242 	for(i=0; i<rdata_num; i++) {
   1243 		if(rdata_atom_is_domain(type, i)) {
   1244 			rdlen_uncompressed += domain_dname(rdatas[i].domain)
   1245 				->name_size;
   1246 		} else {
   1247 			rdlen_uncompressed += rdatas[i].data[0];
   1248 		}
   1249 	}
   1250 	sz = dname->name_size + 2 /*type*/ + 2 /*class*/ + 4 /*ttl*/ +
   1251 		2 /*rdlen*/ + rdlen_uncompressed;
   1252 
   1253 	/* store RR in IXFR data */
   1254 	ixfr_rrs_make_space(rrs, rrs_len, rrs_capacity, sz);
   1255 	if(!*rrs || *rrs_len + sz > *rrs_capacity) {
   1256 		return 0;
   1257 	}
   1258 	/* copy data into add */
   1259 	sp = *rrs + *rrs_len;
   1260 	*rrs_len += sz;
   1261 	memmove(sp, dname_name(dname), dname->name_size);
   1262 	sp += dname->name_size;
   1263 	write_uint16(sp, type);
   1264 	sp += 2;
   1265 	write_uint16(sp, klass);
   1266 	sp += 2;
   1267 	write_uint32(sp, ttl);
   1268 	sp += 4;
   1269 	write_uint16(sp, rdlen_uncompressed);
   1270 	sp += 2;
   1271 	for(i=0; i<rdata_num; i++) {
   1272 		if(rdata_atom_is_domain(type, i)) {
   1273 			memmove(sp, dname_name(domain_dname(rdatas[i].domain)),
   1274 				domain_dname(rdatas[i].domain)->name_size);
   1275 			sp += domain_dname(rdatas[i].domain)->name_size;
   1276 		} else {
   1277 			memmove(sp, &rdatas[i].data[1], rdatas[i].data[0]);
   1278 			sp += rdatas[i].data[0];
   1279 		}
   1280 	}
   1281 	return 1;
   1282 }
   1283 
   1284 void ixfr_store_putrr(struct ixfr_store* ixfr_store, const struct dname* dname,
   1285 	uint16_t type, uint16_t klass, uint32_t ttl, struct buffer* packet,
   1286 	uint16_t rrlen, struct region* temp_region, uint8_t** rrs,
   1287 	size_t* rrs_len, size_t* rrs_capacity)
   1288 {
   1289 	domain_table_type *temptable;
   1290 	rdata_atom_type *rdatas;
   1291 	ssize_t rdata_num;
   1292 	size_t oldpos;
   1293 
   1294 	if(ixfr_store->cancelled)
   1295 		return;
   1296 
   1297 	/* The SOA data is stored with separate calls. And then appended
   1298 	 * during the finish operation. We do not have to store it here
   1299 	 * when called from difffile's IXFR processing with type SOA. */
   1300 	if(type == TYPE_SOA)
   1301 		return;
   1302 	/* make space for these RRs we have now; basically once we
   1303 	 * grow beyond the current allowed amount an older IXFR is deleted. */
   1304 	zone_ixfr_make_space(ixfr_store->zone->ixfr, ixfr_store->zone,
   1305 		ixfr_store->data, ixfr_store);
   1306 	if(ixfr_store->cancelled)
   1307 		return;
   1308 
   1309 	/* parse rdata */
   1310 	oldpos = buffer_position(packet);
   1311 	temptable = domain_table_create(temp_region);
   1312 	rdata_num = rdata_wireformat_to_rdata_atoms(temp_region, temptable,
   1313 		type, rrlen, packet, &rdatas);
   1314 	buffer_set_position(packet, oldpos);
   1315 	if(rdata_num == -1) {
   1316 		log_msg(LOG_ERR, "ixfr_store addrr: cannot parse packet");
   1317 		ixfr_store_cancel(ixfr_store);
   1318 		return;
   1319 	}
   1320 
   1321 	if(!ixfr_putrr(dname, type, klass, ttl, rdatas, rdata_num,
   1322 		rrs, rrs_len, rrs_capacity)) {
   1323 		log_msg(LOG_ERR, "ixfr_store addrr: cannot allocate space");
   1324 		ixfr_store_cancel(ixfr_store);
   1325 		return;
   1326 	}
   1327 }
   1328 
   1329 void ixfr_store_delrr(struct ixfr_store* ixfr_store, const struct dname* dname,
   1330 	uint16_t type, uint16_t klass, uint32_t ttl, struct buffer* packet,
   1331 	uint16_t rrlen, struct region* temp_region)
   1332 {
   1333 	ixfr_store_putrr(ixfr_store, dname, type, klass, ttl, packet, rrlen,
   1334 		temp_region, &ixfr_store->data->del,
   1335 		&ixfr_store->data->del_len, &ixfr_store->del_capacity);
   1336 }
   1337 
   1338 void ixfr_store_addrr(struct ixfr_store* ixfr_store, const struct dname* dname,
   1339 	uint16_t type, uint16_t klass, uint32_t ttl, struct buffer* packet,
   1340 	uint16_t rrlen, struct region* temp_region)
   1341 {
   1342 	ixfr_store_putrr(ixfr_store, dname, type, klass, ttl, packet, rrlen,
   1343 		temp_region, &ixfr_store->data->add,
   1344 		&ixfr_store->data->add_len, &ixfr_store->add_capacity);
   1345 }
   1346 
   1347 int ixfr_store_addrr_rdatas(struct ixfr_store* ixfr_store,
   1348 	const struct dname* dname, uint16_t type, uint16_t klass,
   1349 	uint32_t ttl, rdata_atom_type* rdatas, ssize_t rdata_num)
   1350 {
   1351 	if(ixfr_store->cancelled)
   1352 		return 1;
   1353 	if(type == TYPE_SOA)
   1354 		return 1;
   1355 	return ixfr_putrr(dname, type, klass, ttl, rdatas, rdata_num,
   1356 		&ixfr_store->data->add, &ixfr_store->data->add_len,
   1357 		&ixfr_store->add_capacity);
   1358 }
   1359 
   1360 int ixfr_store_add_newsoa_rdatas(struct ixfr_store* ixfr_store,
   1361 	const struct dname* dname, uint16_t type, uint16_t klass,
   1362 	uint32_t ttl, rdata_atom_type* rdatas, ssize_t rdata_num)
   1363 {
   1364 	size_t capacity = 0;
   1365 	if(ixfr_store->cancelled)
   1366 		return 1;
   1367 	if(!ixfr_putrr(dname, type, klass, ttl, rdatas, rdata_num,
   1368 		&ixfr_store->data->newsoa, &ixfr_store->data->newsoa_len,
   1369 		&ixfr_store->add_capacity))
   1370 		return 0;
   1371 	ixfr_trim_capacity(&ixfr_store->data->newsoa,
   1372 		&ixfr_store->data->newsoa_len, &capacity);
   1373 	return 1;
   1374 }
   1375 
   1376 /* store rr uncompressed */
   1377 int ixfr_storerr_uncompressed(uint8_t* dname, size_t dname_len, uint16_t type,
   1378 	uint16_t klass, uint32_t ttl, uint8_t* rdata, size_t rdata_len,
   1379 	uint8_t** rrs, size_t* rrs_len, size_t* rrs_capacity)
   1380 {
   1381 	size_t sz;
   1382 	uint8_t* sp;
   1383 
   1384 	/* find rdatalen */
   1385 	sz = dname_len + 2 /*type*/ + 2 /*class*/ + 4 /*ttl*/ +
   1386 		2 /*rdlen*/ + rdata_len;
   1387 
   1388 	/* store RR in IXFR data */
   1389 	ixfr_rrs_make_space(rrs, rrs_len, rrs_capacity, sz);
   1390 	if(!*rrs || *rrs_len + sz > *rrs_capacity) {
   1391 		return 0;
   1392 	}
   1393 	/* copy data into add */
   1394 	sp = *rrs + *rrs_len;
   1395 	*rrs_len += sz;
   1396 	memmove(sp, dname, dname_len);
   1397 	sp += dname_len;
   1398 	write_uint16(sp, type);
   1399 	sp += 2;
   1400 	write_uint16(sp, klass);
   1401 	sp += 2;
   1402 	write_uint32(sp, ttl);
   1403 	sp += 4;
   1404 	write_uint16(sp, rdata_len);
   1405 	sp += 2;
   1406 	memmove(sp, rdata, rdata_len);
   1407 	return 1;
   1408 }
   1409 
   1410 int ixfr_store_delrr_uncompressed(struct ixfr_store* ixfr_store,
   1411 	uint8_t* dname, size_t dname_len, uint16_t type, uint16_t klass,
   1412 	uint32_t ttl, uint8_t* rdata, size_t rdata_len)
   1413 {
   1414 	if(ixfr_store->cancelled)
   1415 		return 1;
   1416 	if(type == TYPE_SOA)
   1417 		return 1;
   1418 	return ixfr_storerr_uncompressed(dname, dname_len, type, klass,
   1419 		ttl, rdata, rdata_len, &ixfr_store->data->del,
   1420 		&ixfr_store->data->del_len, &ixfr_store->del_capacity);
   1421 }
   1422 
   1423 int ixfr_store_oldsoa_uncompressed(struct ixfr_store* ixfr_store,
   1424 	uint8_t* dname, size_t dname_len, uint16_t type, uint16_t klass,
   1425 	uint32_t ttl, uint8_t* rdata, size_t rdata_len)
   1426 {
   1427 	size_t capacity = 0;
   1428 	if(ixfr_store->cancelled)
   1429 		return 1;
   1430 	if(!ixfr_storerr_uncompressed(dname, dname_len, type, klass,
   1431 		ttl, rdata, rdata_len, &ixfr_store->data->oldsoa,
   1432 		&ixfr_store->data->oldsoa_len, &capacity))
   1433 		return 0;
   1434 	ixfr_trim_capacity(&ixfr_store->data->oldsoa,
   1435 		&ixfr_store->data->oldsoa_len, &capacity);
   1436 	return 1;
   1437 }
   1438 
   1439 int zone_is_ixfr_enabled(struct zone* zone)
   1440 {
   1441 	return zone->opts->pattern->store_ixfr;
   1442 }
   1443 
   1444 /* compare ixfr elements */
   1445 static int ixfrcompare(const void* x, const void* y)
   1446 {
   1447 	uint32_t* serial_x = (uint32_t*)x;
   1448 	uint32_t* serial_y = (uint32_t*)y;
   1449 	if(*serial_x < *serial_y)
   1450 		return -1;
   1451 	if(*serial_x > *serial_y)
   1452 		return 1;
   1453 	return 0;
   1454 }
   1455 
   1456 struct zone_ixfr* zone_ixfr_create(struct nsd* nsd)
   1457 {
   1458 	struct zone_ixfr* ixfr = xalloc_zero(sizeof(struct zone_ixfr));
   1459 	ixfr->data = rbtree_create(nsd->region, &ixfrcompare);
   1460 	return ixfr;
   1461 }
   1462 
   1463 /* traverse tree postorder */
   1464 static void ixfr_tree_del(struct rbnode* node)
   1465 {
   1466 	if(node == NULL || node == RBTREE_NULL)
   1467 		return;
   1468 	ixfr_tree_del(node->left);
   1469 	ixfr_tree_del(node->right);
   1470 	ixfr_data_free((struct ixfr_data*)node);
   1471 }
   1472 
   1473 /* clear the ixfr data elements */
   1474 static void zone_ixfr_clear(struct zone_ixfr* ixfr)
   1475 {
   1476 	if(!ixfr)
   1477 		return;
   1478 	if(ixfr->data) {
   1479 		ixfr_tree_del(ixfr->data->root);
   1480 		ixfr->data->root = RBTREE_NULL;
   1481 		ixfr->data->count = 0;
   1482 	}
   1483 	ixfr->total_size = 0;
   1484 	ixfr->oldest_serial = 0;
   1485 	ixfr->newest_serial = 0;
   1486 }
   1487 
   1488 void zone_ixfr_free(struct zone_ixfr* ixfr)
   1489 {
   1490 	if(!ixfr)
   1491 		return;
   1492 	if(ixfr->data) {
   1493 		ixfr_tree_del(ixfr->data->root);
   1494 		ixfr->data = NULL;
   1495 	}
   1496 	free(ixfr);
   1497 }
   1498 
   1499 void ixfr_store_delixfrs(struct zone* zone)
   1500 {
   1501 	if(!zone)
   1502 		return;
   1503 	zone_ixfr_clear(zone->ixfr);
   1504 }
   1505 
   1506 /* remove the oldest data entry from the ixfr versions */
   1507 static void zone_ixfr_remove_oldest(struct zone_ixfr* ixfr)
   1508 {
   1509 	if(ixfr->data->count > 0) {
   1510 		struct ixfr_data* oldest = ixfr_data_first(ixfr);
   1511 		if(ixfr->oldest_serial == oldest->oldserial) {
   1512 			if(ixfr->data->count > 1) {
   1513 				struct ixfr_data* next = ixfr_data_next(ixfr, oldest);
   1514 				assert(next);
   1515 				if(next)
   1516 					ixfr->oldest_serial = next->oldserial;
   1517 				else 	ixfr->oldest_serial = oldest->newserial;
   1518 			} else {
   1519 				ixfr->oldest_serial = 0;
   1520 			}
   1521 		}
   1522 		if(ixfr->newest_serial == oldest->oldserial) {
   1523 			ixfr->newest_serial = 0;
   1524 		}
   1525 		zone_ixfr_remove(ixfr, oldest);
   1526 	}
   1527 }
   1528 
   1529 void zone_ixfr_make_space(struct zone_ixfr* ixfr, struct zone* zone,
   1530 	struct ixfr_data* data, struct ixfr_store* ixfr_store)
   1531 {
   1532 	size_t addsize;
   1533 	if(!ixfr || !data)
   1534 		return;
   1535 	if(zone->opts->pattern->ixfr_number == 0) {
   1536 		ixfr_store_cancel(ixfr_store);
   1537 		return;
   1538 	}
   1539 
   1540 	/* Check the number of IXFRs allowed for this zone, if too many,
   1541 	 * shorten the number to make space for another one */
   1542 	while(ixfr->data->count >= zone->opts->pattern->ixfr_number) {
   1543 		zone_ixfr_remove_oldest(ixfr);
   1544 	}
   1545 
   1546 	if(zone->opts->pattern->ixfr_size == 0) {
   1547 		/* no size limits imposed */
   1548 		return;
   1549 	}
   1550 
   1551 	/* Check the size of the current added data element 'data', and
   1552 	 * see if that overflows the maximum storage size for IXFRs for
   1553 	 * this zone, and if so, delete the oldest IXFR to make space */
   1554 	addsize = ixfr_data_size(data);
   1555 	while(ixfr->data->count > 0 && ixfr->total_size + addsize >
   1556 		zone->opts->pattern->ixfr_size) {
   1557 		zone_ixfr_remove_oldest(ixfr);
   1558 	}
   1559 
   1560 	/* if deleting the oldest elements does not work, then this
   1561 	 * IXFR is too big to store and we cancel it */
   1562 	if(ixfr->data->count == 0 && ixfr->total_size + addsize >
   1563 		zone->opts->pattern->ixfr_size) {
   1564 		ixfr_store_cancel(ixfr_store);
   1565 		return;
   1566 	}
   1567 }
   1568 
   1569 void zone_ixfr_remove(struct zone_ixfr* ixfr, struct ixfr_data* data)
   1570 {
   1571 	rbtree_delete(ixfr->data, data->node.key);
   1572 	ixfr->total_size -= ixfr_data_size(data);
   1573 	ixfr_data_free(data);
   1574 }
   1575 
   1576 void zone_ixfr_add(struct zone_ixfr* ixfr, struct ixfr_data* data, int isnew)
   1577 {
   1578 	memset(&data->node, 0, sizeof(data->node));
   1579 	if(ixfr->data->count == 0) {
   1580 		ixfr->oldest_serial = data->oldserial;
   1581 		ixfr->newest_serial = data->oldserial;
   1582 	} else if(isnew) {
   1583 		/* newest entry is last there is */
   1584 		ixfr->newest_serial = data->oldserial;
   1585 	} else {
   1586 		/* added older entry, before the others */
   1587 		ixfr->oldest_serial = data->oldserial;
   1588 	}
   1589 	data->node.key = &data->oldserial;
   1590 	rbtree_insert(ixfr->data, &data->node);
   1591 	ixfr->total_size += ixfr_data_size(data);
   1592 }
   1593 
   1594 struct ixfr_data* zone_ixfr_find_serial(struct zone_ixfr* ixfr,
   1595 	uint32_t qserial)
   1596 {
   1597 	struct ixfr_data* data;
   1598 	if(!ixfr)
   1599 		return NULL;
   1600 	if(!ixfr->data)
   1601 		return NULL;
   1602 	data = (struct ixfr_data*)rbtree_search(ixfr->data, &qserial);
   1603 	if(data) {
   1604 		assert(data->oldserial == qserial);
   1605 		return data;
   1606 	}
   1607 	/* not found */
   1608 	return NULL;
   1609 }
   1610 
   1611 /* calculate the number of files we want */
   1612 static int ixfr_target_number_files(struct zone* zone)
   1613 {
   1614 	int dest_num_files;
   1615 	if(!zone->ixfr || !zone->ixfr->data)
   1616 		return 0;
   1617 	if(!zone_is_ixfr_enabled(zone))
   1618 		return 0;
   1619 	/* if we store ixfr, it is the configured number of files */
   1620 	dest_num_files = (int)zone->opts->pattern->ixfr_number;
   1621 	/* but if the number of available transfers is smaller, store less */
   1622 	if(dest_num_files > (int)zone->ixfr->data->count)
   1623 		dest_num_files = (int)zone->ixfr->data->count;
   1624 	return dest_num_files;
   1625 }
   1626 
   1627 /* create ixfrfile name in buffer for file_num. The num is 1 .. number. */
   1628 static void make_ixfr_name(char* buf, size_t len, const char* zfile,
   1629 	int file_num)
   1630 {
   1631 	if(file_num == 1)
   1632 		snprintf(buf, len, "%s.ixfr", zfile);
   1633 	else snprintf(buf, len, "%s.ixfr.%d", zfile, file_num);
   1634 }
   1635 
   1636 /* create temp ixfrfile name in buffer for file_num. The num is 1 .. number. */
   1637 static void make_ixfr_name_temp(char* buf, size_t len, const char* zfile,
   1638 	int file_num, int temp)
   1639 {
   1640 	if(file_num == 1)
   1641 		snprintf(buf, len, "%s.ixfr%s", zfile, (temp?".temp":""));
   1642 	else snprintf(buf, len, "%s.ixfr.%d%s", zfile, file_num,
   1643 		(temp?".temp":""));
   1644 }
   1645 
   1646 /* see if ixfr file exists */
   1647 static int ixfr_file_exists_ctmp(const char* zfile, int file_num, int temp)
   1648 {
   1649 	struct stat statbuf;
   1650 	char ixfrfile[1024+24];
   1651 	make_ixfr_name_temp(ixfrfile, sizeof(ixfrfile), zfile, file_num, temp);
   1652 	memset(&statbuf, 0, sizeof(statbuf));
   1653 	if(stat(ixfrfile, &statbuf) < 0) {
   1654 		if(errno == ENOENT)
   1655 			return 0;
   1656 		/* file is not usable */
   1657 		return 0;
   1658 	}
   1659 	return 1;
   1660 }
   1661 
   1662 int ixfr_file_exists(const char* zfile, int file_num)
   1663 {
   1664 	return ixfr_file_exists_ctmp(zfile, file_num, 0);
   1665 }
   1666 
   1667 /* see if ixfr file exists */
   1668 static int ixfr_file_exists_temp(const char* zfile, int file_num)
   1669 {
   1670 	return ixfr_file_exists_ctmp(zfile, file_num, 1);
   1671 }
   1672 
   1673 /* unlink an ixfr file */
   1674 static int ixfr_unlink_it_ctmp(const char* zname, const char* zfile,
   1675 	int file_num, int silent_enoent, int temp)
   1676 {
   1677 	char ixfrfile[1024+24];
   1678 	make_ixfr_name_temp(ixfrfile, sizeof(ixfrfile), zfile, file_num, temp);
   1679 	VERBOSITY(3, (LOG_INFO, "delete zone %s IXFR data file %s",
   1680 		zname, ixfrfile));
   1681 	if(unlink(ixfrfile) < 0) {
   1682 		if(silent_enoent && errno == ENOENT)
   1683 			return 0;
   1684 		log_msg(LOG_ERR, "error to delete file %s: %s", ixfrfile,
   1685 			strerror(errno));
   1686 		return 0;
   1687 	}
   1688 	return 1;
   1689 }
   1690 
   1691 int ixfr_unlink_it(const char* zname, const char* zfile, int file_num,
   1692 	int silent_enoent)
   1693 {
   1694 	return ixfr_unlink_it_ctmp(zname, zfile, file_num, silent_enoent, 0);
   1695 }
   1696 
   1697 /* unlink an ixfr file */
   1698 static int ixfr_unlink_it_temp(const char* zname, const char* zfile,
   1699 	int file_num, int silent_enoent)
   1700 {
   1701 	return ixfr_unlink_it_ctmp(zname, zfile, file_num, silent_enoent, 1);
   1702 }
   1703 
   1704 /* read ixfr file header */
   1705 int ixfr_read_file_header(const char* zname, const char* zfile,
   1706 	int file_num, uint32_t* oldserial, uint32_t* newserial,
   1707 	size_t* data_size, int enoent_is_err)
   1708 {
   1709 	char ixfrfile[1024+24];
   1710 	char buf[1024];
   1711 	FILE* in;
   1712 	int num_lines = 0, got_old = 0, got_new = 0, got_datasize = 0;
   1713 	make_ixfr_name(ixfrfile, sizeof(ixfrfile), zfile, file_num);
   1714 	in = fopen(ixfrfile, "r");
   1715 	if(!in) {
   1716 		if((errno == ENOENT && enoent_is_err) || (errno != ENOENT))
   1717 			log_msg(LOG_ERR, "could not open %s: %s", ixfrfile,
   1718 				strerror(errno));
   1719 		return 0;
   1720 	}
   1721 	/* read about 10 lines, this is where the header is */
   1722 	while(!(got_old && got_new && got_datasize) && num_lines < 10) {
   1723 		buf[0]=0;
   1724 		buf[sizeof(buf)-1]=0;
   1725 		if(!fgets(buf, sizeof(buf), in)) {
   1726 			log_msg(LOG_ERR, "could not read %s: %s", ixfrfile,
   1727 				strerror(errno));
   1728 			fclose(in);
   1729 			return 0;
   1730 		}
   1731 		num_lines++;
   1732 		if(buf[0]!=0 && buf[strlen(buf)-1]=='\n')
   1733 			buf[strlen(buf)-1]=0;
   1734 		if(strncmp(buf, "; zone ", 7) == 0) {
   1735 			if(strcmp(buf+7, zname) != 0) {
   1736 				log_msg(LOG_ERR, "file has wrong zone, expected zone %s, but found %s in file %s",
   1737 					zname, buf+7, ixfrfile);
   1738 				fclose(in);
   1739 				return 0;
   1740 			}
   1741 		} else if(strncmp(buf, "; from_serial ", 14) == 0) {
   1742 			*oldserial = atoi(buf+14);
   1743 			got_old = 1;
   1744 		} else if(strncmp(buf, "; to_serial ", 12) == 0) {
   1745 			*newserial = atoi(buf+12);
   1746 			got_new = 1;
   1747 		} else if(strncmp(buf, "; data_size ", 12) == 0) {
   1748 			*data_size = (size_t)atoi(buf+12);
   1749 			got_datasize = 1;
   1750 		}
   1751 	}
   1752 	fclose(in);
   1753 	if(!got_old)
   1754 		return 0;
   1755 	if(!got_new)
   1756 		return 0;
   1757 	if(!got_datasize)
   1758 		return 0;
   1759 	return 1;
   1760 }
   1761 
   1762 /* delete rest ixfr files, that are after the current item */
   1763 static void ixfr_delete_rest_files(struct zone* zone, struct ixfr_data* from,
   1764 	const char* zfile, int temp)
   1765 {
   1766 	size_t prevcount = 0;
   1767 	struct ixfr_data* data = from;
   1768 	while(data) {
   1769 		if(data->file_num != 0) {
   1770 			(void)ixfr_unlink_it_ctmp(zone->opts->name, zfile,
   1771 				data->file_num, 0, temp);
   1772 			data->file_num = 0;
   1773 		}
   1774 		data = ixfr_data_prev(zone->ixfr, data, &prevcount);
   1775 	}
   1776 }
   1777 
   1778 void ixfr_delete_superfluous_files(struct zone* zone, const char* zfile,
   1779 	int dest_num_files)
   1780 {
   1781 	int i = dest_num_files + 1;
   1782 	if(!ixfr_file_exists(zfile, i))
   1783 		return;
   1784 	while(ixfr_unlink_it(zone->opts->name, zfile, i, 1)) {
   1785 		i++;
   1786 	}
   1787 }
   1788 
   1789 int ixfr_rename_it(const char* zname, const char* zfile, int oldnum,
   1790 	int oldtemp, int newnum, int newtemp)
   1791 {
   1792 	char ixfrfile_old[1024+24];
   1793 	char ixfrfile_new[1024+24];
   1794 	make_ixfr_name_temp(ixfrfile_old, sizeof(ixfrfile_old), zfile, oldnum,
   1795 		oldtemp);
   1796 	make_ixfr_name_temp(ixfrfile_new, sizeof(ixfrfile_new), zfile, newnum,
   1797 		newtemp);
   1798 	VERBOSITY(3, (LOG_INFO, "rename zone %s IXFR data file %s to %s",
   1799 		zname, ixfrfile_old, ixfrfile_new));
   1800 	if(rename(ixfrfile_old, ixfrfile_new) < 0) {
   1801 		log_msg(LOG_ERR, "error to rename file %s: %s", ixfrfile_old,
   1802 			strerror(errno));
   1803 		return 0;
   1804 	}
   1805 	return 1;
   1806 }
   1807 
   1808 /* delete if we have too many items in memory */
   1809 static void ixfr_delete_memory_items(struct zone* zone, int dest_num_files)
   1810 {
   1811 	if(!zone->ixfr || !zone->ixfr->data)
   1812 		return;
   1813 	if(dest_num_files == (int)zone->ixfr->data->count)
   1814 		return;
   1815 	if(dest_num_files > (int)zone->ixfr->data->count) {
   1816 		/* impossible, dest_num_files should be smaller */
   1817 		return;
   1818 	}
   1819 
   1820 	/* delete oldest ixfr, until we have dest_num_files entries */
   1821 	while(dest_num_files < (int)zone->ixfr->data->count) {
   1822 		zone_ixfr_remove_oldest(zone->ixfr);
   1823 	}
   1824 }
   1825 
   1826 /* rename the ixfr files that need to change name */
   1827 static int ixfr_rename_files(struct zone* zone, const char* zfile,
   1828 	int dest_num_files)
   1829 {
   1830 	struct ixfr_data* data, *startspot = NULL;
   1831 	size_t prevcount = 0;
   1832 	int destnum;
   1833 	if(!zone->ixfr || !zone->ixfr->data)
   1834 		return 1;
   1835 
   1836 	/* the oldest file is at the largest number */
   1837 	data = ixfr_data_first(zone->ixfr);
   1838 	destnum = dest_num_files;
   1839 	if(!data)
   1840 		return 1; /* nothing to do */
   1841 	if(data->file_num == destnum)
   1842 		return 1; /* nothing to do for rename */
   1843 
   1844 	/* rename the files to temporary files, because otherwise the
   1845 	 * items would overwrite each other when the list touches itself.
   1846 	 * On fail, the temporary files are removed and we end up with
   1847 	 * the newly written data plus the remaining files, in order.
   1848 	 * Thus, start the temporary rename at the oldest, then rename
   1849 	 * to the final names starting from the newest. */
   1850 	while(data && data->file_num != 0) {
   1851 		/* if existing file at temporary name, delete that */
   1852 		if(ixfr_file_exists_temp(zfile, data->file_num)) {
   1853 			(void)ixfr_unlink_it_temp(zone->opts->name, zfile,
   1854 				data->file_num, 0);
   1855 		}
   1856 
   1857 		/* rename to temporary name */
   1858 		if(!ixfr_rename_it(zone->opts->name, zfile, data->file_num, 0,
   1859 			data->file_num, 1)) {
   1860 			/* failure, we cannot store files */
   1861 			/* delete the renamed files */
   1862 			ixfr_delete_rest_files(zone, data, zfile, 1);
   1863 			return 0;
   1864 		}
   1865 
   1866 		/* the next cycle should start at the newest file that
   1867 		 * has been renamed to a temporary name */
   1868 		startspot = data;
   1869 		data = ixfr_data_next(zone->ixfr, data);
   1870 		destnum--;
   1871 	}
   1872 
   1873 	/* rename the files to their final name position */
   1874 	data = startspot;
   1875 	while(data && data->file_num != 0) {
   1876 		destnum++;
   1877 
   1878 		/* if there is an existing file, delete it */
   1879 		if(ixfr_file_exists(zfile, destnum)) {
   1880 			(void)ixfr_unlink_it(zone->opts->name, zfile,
   1881 				destnum, 0);
   1882 		}
   1883 
   1884 		if(!ixfr_rename_it(zone->opts->name, zfile, data->file_num, 1, destnum, 0)) {
   1885 			/* failure, we cannot store files */
   1886 			ixfr_delete_rest_files(zone, data, zfile, 1);
   1887 			/* delete the previously renamed files, so in
   1888 			 * memory stays as is, on disk we have the current
   1889 			 * item (and newer transfers) okay. */
   1890 			return 0;
   1891 		}
   1892 		data->file_num = destnum;
   1893 
   1894 		data = ixfr_data_prev(zone->ixfr, data, &prevcount);
   1895 	}
   1896 	return 1;
   1897 }
   1898 
   1899 /* write the ixfr data file header */
   1900 static int ixfr_write_file_header(struct zone* zone, struct ixfr_data* data,
   1901 	FILE* out)
   1902 {
   1903 	if(!fprintf(out, "; IXFR data file\n"))
   1904 		return 0;
   1905 	if(!fprintf(out, "; zone %s\n", zone->opts->name))
   1906 		return 0;
   1907 	if(!fprintf(out, "; from_serial %u\n", (unsigned)data->oldserial))
   1908 		return 0;
   1909 	if(!fprintf(out, "; to_serial %u\n", (unsigned)data->newserial))
   1910 		return 0;
   1911 	if(!fprintf(out, "; data_size %u\n", (unsigned)ixfr_data_size(data)))
   1912 		return 0;
   1913 	if(data->log_str) {
   1914 		if(!fprintf(out, "; %s\n", data->log_str))
   1915 			return 0;
   1916 	}
   1917 	return 1;
   1918 }
   1919 
   1920 /* print rdata on one line */
   1921 static int
   1922 oneline_print_rdata(buffer_type *output, rrtype_descriptor_type *descriptor,
   1923 	rr_type* record)
   1924 {
   1925 	size_t i;
   1926 	size_t saved_position = buffer_position(output);
   1927 
   1928 	for (i = 0; i < record->rdata_count; ++i) {
   1929 		if (i == 0) {
   1930 			buffer_printf(output, "\t");
   1931 		} else {
   1932 			buffer_printf(output, " ");
   1933 		}
   1934 		if (!rdata_atom_to_string(
   1935 			    output,
   1936 			    (rdata_zoneformat_type) descriptor->zoneformat[i],
   1937 			    record->rdatas[i], record))
   1938 		{
   1939 			buffer_set_position(output, saved_position);
   1940 			return 0;
   1941 		}
   1942 	}
   1943 
   1944 	return 1;
   1945 }
   1946 
   1947 /* parse wireformat RR into a struct RR in temp region */
   1948 static int parse_wirerr_into_temp(struct zone* zone, char* fname,
   1949 	struct region* temp, uint8_t* buf, size_t len,
   1950 	const dname_type** dname, struct rr* rr)
   1951 {
   1952 	size_t bufpos = 0;
   1953 	uint16_t rdlen;
   1954 	ssize_t rdata_num;
   1955 	buffer_type packet;
   1956 	domain_table_type* owners;
   1957 	owners = domain_table_create(temp);
   1958 	memset(rr, 0, sizeof(*rr));
   1959 	*dname = dname_make(temp, buf, 1);
   1960 	if(!*dname) {
   1961 		log_msg(LOG_ERR, "failed to write zone %s IXFR data %s: failed to parse dname", zone->opts->name, fname);
   1962 		return 0;
   1963 	}
   1964 	bufpos = (*dname)->name_size;
   1965 	if(bufpos+10 > len) {
   1966 		log_msg(LOG_ERR, "failed to write zone %s IXFR data %s: buffer too short", zone->opts->name, fname);
   1967 		return 0;
   1968 	}
   1969 	rr->type = read_uint16(buf+bufpos);
   1970 	bufpos += 2;
   1971 	rr->klass = read_uint16(buf+bufpos);
   1972 	bufpos += 2;
   1973 	rr->ttl = read_uint32(buf+bufpos);
   1974 	bufpos += 4;
   1975 	rdlen = read_uint16(buf+bufpos);
   1976 	bufpos += 2;
   1977 	if(bufpos + rdlen > len) {
   1978 		log_msg(LOG_ERR, "failed to write zone %s IXFR data %s: buffer too short for rdatalen", zone->opts->name, fname);
   1979 		return 0;
   1980 	}
   1981 	buffer_create_from(&packet, buf+bufpos, rdlen);
   1982 	rdata_num = rdata_wireformat_to_rdata_atoms(
   1983 		temp, owners, rr->type, rdlen, &packet, &rr->rdatas);
   1984 	if(rdata_num == -1) {
   1985 		log_msg(LOG_ERR, "failed to write zone %s IXFR data %s: cannot parse rdata", zone->opts->name, fname);
   1986 		return 0;
   1987 	}
   1988 	rr->rdata_count = rdata_num;
   1989 	return 1;
   1990 }
   1991 
   1992 /* print RR on one line in output buffer. caller must zeroterminate, if
   1993  * that is needed. */
   1994 static int print_rr_oneline(struct buffer* rr_buffer, const dname_type* dname,
   1995 	struct rr* rr)
   1996 {
   1997 	rrtype_descriptor_type *descriptor;
   1998 	descriptor = rrtype_descriptor_by_type(rr->type);
   1999 	buffer_printf(rr_buffer, "%s", dname_to_string(dname, NULL));
   2000 	buffer_printf(rr_buffer, "\t%lu\t%s\t%s", (unsigned long)rr->ttl,
   2001 		rrclass_to_string(rr->klass), rrtype_to_string(rr->type));
   2002 	if(!oneline_print_rdata(rr_buffer, descriptor, rr)) {
   2003 		if(!rdata_atoms_to_unknown_string(rr_buffer,
   2004 			descriptor, rr->rdata_count, rr->rdatas)) {
   2005 			return 0;
   2006 		}
   2007 	}
   2008 	return 1;
   2009 }
   2010 
   2011 /* write one RR to file, on one line */
   2012 static int ixfr_write_rr(struct zone* zone, FILE* out, char* fname,
   2013 	uint8_t* buf, size_t len, struct region* temp, buffer_type* rr_buffer)
   2014 {
   2015 	const dname_type* dname;
   2016 	struct rr rr;
   2017 
   2018 	if(!parse_wirerr_into_temp(zone, fname, temp, buf, len, &dname, &rr)) {
   2019 		region_free_all(temp);
   2020 		return 0;
   2021 	}
   2022 
   2023 	buffer_clear(rr_buffer);
   2024 	if(!print_rr_oneline(rr_buffer, dname, &rr)) {
   2025 		log_msg(LOG_ERR, "failed to write zone %s IXFR data %s: cannot spool RR string into buffer", zone->opts->name, fname);
   2026 		region_free_all(temp);
   2027 		return 0;
   2028 	}
   2029 	buffer_write_u8(rr_buffer, 0);
   2030 	buffer_flip(rr_buffer);
   2031 
   2032 	if(!fprintf(out, "%s\n", buffer_begin(rr_buffer))) {
   2033 		log_msg(LOG_ERR, "failed to write zone %s IXFR data %s: cannot print RR string to file: %s", zone->opts->name, fname, strerror(errno));
   2034 		region_free_all(temp);
   2035 		return 0;
   2036 	}
   2037 	region_free_all(temp);
   2038 	return 1;
   2039 }
   2040 
   2041 /* write ixfr RRs to file */
   2042 static int ixfr_write_rrs(struct zone* zone, FILE* out, char* fname,
   2043 	uint8_t* buf, size_t len, struct region* temp, buffer_type* rr_buffer)
   2044 {
   2045 	size_t current = 0;
   2046 	if(!buf || len == 0)
   2047 		return 1;
   2048 	while(current < len) {
   2049 		size_t rrlen = count_rr_length(buf, len, current);
   2050 		if(rrlen == 0)
   2051 			return 0;
   2052 		if(current + rrlen > len)
   2053 			return 0;
   2054 		if(!ixfr_write_rr(zone, out, fname, buf+current, rrlen,
   2055 			temp, rr_buffer))
   2056 			return 0;
   2057 		current += rrlen;
   2058 	}
   2059 	return 1;
   2060 }
   2061 
   2062 /* write the ixfr data file data */
   2063 static int ixfr_write_file_data(struct zone* zone, struct ixfr_data* data,
   2064 	FILE* out, char* fname)
   2065 {
   2066 	struct region* temp, *rrtemp;
   2067 	buffer_type* rr_buffer;
   2068 	temp = region_create(xalloc, free);
   2069 	rrtemp = region_create(xalloc, free);
   2070 	rr_buffer = buffer_create(rrtemp, MAX_RDLENGTH);
   2071 
   2072 	if(!ixfr_write_rrs(zone, out, fname, data->newsoa, data->newsoa_len,
   2073 		temp, rr_buffer)) {
   2074 		region_destroy(temp);
   2075 		region_destroy(rrtemp);
   2076 		return 0;
   2077 	}
   2078 	if(!ixfr_write_rrs(zone, out, fname, data->oldsoa, data->oldsoa_len,
   2079 		temp, rr_buffer)) {
   2080 		region_destroy(temp);
   2081 		region_destroy(rrtemp);
   2082 		return 0;
   2083 	}
   2084 	if(!ixfr_write_rrs(zone, out, fname, data->del, data->del_len,
   2085 		temp, rr_buffer)) {
   2086 		region_destroy(temp);
   2087 		region_destroy(rrtemp);
   2088 		return 0;
   2089 	}
   2090 	if(!ixfr_write_rrs(zone, out, fname, data->add, data->add_len,
   2091 		temp, rr_buffer)) {
   2092 		region_destroy(temp);
   2093 		region_destroy(rrtemp);
   2094 		return 0;
   2095 	}
   2096 	region_destroy(temp);
   2097 	region_destroy(rrtemp);
   2098 	return 1;
   2099 }
   2100 
   2101 int ixfr_write_file(struct zone* zone, struct ixfr_data* data,
   2102 	const char* zfile, int file_num)
   2103 {
   2104 	char ixfrfile[1024+24];
   2105 	FILE* out;
   2106 	make_ixfr_name(ixfrfile, sizeof(ixfrfile), zfile, file_num);
   2107 	VERBOSITY(1, (LOG_INFO, "writing zone %s IXFR data to file %s",
   2108 		zone->opts->name, ixfrfile));
   2109 	out = fopen(ixfrfile, "w");
   2110 	if(!out) {
   2111 		log_msg(LOG_ERR, "could not open for writing zone %s IXFR file %s: %s",
   2112 			zone->opts->name, ixfrfile, strerror(errno));
   2113 		return 0;
   2114 	}
   2115 
   2116 	if(!ixfr_write_file_header(zone, data, out)) {
   2117 		log_msg(LOG_ERR, "could not write file header for zone %s IXFR file %s: %s",
   2118 			zone->opts->name, ixfrfile, strerror(errno));
   2119 		fclose(out);
   2120 		return 0;
   2121 	}
   2122 	if(!ixfr_write_file_data(zone, data, out, ixfrfile)) {
   2123 		fclose(out);
   2124 		return 0;
   2125 	}
   2126 
   2127 	fclose(out);
   2128 	data->file_num = file_num;
   2129 	return 1;
   2130 }
   2131 
   2132 /* write the ixfr files that need to be stored on disk */
   2133 static void ixfr_write_files(struct zone* zone, const char* zfile)
   2134 {
   2135 	size_t prevcount = 0;
   2136 	int num;
   2137 	struct ixfr_data* data;
   2138 	if(!zone->ixfr || !zone->ixfr->data)
   2139 		return; /* nothing to write */
   2140 
   2141 	/* write unwritten files to disk */
   2142 	data = ixfr_data_last(zone->ixfr);
   2143 	num=1;
   2144 	while(data && data->file_num == 0) {
   2145 		if(!ixfr_write_file(zone, data, zfile, num)) {
   2146 			/* There could be more files that are sitting on the
   2147 			 * disk, remove them, they are not used without
   2148 			 * this ixfr file.
   2149 			 *
   2150 			 * Give this element a file num, so it can be
   2151 			 * deleted, it failed to write. It may be partial,
   2152 			 * and we do not want to read that back in.
   2153 			 * We are left with the newer transfers, that form
   2154 			 * a correct list of transfers, that are wholly
   2155 			 * written. */
   2156 			data->file_num = num;
   2157 			ixfr_delete_rest_files(zone, data, zfile, 0);
   2158 			return;
   2159 		}
   2160 		num++;
   2161 		data = ixfr_data_prev(zone->ixfr, data, &prevcount);
   2162 	}
   2163 }
   2164 
   2165 void ixfr_write_to_file(struct zone* zone, const char* zfile)
   2166 {
   2167 	int dest_num_files = 0;
   2168 	/* we just wrote the zonefile zfile, and it is time to write
   2169 	 * the IXFR contents to the disk too. */
   2170 	/* find out what the target number of files is that we want on
   2171 	 * the disk */
   2172 	dest_num_files = ixfr_target_number_files(zone);
   2173 
   2174 	/* delete if we have more than we need */
   2175 	ixfr_delete_superfluous_files(zone, zfile, dest_num_files);
   2176 
   2177 	/* delete if we have too much in memory */
   2178 	ixfr_delete_memory_items(zone, dest_num_files);
   2179 
   2180 	/* rename the transfers that we have that already have a file */
   2181 	if(!ixfr_rename_files(zone, zfile, dest_num_files))
   2182 		return;
   2183 
   2184 	/* write the transfers that are not written yet */
   2185 	ixfr_write_files(zone, zfile);
   2186 }
   2187 
   2188 /* skip whitespace */
   2189 static char* skipwhite(char* str)
   2190 {
   2191 	while(isspace((unsigned char)*str))
   2192 		str++;
   2193 	return str;
   2194 }
   2195 
   2196 /* read one RR from file */
   2197 static int ixfr_data_readrr(struct zone* zone, FILE* in, const char* ixfrfile,
   2198 	struct region* tempregion, struct domain_table* temptable,
   2199 	struct zone* tempzone, struct rr** rr)
   2200 {
   2201 	char line[65536];
   2202 	char* str;
   2203 	struct domain* domain_parsed = NULL;
   2204 	int num_rrs = 0;
   2205 	line[sizeof(line)-1]=0;
   2206 	while(!feof(in)) {
   2207 		if(!fgets(line, sizeof(line), in)) {
   2208 			if(errno == 0) {
   2209 				log_msg(LOG_ERR, "zone %s IXFR data %s: "
   2210 					"unexpected end of file", zone->opts->name, ixfrfile);
   2211 				return 0;
   2212 			}
   2213 			log_msg(LOG_ERR, "zone %s IXFR data %s: "
   2214 				"cannot read: %s", zone->opts->name, ixfrfile,
   2215 				strerror(errno));
   2216 			return 0;
   2217 		}
   2218 		str = skipwhite(line);
   2219 		if(str[0] == 0) {
   2220 			/* empty line */
   2221 			continue;
   2222 		}
   2223 		if(str[0] == ';') {
   2224 			/* comment line */
   2225 			continue;
   2226 		}
   2227 		if(zonec_parse_string(tempregion, temptable, tempzone,
   2228 			line, &domain_parsed, &num_rrs)) {
   2229 			log_msg(LOG_ERR, "zone %s IXFR data %s: parse error",
   2230 				zone->opts->name, ixfrfile);
   2231 			return 0;
   2232 		}
   2233 		if(num_rrs != 1) {
   2234 			log_msg(LOG_ERR, "zone %s IXFR data %s: parse error",
   2235 				zone->opts->name, ixfrfile);
   2236 			return 0;
   2237 		}
   2238 		*rr = &domain_parsed->rrsets->rrs[0];
   2239 		return 1;
   2240 	}
   2241 	log_msg(LOG_ERR, "zone %s IXFR data %s: file too short, no newsoa",
   2242 		zone->opts->name, ixfrfile);
   2243 	return 0;
   2244 }
   2245 
   2246 /* delete from domain table */
   2247 static void domain_table_delete(struct domain_table* table,
   2248 	struct domain* domain)
   2249 {
   2250 #ifdef USE_RADIX_TREE
   2251 	radix_delete(table->nametree, domain->rnode);
   2252 #else
   2253 	rbtree_delete(table->names_to_domains, domain->node.key);
   2254 #endif
   2255 }
   2256 
   2257 /* can we delete temp domain */
   2258 static int can_del_temp_domain(struct domain* domain)
   2259 {
   2260 	struct domain* n;
   2261 	/* we want to keep the zone apex */
   2262 	if(domain->is_apex)
   2263 		return 0;
   2264 	if(domain->rrsets)
   2265 		return 0;
   2266 	if(domain->usage)
   2267 		return 0;
   2268 	/* check if there are domains under it */
   2269 	n = domain_next(domain);
   2270 	if(n && domain_is_subdomain(n, domain))
   2271 		return 0;
   2272 	return 1;
   2273 }
   2274 
   2275 /* delete temporary domain */
   2276 static void ixfr_temp_deldomain(struct domain_table* temptable,
   2277 	struct domain* domain)
   2278 {
   2279 	struct domain* p;
   2280 	if(!can_del_temp_domain(domain))
   2281 		return;
   2282 	p = domain->parent;
   2283 	/* see if this domain is someones wildcard-child-closest-match,
   2284 	 * which can only be the parent, and then it should use the
   2285 	 * one-smaller than this domain as closest-match. */
   2286 	if(domain->parent &&
   2287 		domain->parent->wildcard_child_closest_match == domain)
   2288 		domain->parent->wildcard_child_closest_match =
   2289 			domain_previous_existing_child(domain);
   2290 	domain_table_delete(temptable, domain);
   2291 	while(p) {
   2292 		struct domain* up = p->parent;
   2293 		if(!can_del_temp_domain(p))
   2294 			break;
   2295 		if(p->parent && p->parent->wildcard_child_closest_match == p)
   2296 			p->parent->wildcard_child_closest_match =
   2297 				domain_previous_existing_child(p);
   2298 		domain_table_delete(temptable, p);
   2299 		p = up;
   2300 	}
   2301 }
   2302 
   2303 /* clear out the just read RR from the temp table */
   2304 static void clear_temp_table_of_rr(struct domain_table* temptable,
   2305 	struct zone* tempzone, struct rr* rr)
   2306 {
   2307 #if 0 /* clear out by removing everything, alternate for the cleanout code */
   2308 	/* clear domains from the tempzone,
   2309 	 * the only domain left is the zone apex and its parents */
   2310 	domain_type* domain;
   2311 #ifdef USE_RADIX_TREE
   2312 	struct radnode* first = radix_first(temptable->nametree);
   2313 	domain = first?(domain_type*)first->elem:NULL;
   2314 #else
   2315 	domain = (domain_type*)rbtree_first(temptable->names_to_domains);
   2316 #endif
   2317 	while(domain != (domain_type*)RBTREE_NULL && domain) {
   2318 		domain_type* next = domain_next(domain);
   2319 		if(domain != tempzone->apex &&
   2320 			!domain_is_subdomain(tempzone->apex, domain)) {
   2321 			domain_table_delete(temptable, domain);
   2322 		} else {
   2323 			if(!domain->parent /* is the root */ ||
   2324 				domain == tempzone->apex)
   2325 				domain->usage = 1;
   2326 			else	domain->usage = 0;
   2327 		}
   2328 		domain = next;
   2329 	}
   2330 
   2331 	if(rr->owner == tempzone->apex) {
   2332 		tempzone->apex->rrsets = NULL;
   2333 		tempzone->soa_rrset = NULL;
   2334 		tempzone->soa_nx_rrset = NULL;
   2335 		tempzone->ns_rrset = NULL;
   2336 	}
   2337 	return;
   2338 #endif
   2339 
   2340 	/* clear domains in the rdata */
   2341 	unsigned i;
   2342 	for(i=0; i<rr->rdata_count; i++) {
   2343 		if(rdata_atom_is_domain(rr->type, i)) {
   2344 			/* clear out that dname */
   2345 			struct domain* domain =
   2346 				rdata_atom_domain(rr->rdatas[i]);
   2347 			domain->usage --;
   2348 			if(domain != tempzone->apex && domain->usage == 0)
   2349 				ixfr_temp_deldomain(temptable, domain);
   2350 		}
   2351 	}
   2352 
   2353 	/* clear domain_parsed */
   2354 	if(rr->owner == tempzone->apex) {
   2355 		tempzone->apex->rrsets = NULL;
   2356 		tempzone->soa_rrset = NULL;
   2357 		tempzone->soa_nx_rrset = NULL;
   2358 		tempzone->ns_rrset = NULL;
   2359 	} else {
   2360 		rr->owner->rrsets = NULL;
   2361 		if(rr->owner->usage == 0) {
   2362 			ixfr_temp_deldomain(temptable, rr->owner);
   2363 		}
   2364 	}
   2365 }
   2366 
   2367 /* read ixfr data new SOA */
   2368 static int ixfr_data_readnewsoa(struct ixfr_data* data, struct zone* zone,
   2369 	FILE* in, const char* ixfrfile, struct region* tempregion,
   2370 	struct domain_table* temptable, struct zone* tempzone,
   2371 	uint32_t dest_serial)
   2372 {
   2373 	struct rr* rr;
   2374 	size_t capacity = 0;
   2375 	if(!ixfr_data_readrr(zone, in, ixfrfile, tempregion, temptable,
   2376 		tempzone, &rr))
   2377 		return 0;
   2378 	if(rr->type != TYPE_SOA) {
   2379 		log_msg(LOG_ERR, "zone %s ixfr data %s: IXFR data does not start with SOA",
   2380 			zone->opts->name, ixfrfile);
   2381 		return 0;
   2382 	}
   2383 	if(rr->klass != CLASS_IN) {
   2384 		log_msg(LOG_ERR, "zone %s ixfr data %s: IXFR data is not class IN",
   2385 			zone->opts->name, ixfrfile);
   2386 		return 0;
   2387 	}
   2388 	if(!zone->apex) {
   2389 		log_msg(LOG_ERR, "zone %s ixfr data %s: zone has no apex, no zone data",
   2390 			zone->opts->name, ixfrfile);
   2391 		return 0;
   2392 	}
   2393 	if(dname_compare(domain_dname(zone->apex), domain_dname(rr->owner)) != 0) {
   2394 		log_msg(LOG_ERR, "zone %s ixfr data %s: IXFR data wrong SOA for zone %s",
   2395 			zone->opts->name, ixfrfile, domain_to_string(rr->owner));
   2396 		return 0;
   2397 	}
   2398 	data->newserial = soa_rr_get_serial(rr);
   2399 	if(data->newserial != dest_serial) {
   2400 		log_msg(LOG_ERR, "zone %s ixfr data %s: IXFR data contains the wrong version, serial %u but want destination serial %u",
   2401 			zone->opts->name, ixfrfile, data->newserial,
   2402 			dest_serial);
   2403 		return 0;
   2404 	}
   2405 	if(!ixfr_putrr(domain_dname(rr->owner), rr->type, rr->klass, rr->ttl, rr->rdatas, rr->rdata_count, &data->newsoa, &data->newsoa_len, &capacity)) {
   2406 		log_msg(LOG_ERR, "zone %s ixfr data %s: cannot allocate space",
   2407 			zone->opts->name, ixfrfile);
   2408 		return 0;
   2409 	}
   2410 	clear_temp_table_of_rr(temptable, tempzone, rr);
   2411 	region_free_all(tempregion);
   2412 	ixfr_trim_capacity(&data->newsoa, &data->newsoa_len, &capacity);
   2413 	return 1;
   2414 }
   2415 
   2416 /* read ixfr data old SOA */
   2417 static int ixfr_data_readoldsoa(struct ixfr_data* data, struct zone* zone,
   2418 	FILE* in, const char* ixfrfile, struct region* tempregion,
   2419 	struct domain_table* temptable, struct zone* tempzone,
   2420 	uint32_t* dest_serial)
   2421 {
   2422 	struct rr* rr;
   2423 	size_t capacity = 0;
   2424 	if(!ixfr_data_readrr(zone, in, ixfrfile, tempregion, temptable,
   2425 		tempzone, &rr))
   2426 		return 0;
   2427 	if(rr->type != TYPE_SOA) {
   2428 		log_msg(LOG_ERR, "zone %s ixfr data %s: IXFR data 2nd RR is not SOA",
   2429 			zone->opts->name, ixfrfile);
   2430 		return 0;
   2431 	}
   2432 	if(rr->klass != CLASS_IN) {
   2433 		log_msg(LOG_ERR, "zone %s ixfr data %s: IXFR data 2ndSOA is not class IN",
   2434 			zone->opts->name, ixfrfile);
   2435 		return 0;
   2436 	}
   2437 	if(!zone->apex) {
   2438 		log_msg(LOG_ERR, "zone %s ixfr data %s: zone has no apex, no zone data",
   2439 			zone->opts->name, ixfrfile);
   2440 		return 0;
   2441 	}
   2442 	if(dname_compare(domain_dname(zone->apex), domain_dname(rr->owner)) != 0) {
   2443 		log_msg(LOG_ERR, "zone %s ixfr data %s: IXFR data wrong 2nd SOA for zone %s",
   2444 			zone->opts->name, ixfrfile, domain_to_string(rr->owner));
   2445 		return 0;
   2446 	}
   2447 	data->oldserial = soa_rr_get_serial(rr);
   2448 	if(!ixfr_putrr(domain_dname(rr->owner), rr->type, rr->klass, rr->ttl, rr->rdatas, rr->rdata_count, &data->oldsoa, &data->oldsoa_len, &capacity)) {
   2449 		log_msg(LOG_ERR, "zone %s ixfr data %s: cannot allocate space",
   2450 			zone->opts->name, ixfrfile);
   2451 		return 0;
   2452 	}
   2453 	clear_temp_table_of_rr(temptable, tempzone, rr);
   2454 	region_free_all(tempregion);
   2455 	ixfr_trim_capacity(&data->oldsoa, &data->oldsoa_len, &capacity);
   2456 	*dest_serial = data->oldserial;
   2457 	return 1;
   2458 }
   2459 
   2460 /* read ixfr data del section */
   2461 static int ixfr_data_readdel(struct ixfr_data* data, struct zone* zone,
   2462 	FILE* in, const char* ixfrfile, struct region* tempregion,
   2463 	struct domain_table* temptable, struct zone* tempzone)
   2464 {
   2465 	struct rr* rr;
   2466 	size_t capacity = 0;
   2467 	while(1) {
   2468 		if(!ixfr_data_readrr(zone, in, ixfrfile, tempregion, temptable,
   2469 			tempzone, &rr))
   2470 			return 0;
   2471 		if(!ixfr_putrr(domain_dname(rr->owner), rr->type, rr->klass, rr->ttl, rr->rdatas, rr->rdata_count, &data->del, &data->del_len, &capacity)) {
   2472 			log_msg(LOG_ERR, "zone %s ixfr data %s: cannot allocate space",
   2473 				zone->opts->name, ixfrfile);
   2474 			return 0;
   2475 		}
   2476 		/* check SOA and also serial, because there could be other
   2477 		 * add and del sections from older versions collated, we can
   2478 		 * see this del section end when it has the serial */
   2479 		if(rr->type == TYPE_SOA &&
   2480 			soa_rr_get_serial(rr) == data->newserial) {
   2481 			/* end of del section. */
   2482 			clear_temp_table_of_rr(temptable, tempzone, rr);
   2483 			region_free_all(tempregion);
   2484 			break;
   2485 		}
   2486 		clear_temp_table_of_rr(temptable, tempzone, rr);
   2487 		region_free_all(tempregion);
   2488 	}
   2489 	ixfr_trim_capacity(&data->del, &data->del_len, &capacity);
   2490 	return 1;
   2491 }
   2492 
   2493 /* read ixfr data add section */
   2494 static int ixfr_data_readadd(struct ixfr_data* data, struct zone* zone,
   2495 	FILE* in, const char* ixfrfile, struct region* tempregion,
   2496 	struct domain_table* temptable, struct zone* tempzone)
   2497 {
   2498 	struct rr* rr;
   2499 	size_t capacity = 0;
   2500 	while(1) {
   2501 		if(!ixfr_data_readrr(zone, in, ixfrfile, tempregion, temptable,
   2502 			tempzone, &rr))
   2503 			return 0;
   2504 		if(!ixfr_putrr(domain_dname(rr->owner), rr->type, rr->klass, rr->ttl, rr->rdatas, rr->rdata_count, &data->add, &data->add_len, &capacity)) {
   2505 			log_msg(LOG_ERR, "zone %s ixfr data %s: cannot allocate space",
   2506 				zone->opts->name, ixfrfile);
   2507 			return 0;
   2508 		}
   2509 		if(rr->type == TYPE_SOA &&
   2510 			soa_rr_get_serial(rr) == data->newserial) {
   2511 			/* end of add section. */
   2512 			clear_temp_table_of_rr(temptable, tempzone, rr);
   2513 			region_free_all(tempregion);
   2514 			break;
   2515 		}
   2516 		clear_temp_table_of_rr(temptable, tempzone, rr);
   2517 		region_free_all(tempregion);
   2518 	}
   2519 	ixfr_trim_capacity(&data->add, &data->add_len, &capacity);
   2520 	return 1;
   2521 }
   2522 
   2523 /* read ixfr data from file */
   2524 static int ixfr_data_read(struct nsd* nsd, struct zone* zone, FILE* in,
   2525 	const char* ixfrfile, uint32_t* dest_serial, int file_num)
   2526 {
   2527 	struct ixfr_data* data = NULL;
   2528 	struct region* tempregion, *stayregion;
   2529 	struct domain_table* temptable;
   2530 	struct zone* tempzone;
   2531 
   2532 	if(zone->ixfr &&
   2533 		zone->ixfr->data->count == zone->opts->pattern->ixfr_number) {
   2534 		VERBOSITY(3, (LOG_INFO, "zone %s skip %s IXFR data because only %d ixfr-number configured",
   2535 			zone->opts->name, ixfrfile, (int)zone->opts->pattern->ixfr_number));
   2536 		return 0;
   2537 	}
   2538 
   2539 	/* the file has header comments, new soa, old soa, delsection,
   2540 	 * addsection. The delsection and addsection end in a SOA of oldver
   2541 	 * and newver respectively. */
   2542 	data = xalloc_zero(sizeof(*data));
   2543 	data->file_num = file_num;
   2544 
   2545 	/* the temp region is cleared after every RR */
   2546 	tempregion = region_create(xalloc, free);
   2547 	/* the stay region holds the temporary data that stays between RRs */
   2548 	stayregion = region_create(xalloc, free);
   2549 	temptable = domain_table_create(stayregion);
   2550 	tempzone = region_alloc_zero(stayregion, sizeof(zone_type));
   2551 	if(!zone->apex) {
   2552 		ixfr_data_free(data);
   2553 		region_destroy(tempregion);
   2554 		region_destroy(stayregion);
   2555 		return 0;
   2556 	}
   2557 	tempzone->apex = domain_table_insert(temptable,
   2558 		domain_dname(zone->apex));
   2559 	temptable->root->usage++;
   2560 	tempzone->apex->usage++;
   2561 	tempzone->opts = zone->opts;
   2562 	/* switch to per RR region for new allocations in temp domain table */
   2563 	temptable->region = tempregion;
   2564 
   2565 	if(!ixfr_data_readnewsoa(data, zone, in, ixfrfile, tempregion,
   2566 		temptable, tempzone, *dest_serial)) {
   2567 		ixfr_data_free(data);
   2568 		region_destroy(tempregion);
   2569 		region_destroy(stayregion);
   2570 		return 0;
   2571 	}
   2572 	if(!ixfr_data_readoldsoa(data, zone, in, ixfrfile, tempregion,
   2573 		temptable, tempzone, dest_serial)) {
   2574 		ixfr_data_free(data);
   2575 		region_destroy(tempregion);
   2576 		region_destroy(stayregion);
   2577 		return 0;
   2578 	}
   2579 	if(!ixfr_data_readdel(data, zone, in, ixfrfile, tempregion, temptable,
   2580 		tempzone)) {
   2581 		ixfr_data_free(data);
   2582 		region_destroy(tempregion);
   2583 		region_destroy(stayregion);
   2584 		return 0;
   2585 	}
   2586 	if(!ixfr_data_readadd(data, zone, in, ixfrfile, tempregion, temptable,
   2587 		tempzone)) {
   2588 		ixfr_data_free(data);
   2589 		region_destroy(tempregion);
   2590 		region_destroy(stayregion);
   2591 		return 0;
   2592 	}
   2593 
   2594 	region_destroy(tempregion);
   2595 	region_destroy(stayregion);
   2596 
   2597 	if(!zone->ixfr)
   2598 		zone->ixfr = zone_ixfr_create(nsd);
   2599 	if(zone->opts->pattern->ixfr_size != 0 &&
   2600 		zone->ixfr->total_size + ixfr_data_size(data) >
   2601 		zone->opts->pattern->ixfr_size) {
   2602 		VERBOSITY(3, (LOG_INFO, "zone %s skip %s IXFR data because only ixfr-size: %u configured, and it is %u size",
   2603 			zone->opts->name, ixfrfile, (unsigned)zone->opts->pattern->ixfr_size, (unsigned)ixfr_data_size(data)));
   2604 		ixfr_data_free(data);
   2605 		return 0;
   2606 	}
   2607 	zone_ixfr_add(zone->ixfr, data, 0);
   2608 	VERBOSITY(3, (LOG_INFO, "zone %s read %s IXFR data of %u bytes",
   2609 		zone->opts->name, ixfrfile, (unsigned)ixfr_data_size(data)));
   2610 	return 1;
   2611 }
   2612 
   2613 /* try to read the next ixfr file. returns false if it fails or if it
   2614  * does not fit in the configured sizes */
   2615 static int ixfr_read_one_more_file(struct nsd* nsd, struct zone* zone,
   2616 	const char* zfile, int num_files, uint32_t *dest_serial)
   2617 {
   2618 	char ixfrfile[1024+24];
   2619 	FILE* in;
   2620 	int file_num = num_files+1;
   2621 	make_ixfr_name(ixfrfile, sizeof(ixfrfile), zfile, file_num);
   2622 	in = fopen(ixfrfile, "r");
   2623 	if(!in) {
   2624 		if(errno == ENOENT) {
   2625 			/* the file does not exist, we reached the end
   2626 			 * of the list of IXFR files */
   2627 			return 0;
   2628 		}
   2629 		log_msg(LOG_ERR, "could not read zone %s IXFR file %s: %s",
   2630 			zone->opts->name, ixfrfile, strerror(errno));
   2631 		return 0;
   2632 	}
   2633 	warn_if_directory("IXFR data", in, ixfrfile);
   2634 	if(!ixfr_data_read(nsd, zone, in, ixfrfile, dest_serial, file_num)) {
   2635 		fclose(in);
   2636 		return 0;
   2637 	}
   2638 	fclose(in);
   2639 	return 1;
   2640 }
   2641 
   2642 void ixfr_read_from_file(struct nsd* nsd, struct zone* zone, const char* zfile)
   2643 {
   2644 	uint32_t serial;
   2645 	int num_files = 0;
   2646 	/* delete the existing data, the zone data in memory has likely
   2647 	 * changed, eg. due to reading a new zonefile. So that needs new
   2648 	 * IXFRs */
   2649 	zone_ixfr_clear(zone->ixfr);
   2650 
   2651 	/* track the serial number that we need to end up with, and check
   2652 	 * that the IXFRs match up and result in the required version */
   2653 	serial = zone_get_current_serial(zone);
   2654 
   2655 	while(ixfr_read_one_more_file(nsd, zone, zfile, num_files, &serial)) {
   2656 		num_files++;
   2657 	}
   2658 	if(num_files > 0) {
   2659 		VERBOSITY(1, (LOG_INFO, "zone %s read %d IXFR transfers with success",
   2660 			zone->opts->name, num_files));
   2661 	}
   2662 }
   2663