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