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