Home | History | Annotate | Line # | Download | only in dist
xfrd.c revision 1.1.1.9
      1 /*
      2  * xfrd.c - XFR (transfer) Daemon source file. Coordinates SOA updates.
      3  *
      4  * Copyright (c) 2001-2006, NLnet Labs. All rights reserved.
      5  *
      6  * See LICENSE for the license.
      7  *
      8  */
      9 
     10 #include "config.h"
     11 #include <assert.h>
     12 #include <string.h>
     13 #include <unistd.h>
     14 #include <stdlib.h>
     15 #include <errno.h>
     16 #include <sys/types.h>
     17 #include <sys/wait.h>
     18 #include <inttypes.h>
     19 #include "xfrd.h"
     20 #include "xfrd-tcp.h"
     21 #include "xfrd-disk.h"
     22 #include "xfrd-notify.h"
     23 #include "xfrd-catalog-zones.h"
     24 #include "options.h"
     25 #include "util.h"
     26 #include "netio.h"
     27 #include "region-allocator.h"
     28 #include "nsd.h"
     29 #include "packet.h"
     30 #include "rdata.h"
     31 #include "difffile.h"
     32 #include "ipc.h"
     33 #include "remote.h"
     34 #include "rrl.h"
     35 #ifdef USE_DNSTAP
     36 #include "dnstap/dnstap_collector.h"
     37 #endif
     38 #ifdef USE_METRICS
     39 #include "metrics.h"
     40 #endif /* USE_METRICS */
     41 
     42 #ifdef HAVE_SYSTEMD
     43 #include <systemd/sd-daemon.h>
     44 #endif
     45 
     46 #ifdef HAVE_SSL
     47 #include <openssl/ssl.h>
     48 #include <openssl/x509.h>
     49 #include <openssl/evp.h>
     50 #endif
     51 
     52 #define XFRD_UDP_TIMEOUT 10 /* seconds, before a udp request times out */
     53 #define XFRD_NO_IXFR_CACHE 172800 /* 48h before retrying ixfr's after notimpl */
     54 #define XFRD_MAX_ROUNDS 1 /* max number of rounds along the masters */
     55 #define XFRD_TSIG_MAX_UNSIGNED 103 /* max number of packets without tsig in a tcp stream. */
     56 			/* rfc recommends 100, +3 for offbyone errors/interoperability. */
     57 #define XFRD_CHILD_REAP_TIMEOUT 60 /* seconds to wakeup and reap lost children */
     58 		/* these are reload processes that SIGCHILDed but the signal
     59 		 * was lost, and need waitpid to remove their process entry. */
     60 
     61 /* the daemon state */
     62 xfrd_state_type* xfrd = 0;
     63 
     64 /* main xfrd loop */
     65 static void xfrd_main(void);
     66 /* shut down xfrd, close sockets. */
     67 static void xfrd_shutdown(void);
     68 /* delete pending task xfr files in tmp */
     69 static void xfrd_clean_pending_tasks(struct nsd* nsd, udb_base* u);
     70 /* create zone rbtree at start */
     71 static void xfrd_init_zones(void);
     72 /* initial handshake with SOAINFO from main and send expire to main */
     73 static void xfrd_receive_soa(int socket, int shortsoa);
     74 
     75 /* handle incoming notification message. soa can be NULL. true if transfer needed. */
     76 static int xfrd_handle_incoming_notify(xfrd_zone_type* zone,
     77 	xfrd_soa_type* soa);
     78 
     79 /* call with buffer just after the soa dname. returns 0 on error. */
     80 static int xfrd_parse_soa_info(buffer_type* packet, xfrd_soa_type* soa);
     81 /* set the zone state to a new state (takes care of expiry messages) */
     82 static void xfrd_set_zone_state(xfrd_zone_type* zone,
     83 	enum xfrd_zone_state new_zone_state);
     84 /* set timer for retry amount (depends on zone_state) */
     85 static void xfrd_set_timer_retry(xfrd_zone_type* zone);
     86 /* set timer for refresh timeout (depends on zone_state) */
     87 static void xfrd_set_timer_refresh(xfrd_zone_type* zone);
     88 
     89 /* set reload timeout */
     90 static void xfrd_set_reload_timeout(void);
     91 /* handle reload timeout */
     92 static void xfrd_handle_reload(int fd, short event, void* arg);
     93 /* handle child timeout */
     94 static void xfrd_handle_child_timer(int fd, short event, void* arg);
     95 
     96 /* send ixfr request, returns fd of connection to read on */
     97 static int xfrd_send_ixfr_request_udp(xfrd_zone_type* zone);
     98 /* obtain udp socket slot */
     99 static void xfrd_udp_obtain(xfrd_zone_type* zone);
    100 
    101 /* read data via udp */
    102 static void xfrd_udp_read(xfrd_zone_type* zone);
    103 
    104 /* find master by notify number */
    105 static int find_same_master_notify(xfrd_zone_type* zone, int acl_num_nfy);
    106 
    107 /* set the write timer to activate */
    108 static void xfrd_write_timer_set(void);
    109 
    110 static void xfrd_free_zone_xfr(xfrd_zone_type* zone, xfrd_xfr_type* xfr);
    111 
    112 static void
    113 xfrd_signal_callback(int sig, short event, void* ATTR_UNUSED(arg))
    114 {
    115 	if(!(event & EV_SIGNAL))
    116 		return;
    117 	sig_handler(sig);
    118 }
    119 
    120 static struct event* xfrd_sig_evs[10];
    121 static int xfrd_sig_num = 0;
    122 
    123 static void
    124 xfrd_sigsetup(int sig)
    125 {
    126 	struct event *ev = xalloc_zero(sizeof(*ev));
    127 	assert(xfrd_sig_num <= (int)(sizeof(xfrd_sig_evs)/sizeof(ev)));
    128 	xfrd_sig_evs[xfrd_sig_num++] = ev;
    129 	signal_set(ev, sig, xfrd_signal_callback, NULL);
    130 	if(event_base_set(xfrd->event_base, ev) != 0) {
    131 		log_msg(LOG_ERR, "xfrd sig handler: event_base_set failed");
    132 	}
    133 	if(signal_add(ev, NULL) != 0) {
    134 		log_msg(LOG_ERR, "xfrd sig handler: signal_add failed");
    135 	}
    136 }
    137 
    138 void
    139 xfrd_init(int socket, struct nsd* nsd, int shortsoa, int reload_active,
    140 	pid_t nsd_pid)
    141 {
    142 	region_type* region;
    143 	size_t i;
    144 
    145 	assert(xfrd == 0);
    146 	/* to setup signalhandling */
    147 	nsd->server_kind = NSD_SERVER_MAIN;
    148 
    149 	region = region_create_custom(xalloc, free, DEFAULT_CHUNK_SIZE,
    150 		DEFAULT_LARGE_OBJECT_SIZE, DEFAULT_INITIAL_CLEANUP_SIZE, 1);
    151 	xfrd = (xfrd_state_type*)region_alloc(region, sizeof(xfrd_state_type));
    152 	memset(xfrd, 0, sizeof(xfrd_state_type));
    153 	xfrd->region = region;
    154 	xfrd->xfrd_start_time = time(0);
    155 	xfrd->event_base = nsd_child_event_base();
    156 	if(!xfrd->event_base) {
    157 		log_msg(LOG_ERR, "xfrd: cannot create event base");
    158 		exit(1);
    159 	}
    160 	xfrd->nsd = nsd;
    161 	xfrd->packet = buffer_create(xfrd->region, QIOBUFSZ);
    162 	xfrd->udp_waiting_first = NULL;
    163 	xfrd->udp_waiting_last = NULL;
    164 	xfrd->udp_use_num = 0;
    165 	xfrd->got_time = 0;
    166 	xfrd->xfrfilenumber = 0;
    167 #ifdef USE_ZONE_STATS
    168 	xfrd->zonestat_safe = nsd->zonestatdesired;
    169 #endif
    170 	xfrd->activated_first = NULL;
    171 	xfrd->last_task = region_alloc(xfrd->region, sizeof(*xfrd->last_task));
    172 	udb_ptr_init(xfrd->last_task, xfrd->nsd->task[xfrd->nsd->mytask]);
    173 	assert(shortsoa || udb_base_get_userdata(xfrd->nsd->task[xfrd->nsd->mytask])->data == 0);
    174 
    175 	xfrd->reload_handler.ev_fd = -1;
    176 	xfrd->reload_added = 0;
    177 	xfrd->reload_timeout.tv_sec = 0;
    178 	xfrd->reload_cmd_last_sent = xfrd->xfrd_start_time;
    179 	xfrd->reload_cmd_first_sent = 0;
    180 	xfrd->reload_failed = 0;
    181 	xfrd->can_send_reload = !reload_active;
    182 	xfrd->reload_pid = nsd_pid;
    183 	xfrd->child_timer_added = 0;
    184 
    185 	xfrd->ipc_send_blocked = 0;
    186 	memset(&xfrd->ipc_handler, 0, sizeof(xfrd->ipc_handler));
    187 	event_set(&xfrd->ipc_handler, socket, EV_PERSIST|EV_READ,
    188 		xfrd_handle_ipc, xfrd);
    189 	if(event_base_set(xfrd->event_base, &xfrd->ipc_handler) != 0)
    190 		log_msg(LOG_ERR, "xfrd ipc handler: event_base_set failed");
    191 	if(event_add(&xfrd->ipc_handler, NULL) != 0)
    192 		log_msg(LOG_ERR, "xfrd ipc handler: event_add failed");
    193 	xfrd->ipc_handler_flags = EV_PERSIST|EV_READ;
    194 	xfrd->notify_events = (struct event *) region_alloc_array_zero(
    195 		xfrd->region, nsd->child_count * 2, sizeof(struct event));
    196 	xfrd->notify_pipes = (struct xfrd_tcp *) region_alloc_array_zero(
    197 		xfrd->region, nsd->child_count * 2, sizeof(struct xfrd_tcp));
    198 	for(i = 0; i < 2 * nsd->child_count; i++) {
    199 		int fd = nsd->serve2xfrd_fd_recv[i];
    200 		xfrd->notify_pipes[i].fd = fd;
    201 		xfrd->notify_pipes[i].packet = buffer_create(xfrd->region, QIOBUFSZ);
    202 		event_set(&xfrd->notify_events[i], fd,
    203 				EV_PERSIST|EV_READ, xfrd_handle_notify, &xfrd->notify_pipes[i]);
    204 		if(event_base_set(xfrd->event_base, &xfrd->notify_events[i]) != 0)
    205 			log_msg( LOG_ERR
    206 			       , "xfrd notify_event: event_base_set failed");
    207 		if(event_add(&xfrd->notify_events[i], NULL) != 0)
    208 			log_msg(LOG_ERR, "xfrd notify_event: event_add failed");
    209 	}
    210 	xfrd->need_to_send_reload = 0;
    211 	xfrd->need_to_send_shutdown = 0;
    212 	xfrd->need_to_send_stats = 0;
    213 
    214 	xfrd->write_zonefile_needed = 0;
    215 	if(nsd->options->zonefiles_write)
    216 		xfrd_write_timer_set();
    217 
    218 	xfrd->notify_waiting_first = NULL;
    219 	xfrd->notify_waiting_last = NULL;
    220 	xfrd->notify_udp_num = 0;
    221 
    222 	daemon_remote_attach(xfrd->nsd->rc, xfrd);
    223 
    224 #ifdef USE_METRICS
    225 	daemon_metrics_attach(xfrd->nsd->metrics, xfrd);
    226 #endif /* USE_METRICS */
    227 
    228 	xfrd->tcp_set = xfrd_tcp_set_create(xfrd->region, nsd->options->tls_cert_bundle, nsd->options->xfrd_tcp_max, nsd->options->xfrd_tcp_pipeline);
    229 	xfrd->tcp_set->tcp_timeout = nsd->tcp_timeout;
    230 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_GETRANDOM)
    231 	srandom((unsigned long) getpid() * (unsigned long) time(NULL));
    232 #endif
    233 
    234 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd pre-startup"));
    235 	xfrd_init_zones();
    236 	xfrd_receive_soa(socket, shortsoa);
    237 	if(nsd->options->xfrdfile != NULL && nsd->options->xfrdfile[0]!=0)
    238 		xfrd_read_state(xfrd);
    239 
    240 	/* did we get killed before startup was successful? */
    241 	if(nsd->signal_hint_shutdown) {
    242 		kill(nsd_pid, SIGTERM);
    243 		xfrd_shutdown();
    244 		return;
    245 	}
    246 
    247 	/* init libevent signals now, so that in the previous init scripts
    248 	 * the normal sighandler is called, and can set nsd->signal_hint..
    249 	 * these are also looked at in sig_process before we run the main loop*/
    250 	xfrd_sigsetup(SIGHUP);
    251 	xfrd_sigsetup(SIGTERM);
    252 	xfrd_sigsetup(SIGQUIT);
    253 	xfrd_sigsetup(SIGCHLD);
    254 	xfrd_sigsetup(SIGALRM);
    255 	xfrd_sigsetup(SIGILL);
    256 	xfrd_sigsetup(SIGUSR1);
    257 	xfrd_sigsetup(SIGINT);
    258 
    259 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd startup"));
    260 #ifdef HAVE_SYSTEMD
    261 	sd_notify(0, "READY=1");
    262 #endif
    263 	xfrd_main();
    264 }
    265 
    266 static void
    267 xfrd_process_activated(void)
    268 {
    269 	xfrd_zone_type* zone;
    270 	while((zone = xfrd->activated_first)) {
    271 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd zone %s activation",
    272 			zone->apex_str));
    273 		/* pop zone from activated list */
    274 		xfrd->activated_first = zone->activated_next;
    275 		if(zone->activated_next)
    276 			zone->activated_next->activated_prev = NULL;
    277 		zone->is_activated = 0;
    278 		/* run it : no events, specifically not the TIMEOUT event,
    279 		 * so that running zone transfers are not interrupted */
    280 		xfrd_handle_zone(zone->zone_handler.ev_fd, 0, zone);
    281 	}
    282 }
    283 
    284 static void
    285 xfrd_sig_process(void)
    286 {
    287 	int status;
    288 	pid_t child_pid;
    289 
    290 	if(xfrd->nsd->signal_hint_quit || xfrd->nsd->signal_hint_shutdown) {
    291 		xfrd->nsd->signal_hint_quit = 0;
    292 		xfrd->nsd->signal_hint_shutdown = 0;
    293 		xfrd->need_to_send_shutdown = 1;
    294 		if(!(xfrd->ipc_handler_flags&EV_WRITE)) {
    295 			ipc_xfrd_set_listening(xfrd, EV_PERSIST|EV_READ|EV_WRITE);
    296 		}
    297 	} else if(xfrd->nsd->signal_hint_reload_hup) {
    298 		log_msg(LOG_WARNING, "SIGHUP received, reloading...");
    299 		xfrd->nsd->signal_hint_reload_hup = 0;
    300 		if(xfrd->nsd->options->reload_config) {
    301 			xfrd_reload_config(xfrd);
    302 		}
    303 		if(xfrd->nsd->options->zonefiles_check) {
    304 			task_new_check_zonefiles(xfrd->nsd->task[
    305 				xfrd->nsd->mytask], xfrd->last_task, NULL);
    306 		}
    307 		xfrd_set_reload_now(xfrd);
    308 	} else if(xfrd->nsd->signal_hint_statsusr) {
    309 		xfrd->nsd->signal_hint_statsusr = 0;
    310 		xfrd->need_to_send_stats = 1;
    311 		if(!(xfrd->ipc_handler_flags&EV_WRITE)) {
    312 			ipc_xfrd_set_listening(xfrd, EV_PERSIST|EV_READ|EV_WRITE);
    313 		}
    314 	}
    315 
    316 	/* collect children that exited. */
    317 	xfrd->nsd->signal_hint_child = 0;
    318 	while((child_pid = waitpid(-1, &status, WNOHANG)) != -1 && child_pid != 0) {
    319 		if(status != 0) {
    320 			log_msg(LOG_ERR, "process %d exited with status %d",
    321 				(int)child_pid, status);
    322 		}
    323 	}
    324 	if(!xfrd->child_timer_added) {
    325 		struct timeval tv;
    326 		tv.tv_sec = XFRD_CHILD_REAP_TIMEOUT;
    327 		tv.tv_usec = 0;
    328 		memset(&xfrd->child_timer, 0, sizeof(xfrd->child_timer));
    329 		event_set(&xfrd->child_timer, -1, EV_TIMEOUT,
    330 			xfrd_handle_child_timer, xfrd);
    331 		if(event_base_set(xfrd->event_base, &xfrd->child_timer) != 0)
    332 			log_msg(LOG_ERR, "xfrd child timer: event_base_set failed");
    333 		if(event_add(&xfrd->child_timer, &tv) != 0)
    334 			log_msg(LOG_ERR, "xfrd child timer: event_add failed");
    335 		xfrd->child_timer_added = 1;
    336 	}
    337 }
    338 
    339 static void
    340 xfrd_main(void)
    341 {
    342 	/* we may have signals from the startup period, process them */
    343 	xfrd_sig_process();
    344 	xfrd->shutdown = 0;
    345 	while(!xfrd->shutdown)
    346 	{
    347 		/* xfrd_sig_process takes care of reading zones on SIGHUP */
    348 		xfrd_process_catalog_producer_zones();
    349 		xfrd_process_catalog_consumer_zones();
    350 		/* process activated zones before blocking in select again */
    351 		xfrd_process_activated();
    352 		/* dispatch may block for a longer period, so current is gone */
    353 		xfrd->got_time = 0;
    354 		if(event_base_loop(xfrd->event_base, EVLOOP_ONCE) == -1) {
    355 			if (errno != EINTR) {
    356 				log_msg(LOG_ERR,
    357 					"xfrd dispatch failed: %s",
    358 					strerror(errno));
    359 			}
    360 		}
    361 		xfrd_sig_process();
    362 	}
    363 	xfrd_shutdown();
    364 }
    365 
    366 static void
    367 xfrd_shutdown()
    368 {
    369 	xfrd_zone_type* zone;
    370 
    371 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd shutdown"));
    372 #ifdef HAVE_SYSTEMD
    373 	sd_notify(0, "STOPPING=1");
    374 #endif
    375 	event_del(&xfrd->ipc_handler);
    376 	close(xfrd->ipc_handler.ev_fd); /* notifies parent we stop */
    377 	zone_list_close(nsd.options);
    378 	if(xfrd->nsd->options->xfrdfile != NULL && xfrd->nsd->options->xfrdfile[0]!=0)
    379 		xfrd_write_state(xfrd);
    380 	if(xfrd->reload_added) {
    381 		event_del(&xfrd->reload_handler);
    382 		xfrd->reload_added = 0;
    383 	}
    384 	if(xfrd->child_timer_added) {
    385 		event_del(&xfrd->child_timer);
    386 		xfrd->child_timer_added = 0;
    387 	}
    388 	if(xfrd->nsd->options->zonefiles_write) {
    389 		event_del(&xfrd->write_timer);
    390 	}
    391 	daemon_remote_close(xfrd->nsd->rc); /* close sockets of rc */
    392 	/* close sockets */
    393 	RBTREE_FOR(zone, xfrd_zone_type*, xfrd->zones)
    394 	{
    395 		if(zone->event_added) {
    396 			event_del(&zone->zone_handler);
    397 			if(zone->zone_handler.ev_fd != -1) {
    398 				close(zone->zone_handler.ev_fd);
    399 				zone->zone_handler.ev_fd = -1;
    400 			}
    401 			zone->event_added = 0;
    402 		}
    403 	}
    404 	close_notify_fds(xfrd->notify_zones);
    405 
    406 	/* wait for server parent (if necessary) */
    407 	if(xfrd->reload_pid != -1) {
    408 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd wait for servermain %d",
    409 			(int)xfrd->reload_pid));
    410 		while(1) {
    411 			if(waitpid(xfrd->reload_pid, NULL, 0) == -1) {
    412 				if(errno == EINTR) continue;
    413 				if(errno == ECHILD) break;
    414 				log_msg(LOG_ERR, "xfrd: waitpid(%d): %s",
    415 					(int)xfrd->reload_pid, strerror(errno));
    416 			}
    417 			break;
    418 		}
    419 	}
    420 
    421 	/* if we are killed past this point this is not a problem,
    422 	 * some files left in /tmp are cleaned by the OS, but it is neater
    423 	 * to clean them out */
    424 
    425 	/* unlink xfr files for running transfers */
    426 	RBTREE_FOR(zone, xfrd_zone_type*, xfrd->zones)
    427 	{
    428 		xfrd_xfr_type *xfr;
    429 		for(xfr = zone->latest_xfr; xfr != NULL; xfr = xfr->prev) {
    430 			if (xfr->acquired == 0)
    431 				continue;
    432 			xfrd_unlink_xfrfile(xfrd->nsd, xfr->xfrfilenumber);
    433 		}
    434 	}
    435 	/* unlink xfr files in not-yet-done task file */
    436 	xfrd_clean_pending_tasks(xfrd->nsd, xfrd->nsd->task[xfrd->nsd->mytask]);
    437 	xfrd_del_tempdir(xfrd->nsd);
    438 	daemon_remote_delete(xfrd->nsd->rc); /* ssl-delete secret keys */
    439 #ifdef HAVE_SSL
    440 	if (xfrd->nsd->tls_ctx)
    441 		SSL_CTX_free(xfrd->nsd->tls_ctx);
    442 #  ifdef HAVE_TLS_1_3
    443 	if (xfrd->tcp_set->ssl_ctx) {
    444 		int i;
    445 		for(i=0; i<xfrd->tcp_set->tcp_max; i++) {
    446 			if(xfrd->tcp_set->tcp_state[i] &&
    447 				xfrd->tcp_set->tcp_state[i]->ssl) {
    448 				SSL_free(xfrd->tcp_set->tcp_state[i]->ssl);
    449 				xfrd->tcp_set->tcp_state[i]->ssl = NULL;
    450 			}
    451 		}
    452 		SSL_CTX_free(xfrd->tcp_set->ssl_ctx);
    453 	}
    454 #  endif
    455 #endif
    456 #ifdef USE_DNSTAP
    457 	dt_collector_close(nsd.dt_collector, &nsd);
    458 #endif
    459 
    460 	/* process-exit cleans up memory used by xfrd process */
    461 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd shutdown complete"));
    462 #ifdef MEMCLEAN /* OS collects memory pages */
    463 	if(xfrd->nsd->db) {
    464 		namedb_close(xfrd->nsd->db);
    465 	}
    466 	/* TODO: cleanup xfrd->catalog_consumer_zones and xfrd->catalog_producer_zones */
    467 	if(xfrd->zones) {
    468 		xfrd_zone_type* z;
    469 		RBTREE_FOR(z, xfrd_zone_type*, xfrd->zones) {
    470 			while(z->latest_xfr != NULL) {
    471 				xfrd_free_zone_xfr(z, z->latest_xfr);
    472 			}
    473 		}
    474 	}
    475 	if(xfrd->notify_zones) {
    476 		struct notify_zone* n;
    477 		RBTREE_FOR(n, struct notify_zone*, xfrd->notify_zones) {
    478 			tsig_delete_record(&n->notify_tsig, NULL);
    479 		}
    480 	}
    481 	if(xfrd_sig_num > 0) {
    482 		int i;
    483 		for(i=0; i<xfrd_sig_num; i++) {
    484 			signal_del(xfrd_sig_evs[i]);
    485 			free(xfrd_sig_evs[i]);
    486 		}
    487 	}
    488 #ifdef RATELIMIT
    489 	rrl_mmap_deinit();
    490 #endif
    491 #ifdef USE_DNSTAP
    492 	dt_collector_destroy(nsd.dt_collector, &nsd);
    493 #endif
    494 	udb_base_free(nsd.task[0]);
    495 	udb_base_free(nsd.task[1]);
    496 	event_base_free(xfrd->event_base);
    497 	region_destroy(xfrd->region);
    498 	nsd_options_destroy(nsd.options);
    499 	region_destroy(nsd.region);
    500 	log_finalize();
    501 #endif
    502 
    503 	exit(0);
    504 }
    505 
    506 static void
    507 xfrd_clean_pending_tasks(struct nsd* nsd, udb_base* u)
    508 {
    509 	udb_ptr t;
    510 	udb_ptr_new(&t, u, udb_base_get_userdata(u));
    511 	/* no dealloc of entries, we delete the entire file when done */
    512 	while(!udb_ptr_is_null(&t)) {
    513 		if(TASKLIST(&t)->task_type == task_apply_xfr) {
    514 			xfrd_unlink_xfrfile(nsd, TASKLIST(&t)->yesno);
    515 		}
    516 		udb_ptr_set_rptr(&t, u, &TASKLIST(&t)->next);
    517 	}
    518 	udb_ptr_unlink(&t, u);
    519 }
    520 
    521 void
    522 xfrd_init_slave_zone(xfrd_state_type* xfrd, struct zone_options* zone_opt)
    523 {
    524 	int num, num_xot;
    525 	xfrd_zone_type *xzone;
    526 	xzone = (xfrd_zone_type*)region_alloc(xfrd->region,
    527 		sizeof(xfrd_zone_type));
    528 	memset(xzone, 0, sizeof(xfrd_zone_type));
    529 	xzone->apex = zone_opt->node.key;
    530 	xzone->apex_str = zone_opt->name;
    531 	xzone->state = xfrd_zone_refreshing;
    532 	xzone->zone_options = zone_opt;
    533 	/* first retry will use first master */
    534 	xzone->master = xzone->zone_options->pattern->request_xfr;
    535 	xzone->master_num = 0;
    536 	xzone->next_master = 0;
    537 	xzone->fresh_xfr_timeout = XFRD_TRANSFER_TIMEOUT_START;
    538 
    539 	xzone->soa_nsd_acquired = 0;
    540 	xzone->soa_disk_acquired = 0;
    541 	xzone->latest_xfr = NULL;
    542 	xzone->soa_notified_acquired = 0;
    543 	/* [0]=1, [1]=0; "." domain name */
    544 	xzone->soa_nsd.prim_ns[0] = 1;
    545 	xzone->soa_nsd.email[0] = 1;
    546 	xzone->soa_disk.prim_ns[0]=1;
    547 	xzone->soa_disk.email[0]=1;
    548 	xzone->soa_notified.prim_ns[0]=1;
    549 	xzone->soa_notified.email[0]=1;
    550 
    551 	xzone->zone_handler.ev_fd = -1;
    552 	xzone->zone_handler_flags = 0;
    553 	xzone->event_added = 0;
    554 
    555 	xzone->tcp_conn = -1;
    556 	xzone->tcp_waiting = 0;
    557 	xzone->udp_waiting = 0;
    558 	xzone->is_activated = 0;
    559 
    560 	xzone->multi_master_first_master = -1;
    561 	xzone->multi_master_update_check = -1;
    562 
    563 	/* set refreshing anyway, if we have data it may be old */
    564 	xfrd_set_refresh_now(xzone);
    565 
    566 	/*Check all or none of acls use XoT*/
    567 	num = 0;
    568 	num_xot = 0;
    569 	for (; xzone->master != NULL; xzone->master = xzone->master->next, num++) {
    570 		if (xzone->master->tls_auth_options != NULL) num_xot++;
    571 	}
    572 	if (num_xot != 0 && num != num_xot)
    573 		log_msg(LOG_WARNING, "Some but not all request-xfrs for %s have XFR-over-TLS configured",
    574 			xzone->apex_str);
    575 
    576 	xzone->node.key = xzone->apex;
    577 	rbtree_insert(xfrd->zones, (rbnode_type*)xzone);
    578 }
    579 
    580 static void
    581 xfrd_init_zones()
    582 {
    583 	struct zone_options *zone_opt;
    584 	assert(xfrd->zones == 0);
    585 
    586 	xfrd->zones = rbtree_create(xfrd->region,
    587 		(int (*)(const void *, const void *)) dname_compare);
    588 	xfrd->notify_zones = rbtree_create(xfrd->region,
    589 		(int (*)(const void *, const void *)) dname_compare);
    590 	xfrd->catalog_consumer_zones = rbtree_create(xfrd->region,
    591 		(int (*)(const void *, const void *)) dname_compare);
    592 	xfrd->catalog_producer_zones = rbtree_create(xfrd->region,
    593 		(int (*)(const void *, const void *)) dname_compare);
    594 
    595 	RBTREE_FOR(zone_opt, struct zone_options*, xfrd->nsd->options->zone_options)
    596 	{
    597 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: adding %s zone",
    598 			zone_opt->name));
    599 
    600 		if(zone_is_catalog_consumer(zone_opt)) {
    601 			DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s "
    602 				"is a catalog consumer zone", zone_opt->name));
    603 			xfrd_init_catalog_consumer_zone(xfrd, zone_opt);
    604 		}
    605 		if(zone_is_catalog_producer_member(zone_opt)) {
    606 			xfrd_add_catalog_producer_member(
    607 					as_catalog_member_zone(zone_opt));
    608 		}
    609 		init_notify_send(xfrd->notify_zones, xfrd->region, zone_opt);
    610 		if(!zone_is_slave(zone_opt)) {
    611 			DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s, "
    612 				"master zone has no outgoing xfr requests",
    613 				zone_opt->name));
    614 			continue;
    615 		}
    616 		xfrd_init_slave_zone(xfrd, zone_opt);
    617 	}
    618 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: started server %d "
    619 		"secondary zones, %d catalog zones", (int)xfrd->zones->count,
    620 		(int)xfrd->catalog_consumer_zones->count));
    621 }
    622 
    623 static void
    624 apply_xfrs_to_consumer_zone(struct xfrd_catalog_consumer_zone* consumer_zone,
    625 		zone_type* dbzone, xfrd_xfr_type* xfr)
    626 {
    627 	FILE* df;
    628 
    629 	if(xfr->msg_is_ixfr) {
    630 		uint32_t soa_serial=0, after_serial=0;
    631 		xfrd_xfr_type* prev;
    632 
    633 		if(dbzone->soa_rrset == NULL || dbzone->soa_rrset->rrs == NULL
    634 		|| dbzone->soa_rrset->rrs[0]->rdlength < 20+2*sizeof(void*)
    635 		|| !retrieve_soa_rdata_serial(dbzone->soa_rrset->rrs[0],
    636 			&soa_serial)) {
    637 
    638 			make_catalog_consumer_invalid(consumer_zone,
    639 			       "could not apply ixfr on catalog consumer zone "
    640 			       "\'%s\': invalid SOA resource record",
    641 			       consumer_zone->options->name);
    642 			return;
    643 		}
    644 		if(soa_serial == xfr->msg_old_serial)
    645 			goto apply_xfr;
    646 		for(prev = xfr->prev; prev; prev = prev->prev) {
    647 			if(!prev->sent)
    648 				continue;
    649 			if(xfr->msg_old_serial != prev->msg_new_serial)
    650 				continue;
    651 			apply_xfrs_to_consumer_zone(consumer_zone, dbzone, prev);
    652 			break;
    653 		}
    654 		if(!prev
    655 		|| !retrieve_soa_rdata_serial(dbzone->soa_rrset->rrs[0],
    656 			&after_serial)
    657 		|| xfr->msg_old_serial != after_serial) {
    658 			make_catalog_consumer_invalid(consumer_zone,
    659 			       "could not find and/or apply xfrs for catalog "
    660 			       "consumer zone \'%s\': to update to serial %u",
    661 			       consumer_zone->options->name,
    662 			       xfr->msg_new_serial);
    663 			return;
    664 		}
    665 	}
    666 apply_xfr:
    667 	DEBUG(DEBUG_IPC,1, (LOG_INFO, "apply %sXFR %u -> %u to consumer zone "
    668 		"\'%s\'", (xfr->msg_is_ixfr ? "I" : "A"), xfr->msg_old_serial,
    669 		xfr->msg_new_serial, consumer_zone->options->name));
    670 
    671 	if(!(df = xfrd_open_xfrfile(xfrd->nsd, xfr->xfrfilenumber, "r"))) {
    672 		make_catalog_consumer_invalid(consumer_zone,
    673 		       "could not open transfer file %lld: %s",
    674 		       (long long)xfr->xfrfilenumber, strerror(errno));
    675 
    676 	} else if(0 >= apply_ixfr_for_zone(xfrd->nsd, dbzone, df,
    677 			xfrd->nsd->options, NULL, xfr->xfrfilenumber)) {
    678 		make_catalog_consumer_invalid(consumer_zone,
    679 			"error processing transfer file %lld",
    680 			(long long)xfr->xfrfilenumber);
    681 		fclose(df);
    682 	} else {
    683 		/* Make valid for reprocessing */
    684 		make_catalog_consumer_valid(consumer_zone);
    685 		fclose(df);
    686 		DEBUG(DEBUG_IPC,1, (LOG_INFO, "%sXFR %u -> %u to consumer zone \'%s\' "
    687 			"applied", (xfr->msg_is_ixfr ? "I" : "A"), xfr->msg_old_serial,
    688 			xfr->msg_new_serial, consumer_zone->options->name));
    689 	}
    690 }
    691 
    692 static void
    693 xfrd_process_soa_info_task(struct task_list_d* task)
    694 {
    695 	xfrd_soa_type soa;
    696 	xfrd_soa_type* soa_ptr = &soa;
    697 	xfrd_zone_type* zone;
    698 	struct xfrd_catalog_producer_zone* producer_zone;
    699 	struct xfrd_catalog_consumer_zone* consumer_zone = NULL;
    700 	zone_type* dbzone = NULL;
    701 	xfrd_xfr_type* xfr;
    702 	xfrd_xfr_type* prev_xfr;
    703 	enum soainfo_hint hint;
    704 #ifndef NDEBUG
    705 	time_t before;
    706 #endif
    707 	time_t acquired = 0;
    708 	DEBUG(DEBUG_IPC,1, (LOG_INFO, "xfrd: process SOAINFO %s",
    709 		dname_to_string(task->zname, 0)));
    710 	zone = (xfrd_zone_type*)rbtree_search(xfrd->zones, task->zname);
    711 	hint = (enum soainfo_hint)task->yesno;
    712 	if(task->size <= sizeof(struct task_list_d)+dname_total_size(
    713 		task->zname)+sizeof(uint32_t)*6 + sizeof(uint8_t)*2) {
    714 		DEBUG(DEBUG_IPC,1, (LOG_INFO, "SOAINFO for %s %s zone",
    715 			dname_to_string(task->zname,0),
    716 			hint == soainfo_bad ? "kept" : "lost"));
    717 		soa_ptr = NULL;
    718 		/* discard all updates */
    719 #ifndef NDEBUG
    720 		before = xfrd_time();
    721 #endif
    722 	} else {
    723 		uint8_t* p = (uint8_t*)task->zname + dname_total_size(
    724 			task->zname);
    725 		/* read the soa info */
    726 		memset(&soa, 0, sizeof(soa));
    727 		/* left out type, klass, count for speed */
    728 		soa.type = htons(TYPE_SOA);
    729 		soa.klass = htons(CLASS_IN);
    730 		memmove(&soa.ttl, p, sizeof(uint32_t));
    731 		p += sizeof(uint32_t);
    732 		memmove(soa.prim_ns, p, sizeof(uint8_t));
    733 		p += sizeof(uint8_t);
    734 		memmove(soa.prim_ns+1, p, soa.prim_ns[0]);
    735 		p += soa.prim_ns[0];
    736 		memmove(soa.email, p, sizeof(uint8_t));
    737 		p += sizeof(uint8_t);
    738 		memmove(soa.email+1, p, soa.email[0]);
    739 		p += soa.email[0];
    740 		memmove(&soa.serial, p, sizeof(uint32_t));
    741 		p += sizeof(uint32_t);
    742 		memmove(&soa.refresh, p, sizeof(uint32_t));
    743 		p += sizeof(uint32_t);
    744 		memmove(&soa.retry, p, sizeof(uint32_t));
    745 		p += sizeof(uint32_t);
    746 		memmove(&soa.expire, p, sizeof(uint32_t));
    747 		p += sizeof(uint32_t);
    748 		memmove(&soa.minimum, p, sizeof(uint32_t));
    749 		/* p += sizeof(uint32_t); if we wanted to read further */
    750 		DEBUG(DEBUG_IPC,1, (LOG_INFO, "SOAINFO for %s %u",
    751 			dname_to_string(task->zname,0),
    752 			(unsigned)ntohl(soa.serial)));
    753 		/* discard all updates received before initial reload unless
    754 		   reload was successful */
    755 #ifndef NDEBUG
    756 		before = xfrd->reload_cmd_first_sent;
    757 #endif
    758 	}
    759 
    760 	if(zone)
    761 		; /* pass */
    762 
    763 	else if((producer_zone = (struct xfrd_catalog_producer_zone*)
    764 			rbtree_search(xfrd->catalog_producer_zones, task->zname))) {
    765 		struct xfrd_producer_xfr* pxfr, *next_pxfr;
    766 
    767 		DEBUG(DEBUG_IPC,1, (LOG_INFO, "Zone %s is catalog producer",
    768 			dname_to_string(task->zname,0)));
    769 
    770 		if(hint != soainfo_ok)
    771 			producer_zone->axfr = 1;
    772 
    773 		for(pxfr = producer_zone->latest_pxfr; pxfr; pxfr = next_pxfr) {
    774 			next_pxfr = pxfr->next;
    775 
    776 			DEBUG(DEBUG_IPC,1, (LOG_INFO, "pxfr for zone %s for serial %u",
    777 				dname_to_string(task->zname,0), pxfr->serial));
    778 
    779 			if(hint != soainfo_ok)
    780 				; /* pass */
    781 			else if(!soa_ptr || soa_ptr->serial != htonl(pxfr->serial))
    782 				continue;
    783 
    784 			else if(xfrd->reload_failed) {
    785 				DEBUG(DEBUG_IPC, 1,
    786 					(LOG_INFO, "xfrd: zone %s mark update "
    787 					           "to serial %u verified",
    788 					           producer_zone->options->name,
    789 					           pxfr->serial));
    790 				diff_update_commit(
    791 					producer_zone->options->name,
    792 					DIFF_VERIFIED, xfrd->nsd,
    793 					pxfr->xfrfilenumber);
    794 				return;
    795 			}
    796 			DEBUG(DEBUG_IPC, 1,
    797 				(LOG_INFO, "xfrd: zone %s delete update to "
    798 				 "serial %u", producer_zone->options->name,
    799 				 pxfr->serial));
    800 			xfrd_unlink_xfrfile(xfrd->nsd, pxfr->xfrfilenumber);
    801 			if((*pxfr->prev_next_ptr = pxfr->next))
    802 				pxfr->next->prev_next_ptr = pxfr->prev_next_ptr;
    803 			region_recycle(xfrd->region, pxfr, sizeof(*pxfr));
    804 			notify_handle_master_zone_soainfo(xfrd->notify_zones,
    805 				task->zname, soa_ptr);
    806 		}
    807 		return;
    808 	} else {
    809 		DEBUG(DEBUG_IPC,1, (LOG_INFO, "xfrd: zone %s primary zone updated",
    810 			dname_to_string(task->zname,0)));
    811 		notify_handle_master_zone_soainfo(xfrd->notify_zones,
    812 			task->zname, soa_ptr);
    813 		return;
    814 	}
    815 	if(xfrd->nsd->db
    816 	&& xfrd->catalog_consumer_zones
    817 #ifndef MULTIPLE_CATALOG_CONSUMER_ZONES
    818 	&& xfrd->catalog_consumer_zones->count == 1
    819 #endif
    820 	&& (consumer_zone = (struct xfrd_catalog_consumer_zone*)rbtree_search(
    821 			xfrd->catalog_consumer_zones, task->zname))) {
    822 		dbzone = namedb_find_or_create_zone( xfrd->nsd->db, task->zname
    823 		                                   , consumer_zone->options);
    824 	}
    825 	/* soainfo_gone and soainfo_bad are straightforward, delete all updates
    826 	   that were transfered, i.e. acquired != 0. soainfo_ok is more
    827 	   complicated as it is possible that there are subsequent corrupt or
    828 	   inconsistent updates */
    829 	for(xfr = zone->latest_xfr; xfr; xfr = prev_xfr) {
    830 		prev_xfr = xfr->prev;
    831 		/* skip incomplete updates */
    832 		if(!xfr->acquired) {
    833 			continue;
    834 		}
    835 		if(hint == soainfo_ok) {
    836 			/* skip non-queued updates */
    837 			if(!xfr->sent)
    838 				continue;
    839 			assert(xfr->acquired <= before);
    840 		}
    841 		if(hint == soainfo_ok && soa_ptr) {
    842 			/* soa_ptr should be true if soainfo_ok. If no
    843 			 * soa_ptr or soa_info_bad or gone delete all
    844 			 * the transfers. */
    845 
    846 			/* updates are applied in-order, acquired time of
    847 			   most-recent update is used as baseline */
    848 			if(!acquired) {
    849 				acquired = xfr->acquired;
    850 			}
    851 			if(xfrd->reload_failed) {
    852 				DEBUG(DEBUG_IPC, 1,
    853 					(LOG_INFO, "xfrd: zone %s mark update "
    854 					           "to serial %u verified",
    855 					           zone->apex_str,
    856 					           xfr->msg_new_serial));
    857 				diff_update_commit(
    858 					zone->apex_str, DIFF_VERIFIED,
    859 					xfrd->nsd, xfr->xfrfilenumber);
    860 				return;
    861 			}
    862 			if(consumer_zone && dbzone &&
    863 				/* Call consumer apply for most recent update*/
    864 				(soa_ptr && soa_ptr->serial == htonl(xfr->msg_new_serial)))
    865 				apply_xfrs_to_consumer_zone(
    866 					consumer_zone, dbzone, xfr);
    867 		}
    868 		DEBUG(DEBUG_IPC, 1,
    869 			(LOG_INFO, "xfrd: zone %s delete update to serial %u",
    870 			           zone->apex_str,
    871 			           xfr->msg_new_serial));
    872 		xfrd_delete_zone_xfr(zone, xfr);
    873 	}
    874 
    875 	/* update zone state */
    876 	switch(hint) {
    877 	case soainfo_bad:
    878 		/* "rollback" on-disk soa information */
    879 		zone->soa_disk_acquired = zone->soa_nsd_acquired;
    880 		zone->soa_disk = zone->soa_nsd;
    881 
    882 		if(xfrd_time() - zone->soa_disk_acquired
    883 			>= (time_t)ntohl(zone->soa_disk.expire))
    884 		{
    885 			/* zone expired */
    886 			xfrd_set_zone_state(zone, xfrd_zone_expired);
    887 		}
    888 		/* do not refresh right away, like with corrupt or inconsistent
    889 		   updates, because the zone is likely not fixed on the primary
    890 		   yet. an immediate refresh can therefore potentially trigger
    891 		   an update loop */
    892 		xfrd_set_timer_retry(zone);
    893 
    894 		if(zone->soa_notified_acquired != 0 &&
    895 			(zone->soa_notified.serial == 0 ||
    896 			 compare_serial(ntohl(zone->soa_disk.serial),
    897 			                ntohl(zone->soa_notified.serial)) >= 0))
    898 		{	/* read was in response to this notification */
    899 			zone->soa_notified_acquired = 0;
    900 		}
    901 		if(zone->soa_notified_acquired && zone->state == xfrd_zone_ok)
    902 		{
    903 			/* refresh because of notification */
    904 			xfrd_set_zone_state(zone, xfrd_zone_refreshing);
    905 			xfrd_set_refresh_now(zone);
    906 		}
    907 		break;
    908 	case soainfo_ok:
    909 		if(xfrd->reload_failed)
    910 			break;
    911 		/* fall through */
    912 	case soainfo_gone:
    913 		xfrd_handle_incoming_soa(zone, soa_ptr, acquired);
    914 		break;
    915 	}
    916 }
    917 
    918 static void
    919 xfrd_receive_soa(int socket, int shortsoa)
    920 {
    921 	sig_atomic_t cmd;
    922 	struct udb_base* xtask = xfrd->nsd->task[xfrd->nsd->mytask];
    923 	udb_ptr last_task, t;
    924 	xfrd_zone_type* zone;
    925 
    926 	if(!shortsoa) {
    927 		/* put all expired zones into mytask */
    928 		udb_ptr_init(&last_task, xtask);
    929 		RBTREE_FOR(zone, xfrd_zone_type*, xfrd->zones) {
    930 			if(zone->state == xfrd_zone_expired) {
    931 				task_new_expire(xtask, &last_task, zone->apex, 1);
    932 			}
    933 		}
    934 		udb_ptr_unlink(&last_task, xtask);
    935 
    936 		/* send RELOAD to main to give it this tasklist */
    937 		task_process_sync(xtask);
    938 		cmd = NSD_RELOAD;
    939 		if(!write_socket(socket, &cmd,  sizeof(cmd))) {
    940 			log_msg(LOG_ERR, "problems sending reload xfrdtomain: %s",
    941 				strerror(errno));
    942 		}
    943 	}
    944 
    945 	/* receive RELOAD_DONE to get SOAINFO tasklist */
    946 	if(block_read(&nsd, socket, &cmd, sizeof(cmd), -1) != sizeof(cmd) ||
    947 		cmd != NSD_RELOAD_DONE) {
    948 		if(nsd.signal_hint_shutdown)
    949 			return;
    950 		log_msg(LOG_ERR, "did not get start signal from main");
    951 		exit(1);
    952 	}
    953 	if(block_read(NULL, socket, &xfrd->reload_pid, sizeof(pid_t), -1)
    954 		!= sizeof(pid_t)) {
    955 		log_msg(LOG_ERR, "xfrd cannot get reload_pid");
    956 	}
    957 
    958 	/* process tasklist (SOAINFO data) */
    959 	udb_ptr_unlink(xfrd->last_task, xtask);
    960 	/* if shortsoa: then use my own taskdb that nsdparent filled */
    961 	if(!shortsoa)
    962 		xfrd->nsd->mytask = 1 - xfrd->nsd->mytask;
    963 	xtask = xfrd->nsd->task[xfrd->nsd->mytask];
    964 	task_remap(xtask);
    965 	udb_ptr_new(&t, xtask, udb_base_get_userdata(xtask));
    966 	while(!udb_ptr_is_null(&t)) {
    967 		xfrd_process_soa_info_task(TASKLIST(&t));
    968 	 	udb_ptr_set_rptr(&t, xtask, &TASKLIST(&t)->next);
    969 	}
    970 	udb_ptr_unlink(&t, xtask);
    971 	task_clear(xtask);
    972 	udb_ptr_init(xfrd->last_task, xfrd->nsd->task[xfrd->nsd->mytask]);
    973 
    974 	if(!shortsoa) {
    975 		/* receive RELOAD_DONE that signals the other tasklist is
    976 		 * empty, and thus xfrd can operate (can call reload and swap
    977 		 * to the other, empty, tasklist) */
    978 		if(block_read(NULL, socket, &cmd, sizeof(cmd), -1) !=
    979 			sizeof(cmd) ||
    980 			cmd != NSD_RELOAD_DONE) {
    981 			log_msg(LOG_ERR, "did not get start signal 2 from "
    982 				"main");
    983 			exit(1);
    984 		}
    985 	} else {
    986 		/* for shortsoa version, do expire later */
    987 		/* if expire notifications, put in my task and
    988 		 * schedule a reload to make sure they are processed */
    989 		RBTREE_FOR(zone, xfrd_zone_type*, xfrd->zones) {
    990 			if(zone->state == xfrd_zone_expired) {
    991 				xfrd_send_expire_notification(zone);
    992 			}
    993 		}
    994 	}
    995 }
    996 
    997 void
    998 xfrd_reopen_logfile(void)
    999 {
   1000 	if (xfrd->nsd->file_rotation_ok)
   1001 		log_reopen(xfrd->nsd->log_filename, 0);
   1002 }
   1003 
   1004 void
   1005 xfrd_deactivate_zone(xfrd_zone_type* z)
   1006 {
   1007 	if(z->is_activated) {
   1008 		/* delete from activated list */
   1009 		if(z->activated_prev)
   1010 			z->activated_prev->activated_next = z->activated_next;
   1011 		else	xfrd->activated_first = z->activated_next;
   1012 		if(z->activated_next)
   1013 			z->activated_next->activated_prev = z->activated_prev;
   1014 		z->is_activated = 0;
   1015 	}
   1016 }
   1017 
   1018 void
   1019 xfrd_del_slave_zone(xfrd_state_type* xfrd, const dname_type* dname)
   1020 {
   1021 	xfrd_zone_type* z = (xfrd_zone_type*)rbtree_delete(xfrd->zones, dname);
   1022 	if(!z) return;
   1023 
   1024 	/* io */
   1025 	if(z->tcp_waiting) {
   1026 		/* delete from tcp waiting list */
   1027 		if(z->tcp_waiting_prev)
   1028 			z->tcp_waiting_prev->tcp_waiting_next =
   1029 				z->tcp_waiting_next;
   1030 		else xfrd->tcp_set->tcp_waiting_first = z->tcp_waiting_next;
   1031 		if(z->tcp_waiting_next)
   1032 			z->tcp_waiting_next->tcp_waiting_prev =
   1033 				z->tcp_waiting_prev;
   1034 		else xfrd->tcp_set->tcp_waiting_last = z->tcp_waiting_prev;
   1035 		z->tcp_waiting = 0;
   1036 	}
   1037 	if(z->udp_waiting) {
   1038 		/* delete from udp waiting list */
   1039 		if(z->udp_waiting_prev)
   1040 			z->udp_waiting_prev->udp_waiting_next =
   1041 				z->udp_waiting_next;
   1042 		else	xfrd->udp_waiting_first = z->udp_waiting_next;
   1043 		if(z->udp_waiting_next)
   1044 			z->udp_waiting_next->udp_waiting_prev =
   1045 				z->udp_waiting_prev;
   1046 		else	xfrd->udp_waiting_last = z->udp_waiting_prev;
   1047 		z->udp_waiting = 0;
   1048 	}
   1049 	xfrd_deactivate_zone(z);
   1050 	if(z->tcp_conn != -1) {
   1051 		xfrd_tcp_release(xfrd->tcp_set, z);
   1052 	} else if(z->zone_handler.ev_fd != -1 && z->event_added) {
   1053 		xfrd_udp_release(z);
   1054 	}
   1055 	if(z->event_added)
   1056 		event_del(&z->zone_handler);
   1057 
   1058 	while(z->latest_xfr) xfrd_delete_zone_xfr(z, z->latest_xfr);
   1059 
   1060 	/* z->dname is recycled when the zone_options is removed */
   1061 	region_recycle(xfrd->region, z, sizeof(*z));
   1062 }
   1063 
   1064 void
   1065 xfrd_free_namedb(struct nsd* nsd)
   1066 {
   1067 	namedb_close(nsd->db);
   1068 	nsd->db = 0;
   1069 }
   1070 
   1071 static void
   1072 xfrd_set_timer_refresh(xfrd_zone_type* zone)
   1073 {
   1074 	time_t set_refresh;
   1075 	time_t set_expire;
   1076 	time_t set;
   1077 	if(zone->soa_disk_acquired == 0 || zone->state != xfrd_zone_ok) {
   1078 		xfrd_set_timer_retry(zone);
   1079 		return;
   1080 	}
   1081 	/* refresh or expire timeout, whichever is earlier */
   1082 	set_refresh = bound_soa_disk_refresh(zone);
   1083 	set_expire  = bound_soa_disk_expire(zone);
   1084 	set = zone->soa_disk_acquired + ( set_refresh < set_expire
   1085 	                                ? set_refresh : set_expire );
   1086 
   1087 	/* set point in time to period for xfrd_set_timer() */
   1088 	xfrd_set_timer(zone, within_refresh_bounds(zone,
   1089 		  set > xfrd_time()
   1090 		? set - xfrd_time() : XFRD_LOWERBOUND_REFRESH));
   1091 }
   1092 
   1093 static void
   1094 xfrd_set_timer_retry(xfrd_zone_type* zone)
   1095 {
   1096 	time_t set_retry;
   1097 	time_t set_expire;
   1098 	int mult;
   1099 	/* perform exponential backoff in all the cases */
   1100 	if(zone->fresh_xfr_timeout == 0)
   1101 		zone->fresh_xfr_timeout = XFRD_TRANSFER_TIMEOUT_START;
   1102 	else {
   1103 		/* exponential backoff - some master data in zones is paid-for
   1104 		   but non-working, and will not get fixed. */
   1105 		zone->fresh_xfr_timeout *= 2;
   1106 		if(zone->fresh_xfr_timeout > XFRD_TRANSFER_TIMEOUT_MAX)
   1107 			zone->fresh_xfr_timeout = XFRD_TRANSFER_TIMEOUT_MAX;
   1108 	}
   1109 	/* exponential backoff multiplier, starts at 1, backs off */
   1110 	mult = zone->fresh_xfr_timeout / XFRD_TRANSFER_TIMEOUT_START;
   1111 	if(mult == 0) mult = 1;
   1112 
   1113 	/* set timer for next retry or expire timeout if earlier. */
   1114 	if(zone->soa_disk_acquired == 0) {
   1115 		/* if no information, use reasonable timeout
   1116 		 * within configured and defined bounds
   1117 		 */
   1118 		xfrd_set_timer(zone,
   1119 			within_retry_bounds(zone, zone->fresh_xfr_timeout
   1120 				+ random_generate(zone->fresh_xfr_timeout)));
   1121 		return;
   1122 	}
   1123 	/* exponential backoff within configured and defined bounds */
   1124 	set_retry = within_retry_bounds(zone,
   1125 			ntohl(zone->soa_disk.retry) * mult);
   1126 	if(zone->state == xfrd_zone_expired) {
   1127 		xfrd_set_timer(zone, set_retry);
   1128 		return;
   1129 	}
   1130 	/* retry or expire timeout, whichever is earlier */
   1131 	set_expire = zone->soa_disk_acquired + bound_soa_disk_expire(zone);
   1132 	if(xfrd_time() + set_retry < set_expire) {
   1133 		xfrd_set_timer(zone, set_retry);
   1134 		return;
   1135 	}
   1136 	/* Not expired, but next retry will be > than expire timeout.
   1137 	 * Retry when the expire timeout runs out.
   1138 	 * set_expire is below retry upper bounds (if statement above),
   1139 	 * but not necessarily above lower bounds,
   1140 	 * so use within_retry_bounds() again.
   1141 	 */
   1142 	xfrd_set_timer(zone, within_retry_bounds(zone,
   1143 		  set_expire > xfrd_time()
   1144 		? set_expire - xfrd_time() : XFRD_LOWERBOUND_RETRY));
   1145 }
   1146 
   1147 void
   1148 xfrd_handle_zone(int ATTR_UNUSED(fd), short event, void* arg)
   1149 {
   1150 	xfrd_zone_type* zone = (xfrd_zone_type*)arg;
   1151 
   1152 	if(zone->tcp_conn != -1) {
   1153 		if(event == 0) /* activated, but already in TCP, nothing to do*/
   1154 			return;
   1155 		/* busy in tcp transaction: an internal error */
   1156 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s event tcp", zone->apex_str));
   1157 		xfrd_tcp_release(xfrd->tcp_set, zone);
   1158 		/* continue to retry; as if a timeout happened */
   1159 		event = EV_TIMEOUT;
   1160 	}
   1161 
   1162 	if((event & EV_READ)) {
   1163 		/* busy in udp transaction */
   1164 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s event udp read", zone->apex_str));
   1165 		xfrd_udp_read(zone);
   1166 		return;
   1167 	}
   1168 
   1169 	/* timeout */
   1170 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s timeout", zone->apex_str));
   1171 	if(zone->zone_handler.ev_fd != -1 && zone->event_added &&
   1172 		(event & EV_TIMEOUT)) {
   1173 		assert(zone->tcp_conn == -1);
   1174 		xfrd_udp_release(zone);
   1175 	}
   1176 
   1177 	if(zone->tcp_waiting) {
   1178 		DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s skips retry, TCP connections full",
   1179 			zone->apex_str));
   1180 		xfrd_unset_timer(zone);
   1181 		return;
   1182 	}
   1183 	if(zone->udp_waiting) {
   1184 		DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s skips retry, UDP connections full",
   1185 			zone->apex_str));
   1186 		xfrd_unset_timer(zone);
   1187 		return;
   1188 	}
   1189 
   1190 	if(zone->soa_disk_acquired)
   1191 	{
   1192 		if (zone->state != xfrd_zone_expired &&
   1193 			xfrd_time() >= zone->soa_disk_acquired
   1194 					+ bound_soa_disk_expire(zone)) {
   1195 			/* zone expired */
   1196 			log_msg(LOG_ERR, "xfrd: zone %s has expired", zone->apex_str);
   1197 			xfrd_set_zone_state(zone, xfrd_zone_expired);
   1198 		}
   1199 		else if(zone->state == xfrd_zone_ok &&
   1200 			xfrd_time() >= zone->soa_disk_acquired
   1201 			               + bound_soa_disk_refresh(zone)) {
   1202 			/* zone goes to refreshing state. */
   1203 			DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s is refreshing", zone->apex_str));
   1204 			xfrd_set_zone_state(zone, xfrd_zone_refreshing);
   1205 		}
   1206 	}
   1207 
   1208 	/* only make a new request if no request is running (UDPorTCP) */
   1209 	if(zone->zone_handler.ev_fd == -1 && zone->tcp_conn == -1) {
   1210 		/* make a new request */
   1211 		xfrd_make_request(zone);
   1212 	}
   1213 }
   1214 
   1215 void
   1216 xfrd_make_request(xfrd_zone_type* zone)
   1217 {
   1218 	if(zone->next_master != -1) {
   1219 		/* we are told to use this next master */
   1220 		DEBUG(DEBUG_XFRD,1, (LOG_INFO,
   1221 			"xfrd zone %s use primary %i",
   1222 			zone->apex_str, zone->next_master));
   1223 		zone->master_num = zone->next_master;
   1224 		zone->master = acl_find_num(zone->zone_options->pattern->
   1225 			request_xfr, zone->master_num);
   1226 		/* if there is no next master, fallback to use the first one */
   1227 		if(!zone->master) {
   1228 			zone->master = zone->zone_options->pattern->request_xfr;
   1229 			zone->master_num = 0;
   1230 		}
   1231 		/* fallback to cycle master */
   1232 		zone->next_master = -1;
   1233 		zone->round_num = 0; /* fresh set of retries after notify */
   1234 	} else {
   1235 		/* cycle master */
   1236 
   1237 		if(zone->round_num != -1 && zone->master && zone->master->next)
   1238 		{
   1239 			/* try the next master */
   1240 			zone->master = zone->master->next;
   1241 			zone->master_num++;
   1242 		} else {
   1243 			/* start a new round */
   1244 			zone->master = zone->zone_options->pattern->request_xfr;
   1245 			zone->master_num = 0;
   1246 			zone->round_num++;
   1247 		}
   1248 		if(zone->round_num >= XFRD_MAX_ROUNDS) {
   1249 			/* tried all servers that many times, wait */
   1250 			zone->round_num = -1;
   1251 			xfrd_set_timer_retry(zone);
   1252 			DEBUG(DEBUG_XFRD,1, (LOG_INFO,
   1253 				"xfrd zone %s makereq wait_retry, rd %d mr %d nx %d",
   1254 				zone->apex_str, zone->round_num, zone->master_num, zone->next_master));
   1255                        zone->multi_master_first_master = -1;
   1256                        return;
   1257                }
   1258 	}
   1259 
   1260 	/* multi-master-check */
   1261 	if(zone->zone_options->pattern->multi_primary_check) {
   1262 		if(zone->multi_master_first_master == zone->master_num &&
   1263 			zone->round_num > 0 &&
   1264 			zone->state != xfrd_zone_expired) {
   1265 			/* tried all servers and update zone */
   1266 			if(zone->multi_master_update_check >= 0) {
   1267 				VERBOSITY(2, (LOG_INFO, "xfrd: multi primary "
   1268 					"check: zone %s completed transfers",
   1269 					zone->apex_str));
   1270 			}
   1271 			zone->round_num = -1; /* next try start anew */
   1272 			zone->multi_master_first_master = -1;
   1273 			xfrd_set_timer_refresh(zone);
   1274 			return;
   1275 		}
   1276 		if(zone->multi_master_first_master < 0) {
   1277 			zone->multi_master_first_master = zone->master_num;
   1278 			zone->multi_master_update_check = -1;
   1279 		}
   1280 	}
   1281 
   1282 	/* cache ixfr_disabled only for XFRD_NO_IXFR_CACHE time */
   1283 	if (zone->master->ixfr_disabled &&
   1284 	   (zone->master->ixfr_disabled + XFRD_NO_IXFR_CACHE) <= time(NULL)) {
   1285 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "clear negative caching ixfr "
   1286 						"disabled for primary %s num "
   1287 						"%d ",
   1288 			zone->master->ip_address_spec, zone->master_num));
   1289 		zone->master->ixfr_disabled = 0;
   1290 	}
   1291 
   1292 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd zone %s make request round %d mr %d nx %d",
   1293 		zone->apex_str, zone->round_num, zone->master_num, zone->next_master));
   1294 	/* perform xfr request */
   1295 	if (!zone->master->use_axfr_only && zone->soa_disk_acquired > 0 &&
   1296 		!zone->master->ixfr_disabled) {
   1297 
   1298 		if (zone->master->allow_udp) {
   1299 			xfrd_set_timer(zone, XFRD_UDP_TIMEOUT);
   1300 			xfrd_udp_obtain(zone);
   1301 		}
   1302 		else { /* doing 3 rounds of IXFR/TCP might not be useful */
   1303 			xfrd_set_timer(zone, xfrd->tcp_set->tcp_timeout);
   1304 			xfrd_tcp_obtain(xfrd->tcp_set, zone);
   1305 		}
   1306 	}
   1307 	else if (zone->master->use_axfr_only || zone->soa_disk_acquired <= 0) {
   1308 		xfrd_set_timer(zone, xfrd->tcp_set->tcp_timeout);
   1309 		xfrd_tcp_obtain(xfrd->tcp_set, zone);
   1310 	}
   1311 	else if (zone->master->ixfr_disabled) {
   1312 		if (zone->zone_options->pattern->allow_axfr_fallback) {
   1313 			xfrd_set_timer(zone, xfrd->tcp_set->tcp_timeout);
   1314 			xfrd_tcp_obtain(xfrd->tcp_set, zone);
   1315 		} else {
   1316 			DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd zone %s axfr "
   1317 				"fallback not allowed, skipping primary %s.",
   1318 				zone->apex_str, zone->master->ip_address_spec));
   1319 		}
   1320 	}
   1321 }
   1322 
   1323 static void
   1324 xfrd_udp_obtain(xfrd_zone_type* zone)
   1325 {
   1326 	assert(zone->udp_waiting == 0);
   1327 	if(zone->tcp_conn != -1) {
   1328 		/* no tcp and udp at the same time */
   1329 		xfrd_tcp_release(xfrd->tcp_set, zone);
   1330 	}
   1331 	if(xfrd->udp_use_num < XFRD_MAX_UDP) {
   1332 		int fd;
   1333 		xfrd->udp_use_num++;
   1334 		fd = xfrd_send_ixfr_request_udp(zone);
   1335 		if(fd == -1)
   1336 			xfrd->udp_use_num--;
   1337 		else {
   1338 			if(zone->event_added)
   1339 				event_del(&zone->zone_handler);
   1340 			memset(&zone->zone_handler, 0,
   1341 				sizeof(zone->zone_handler));
   1342 			event_set(&zone->zone_handler, fd,
   1343 				EV_PERSIST|EV_READ|EV_TIMEOUT,
   1344 				xfrd_handle_zone, zone);
   1345 			if(event_base_set(xfrd->event_base, &zone->zone_handler) != 0)
   1346 				log_msg(LOG_ERR, "xfrd udp: event_base_set failed");
   1347 			if(event_add(&zone->zone_handler, &zone->timeout) != 0)
   1348 				log_msg(LOG_ERR, "xfrd udp: event_add failed");
   1349 			zone->zone_handler_flags=EV_PERSIST|EV_READ|EV_TIMEOUT;
   1350 			zone->event_added = 1;
   1351 		}
   1352 		return;
   1353 	}
   1354 	/* queue the zone as last */
   1355 	zone->udp_waiting = 1;
   1356 	zone->udp_waiting_next = NULL;
   1357 	zone->udp_waiting_prev = xfrd->udp_waiting_last;
   1358 	if(!xfrd->udp_waiting_first)
   1359 		xfrd->udp_waiting_first = zone;
   1360 	if(xfrd->udp_waiting_last)
   1361 		xfrd->udp_waiting_last->udp_waiting_next = zone;
   1362 	xfrd->udp_waiting_last = zone;
   1363 	xfrd_unset_timer(zone);
   1364 }
   1365 
   1366 time_t
   1367 xfrd_time()
   1368 {
   1369 	if(!xfrd->got_time) {
   1370 		xfrd->current_time = time(0);
   1371 		xfrd->got_time = 1;
   1372 	}
   1373 	return xfrd->current_time;
   1374 }
   1375 
   1376 void
   1377 xfrd_copy_soa(xfrd_soa_type* soa, rr_type* rr)
   1378 {
   1379 	const uint8_t* rr_ns_wire = dname_name(domain_dname(rdata_domain_ref(rr)));
   1380 	uint8_t rr_ns_len = domain_dname(rdata_domain_ref(rr))->name_size;
   1381 	const uint8_t* rr_em_wire = dname_name(domain_dname(
   1382 		rdata_domain_ref_offset(rr, sizeof(void*))));
   1383 	uint8_t rr_em_len = domain_dname(rdata_domain_ref_offset(rr,
   1384 		sizeof(void*)))->name_size;
   1385 	uint8_t* p;
   1386 
   1387 	if(rr->type != TYPE_SOA || rr->rdlength != 20+2*sizeof(void*)) {
   1388 		log_msg(LOG_ERR, "xfrd: copy_soa called with bad rr, type %d rrs %u.",
   1389 			rr->type, (unsigned)rr->rdlength);
   1390 		return;
   1391 	}
   1392 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: copy_soa rr, type %d rrs %u, ttl %u.",
   1393 			(int)rr->type, (unsigned)rr->rdlength, (unsigned)rr->ttl));
   1394 	soa->type = htons(rr->type);
   1395 	soa->klass = htons(rr->klass);
   1396 	soa->ttl = htonl(rr->ttl);
   1397 
   1398 	/* copy dnames */
   1399 	soa->prim_ns[0] = rr_ns_len;
   1400 	memcpy(soa->prim_ns+1, rr_ns_wire, rr_ns_len);
   1401 	soa->email[0] = rr_em_len;
   1402 	memcpy(soa->email+1, rr_em_wire, rr_em_len);
   1403 
   1404 	/* already in network format */
   1405 	p = rr->rdata + 2*sizeof(void*);
   1406 	memcpy(&soa->serial, p, sizeof(uint32_t));
   1407 	memcpy(&soa->refresh, p+4, sizeof(uint32_t));
   1408 	memcpy(&soa->retry, p+8, sizeof(uint32_t));
   1409 	memcpy(&soa->expire, p+12, sizeof(uint32_t));
   1410 	memcpy(&soa->minimum, p+16, sizeof(uint32_t));
   1411 	DEBUG(DEBUG_XFRD,1, (LOG_INFO,
   1412 		"xfrd: copy_soa rr, serial %u refresh %u retry %u expire %u",
   1413 		(unsigned)ntohl(soa->serial), (unsigned)ntohl(soa->refresh),
   1414 		(unsigned)ntohl(soa->retry), (unsigned)ntohl(soa->expire)));
   1415 }
   1416 
   1417 static void
   1418 xfrd_set_zone_state(xfrd_zone_type* zone, enum xfrd_zone_state s)
   1419 {
   1420 	if(s != zone->state) {
   1421 		enum xfrd_zone_state old = zone->state;
   1422 		zone->state = s;
   1423 		if((s == xfrd_zone_expired || old == xfrd_zone_expired)
   1424 			&& s!=old) {
   1425 			xfrd_send_expire_notification(zone);
   1426 		}
   1427 	}
   1428 }
   1429 
   1430 void
   1431 xfrd_set_refresh_now(xfrd_zone_type* zone)
   1432 {
   1433 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd zone %s is activated, state %d",
   1434 		zone->apex_str, zone->state));
   1435 	if(!zone->is_activated) {
   1436 		/* push onto list */
   1437 		zone->activated_prev = 0;
   1438 		zone->activated_next = xfrd->activated_first;
   1439 		if(xfrd->activated_first)
   1440 			xfrd->activated_first->activated_prev = zone;
   1441 		xfrd->activated_first = zone;
   1442 		zone->is_activated = 1;
   1443 	}
   1444 }
   1445 
   1446 void
   1447 xfrd_unset_timer(xfrd_zone_type* zone)
   1448 {
   1449 	assert(zone->zone_handler.ev_fd == -1);
   1450 	if(zone->event_added)
   1451 		event_del(&zone->zone_handler);
   1452 	zone->zone_handler_flags = 0;
   1453 	zone->event_added = 0;
   1454 }
   1455 
   1456 void
   1457 xfrd_set_timer(xfrd_zone_type* zone, time_t t)
   1458 {
   1459 	int fd = zone->zone_handler.ev_fd;
   1460 	int fl = ((fd == -1)?EV_TIMEOUT:zone->zone_handler_flags);
   1461 	if(t > XFRD_TRANSFER_TIMEOUT_MAX)
   1462 		t = XFRD_TRANSFER_TIMEOUT_MAX;
   1463 	/* randomize the time, within 90%-100% of original */
   1464 	/* not later so zones cannot expire too late */
   1465 	/* only for times far in the future */
   1466 	if(t > 10) {
   1467 		time_t base = t*9/10;
   1468 		t = base + random_generate(t-base);
   1469 	}
   1470 
   1471 	/* keep existing flags and fd, but re-add with timeout */
   1472 	if(zone->event_added)
   1473 		event_del(&zone->zone_handler);
   1474 	else	fd = -1;
   1475 	zone->timeout.tv_sec = t;
   1476 	zone->timeout.tv_usec = 0;
   1477 	memset(&zone->zone_handler, 0, sizeof(zone->zone_handler));
   1478 	event_set(&zone->zone_handler, fd, fl, xfrd_handle_zone, zone);
   1479 	if(event_base_set(xfrd->event_base, &zone->zone_handler) != 0)
   1480 		log_msg(LOG_ERR, "xfrd timer: event_base_set failed");
   1481 	if(event_add(&zone->zone_handler, &zone->timeout) != 0)
   1482 		log_msg(LOG_ERR, "xfrd timer: event_add failed");
   1483 	zone->zone_handler_flags = fl;
   1484 	zone->event_added = 1;
   1485 }
   1486 
   1487 void
   1488 xfrd_handle_incoming_soa(xfrd_zone_type* zone,
   1489 	xfrd_soa_type* soa, time_t acquired)
   1490 {
   1491 	time_t seconds_since_acquired;
   1492 	if(soa == NULL) {
   1493 		/* nsd no longer has a zone in memory */
   1494 		zone->soa_nsd_acquired = 0;
   1495 		zone->soa_disk_acquired = 0;
   1496 		xfrd_set_zone_state(zone, xfrd_zone_refreshing);
   1497 		xfrd_set_refresh_now(zone);
   1498 		return;
   1499 	}
   1500 	if(zone->soa_nsd_acquired && soa->serial == zone->soa_nsd.serial)
   1501 		return;
   1502 
   1503 	if(zone->soa_disk_acquired) {
   1504 		int cmp = compare_serial(ntohl(soa->serial), ntohl(zone->soa_disk.serial));
   1505 
   1506 		/* soa is from an update if serial equals soa_disk.serial or
   1507 		   serial is less than soa_disk.serial and the acquired time is
   1508 		   before the reload was first requested */
   1509 		if(!((cmp == 0) || (cmp < 0 && acquired != 0))) {
   1510 			goto zonefile;
   1511 		}
   1512 
   1513 		/* acquired time of an update may not match time registered in
   1514 		   in soa_disk_acquired as a refresh indicating the current
   1515 		   serial may have occurred before the reload finished */
   1516 		if(cmp == 0) {
   1517 			acquired = zone->soa_disk_acquired;
   1518 		}
   1519 
   1520 		/* soa in disk has been loaded in memory */
   1521 		{
   1522 			uint32_t soa_serial, soa_nsd_serial;
   1523 			soa_serial = ntohl(soa->serial);
   1524 			soa_nsd_serial = ntohl(zone->soa_nsd.serial);
   1525 			if (compare_serial(soa_serial, soa_nsd_serial) > 0)
   1526 				log_msg(LOG_INFO, "zone %s serial %"PRIu32" is updated to %"PRIu32,
   1527 					zone->apex_str, soa_nsd_serial, soa_serial);
   1528 			else
   1529 				log_msg(LOG_INFO, "zone %s serial is updated to %"PRIu32,
   1530 					zone->apex_str, soa_serial);
   1531 		}
   1532 		zone->soa_nsd = *soa;
   1533 		zone->soa_nsd_acquired = acquired;
   1534 		xfrd->write_zonefile_needed = 1;
   1535 		seconds_since_acquired =
   1536 			  xfrd_time() > zone->soa_disk_acquired
   1537 			? xfrd_time() - zone->soa_disk_acquired : 0;
   1538 
   1539 		if(seconds_since_acquired < bound_soa_disk_refresh(zone))
   1540 		{
   1541 			xfrd_set_zone_state(zone, xfrd_zone_ok);
   1542 		}
   1543 
   1544 		/* update refresh timers based on disk soa, unless there are
   1545 		   pending updates. i.e. serial != soa_disk.serial */
   1546 		if (cmp == 0) {
   1547 			/* reset exponential backoff, we got a normal timer now */
   1548 			zone->fresh_xfr_timeout = 0;
   1549 			if(seconds_since_acquired < bound_soa_disk_refresh(zone))
   1550 			{
   1551 				/* zone ok, wait for refresh time */
   1552 				zone->round_num = -1;
   1553 				xfrd_set_timer_refresh(zone);
   1554 			} else if(seconds_since_acquired < bound_soa_disk_expire(zone))
   1555 			{
   1556 				/* zone refreshing */
   1557 				xfrd_set_zone_state(zone, xfrd_zone_refreshing);
   1558 				xfrd_set_refresh_now(zone);
   1559 			}
   1560 			if(seconds_since_acquired >= bound_soa_disk_expire(zone))
   1561 			{
   1562 				/* zone expired */
   1563 				xfrd_set_zone_state(zone, xfrd_zone_expired);
   1564 				xfrd_set_refresh_now(zone);
   1565 			}
   1566 
   1567 			if(zone->soa_notified_acquired != 0 &&
   1568 				(zone->soa_notified.serial == 0 ||
   1569 				 compare_serial(ntohl(zone->soa_disk.serial),
   1570 				                ntohl(zone->soa_notified.serial)) >= 0))
   1571 			{	/* read was in response to this notification */
   1572 				zone->soa_notified_acquired = 0;
   1573 			}
   1574 			if(zone->soa_notified_acquired && zone->state == xfrd_zone_ok)
   1575 			{
   1576 				/* refresh because of notification */
   1577 				xfrd_set_zone_state(zone, xfrd_zone_refreshing);
   1578 				xfrd_set_refresh_now(zone);
   1579 			}
   1580 		}
   1581 		xfrd_send_notify(xfrd->notify_zones, zone->apex, &zone->soa_nsd);
   1582 		return;
   1583 	}
   1584 
   1585 zonefile:
   1586 	acquired = xfrd_time();
   1587 	/* user must have manually provided zone data */
   1588 	DEBUG(DEBUG_XFRD,1, (LOG_INFO,
   1589 		"xfrd: zone %s serial %u from zonefile. refreshing",
   1590 		zone->apex_str, (unsigned)ntohl(soa->serial)));
   1591 	zone->soa_nsd = *soa;
   1592 	zone->soa_disk = *soa;
   1593 	zone->soa_nsd_acquired = acquired;
   1594 	zone->soa_disk_acquired = acquired;
   1595 	if(zone->soa_notified_acquired != 0 &&
   1596 		(zone->soa_notified.serial == 0 ||
   1597 	   	compare_serial(ntohl(zone->soa_disk.serial),
   1598 			ntohl(zone->soa_notified.serial)) >= 0))
   1599 	{	/* user provided in response to this notification */
   1600 		zone->soa_notified_acquired = 0;
   1601 	}
   1602 	xfrd_set_zone_state(zone, xfrd_zone_refreshing);
   1603 	xfrd_set_refresh_now(zone);
   1604 	xfrd_send_notify(xfrd->notify_zones, zone->apex, &zone->soa_nsd);
   1605 }
   1606 
   1607 void
   1608 xfrd_send_expire_notification(xfrd_zone_type* zone)
   1609 {
   1610 	task_new_expire(xfrd->nsd->task[xfrd->nsd->mytask], xfrd->last_task,
   1611 		zone->apex, zone->state == xfrd_zone_expired);
   1612 	xfrd_set_reload_timeout();
   1613 }
   1614 
   1615 int
   1616 xfrd_udp_read_packet(buffer_type* packet, int fd, struct sockaddr* src,
   1617 	socklen_t* srclen)
   1618 {
   1619 	ssize_t received;
   1620 
   1621 	/* read the data */
   1622 	buffer_clear(packet);
   1623 	received = recvfrom(fd, buffer_begin(packet), buffer_remaining(packet),
   1624 		0, src, srclen);
   1625 	if(received == -1) {
   1626 		log_msg(LOG_ERR, "xfrd: recvfrom failed: %s",
   1627 			strerror(errno));
   1628 		return 0;
   1629 	}
   1630 	buffer_set_limit(packet, received);
   1631 	return 1;
   1632 }
   1633 
   1634 void
   1635 xfrd_udp_release(xfrd_zone_type* zone)
   1636 {
   1637 	assert(zone->udp_waiting == 0);
   1638 	if(zone->event_added)
   1639 		event_del(&zone->zone_handler);
   1640 	if(zone->zone_handler.ev_fd != -1) {
   1641 		close(zone->zone_handler.ev_fd);
   1642 	}
   1643 	zone->zone_handler.ev_fd = -1;
   1644 	zone->zone_handler_flags = 0;
   1645 	zone->event_added = 0;
   1646 	/* see if there are waiting zones */
   1647 	if(xfrd->udp_use_num == XFRD_MAX_UDP)
   1648 	{
   1649 		while(xfrd->udp_waiting_first) {
   1650 			/* snip off waiting list */
   1651 			xfrd_zone_type* wz = xfrd->udp_waiting_first;
   1652 			assert(wz->udp_waiting);
   1653 			wz->udp_waiting = 0;
   1654 			xfrd->udp_waiting_first = wz->udp_waiting_next;
   1655 			if(wz->udp_waiting_next)
   1656 				wz->udp_waiting_next->udp_waiting_prev = NULL;
   1657 			if(xfrd->udp_waiting_last == wz)
   1658 				xfrd->udp_waiting_last = NULL;
   1659 			/* see if this zone needs udp connection */
   1660 			if(wz->tcp_conn == -1) {
   1661 				int fd = xfrd_send_ixfr_request_udp(wz);
   1662 				if(fd != -1) {
   1663 					if(wz->event_added)
   1664 						event_del(&wz->zone_handler);
   1665 					memset(&wz->zone_handler, 0,
   1666 						sizeof(wz->zone_handler));
   1667 					event_set(&wz->zone_handler, fd,
   1668 						EV_READ|EV_TIMEOUT|EV_PERSIST,
   1669 						xfrd_handle_zone, wz);
   1670 					if(event_base_set(xfrd->event_base,
   1671 						&wz->zone_handler) != 0)
   1672 						log_msg(LOG_ERR, "cannot set event_base for ixfr");
   1673 					if(event_add(&wz->zone_handler, &wz->timeout) != 0)
   1674 						log_msg(LOG_ERR, "cannot add event for ixfr");
   1675 					wz->zone_handler_flags = EV_READ|EV_TIMEOUT|EV_PERSIST;
   1676 					wz->event_added = 1;
   1677 					return;
   1678 				} else {
   1679 					/* make this zone do something with
   1680 					 * this failure to act */
   1681 					xfrd_set_refresh_now(wz);
   1682 				}
   1683 			}
   1684 		}
   1685 	}
   1686 	/* no waiting zones */
   1687 	if(xfrd->udp_use_num > 0)
   1688 		xfrd->udp_use_num--;
   1689 }
   1690 
   1691 /** disable ixfr for master */
   1692 void
   1693 xfrd_disable_ixfr(xfrd_zone_type* zone)
   1694 {
   1695 	if(!(zone->master->ixfr_disabled &&
   1696 		(zone->master->ixfr_disabled + XFRD_NO_IXFR_CACHE) <= time(NULL))) {
   1697 		/* start new round, with IXFR disabled */
   1698 		zone->round_num = 0;
   1699 		zone->next_master = zone->master_num;
   1700 	}
   1701 	zone->master->ixfr_disabled = time(NULL);
   1702 }
   1703 
   1704 static void
   1705 xfrd_udp_read(xfrd_zone_type* zone)
   1706 {
   1707 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s read udp data", zone->apex_str));
   1708 	if(!xfrd_udp_read_packet(xfrd->packet, zone->zone_handler.ev_fd,
   1709 		NULL, NULL)) {
   1710 		zone->master->bad_xfr_count++;
   1711 		if (zone->master->bad_xfr_count > 2) {
   1712 			xfrd_disable_ixfr(zone);
   1713 			zone->master->bad_xfr_count = 0;
   1714 		}
   1715 		/* drop packet */
   1716 		xfrd_udp_release(zone);
   1717 		/* query next server */
   1718 		xfrd_make_request(zone);
   1719 		return;
   1720 	}
   1721 	switch(xfrd_handle_received_xfr_packet(zone, xfrd->packet)) {
   1722 		case xfrd_packet_tcp:
   1723 			xfrd_set_timer(zone, xfrd->tcp_set->tcp_timeout);
   1724 			xfrd_udp_release(zone);
   1725 			xfrd_tcp_obtain(xfrd->tcp_set, zone);
   1726 			break;
   1727 		case xfrd_packet_transfer:
   1728 			if(zone->zone_options->pattern->multi_primary_check) {
   1729 				xfrd_udp_release(zone);
   1730 				xfrd_make_request(zone);
   1731 				break;
   1732 			}
   1733 			/* fallthrough */
   1734 		case xfrd_packet_newlease:
   1735 			/* nothing more to do */
   1736 			assert(zone->round_num == -1);
   1737 			xfrd_udp_release(zone);
   1738 			break;
   1739 		case xfrd_packet_notimpl:
   1740 			xfrd_disable_ixfr(zone);
   1741 			/* drop packet */
   1742 			xfrd_udp_release(zone);
   1743 			/* query next server */
   1744 			xfrd_make_request(zone);
   1745 			break;
   1746 		case xfrd_packet_more:
   1747 		case xfrd_packet_drop:
   1748 			/* drop packet */
   1749 			xfrd_udp_release(zone);
   1750 			/* query next server */
   1751 			xfrd_make_request(zone);
   1752 			break;
   1753 		case xfrd_packet_bad:
   1754 		default:
   1755 			zone->master->bad_xfr_count++;
   1756 			if (zone->master->bad_xfr_count > 2) {
   1757 				xfrd_disable_ixfr(zone);
   1758 				zone->master->bad_xfr_count = 0;
   1759 			}
   1760 			/* drop packet */
   1761 			xfrd_udp_release(zone);
   1762 			/* query next server */
   1763 			xfrd_make_request(zone);
   1764 			break;
   1765 	}
   1766 }
   1767 
   1768 int
   1769 xfrd_send_udp(struct acl_options* acl, buffer_type* packet,
   1770 	struct acl_options* ifc)
   1771 {
   1772 #ifdef INET6
   1773 	struct sockaddr_storage to;
   1774 #else
   1775 	struct sockaddr_in to;
   1776 #endif /* INET6 */
   1777 	int fd, family;
   1778 
   1779 	/* this will set the remote port to acl->port or TCP_PORT */
   1780 	socklen_t to_len = xfrd_acl_sockaddr_to(acl, &to);
   1781 
   1782 	/* get the address family of the remote host */
   1783 	if(acl->is_ipv6) {
   1784 #ifdef INET6
   1785 		family = PF_INET6;
   1786 #else
   1787 		return -1;
   1788 #endif /* INET6 */
   1789 	} else {
   1790 		family = PF_INET;
   1791 	}
   1792 
   1793 	fd = socket(family, SOCK_DGRAM, IPPROTO_UDP);
   1794 	if(fd == -1) {
   1795 		log_msg(LOG_ERR, "xfrd: cannot create udp socket to %s: %s",
   1796 			acl->ip_address_spec, strerror(errno));
   1797 		return -1;
   1798 	}
   1799 
   1800 	/* bind it */
   1801 	if (!xfrd_bind_local_interface(fd, ifc, acl, 0)) {
   1802 		log_msg(LOG_ERR, "xfrd: cannot bind outgoing interface '%s' to "
   1803 				 "udp socket: No matching ip addresses found",
   1804 			ifc->ip_address_spec);
   1805 		close(fd);
   1806 		return -1;
   1807 	}
   1808 
   1809 	/* send it (udp) */
   1810 	if(sendto(fd,
   1811 		buffer_current(packet),
   1812 		buffer_remaining(packet), 0,
   1813 		(struct sockaddr*)&to, to_len) == -1)
   1814 	{
   1815 		log_msg(LOG_ERR, "xfrd: sendto %s failed %s",
   1816 			acl->ip_address_spec, strerror(errno));
   1817 		close(fd);
   1818 		return -1;
   1819 	}
   1820 	return fd;
   1821 }
   1822 
   1823 int
   1824 xfrd_bind_local_interface(int sockd, struct acl_options* ifc,
   1825 	struct acl_options* acl, int tcp)
   1826 {
   1827 #ifdef SO_LINGER
   1828 	struct linger linger = {1, 0};
   1829 #endif
   1830 	socklen_t frm_len;
   1831 #ifdef INET6
   1832 	struct sockaddr_storage frm;
   1833 #else
   1834 	struct sockaddr_in frm;
   1835 #endif /* INET6 */
   1836 	int ret = 1;
   1837 
   1838 	if (!ifc) /* no outgoing interface set */
   1839 		return 1;
   1840 
   1841 	while (ifc) {
   1842 		if (ifc->is_ipv6 != acl->is_ipv6) {
   1843 			/* check if we have a matching address family */
   1844 			ifc = ifc->next;
   1845 			continue;
   1846 		}
   1847 
   1848 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: bind() %s to %s socket",
   1849 			ifc->ip_address_spec, tcp? "tcp":"udp"));
   1850 		ret = 0;
   1851 		frm_len = xfrd_acl_sockaddr_frm(ifc, &frm);
   1852 
   1853 		if (tcp) {
   1854 #ifdef SO_REUSEADDR
   1855 			if (setsockopt(sockd, SOL_SOCKET, SO_REUSEADDR, &frm,
   1856 				frm_len) < 0) {
   1857 				VERBOSITY(2, (LOG_WARNING, "xfrd: setsockopt "
   1858 			     "SO_REUSEADDR failed: %s", strerror(errno)));
   1859 			}
   1860 #else
   1861 			VERBOSITY(2, (LOG_WARNING, "xfrd: setsockopt SO_REUSEADDR "
   1862 			     "failed: SO_REUSEADDR not defined"));
   1863 #endif /* SO_REUSEADDR */
   1864 
   1865 			if (ifc->port != 0) {
   1866 #ifdef SO_LINGER
   1867 				if (setsockopt(sockd, SOL_SOCKET, SO_LINGER,
   1868 					&linger, sizeof(linger)) < 0) {
   1869 					VERBOSITY(2, (LOG_WARNING, "xfrd: setsockopt "
   1870 				     "SO_LINGER failed: %s", strerror(errno)));
   1871 				}
   1872 #else
   1873 				VERBOSITY(2, (LOG_WARNING, "xfrd: setsockopt SO_LINGER "
   1874 					"failed: SO_LINGER not defined"));
   1875 #endif /* SO_LINGER */
   1876 			}
   1877 		}
   1878 
   1879 		/* found one */
   1880 		if(bind(sockd, (struct sockaddr*)&frm, frm_len) >= 0) {
   1881 			DEBUG(DEBUG_XFRD,2, (LOG_INFO, "xfrd: bind() %s to %s "
   1882 						       "socket was successful",
   1883 			ifc->ip_address_spec, tcp? "tcp":"udp"));
   1884 			return 1;
   1885 		}
   1886 
   1887 		DEBUG(DEBUG_XFRD,2, (LOG_INFO, "xfrd: bind() %s to %s socket"
   1888 					       "failed: %s",
   1889 			ifc->ip_address_spec, tcp? "tcp":"udp",
   1890 			strerror(errno)));
   1891 
   1892 		log_msg(LOG_WARNING, "xfrd: could not bind source address:port to "
   1893 		     "socket: %s", strerror(errno));
   1894 		/* try another */
   1895 		ifc = ifc->next;
   1896 	}
   1897 	return ret;
   1898 }
   1899 
   1900 void
   1901 xfrd_tsig_sign_request(buffer_type* packet, tsig_record_type* tsig,
   1902 	struct acl_options* acl)
   1903 {
   1904 	tsig_algorithm_type* algo;
   1905 	assert(acl->key_options && acl->key_options->tsig_key);
   1906 	algo = tsig_get_algorithm_by_name(acl->key_options->algorithm);
   1907 	if(!algo) {
   1908 		log_msg(LOG_ERR, "tsig unknown algorithm %s",
   1909 			acl->key_options->algorithm);
   1910 		return;
   1911 	}
   1912 	assert(algo);
   1913 	tsig_init_record(tsig, algo, acl->key_options->tsig_key);
   1914 	tsig_init_query(tsig, ID(packet));
   1915 	tsig_prepare(tsig);
   1916 	tsig_update(tsig, packet, buffer_position(packet));
   1917 	tsig_sign(tsig);
   1918 	tsig_append_rr(tsig, packet);
   1919 	ARCOUNT_SET(packet, ARCOUNT(packet) + 1);
   1920 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "appending tsig to packet"));
   1921 	/* prepare for validating tsigs */
   1922 	tsig_prepare(tsig);
   1923 }
   1924 
   1925 static int
   1926 xfrd_send_ixfr_request_udp(xfrd_zone_type* zone)
   1927 {
   1928 	int fd, apex_compress = 0;
   1929 
   1930 	/* make sure we have a master to query the ixfr request to */
   1931 	assert(zone->master);
   1932 
   1933 	if(zone->tcp_conn != -1) {
   1934 		/* tcp is using the zone_handler.fd */
   1935 		log_msg(LOG_ERR, "xfrd: %s tried to send udp whilst tcp engaged",
   1936 			zone->apex_str);
   1937 		return -1;
   1938 	}
   1939 	xfrd_setup_packet(xfrd->packet, TYPE_IXFR, CLASS_IN, zone->apex,
   1940 		qid_generate(), &apex_compress);
   1941 	zone->query_id = ID(xfrd->packet);
   1942 	xfrd_prepare_zone_xfr(zone, TYPE_IXFR);
   1943 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "sent query with ID %d", zone->query_id));
   1944         NSCOUNT_SET(xfrd->packet, 1);
   1945 	xfrd_write_soa_buffer(xfrd->packet, zone->apex, &zone->soa_disk,
   1946 		apex_compress);
   1947 	/* if we have tsig keys, sign the ixfr query */
   1948 	if(zone->master->key_options && zone->master->key_options->tsig_key) {
   1949 		xfrd_tsig_sign_request(
   1950 			xfrd->packet, &zone->latest_xfr->tsig, zone->master);
   1951 	}
   1952 	buffer_flip(xfrd->packet);
   1953 	xfrd_set_timer(zone, XFRD_UDP_TIMEOUT);
   1954 
   1955 	if((fd = xfrd_send_udp(zone->master, xfrd->packet,
   1956 		zone->zone_options->pattern->outgoing_interface)) == -1)
   1957 		return -1;
   1958 
   1959 	DEBUG(DEBUG_XFRD,1, (LOG_INFO,
   1960 		"xfrd sent udp request for ixfr=%u for zone %s to %s",
   1961 		(unsigned)ntohl(zone->soa_disk.serial),
   1962 		zone->apex_str, zone->master->ip_address_spec));
   1963 	return fd;
   1964 }
   1965 
   1966 static int xfrd_parse_soa_info(buffer_type* packet, xfrd_soa_type* soa)
   1967 {
   1968 	if(!buffer_available(packet, 10))
   1969 		return 0;
   1970 	soa->type = htons(buffer_read_u16(packet));
   1971 	soa->klass = htons(buffer_read_u16(packet));
   1972 	soa->ttl = htonl(buffer_read_u32(packet));
   1973 	if(ntohs(soa->type) != TYPE_SOA || ntohs(soa->klass) != CLASS_IN)
   1974 	{
   1975 		return 0;
   1976 	}
   1977 
   1978 	if(!buffer_available(packet, buffer_read_u16(packet)) /* rdata length */ ||
   1979 		!(soa->prim_ns[0] = dname_make_wire_from_packet(soa->prim_ns+1, packet, 1)) ||
   1980 		!(soa->email[0] = dname_make_wire_from_packet(soa->email+1, packet, 1)))
   1981 	{
   1982 		return 0;
   1983 	}
   1984 	soa->serial = htonl(buffer_read_u32(packet));
   1985 	soa->refresh = htonl(buffer_read_u32(packet));
   1986 	soa->retry = htonl(buffer_read_u32(packet));
   1987 	soa->expire = htonl(buffer_read_u32(packet));
   1988 	soa->minimum = htonl(buffer_read_u32(packet));
   1989 
   1990 	return 1;
   1991 }
   1992 
   1993 
   1994 /*
   1995  * Check the RRs in an IXFR/AXFR reply.
   1996  * returns 0 on error, 1 on correct parseable packet.
   1997  * done = 1 if the last SOA in an IXFR/AXFR has been seen.
   1998  * soa then contains that soa info.
   1999  * (soa contents is modified by the routine)
   2000  */
   2001 static int
   2002 xfrd_xfr_check_rrs(xfrd_zone_type* zone, buffer_type* packet, size_t count,
   2003 	int *done, xfrd_soa_type* soa, region_type* temp)
   2004 {
   2005 	/* first RR has already been checked */
   2006 	const struct nsd_type_descriptor *descriptor;
   2007 	uint32_t tmp_serial = 0;
   2008 	uint16_t type, rrlen;
   2009 	size_t i, soapos, mempos;
   2010 	const dname_type* dname;
   2011 	struct rr* rr;
   2012 	int32_t code;
   2013 	domain_table_type* owners;
   2014 
   2015 	for(i=0; i<count; ++i,++zone->latest_xfr->msg_rr_count)
   2016 	{
   2017 		if (*done) {
   2018 			DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr has "
   2019 				"trailing garbage", zone->apex_str));
   2020 			return 0;
   2021 		}
   2022 		region_free_all(temp);
   2023 		owners = domain_table_create(temp);
   2024 		/* check the dname for errors */
   2025 		dname = dname_make_from_packet(temp, packet, 1, 1);
   2026 		if(!dname) {
   2027 			DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr unable "
   2028 				"to parse owner name", zone->apex_str));
   2029 			return 0;
   2030 		}
   2031 		if(!buffer_available(packet, 10)) {
   2032 			DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr hdr "
   2033 				"too small", zone->apex_str));
   2034 			return 0;
   2035 		}
   2036 		soapos = buffer_position(packet);
   2037 		type = buffer_read_u16(packet);
   2038 		(void)buffer_read_u16(packet); /* class */
   2039 		(void)buffer_read_u32(packet); /* ttl */
   2040 		rrlen = buffer_read_u16(packet);
   2041 		if(!buffer_available(packet, rrlen)) {
   2042 			DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr pkt "
   2043 				"too small", zone->apex_str));
   2044 			return 0;
   2045 		}
   2046 		mempos = buffer_position(packet);
   2047 
   2048 		descriptor = nsd_type_descriptor(type);
   2049 		code = descriptor->read_rdata(owners, rrlen, packet, &rr);
   2050 		if(code < 0) {
   2051 			DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr unable "
   2052 				"to parse rdata %s %s %s", zone->apex_str,
   2053 				dname_to_string(dname,0),
   2054 				rrtype_to_string(type),
   2055 				read_rdata_fail_str(code)));
   2056 			return 0;
   2057 		}
   2058 		if(type == TYPE_SOA) {
   2059 			/* check the SOAs */
   2060 			buffer_set_position(packet, soapos);
   2061 			if(!xfrd_parse_soa_info(packet, soa)) {
   2062 				DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr "
   2063 					"unable to parse soainfo", zone->apex_str));
   2064 				return 0;
   2065 			}
   2066 			if(zone->latest_xfr->msg_rr_count == 1 &&
   2067 				ntohl(soa->serial) != zone->latest_xfr->msg_new_serial) {
   2068 				/* 2nd RR is SOA with lower serial, this is an IXFR */
   2069 				zone->latest_xfr->msg_is_ixfr = 1;
   2070 				if(!zone->soa_disk_acquired) {
   2071 					DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr "
   2072 						"got ixfr but need axfr", zone->apex_str));
   2073 					return 0; /* got IXFR but need AXFR */
   2074 				}
   2075 				if(ntohl(soa->serial) != ntohl(zone->soa_disk.serial)) {
   2076 					DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr "
   2077 						"bad start serial", zone->apex_str));
   2078 					return 0; /* bad start serial in IXFR */
   2079 				}
   2080 				zone->latest_xfr->msg_old_serial = ntohl(soa->serial);
   2081 				tmp_serial = ntohl(soa->serial);
   2082 			}
   2083 			else if(ntohl(soa->serial) == zone->latest_xfr->msg_new_serial) {
   2084 				/* saw another SOA of new serial. */
   2085 				if(zone->latest_xfr->msg_is_ixfr == 1) {
   2086 					zone->latest_xfr->msg_is_ixfr = 2; /* seen middle SOA in ixfr */
   2087 				} else {
   2088 					/* 2nd SOA for AXFR or 3rd newSOA for IXFR */
   2089 					*done = 1;
   2090 				}
   2091 			}
   2092 			else if (zone->latest_xfr->msg_is_ixfr) {
   2093 				/* some additional checks */
   2094 				if(ntohl(soa->serial) > zone->latest_xfr->msg_new_serial) {
   2095 					DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr "
   2096 						"bad middle serial", zone->apex_str));
   2097 					return 0; /* bad middle serial in IXFR */
   2098 				}
   2099 				if(ntohl(soa->serial) < tmp_serial) {
   2100 					DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr "
   2101 						"serial decreasing not allowed", zone->apex_str));
   2102 					return 0; /* middle serial decreases in IXFR */
   2103 				}
   2104 				/* serial ok, update tmp serial */
   2105 				tmp_serial = ntohl(soa->serial);
   2106 			}
   2107 		}
   2108 		buffer_set_position(packet, mempos);
   2109 		buffer_skip(packet, rrlen);
   2110 	}
   2111 	/* packet seems to have a valid DNS RR structure */
   2112 	return 1;
   2113 }
   2114 
   2115 static int
   2116 xfrd_xfr_process_tsig(xfrd_zone_type* zone, buffer_type* packet)
   2117 {
   2118 	int have_tsig = 0;
   2119 	assert(zone && zone->master && zone->master->key_options
   2120 		&& zone->master->key_options->tsig_key && packet);
   2121 	if(!tsig_find_rr(&zone->latest_xfr->tsig, packet)) {
   2122 		log_msg(LOG_ERR, "xfrd: zone %s, from %s: malformed tsig RR",
   2123 			zone->apex_str, zone->master->ip_address_spec);
   2124 		return 0;
   2125 	}
   2126 	if(zone->latest_xfr->tsig.status == TSIG_OK) {
   2127 		have_tsig = 1;
   2128 		if (zone->latest_xfr->tsig.error_code != TSIG_ERROR_NOERROR) {
   2129 			log_msg(LOG_ERR, "xfrd: zone %s, from %s: tsig error "
   2130 				"(%s)", zone->apex_str,
   2131 				zone->master->ip_address_spec,
   2132 				tsig_error(zone->latest_xfr->tsig.error_code));
   2133 		}
   2134 	}
   2135 	if(have_tsig) {
   2136 		/* strip the TSIG resource record off... */
   2137 		buffer_set_limit(packet, zone->latest_xfr->tsig.position);
   2138 		ARCOUNT_SET(packet, ARCOUNT(packet) - 1);
   2139 	}
   2140 
   2141 	/* keep running the TSIG hash */
   2142 	tsig_update(&zone->latest_xfr->tsig, packet, buffer_limit(packet));
   2143 	if(have_tsig) {
   2144 		if (!tsig_verify(&zone->latest_xfr->tsig)) {
   2145 			log_msg(LOG_ERR, "xfrd: zone %s, from %s: bad tsig signature",
   2146 				zone->apex_str, zone->master->ip_address_spec);
   2147 			return 0;
   2148 		}
   2149 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s, from %s: good tsig signature",
   2150 			zone->apex_str, zone->master->ip_address_spec));
   2151 		/* prepare for next tsigs */
   2152 		tsig_prepare(&zone->latest_xfr->tsig);
   2153 	}
   2154 	else if(zone->latest_xfr->tsig.updates_since_last_prepare > XFRD_TSIG_MAX_UNSIGNED) {
   2155 		/* we allow a number of non-tsig signed packets */
   2156 		log_msg(LOG_INFO, "xfrd: zone %s, from %s: too many consecutive "
   2157 			"packets without TSIG", zone->apex_str,
   2158 			zone->master->ip_address_spec);
   2159 		return 0;
   2160 	}
   2161 
   2162 	if(!have_tsig && zone->latest_xfr->msg_seq_nr == 0) {
   2163 		log_msg(LOG_ERR, "xfrd: zone %s, from %s: no tsig in first packet of reply",
   2164 			zone->apex_str, zone->master->ip_address_spec);
   2165 		return 0;
   2166 	}
   2167 	return 1;
   2168 }
   2169 
   2170 /* parse the received packet. returns xfrd packet result code. */
   2171 static enum xfrd_packet_result
   2172 xfrd_parse_received_xfr_packet(xfrd_zone_type* zone, buffer_type* packet,
   2173 	xfrd_soa_type* soa)
   2174 {
   2175 	size_t rr_count;
   2176 	size_t qdcount = QDCOUNT(packet);
   2177 	size_t ancount = ANCOUNT(packet), ancount_todo;
   2178 	size_t nscount = NSCOUNT(packet);
   2179 	int done = 0;
   2180 	region_type* tempregion = NULL;
   2181 	assert(zone->master);
   2182 
   2183 	/* has to be axfr / ixfr reply */
   2184 	if(!buffer_available(packet, QHEADERSZ)) {
   2185 		log_msg(LOG_INFO, "packet too small");
   2186 		return xfrd_packet_bad;
   2187 	}
   2188 
   2189 	/* only check ID in first response message. Could also check that
   2190 	 * AA bit and QR bit are set, but not needed.
   2191 	 */
   2192 	DEBUG(DEBUG_XFRD,2, (LOG_INFO,
   2193 		"got query with ID %d and %d needed", ID(packet), zone->query_id));
   2194 	if(ID(packet) != zone->query_id) {
   2195 		log_msg(LOG_ERR, "xfrd: zone %s received bad query id from %s, "
   2196 				 "dropped",
   2197 			zone->apex_str, zone->master->ip_address_spec);
   2198 		return xfrd_packet_bad;
   2199 	}
   2200 	/* check RCODE in all response messages */
   2201 	if(RCODE(packet) != RCODE_OK) {
   2202 		/* for IXFR failures, do not log unless higher verbosity */
   2203 		if(!(verbosity < 3 && (RCODE(packet) == RCODE_IMPL ||
   2204 			RCODE(packet) == RCODE_FORMAT) &&
   2205 			!zone->master->ixfr_disabled &&
   2206 			!zone->master->use_axfr_only)) {
   2207 			log_msg(LOG_ERR, "xfrd: zone %s received error code %s from "
   2208 				 	"%s",
   2209 				zone->apex_str, rcode2str(RCODE(packet)),
   2210 				zone->master->ip_address_spec);
   2211 		}
   2212 		if (RCODE(packet) == RCODE_IMPL ||
   2213 			RCODE(packet) == RCODE_FORMAT) {
   2214 			return xfrd_packet_notimpl;
   2215 		}
   2216 		if (RCODE(packet) != RCODE_NOTAUTH) {
   2217 			/* RFC 2845: If NOTAUTH, client should do TSIG checking */
   2218 			return xfrd_packet_drop;
   2219 		}
   2220 	}
   2221 	/* check TSIG */
   2222 	if(zone->master->key_options) {
   2223 		if(!xfrd_xfr_process_tsig(zone, packet)) {
   2224 			DEBUG(DEBUG_XFRD,1, (LOG_ERR, "dropping xfr reply due "
   2225 				"to bad TSIG"));
   2226 			return xfrd_packet_bad;
   2227 		}
   2228 	}
   2229 	if (RCODE(packet) == RCODE_NOTAUTH) {
   2230 		return xfrd_packet_drop;
   2231 	}
   2232 
   2233 	buffer_skip(packet, QHEADERSZ);
   2234 	if(qdcount > 64 || ancount > 65530 || nscount > 65530) {
   2235 		/* 0 or 1 question section rr, and 64k limits other counts */
   2236 		DEBUG(DEBUG_XFRD,1, (LOG_ERR, "dropping xfr reply, impossibly "
   2237 			"high record count"));
   2238 		return xfrd_packet_bad;
   2239 	}
   2240 
   2241 	/* skip question section */
   2242 	for(rr_count = 0; rr_count < qdcount; ++rr_count) {
   2243 		if (!packet_skip_rr(packet, 1)) {
   2244 			log_msg(LOG_ERR, "xfrd: zone %s, from %s: bad RR in "
   2245 					 		 "question section",
   2246 				zone->apex_str, zone->master->ip_address_spec);
   2247 			return xfrd_packet_bad;
   2248 		}
   2249 	}
   2250 	if(zone->latest_xfr->msg_rr_count == 0 && ancount == 0) {
   2251 		if(zone->tcp_conn == -1 && TC(packet)) {
   2252 			DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: TC flagged"));
   2253 			return xfrd_packet_tcp;
   2254 		}
   2255 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: too short xfr packet: no "
   2256 					       			   "answer"));
   2257 		/* if IXFR is unknown, fallback to AXFR (if allowed) */
   2258 		if (nscount == 1) {
   2259 			if(!packet_skip_dname(packet) || !xfrd_parse_soa_info(packet, soa)) {
   2260 				DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s, from %s: "
   2261 					"no SOA begins authority section",
   2262 					zone->apex_str, zone->master->ip_address_spec));
   2263 				return xfrd_packet_bad;
   2264 			}
   2265 			return xfrd_packet_notimpl;
   2266 		}
   2267 		return xfrd_packet_bad;
   2268 	}
   2269 	ancount_todo = ancount;
   2270 
   2271 	tempregion = region_create(xalloc, free);
   2272 	if(zone->latest_xfr->msg_rr_count == 0) {
   2273 		const dname_type* soaname = dname_make_from_packet(tempregion,
   2274 			packet, 1, 1);
   2275 		if(!soaname) { /* parse failure */
   2276 			DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s, from %s: "
   2277 				"parse error in SOA record",
   2278 				zone->apex_str, zone->master->ip_address_spec));
   2279 			region_destroy(tempregion);
   2280 			return xfrd_packet_bad;
   2281 		}
   2282 		if(dname_compare(soaname, zone->apex) != 0) { /* wrong name */
   2283 			DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s, from %s: "
   2284 				"wrong SOA record",
   2285 				zone->apex_str, zone->master->ip_address_spec));
   2286 			region_destroy(tempregion);
   2287 			return xfrd_packet_bad;
   2288 		}
   2289 
   2290 		/* parse the first RR, see if it is a SOA */
   2291 		if(!xfrd_parse_soa_info(packet, soa))
   2292 		{
   2293 			DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s, from %s: "
   2294 						      "bad SOA rdata",
   2295 				zone->apex_str, zone->master->ip_address_spec));
   2296 			region_destroy(tempregion);
   2297 			return xfrd_packet_bad;
   2298 		}
   2299 		if(zone->soa_disk_acquired != 0 &&
   2300 			zone->state != xfrd_zone_expired /* if expired - accept anything */ &&
   2301 			compare_serial(ntohl(soa->serial), ntohl(zone->soa_disk.serial)) < 0) {
   2302                         DEBUG(DEBUG_XFRD,1, (LOG_INFO,
   2303                                 "xfrd: zone %s ignoring old serial (%u/%u) from %s",
   2304                                 zone->apex_str, ntohl(zone->soa_disk.serial), ntohl(soa->serial), zone->master->ip_address_spec));
   2305                         VERBOSITY(1, (LOG_INFO,
   2306                                 "xfrd: zone %s ignoring old serial (%u/%u) from %s",
   2307                                 zone->apex_str, ntohl(zone->soa_disk.serial), ntohl(soa->serial), zone->master->ip_address_spec));
   2308 			region_destroy(tempregion);
   2309 			return xfrd_packet_bad;
   2310 		}
   2311 		if(zone->soa_disk_acquired != 0 && zone->soa_disk.serial == soa->serial) {
   2312 			DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s got "
   2313 						       "update indicating "
   2314 						       "current serial",
   2315 				zone->apex_str));
   2316 			/* (even if notified) the lease on the current soa is renewed */
   2317 			zone->soa_disk_acquired = xfrd_time();
   2318 			if(zone->soa_nsd.serial == soa->serial)
   2319 				zone->soa_nsd_acquired = xfrd_time();
   2320 			xfrd_set_zone_state(zone, xfrd_zone_ok);
   2321  			DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s is ok",
   2322 				zone->apex_str));
   2323 			if(zone->zone_options->pattern->multi_primary_check) {
   2324 				region_destroy(tempregion);
   2325 				return xfrd_packet_drop;
   2326 			}
   2327 			if(zone->soa_notified_acquired == 0) {
   2328 				/* not notified or anything, so stop asking around */
   2329 				zone->round_num = -1; /* next try start a new round */
   2330 				xfrd_set_timer_refresh(zone);
   2331 				region_destroy(tempregion);
   2332 				return xfrd_packet_newlease;
   2333 			}
   2334 			/* try next master */
   2335 			region_destroy(tempregion);
   2336 			return xfrd_packet_drop;
   2337 		}
   2338 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "IXFR reply has ok serial (have \
   2339 %u, reply %u).", (unsigned)zone->soa_disk_acquired ? ntohl(zone->soa_disk.serial) : 0, (unsigned)ntohl(soa->serial)));
   2340 		/* serial is newer than soa_disk */
   2341 		if(ancount == 1) {
   2342 			/* single record means it is like a notify */
   2343 			(void)xfrd_handle_incoming_notify(zone, soa);
   2344 		}
   2345 		else if(zone->soa_notified_acquired && zone->soa_notified.serial &&
   2346 			compare_serial(ntohl(zone->soa_notified.serial), ntohl(soa->serial)) < 0) {
   2347 			/* this AXFR/IXFR notifies me that an even newer serial exists */
   2348 			zone->soa_notified.serial = soa->serial;
   2349 		}
   2350 		zone->latest_xfr->msg_new_serial = ntohl(soa->serial);
   2351 		zone->latest_xfr->msg_rr_count = 1;
   2352 		zone->latest_xfr->msg_is_ixfr = 0;
   2353 		if(zone->soa_disk_acquired)
   2354 			zone->latest_xfr->msg_old_serial = ntohl(zone->soa_disk.serial);
   2355 		else zone->latest_xfr->msg_old_serial = 0;
   2356 		ancount_todo = ancount - 1;
   2357 	}
   2358 
   2359 	if(zone->tcp_conn == -1 && TC(packet)) {
   2360 		DEBUG(DEBUG_XFRD,1, (LOG_INFO,
   2361 			"xfrd: zone %s received TC from %s. retry tcp.",
   2362 			zone->apex_str, zone->master->ip_address_spec));
   2363 		region_destroy(tempregion);
   2364 		return xfrd_packet_tcp;
   2365 	}
   2366 
   2367 	if(zone->tcp_conn == -1 && ancount < 2) {
   2368 		/* too short to be a real ixfr/axfr data transfer: need at */
   2369 		/* least two RRs in the answer section. */
   2370 		/* The serial is newer, so try tcp to this master. */
   2371 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: udp reply is short. Try "
   2372 					       			   "tcp anyway."));
   2373 		region_destroy(tempregion);
   2374 		return xfrd_packet_tcp;
   2375 	}
   2376 
   2377 	if(!xfrd_xfr_check_rrs(zone, packet, ancount_todo, &done, soa,
   2378 		tempregion))
   2379 	{
   2380 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s sent bad xfr "
   2381 					       			   "reply.", zone->apex_str));
   2382 		region_destroy(tempregion);
   2383 		return xfrd_packet_bad;
   2384 	}
   2385 	region_destroy(tempregion);
   2386 	if(zone->tcp_conn == -1 && done == 0) {
   2387 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: udp reply incomplete"));
   2388 		return xfrd_packet_bad;
   2389 	}
   2390 	if(done == 0)
   2391 		return xfrd_packet_more;
   2392 	if(zone->master->key_options) {
   2393 		if(zone->latest_xfr->tsig.updates_since_last_prepare != 0) {
   2394 			log_msg(LOG_INFO, "xfrd: last packet of reply has no "
   2395 					 		  "TSIG");
   2396 			return xfrd_packet_bad;
   2397 		}
   2398 	}
   2399 	return xfrd_packet_transfer;
   2400 }
   2401 
   2402 const char*
   2403 xfrd_pretty_time(time_t v)
   2404 {
   2405 	struct tm* tm = localtime(&v);
   2406 	static char buf[64];
   2407 	if(!strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", tm))
   2408 		snprintf(buf, sizeof(buf), "strftime-err-%u", (unsigned)v);
   2409 	return buf;
   2410 }
   2411 
   2412 static void
   2413 xfrd_free_zone_xfr(xfrd_zone_type *zone, xfrd_xfr_type *xfr)
   2414 {
   2415 	if(xfr == zone->latest_xfr) {
   2416 		assert(xfr->next == NULL);
   2417 		if((zone->latest_xfr = xfr->prev) != NULL)
   2418 			zone->latest_xfr->next = NULL;
   2419 	} else {
   2420 		if(xfr->next != NULL)
   2421 			xfr->next->prev = xfr->prev;
   2422 		if(xfr->prev != NULL)
   2423 			xfr->prev->next = xfr->next;
   2424 	}
   2425 	tsig_delete_record(&xfr->tsig, xfrd->region);
   2426 	region_recycle(xfrd->region, xfr, sizeof(*xfr));
   2427 }
   2428 
   2429 void
   2430 xfrd_delete_zone_xfr(xfrd_zone_type *zone, xfrd_xfr_type *xfr)
   2431 {
   2432 	if(xfr->acquired != 0 || xfr->msg_seq_nr != 0) {
   2433 		xfrd_unlink_xfrfile(xfrd->nsd, xfr->xfrfilenumber);
   2434 	}
   2435 	xfrd_free_zone_xfr(zone, xfr);
   2436 }
   2437 
   2438 xfrd_xfr_type *
   2439 xfrd_prepare_zone_xfr(xfrd_zone_type *zone, uint16_t query_type)
   2440 {
   2441 	xfrd_xfr_type *xfr;
   2442 
   2443 	/* old transfer needs to be removed still? */
   2444 	if(zone->latest_xfr != NULL && !zone->latest_xfr->acquired) {
   2445 		xfrd_delete_zone_xfr(zone, zone->latest_xfr);
   2446 	}
   2447 
   2448 	xfr = region_alloc_zero(xfrd->region, sizeof(*xfr));
   2449 	if((xfr->prev = zone->latest_xfr) != NULL) {
   2450 		xfr->prev->next = xfr;
   2451 	}
   2452 	tsig_create_record_custom(&xfr->tsig, NULL, 0, 0, 4);
   2453 	zone->latest_xfr = xfr;
   2454 	xfr->query_type = query_type;
   2455 
   2456 	return xfr;
   2457 }
   2458 
   2459 enum xfrd_packet_result
   2460 xfrd_handle_received_xfr_packet(xfrd_zone_type* zone, buffer_type* packet)
   2461 {
   2462 	xfrd_soa_type soa;
   2463 	enum xfrd_packet_result res;
   2464         uint64_t xfrfile_size;
   2465 	assert(zone->latest_xfr);
   2466 
   2467 	/* parse and check the packet - see if it ends the xfr */
   2468 	switch((res=xfrd_parse_received_xfr_packet(zone, packet, &soa)))
   2469 	{
   2470 		case xfrd_packet_more:
   2471 		case xfrd_packet_transfer:
   2472 			/* continue with commit */
   2473 			break;
   2474 		case xfrd_packet_newlease:
   2475 			return xfrd_packet_newlease;
   2476 		case xfrd_packet_tcp:
   2477 			return xfrd_packet_tcp;
   2478 		case xfrd_packet_notimpl:
   2479 		case xfrd_packet_bad:
   2480 		case xfrd_packet_drop:
   2481 		default:
   2482 		{
   2483 			/* rollback */
   2484 			if(zone->latest_xfr->msg_seq_nr > 0) {
   2485 				/* do not process xfr - if only one part simply ignore it. */
   2486 				/* delete file with previous parts of commit */
   2487 				xfrd_unlink_xfrfile(xfrd->nsd, zone->latest_xfr->xfrfilenumber);
   2488 				VERBOSITY(1, (LOG_INFO, "xfrd: zone %s "
   2489 					"reverted transfer %u from %s",
   2490 					zone->apex_str, zone->latest_xfr->msg_rr_count?
   2491 					(int)zone->latest_xfr->msg_new_serial:0,
   2492 					zone->master->ip_address_spec));
   2493 				zone->latest_xfr->msg_seq_nr = 0;
   2494 			} else if (res == xfrd_packet_bad) {
   2495 				VERBOSITY(1, (LOG_INFO, "xfrd: zone %s "
   2496 					"bad transfer %u from %s",
   2497 					zone->apex_str, zone->latest_xfr->msg_rr_count?
   2498 					(int)zone->latest_xfr->msg_new_serial:0,
   2499 					zone->master->ip_address_spec));
   2500 			}
   2501 			if (res == xfrd_packet_notimpl
   2502 				&& zone->latest_xfr->query_type == TYPE_IXFR)
   2503 				return res;
   2504 			else
   2505 				return xfrd_packet_bad;
   2506 		}
   2507 	}
   2508 
   2509 	/* dump reply on disk to diff file */
   2510 	/* if first part, get new filenumber.  Numbers can wrap around, 64bit
   2511 	 * is enough so we do not collide with older-transfers-in-progress */
   2512 	if(zone->latest_xfr->msg_seq_nr == 0)
   2513 		zone->latest_xfr->xfrfilenumber = xfrd->xfrfilenumber++;
   2514 	diff_write_packet(dname_to_string(zone->apex,0),
   2515 		zone->zone_options->pattern->pname,
   2516 		zone->latest_xfr->msg_old_serial,
   2517 		zone->latest_xfr->msg_new_serial,
   2518 		zone->latest_xfr->msg_seq_nr,
   2519 		buffer_begin(packet), buffer_limit(packet), xfrd->nsd,
   2520 		zone->latest_xfr->xfrfilenumber);
   2521 
   2522 	if(verbosity < 4 || zone->latest_xfr->msg_seq_nr == 0)
   2523 		; /* pass */
   2524 
   2525 	else if((verbosity >= 6)
   2526 	     || (verbosity >= 5 && zone->latest_xfr->msg_seq_nr %  1000 == 0)
   2527 	     || (verbosity >= 4 && zone->latest_xfr->msg_seq_nr % 10000 == 0)) {
   2528 		VERBOSITY(4, (LOG_INFO,
   2529 			"xfrd: zone %s written received XFR packet %u from %s "
   2530 			"with serial %u to disk", zone->apex_str,
   2531 			zone->latest_xfr->msg_seq_nr,
   2532 			zone->master->ip_address_spec,
   2533 			(int)zone->latest_xfr->msg_new_serial));
   2534 	}
   2535 	zone->latest_xfr->msg_seq_nr++;
   2536 
   2537 	xfrfile_size = xfrd_get_xfrfile_size(
   2538 		xfrd->nsd, zone->latest_xfr->xfrfilenumber);
   2539 	if( zone->zone_options->pattern->size_limit_xfr != 0 &&
   2540 	    xfrfile_size > zone->zone_options->pattern->size_limit_xfr ) {
   2541             /*	    xfrd_unlink_xfrfile(xfrd->nsd, zone->xfrfilenumber);
   2542                     xfrd_set_reload_timeout(); */
   2543             log_msg(LOG_INFO, "xfrd : transferred zone data was too large %llu", (long long unsigned)xfrfile_size);
   2544 	    return xfrd_packet_bad;
   2545 	}
   2546 	if(res == xfrd_packet_more) {
   2547 		/* wait for more */
   2548 		return xfrd_packet_more;
   2549 	}
   2550 
   2551 	/* done. we are completely sure of this */
   2552 	buffer_clear(packet);
   2553 	buffer_printf(packet, "received update to serial %u at %s from %s",
   2554 		(unsigned)zone->latest_xfr->msg_new_serial, xfrd_pretty_time(xfrd_time()),
   2555 		zone->master->ip_address_spec);
   2556 	if(zone->master->key_options) {
   2557 		buffer_printf(packet, " TSIG verified with key %s",
   2558 			zone->master->key_options->name);
   2559 	}
   2560 
   2561 	if(zone->master->tls_auth_options && zone->master->tls_auth_options->auth_domain_name) {
   2562 		buffer_printf(packet, " TLS authenticated with domain %s",
   2563 			zone->master->tls_auth_options->auth_domain_name);
   2564 #ifdef HAVE_TLS_1_3
   2565 		/* Get certificate information from the TLS connection */
   2566 		if (zone->tcp_conn != -1) {
   2567 			struct xfrd_tcp_pipeline* tp = NULL;
   2568 			struct region* tmpregion = region_create(xalloc, free);
   2569 			char *cert_serial=NULL, *key_id=NULL,
   2570 				*cert_algorithm=NULL, *tls_version=NULL;
   2571 			/* Find the pipeline for this zone */
   2572 			for (int i = 0; i < xfrd->tcp_set->tcp_max; i++) {
   2573 				struct xfrd_tcp_pipeline* test_tp = xfrd->tcp_set->tcp_state[i];
   2574 				if (test_tp && test_tp->ssl && test_tp->handshake_done) {
   2575 					/* Check if this pipeline is handling our zone */
   2576 					struct xfrd_tcp_pipeline_id* zid;
   2577 					RBTREE_FOR(zid, struct xfrd_tcp_pipeline_id*, test_tp->zone_per_id) {
   2578 						if (zid->zone == zone) {
   2579 							tp = test_tp;
   2580 							break;
   2581 						}
   2582 					}
   2583 					if (tp) break;
   2584 				}
   2585 			}
   2586 			if(!tmpregion)
   2587 				tp = NULL;
   2588 			if(tp && tp->ssl) {
   2589 				get_cert_info(tp->ssl, tmpregion, &cert_serial,
   2590 					&key_id, &cert_algorithm, &tls_version);
   2591 			} else {
   2592 				tp = NULL;
   2593 			}
   2594 
   2595 			if (tp && cert_serial && cert_serial[0] != '\0') {
   2596 				buffer_printf(packet, " cert-serial:%s", cert_serial);
   2597 			}
   2598 			if (tp && key_id && key_id[0] != '\0') {
   2599 				buffer_printf(packet, " key-id:%s", key_id);
   2600 			}
   2601 			if (tp && cert_algorithm && cert_algorithm[0] != '\0') {
   2602 				buffer_printf(packet, " cert-algo:%s", cert_algorithm);
   2603 			}
   2604 			if (tp && tls_version && tls_version[0] != '\0') {
   2605 				buffer_printf(packet, " tls-version:%s", tls_version);
   2606 			}
   2607 			region_destroy(tmpregion);
   2608 		}
   2609 #endif
   2610 	}
   2611 	buffer_flip(packet);
   2612 	diff_write_commit(zone->apex_str, zone->latest_xfr->msg_old_serial,
   2613 		zone->latest_xfr->msg_new_serial, zone->latest_xfr->msg_seq_nr, 1,
   2614 		(char*)buffer_begin(packet), xfrd->nsd, zone->latest_xfr->xfrfilenumber);
   2615 	VERBOSITY(1, (LOG_INFO, "xfrd: zone %s committed \"%s\"",
   2616 		zone->apex_str, (char*)buffer_begin(packet)));
   2617 	/* now put apply_xfr task on the tasklist if no reload in progress */
   2618 	if(xfrd->can_send_reload &&
   2619 		task_new_apply_xfr(
   2620 			xfrd->nsd->task[xfrd->nsd->mytask],
   2621 			xfrd->last_task,
   2622 			zone->apex,
   2623 			zone->latest_xfr->msg_old_serial,
   2624 			zone->latest_xfr->msg_new_serial,
   2625 			zone->latest_xfr->xfrfilenumber))
   2626 	{
   2627 		zone->latest_xfr->sent = xfrd->nsd->mytask + 1;
   2628 	}
   2629 	/* reset msg seq nr, so if that is nonnull we know xfr file exists */
   2630 	zone->latest_xfr->msg_seq_nr = 0;
   2631 	/* update the disk serial no. */
   2632 	zone->soa_disk_acquired = zone->latest_xfr->acquired = xfrd_time();
   2633 	zone->soa_disk = soa;
   2634 	if(zone->soa_notified_acquired && (
   2635 		zone->soa_notified.serial == 0 ||
   2636 		compare_serial(ntohl(zone->soa_disk.serial),
   2637 		ntohl(zone->soa_notified.serial)) >= 0))
   2638 	{
   2639 		zone->soa_notified_acquired = 0;
   2640 	}
   2641 	if(!zone->soa_notified_acquired) {
   2642 		/* do not set expired zone to ok:
   2643 		 * it would cause nsd to start answering
   2644 		 * bad data, since the zone is not loaded yet.
   2645 		 * if nsd does not reload < retry time, more
   2646 		 * queries (for even newer versions) are made.
   2647 		 * For expired zone after reload it is set ok (SOAINFO ipc). */
   2648 		if(zone->state != xfrd_zone_expired)
   2649 			xfrd_set_zone_state(zone, xfrd_zone_ok);
   2650 		DEBUG(DEBUG_XFRD,1, (LOG_INFO,
   2651 			"xfrd: zone %s is waiting for reload",
   2652 			zone->apex_str));
   2653 		if(zone->zone_options->pattern->multi_primary_check) {
   2654 			zone->multi_master_update_check = zone->master_num;
   2655 			xfrd_set_reload_timeout();
   2656 			return xfrd_packet_transfer;
   2657 		}
   2658 		zone->round_num = -1; /* next try start anew */
   2659 		xfrd_set_timer_refresh(zone);
   2660 		xfrd_set_reload_timeout();
   2661 		return xfrd_packet_transfer;
   2662 	} else {
   2663 		/* try to get an even newer serial */
   2664 		/* pretend it was bad to continue queries */
   2665 		xfrd_set_reload_timeout();
   2666 		return xfrd_packet_bad;
   2667 	}
   2668 }
   2669 
   2670 static void
   2671 xfrd_set_reload_timeout()
   2672 {
   2673 	if(xfrd->nsd->options->xfrd_reload_timeout == -1)
   2674 		return; /* automatic reload disabled. */
   2675 	if(xfrd->reload_timeout.tv_sec == 0 ||
   2676 		xfrd_time() >= (time_t)xfrd->reload_timeout.tv_sec ) {
   2677 		/* no reload wait period (or it passed), do it right away */
   2678 		xfrd_set_reload_now(xfrd);
   2679 		/* start reload wait period */
   2680 		xfrd->reload_timeout.tv_sec = xfrd_time() +
   2681 			xfrd->nsd->options->xfrd_reload_timeout;
   2682 		xfrd->reload_timeout.tv_usec = 0;
   2683 		return;
   2684 	}
   2685 	/* cannot reload now, set that after the timeout a reload has to happen */
   2686 	if(xfrd->reload_added == 0) {
   2687 		struct timeval tv;
   2688 		tv.tv_sec = xfrd->reload_timeout.tv_sec - xfrd_time();
   2689 		tv.tv_usec = 0;
   2690 		if(tv.tv_sec > xfrd->nsd->options->xfrd_reload_timeout)
   2691 			tv.tv_sec = xfrd->nsd->options->xfrd_reload_timeout;
   2692 		memset(&xfrd->reload_handler, 0, sizeof(xfrd->reload_handler));
   2693 		event_set(&xfrd->reload_handler, -1, EV_TIMEOUT,
   2694 			xfrd_handle_reload, xfrd);
   2695 		if(event_base_set(xfrd->event_base, &xfrd->reload_handler) != 0)
   2696 			log_msg(LOG_ERR, "cannot set reload event base");
   2697 		if(event_add(&xfrd->reload_handler, &tv) != 0)
   2698 			log_msg(LOG_ERR, "cannot add reload event");
   2699 		xfrd->reload_added = 1;
   2700 	}
   2701 }
   2702 
   2703 static void
   2704 xfrd_handle_reload(int ATTR_UNUSED(fd), short event, void* ATTR_UNUSED(arg))
   2705 {
   2706 	/* reload timeout */
   2707 	assert((event & EV_TIMEOUT));
   2708 	(void)event;
   2709 	/* timeout wait period after this request is sent */
   2710 	xfrd->reload_added = 0;
   2711 	xfrd->reload_timeout.tv_sec = xfrd_time() +
   2712 		xfrd->nsd->options->xfrd_reload_timeout;
   2713 	xfrd_set_reload_now(xfrd);
   2714 }
   2715 
   2716 void
   2717 xfrd_handle_notify_and_start_xfr(xfrd_zone_type* zone, xfrd_soa_type* soa)
   2718 {
   2719 	if(xfrd_handle_incoming_notify(zone, soa)) {
   2720 		if(zone->zone_handler.ev_fd == -1 && zone->tcp_conn == -1 &&
   2721 			!zone->tcp_waiting && !zone->udp_waiting) {
   2722 			xfrd_set_refresh_now(zone);
   2723 		}
   2724 		/* zones with no content start expbackoff again; this is also
   2725 		 * for nsd-control started transfer commands, and also when
   2726 		 * the master apparently sends notifies (is back up) */
   2727 		if(zone->soa_disk_acquired == 0)
   2728 			zone->fresh_xfr_timeout = XFRD_TRANSFER_TIMEOUT_START;
   2729 	}
   2730 }
   2731 
   2732 void
   2733 xfrd_handle_passed_packet(buffer_type* packet,
   2734 	int acl_num, int acl_num_xfr)
   2735 {
   2736 	uint8_t qnamebuf[MAXDOMAINLEN];
   2737 	uint16_t qtype, qclass;
   2738 	const dname_type* dname;
   2739 	region_type* tempregion = region_create(xalloc, free);
   2740 	xfrd_zone_type* zone;
   2741 
   2742 	buffer_skip(packet, QHEADERSZ);
   2743 	if(!packet_read_query_section(packet, qnamebuf, &qtype, &qclass)) {
   2744 		region_destroy(tempregion);
   2745 		return; /* drop bad packet */
   2746 	}
   2747 
   2748 	dname = dname_make(tempregion, qnamebuf, 1);
   2749 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: got passed packet for %s, acl "
   2750 		   "%d", dname_to_string(dname,0), acl_num));
   2751 
   2752 	/* find the zone */
   2753 	zone = (xfrd_zone_type*)rbtree_search(xfrd->zones, dname);
   2754 	if(!zone) {
   2755 		/* this could be because the zone has been deleted meanwhile */
   2756 		DEBUG(DEBUG_XFRD, 1, (LOG_INFO, "xfrd: incoming packet for "
   2757 			"unknown zone %s", dname_to_string(dname,0)));
   2758 		region_destroy(tempregion);
   2759 		return; /* drop packet for unknown zone */
   2760 	}
   2761 	region_destroy(tempregion);
   2762 
   2763 	/* handle */
   2764 	if(OPCODE(packet) == OPCODE_NOTIFY) {
   2765 		xfrd_soa_type soa;
   2766 		int have_soa = 0;
   2767 		int next;
   2768 		/* get serial from a SOA */
   2769 		if(ANCOUNT(packet) == 1 && packet_skip_dname(packet) &&
   2770 			xfrd_parse_soa_info(packet, &soa)) {
   2771 				have_soa = 1;
   2772 		}
   2773 		xfrd_handle_notify_and_start_xfr(zone, have_soa?&soa:NULL);
   2774 		/* First, see if our notifier has a match in provide-xfr */
   2775 		if (acl_find_num(zone->zone_options->pattern->request_xfr,
   2776 				acl_num_xfr))
   2777 			next = acl_num_xfr;
   2778 		else /* If not, find master that matches notifiers ACL entry */
   2779 			next = find_same_master_notify(zone, acl_num);
   2780 		if(next != -1) {
   2781 			zone->next_master = next;
   2782 			DEBUG(DEBUG_XFRD,1, (LOG_INFO,
   2783 				"xfrd: notify set next primary to query %d",
   2784 				next));
   2785 		}
   2786 	}
   2787 	else {
   2788 		/* ignore other types of messages */
   2789 	}
   2790 }
   2791 
   2792 static int
   2793 xfrd_handle_incoming_notify(xfrd_zone_type* zone, xfrd_soa_type* soa)
   2794 {
   2795 	if(soa && zone->soa_disk_acquired && zone->state != xfrd_zone_expired &&
   2796 	   compare_serial(ntohl(soa->serial),ntohl(zone->soa_disk.serial)) <= 0)
   2797 	{
   2798 		DEBUG(DEBUG_XFRD,1, (LOG_INFO,
   2799 			"xfrd: ignored notify %s %u old serial, zone valid "
   2800 			"(soa disk serial %u)", zone->apex_str,
   2801 			(unsigned)ntohl(soa->serial),
   2802 			(unsigned)ntohl(zone->soa_disk.serial)));
   2803 		return 0; /* ignore notify with old serial, we have a valid zone */
   2804 	}
   2805 	if(soa == 0) {
   2806 		zone->soa_notified.serial = 0;
   2807 	}
   2808 	else if (zone->soa_notified_acquired == 0 ||
   2809 		 zone->soa_notified.serial == 0 ||
   2810 		 compare_serial(ntohl(soa->serial),
   2811 			ntohl(zone->soa_notified.serial)) > 0)
   2812 	{
   2813 		zone->soa_notified = *soa;
   2814 	}
   2815 	zone->soa_notified_acquired = xfrd_time();
   2816 	if(zone->state == xfrd_zone_ok) {
   2817 		xfrd_set_zone_state(zone, xfrd_zone_refreshing);
   2818 	}
   2819 	/* transfer right away */
   2820 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "Handle incoming notify for zone %s",
   2821 		zone->apex_str));
   2822 	return 1;
   2823 }
   2824 
   2825 static int
   2826 find_same_master_notify(xfrd_zone_type* zone, int acl_num_nfy)
   2827 {
   2828 	struct acl_options* nfy_acl = acl_find_num(zone->zone_options->pattern->
   2829 		allow_notify, acl_num_nfy);
   2830 	int num = 0;
   2831 	struct acl_options* master = zone->zone_options->pattern->request_xfr;
   2832 	if(!nfy_acl)
   2833 		return -1;
   2834 	while(master)
   2835 	{
   2836 		if(acl_addr_matches_host(nfy_acl, master))
   2837 			return num;
   2838 		master = master->next;
   2839 		num++;
   2840 	}
   2841 	return -1;
   2842 }
   2843 
   2844 void
   2845 xfrd_check_failed_updates(void)
   2846 {
   2847 	/* see if updates have not come through */
   2848 	xfrd_zone_type* zone;
   2849 	xfrd_xfr_type* xfr;
   2850 	xfrd_xfr_type* prev_xfr;
   2851 	uint8_t sent = (xfrd->nsd->mytask == 0) + 1;
   2852 	RBTREE_FOR(zone, xfrd_zone_type*, xfrd->zones)
   2853 	{
   2854 		/* skip zones without updates */
   2855 		if(!zone->latest_xfr)
   2856 			continue;
   2857 		xfr = zone->latest_xfr;
   2858 		while(!xfr->sent && xfr->prev) {
   2859 			xfr = xfr->prev;
   2860 		}
   2861 
   2862 		/* zone has sent update and no (or different) nsd soa, the
   2863 		   update must be corrupt */
   2864 		if(xfr->sent == sent &&
   2865 			(zone->soa_nsd_acquired == 0 ||
   2866 			 zone->soa_nsd.serial != htonl(xfr->msg_new_serial)))
   2867 		{
   2868 			xfrd_soa_type soa;
   2869 			soa.serial = htonl(xfr->msg_new_serial);
   2870 			log_msg(LOG_ERR, "xfrd: zone %s: soa serial %u update "
   2871 			                 "failed, restarting transfer "
   2872 			                 "(notified zone)",
   2873 			                 zone->apex_str, xfr->msg_new_serial);
   2874 			/* revert the soa; it has not been acquired properly */
   2875 			if(xfr->acquired == zone->soa_nsd_acquired) {
   2876 				/* this was the same as served,
   2877 				 * perform force_axfr , re-download
   2878 				 * same serial from master */
   2879 				zone->soa_disk_acquired = 0;
   2880 				zone->soa_nsd_acquired = 0;
   2881 			} else {
   2882 				/* revert soa to the one in server */
   2883 				zone->soa_disk_acquired = zone->soa_nsd_acquired;
   2884 				zone->soa_disk = zone->soa_nsd;
   2885 			}
   2886 			/* fabricate soa and trigger notify to refetch and
   2887 			 * reload update */
   2888 			memset(&soa, 0, sizeof(soa));
   2889 			soa.serial = htonl(xfr->msg_new_serial);
   2890 			xfrd_handle_incoming_notify(zone, &soa);
   2891 			xfrd_set_timer_refresh(zone);
   2892 			/* delete all pending updates */
   2893 			for(xfr = zone->latest_xfr; xfr; xfr = prev_xfr) {
   2894 				prev_xfr = xfr->prev;
   2895 				/* skip incomplete updates */
   2896 				if(!xfr->acquired)
   2897 					continue;
   2898 				DEBUG(DEBUG_IPC, 1,
   2899 					(LOG_INFO, "xfrd: zone %s delete "
   2900 					           "update to serial %u",
   2901 					           zone->apex_str,
   2902 					           xfr->msg_new_serial));
   2903 				xfrd_delete_zone_xfr(zone, xfr);
   2904 			}
   2905 		}
   2906 	}
   2907 }
   2908 
   2909 void
   2910 xfrd_prepare_zones_for_reload(void)
   2911 {
   2912 	xfrd_zone_type* zone;
   2913 	xfrd_xfr_type* xfr;
   2914 	int reload, send;
   2915 
   2916 	send = 1;
   2917 	reload = 0;
   2918 	RBTREE_FOR(zone, xfrd_zone_type*, xfrd->zones)
   2919 	{
   2920 		xfr = zone->latest_xfr;
   2921 		while(xfr) {
   2922 			if(!xfr->prev)
   2923 				break;
   2924 			xfr = xfr->prev;
   2925 			assert(xfr->acquired);
   2926 		}
   2927 
   2928 		while(xfr && xfr->acquired) {
   2929 			/* skip updates that arrived after failed reload */
   2930 			if(xfrd->reload_cmd_first_sent && !xfr->sent)
   2931 				break;
   2932 			assert(!xfrd->reload_cmd_first_sent ||
   2933 			        xfrd->reload_cmd_first_sent >= xfr->acquired);
   2934 			if(send) {
   2935 				send = task_new_apply_xfr(
   2936 					xfrd->nsd->task[xfrd->nsd->mytask],
   2937 					xfrd->last_task,
   2938 					zone->apex,
   2939 					xfr->msg_old_serial,
   2940 					xfr->msg_new_serial,
   2941 					xfr->xfrfilenumber);
   2942 				if(send && !reload) {
   2943 					reload = 1;
   2944 					xfrd_set_reload_timeout();
   2945 				}
   2946 			}
   2947 			xfr->sent = send ? 1 + xfrd->nsd->mytask : 0;
   2948 			xfr = xfr->next;
   2949 		}
   2950 	}
   2951 }
   2952 
   2953 struct buffer*
   2954 xfrd_get_temp_buffer()
   2955 {
   2956 	return xfrd->packet;
   2957 }
   2958 
   2959 #ifdef USE_ZONE_STATS
   2960 /** process zonestat inc task */
   2961 static void
   2962 xfrd_process_zonestat_inc_task(xfrd_state_type* xfrd, struct task_list_d* task)
   2963 {
   2964 	xfrd->zonestat_safe = (unsigned)task->oldserial;
   2965 	zonestat_remap(xfrd->nsd, 0, xfrd->zonestat_safe*sizeof(struct nsdst));
   2966 	xfrd->nsd->zonestatsize[0] = xfrd->zonestat_safe;
   2967 	zonestat_remap(xfrd->nsd, 1, xfrd->zonestat_safe*sizeof(struct nsdst));
   2968 	xfrd->nsd->zonestatsize[1] = xfrd->zonestat_safe;
   2969 }
   2970 #endif /* USE_ZONE_STATS */
   2971 
   2972 static void
   2973 xfrd_handle_taskresult(xfrd_state_type* xfrd, struct task_list_d* task)
   2974 {
   2975 #ifndef USE_ZONE_STATS
   2976 	(void)xfrd;
   2977 #endif
   2978 	switch(task->task_type) {
   2979 	case task_soa_info:
   2980 		xfrd_process_soa_info_task(task);
   2981 		break;
   2982 #ifdef USE_ZONE_STATS
   2983 	case task_zonestat_inc:
   2984 		xfrd_process_zonestat_inc_task(xfrd, task);
   2985 		break;
   2986 #endif
   2987 	default:
   2988 		log_msg(LOG_WARNING, "unhandled task result in xfrd from "
   2989 			"reload type %d", (int)task->task_type);
   2990 	}
   2991 }
   2992 
   2993 void xfrd_process_task_result(xfrd_state_type* xfrd, struct udb_base* taskudb)
   2994 {
   2995 	udb_ptr t;
   2996 	/* remap it for usage */
   2997 	task_remap(taskudb);
   2998 	/* process the task-results in the taskudb */
   2999 	udb_ptr_new(&t, taskudb, udb_base_get_userdata(taskudb));
   3000 	while(!udb_ptr_is_null(&t)) {
   3001 		xfrd_handle_taskresult(xfrd, TASKLIST(&t));
   3002 		udb_ptr_set_rptr(&t, taskudb, &TASKLIST(&t)->next);
   3003 	}
   3004 	udb_ptr_unlink(&t, taskudb);
   3005 	/* clear the udb so it can be used by xfrd to make new tasks for
   3006 	 * reload, this happens when the reload signal is sent, and thus
   3007 	 * the taskudbs are swapped */
   3008 	task_clear(taskudb);
   3009 #ifdef HAVE_SYSTEMD
   3010 	sd_notify(0, "READY=1");
   3011 #endif
   3012 }
   3013 
   3014 void xfrd_set_reload_now(xfrd_state_type* xfrd)
   3015 {
   3016 #ifdef HAVE_SYSTEMD
   3017 	sd_notify(0, "RELOADING=1");
   3018 #endif
   3019 	xfrd->need_to_send_reload = 1;
   3020 	if(!(xfrd->ipc_handler_flags&EV_WRITE)) {
   3021 		ipc_xfrd_set_listening(xfrd, EV_PERSIST|EV_READ|EV_WRITE);
   3022 	}
   3023 }
   3024 
   3025 static void
   3026 xfrd_handle_write_timer(int ATTR_UNUSED(fd), short event, void* ATTR_UNUSED(arg))
   3027 {
   3028 	/* timeout for write events */
   3029 	assert((event & EV_TIMEOUT));
   3030 	(void)event;
   3031 	if(xfrd->nsd->options->zonefiles_write == 0)
   3032 		return;
   3033 	/* call reload to write changed zonefiles */
   3034 	if(!xfrd->write_zonefile_needed) {
   3035 		DEBUG(DEBUG_XFRD,2, (LOG_INFO, "zonefiles write timer (nothing)"));
   3036 		xfrd_write_timer_set();
   3037 		return;
   3038 	}
   3039 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "zonefiles write timer"));
   3040 	task_new_write_zonefiles(xfrd->nsd->task[xfrd->nsd->mytask],
   3041 		xfrd->last_task, NULL);
   3042 	xfrd_set_reload_now(xfrd);
   3043 	xfrd->write_zonefile_needed = 0;
   3044 	xfrd_write_timer_set();
   3045 }
   3046 
   3047 static void xfrd_write_timer_set()
   3048 {
   3049 	struct timeval tv;
   3050 	if(xfrd->nsd->options->zonefiles_write == 0)
   3051 		return;
   3052 	tv.tv_sec = xfrd->nsd->options->zonefiles_write;
   3053 	tv.tv_usec = 0;
   3054 	memset(&xfrd->write_timer, 0, sizeof(xfrd->write_timer));
   3055 	event_set(&xfrd->write_timer, -1, EV_TIMEOUT,
   3056 		xfrd_handle_write_timer, xfrd);
   3057 	if(event_base_set(xfrd->event_base, &xfrd->write_timer) != 0)
   3058 		log_msg(LOG_ERR, "xfrd write timer: event_base_set failed");
   3059 	if(event_add(&xfrd->write_timer, &tv) != 0)
   3060 		log_msg(LOG_ERR, "xfrd write timer: event_add failed");
   3061 }
   3062 
   3063 static void xfrd_handle_child_timer(int ATTR_UNUSED(fd), short event,
   3064 	void* ATTR_UNUSED(arg))
   3065 {
   3066 	assert((event & EV_TIMEOUT));
   3067 	(void)event;
   3068 	/* only used to wakeup the process to reap children, note the
   3069 	 * event is no longer registered */
   3070 	xfrd->child_timer_added = 0;
   3071 }
   3072