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