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