xref: /openbsd-src/usr.sbin/nsd/xfrd.c (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
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 = ntohl(zone->soa_disk.refresh);
706 	if (set_refresh > zone->zone_options->pattern->max_refresh_time)
707 		set_refresh = zone->zone_options->pattern->max_refresh_time;
708 	else if (set_refresh < zone->zone_options->pattern->min_refresh_time)
709 		set_refresh = zone->zone_options->pattern->min_refresh_time;
710 	set_refresh += zone->soa_disk_acquired;
711 	set_expire = zone->soa_disk_acquired + ntohl(zone->soa_disk.expire);
712 	if(set_refresh < set_expire)
713 		set = set_refresh;
714 	else set = set_expire;
715 	set_min = zone->soa_disk_acquired + XFRD_LOWERBOUND_REFRESH;
716 	if(set < set_min)
717 		set = set_min;
718 	if(set < xfrd_time())
719 		set = 0;
720 	else	set -= xfrd_time();
721 	xfrd_set_timer(zone, set);
722 }
723 
724 static void
725 xfrd_set_timer_retry(xfrd_zone_t* zone)
726 {
727 	time_t set_retry;
728 	/* set timer for next retry or expire timeout if earlier. */
729 	if(zone->soa_disk_acquired == 0) {
730 		/* if no information, use reasonable timeout */
731 		if(zone->fresh_xfr_timeout == 0)
732 			zone->fresh_xfr_timeout = XFRD_TRANSFER_TIMEOUT_START;
733 #ifdef HAVE_ARC4RANDOM_UNIFORM
734 		xfrd_set_timer(zone, zone->fresh_xfr_timeout
735 			+ arc4random_uniform(zone->fresh_xfr_timeout));
736 #elif HAVE_ARC4RANDOM
737 		xfrd_set_timer(zone, zone->fresh_xfr_timeout
738                         + arc4random() % zone->fresh_xfr_timeout);
739 #else
740 		xfrd_set_timer(zone, zone->fresh_xfr_timeout
741 			+ random()%zone->fresh_xfr_timeout);
742 #endif
743 		/* exponential backoff - some master data in zones is paid-for
744 		   but non-working, and will not get fixed. */
745 		zone->fresh_xfr_timeout *= 2;
746 		if(zone->fresh_xfr_timeout > XFRD_TRANSFER_TIMEOUT_MAX)
747 			zone->fresh_xfr_timeout = XFRD_TRANSFER_TIMEOUT_MAX;
748 	} else if(zone->state == xfrd_zone_expired ||
749 		xfrd_time() + (time_t)ntohl(zone->soa_disk.retry) <
750 		zone->soa_disk_acquired + (time_t)ntohl(zone->soa_disk.expire))
751 	{
752 		set_retry = ntohl(zone->soa_disk.retry);
753 		if(set_retry > zone->zone_options->pattern->max_retry_time)
754 			set_retry = zone->zone_options->pattern->max_retry_time;
755 		else if(set_retry < zone->zone_options->pattern->min_retry_time)
756 			set_retry = zone->zone_options->pattern->min_retry_time;
757 		if(set_retry < XFRD_LOWERBOUND_RETRY)
758 			set_retry =  XFRD_LOWERBOUND_RETRY;
759 		xfrd_set_timer(zone, set_retry);
760 	} else {
761 		if(ntohl(zone->soa_disk.expire) < XFRD_LOWERBOUND_RETRY)
762 			xfrd_set_timer(zone, XFRD_LOWERBOUND_RETRY);
763 		else {
764 			if(zone->soa_disk_acquired + (time_t)ntohl(zone->soa_disk.expire) < xfrd_time())
765 				xfrd_set_timer(zone, XFRD_LOWERBOUND_RETRY);
766 			else xfrd_set_timer(zone, zone->soa_disk_acquired +
767 				ntohl(zone->soa_disk.expire) - xfrd_time());
768 		}
769 	}
770 }
771 
772 void
773 xfrd_handle_zone(int ATTR_UNUSED(fd), short event, void* arg)
774 {
775 	xfrd_zone_t* zone = (xfrd_zone_t*)arg;
776 
777 	if(zone->tcp_conn != -1) {
778 		if(event == 0) /* activated, but already in TCP, nothing to do*/
779 			return;
780 		/* busy in tcp transaction: an internal error */
781 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s event tcp", zone->apex_str));
782 		xfrd_tcp_release(xfrd->tcp_set, zone);
783 		/* continue to retry; as if a timeout happened */
784 		event = EV_TIMEOUT;
785 	}
786 
787 	if((event & EV_READ)) {
788 		/* busy in udp transaction */
789 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s event udp read", zone->apex_str));
790 		xfrd_udp_read(zone);
791 		return;
792 	}
793 
794 	/* timeout */
795 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s timeout", zone->apex_str));
796 	if(zone->zone_handler.ev_fd != -1 && zone->event_added &&
797 		(event & EV_TIMEOUT)) {
798 		assert(zone->tcp_conn == -1);
799 		xfrd_udp_release(zone);
800 	}
801 
802 	if(zone->tcp_waiting) {
803 		DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s skips retry, TCP connections full",
804 			zone->apex_str));
805 		xfrd_unset_timer(zone);
806 		return;
807 	}
808 	if(zone->udp_waiting) {
809 		DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s skips retry, UDP connections full",
810 			zone->apex_str));
811 		xfrd_unset_timer(zone);
812 		return;
813 	}
814 
815 	if(zone->soa_disk_acquired)
816 	{
817 		if (zone->state != xfrd_zone_expired &&
818 			xfrd_time() >= zone->soa_disk_acquired + (time_t)ntohl(zone->soa_disk.expire)) {
819 			/* zone expired */
820 			log_msg(LOG_ERR, "xfrd: zone %s has expired", zone->apex_str);
821 			xfrd_set_zone_state(zone, xfrd_zone_expired);
822 		}
823 		else if(zone->state == xfrd_zone_ok &&
824 			xfrd_time() >= zone->soa_disk_acquired + (time_t)ntohl(zone->soa_disk.refresh)) {
825 			/* zone goes to refreshing state. */
826 			DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s is refreshing", zone->apex_str));
827 			xfrd_set_zone_state(zone, xfrd_zone_refreshing);
828 		}
829 	}
830 
831 	/* only make a new request if no request is running (UDPorTCP) */
832 	if(zone->zone_handler.ev_fd == -1 && zone->tcp_conn == -1) {
833 		/* make a new request */
834 		xfrd_make_request(zone);
835 	}
836 }
837 
838 void
839 xfrd_make_request(xfrd_zone_t* zone)
840 {
841 	if(zone->next_master != -1) {
842 		/* we are told to use this next master */
843 		DEBUG(DEBUG_XFRD,1, (LOG_INFO,
844 			"xfrd zone %s use master %i",
845 			zone->apex_str, zone->next_master));
846 		zone->master_num = zone->next_master;
847 		zone->master = acl_find_num(zone->zone_options->pattern->
848 			request_xfr, zone->master_num);
849 		/* if there is no next master, fallback to use the first one */
850 		if(!zone->master) {
851 			zone->master = zone->zone_options->pattern->request_xfr;
852 			zone->master_num = 0;
853 		}
854 		/* fallback to cycle master */
855 		zone->next_master = -1;
856 		zone->round_num = 0; /* fresh set of retries after notify */
857 	} else {
858 		/* cycle master */
859 
860 		if(zone->round_num != -1 && zone->master && zone->master->next)
861 		{
862 			/* try the next master */
863 			zone->master = zone->master->next;
864 			zone->master_num++;
865 		} else {
866 			/* start a new round */
867 			zone->master = zone->zone_options->pattern->request_xfr;
868 			zone->master_num = 0;
869 			zone->round_num++;
870 		}
871 		if(zone->round_num >= XFRD_MAX_ROUNDS) {
872 			/* tried all servers that many times, wait */
873 			zone->round_num = -1;
874 			xfrd_set_timer_retry(zone);
875 			DEBUG(DEBUG_XFRD,1, (LOG_INFO,
876 				"xfrd zone %s makereq wait_retry, rd %d mr %d nx %d",
877 				zone->apex_str, zone->round_num, zone->master_num, zone->next_master));
878 			return;
879 		}
880 	}
881 
882 	/* cache ixfr_disabled only for XFRD_NO_IXFR_CACHE time */
883 	if (zone->master->ixfr_disabled &&
884 	   (zone->master->ixfr_disabled + XFRD_NO_IXFR_CACHE) <= time(NULL)) {
885 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "clear negative caching ixfr "
886 						"disabled for master %s num "
887 						"%d ",
888 			zone->master->ip_address_spec, zone->master_num));
889 		zone->master->ixfr_disabled = 0;
890 	}
891 
892 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd zone %s make request round %d mr %d nx %d",
893 		zone->apex_str, zone->round_num, zone->master_num, zone->next_master));
894 	/* perform xfr request */
895 	if (!zone->master->use_axfr_only && zone->soa_disk_acquired > 0 &&
896 		!zone->master->ixfr_disabled) {
897 
898 		if (zone->master->allow_udp) {
899 			xfrd_set_timer(zone, XFRD_UDP_TIMEOUT);
900 			xfrd_udp_obtain(zone);
901 		}
902 		else { /* doing 3 rounds of IXFR/TCP might not be useful */
903 			xfrd_set_timer(zone, xfrd->tcp_set->tcp_timeout);
904 			xfrd_tcp_obtain(xfrd->tcp_set, zone);
905 		}
906 	}
907 	else if (zone->master->use_axfr_only || zone->soa_disk_acquired <= 0) {
908 		xfrd_set_timer(zone, xfrd->tcp_set->tcp_timeout);
909 		xfrd_tcp_obtain(xfrd->tcp_set, zone);
910 	}
911 	else if (zone->master->ixfr_disabled) {
912 		if (zone->zone_options->pattern->allow_axfr_fallback) {
913 			xfrd_set_timer(zone, xfrd->tcp_set->tcp_timeout);
914 			xfrd_tcp_obtain(xfrd->tcp_set, zone);
915 		} else {
916 			DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd zone %s axfr "
917 				"fallback not allowed, skipping master %s.",
918 				zone->apex_str, zone->master->ip_address_spec));
919 		}
920 	}
921 }
922 
923 static void
924 xfrd_udp_obtain(xfrd_zone_t* zone)
925 {
926 	assert(zone->udp_waiting == 0);
927 	if(zone->tcp_conn != -1) {
928 		/* no tcp and udp at the same time */
929 		xfrd_tcp_release(xfrd->tcp_set, zone);
930 	}
931 	if(xfrd->udp_use_num < XFRD_MAX_UDP) {
932 		int fd;
933 		xfrd->udp_use_num++;
934 		fd = xfrd_send_ixfr_request_udp(zone);
935 		if(fd == -1)
936 			xfrd->udp_use_num--;
937 		else {
938 			if(zone->event_added)
939 				event_del(&zone->zone_handler);
940 			event_set(&zone->zone_handler, fd,
941 				EV_PERSIST|EV_READ|EV_TIMEOUT,
942 				xfrd_handle_zone, zone);
943 			if(event_base_set(xfrd->event_base, &zone->zone_handler) != 0)
944 				log_msg(LOG_ERR, "xfrd udp: event_base_set failed");
945 			if(event_add(&zone->zone_handler, &zone->timeout) != 0)
946 				log_msg(LOG_ERR, "xfrd udp: event_add failed");
947 			zone->zone_handler_flags=EV_PERSIST|EV_READ|EV_TIMEOUT;
948 			zone->event_added = 1;
949 		}
950 		return;
951 	}
952 	/* queue the zone as last */
953 	zone->udp_waiting = 1;
954 	zone->udp_waiting_next = NULL;
955 	zone->udp_waiting_prev = xfrd->udp_waiting_last;
956 	if(!xfrd->udp_waiting_first)
957 		xfrd->udp_waiting_first = zone;
958 	if(xfrd->udp_waiting_last)
959 		xfrd->udp_waiting_last->udp_waiting_next = zone;
960 	xfrd->udp_waiting_last = zone;
961 	xfrd_unset_timer(zone);
962 }
963 
964 time_t
965 xfrd_time()
966 {
967 	if(!xfrd->got_time) {
968 		xfrd->current_time = time(0);
969 		xfrd->got_time = 1;
970 	}
971 	return xfrd->current_time;
972 }
973 
974 void
975 xfrd_copy_soa(xfrd_soa_t* soa, rr_type* rr)
976 {
977 	const uint8_t* rr_ns_wire = dname_name(domain_dname(rdata_atom_domain(rr->rdatas[0])));
978 	uint8_t rr_ns_len = domain_dname(rdata_atom_domain(rr->rdatas[0]))->name_size;
979 	const uint8_t* rr_em_wire = dname_name(domain_dname(rdata_atom_domain(rr->rdatas[1])));
980 	uint8_t rr_em_len = domain_dname(rdata_atom_domain(rr->rdatas[1]))->name_size;
981 
982 	if(rr->type != TYPE_SOA || rr->rdata_count != 7) {
983 		log_msg(LOG_ERR, "xfrd: copy_soa called with bad rr, type %d rrs %u.",
984 			rr->type, rr->rdata_count);
985 		return;
986 	}
987 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: copy_soa rr, type %d rrs %u, ttl %u.",
988 			(int)rr->type, (unsigned)rr->rdata_count, (unsigned)rr->ttl));
989 	soa->type = htons(rr->type);
990 	soa->klass = htons(rr->klass);
991 	soa->ttl = htonl(rr->ttl);
992 	soa->rdata_count = htons(rr->rdata_count);
993 
994 	/* copy dnames */
995 	soa->prim_ns[0] = rr_ns_len;
996 	memcpy(soa->prim_ns+1, rr_ns_wire, rr_ns_len);
997 	soa->email[0] = rr_em_len;
998 	memcpy(soa->email+1, rr_em_wire, rr_em_len);
999 
1000 	/* already in network format */
1001 	memcpy(&soa->serial, rdata_atom_data(rr->rdatas[2]), sizeof(uint32_t));
1002 	memcpy(&soa->refresh, rdata_atom_data(rr->rdatas[3]), sizeof(uint32_t));
1003 	memcpy(&soa->retry, rdata_atom_data(rr->rdatas[4]), sizeof(uint32_t));
1004 	memcpy(&soa->expire, rdata_atom_data(rr->rdatas[5]), sizeof(uint32_t));
1005 	memcpy(&soa->minimum, rdata_atom_data(rr->rdatas[6]), sizeof(uint32_t));
1006 	DEBUG(DEBUG_XFRD,1, (LOG_INFO,
1007 		"xfrd: copy_soa rr, serial %u refresh %u retry %u expire %u",
1008 		(unsigned)ntohl(soa->serial), (unsigned)ntohl(soa->refresh),
1009 		(unsigned)ntohl(soa->retry), (unsigned)ntohl(soa->expire)));
1010 }
1011 
1012 static void
1013 xfrd_set_zone_state(xfrd_zone_t* zone, enum xfrd_zone_state s)
1014 {
1015 	if(s != zone->state) {
1016 		enum xfrd_zone_state old = zone->state;
1017 		zone->state = s;
1018 		if((s == xfrd_zone_expired || old == xfrd_zone_expired)
1019 			&& s!=old) {
1020 			xfrd_send_expire_notification(zone);
1021 		}
1022 	}
1023 }
1024 
1025 void
1026 xfrd_set_refresh_now(xfrd_zone_t* zone)
1027 {
1028 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd zone %s is activated, state %d",
1029 		zone->apex_str, zone->state));
1030 	if(!zone->is_activated) {
1031 		/* push onto list */
1032 		zone->activated_prev = 0;
1033 		zone->activated_next = xfrd->activated_first;
1034 		if(xfrd->activated_first)
1035 			xfrd->activated_first->activated_prev = zone;
1036 		xfrd->activated_first = zone;
1037 		zone->is_activated = 1;
1038 	}
1039 }
1040 
1041 void
1042 xfrd_unset_timer(xfrd_zone_t* zone)
1043 {
1044 	assert(zone->zone_handler.ev_fd == -1);
1045 	if(zone->event_added)
1046 		event_del(&zone->zone_handler);
1047 	zone->zone_handler_flags = 0;
1048 	zone->event_added = 0;
1049 }
1050 
1051 void
1052 xfrd_set_timer(xfrd_zone_t* zone, time_t t)
1053 {
1054 	int fd = zone->zone_handler.ev_fd;
1055 	int fl = ((fd == -1)?EV_TIMEOUT:zone->zone_handler_flags);
1056 	/* randomize the time, within 90%-100% of original */
1057 	/* not later so zones cannot expire too late */
1058 	/* only for times far in the future */
1059 	if(t > 10) {
1060 		time_t base = t*9/10;
1061 #ifdef HAVE_ARC4RANDOM_UNIFORM
1062 		t = base + arc4random_uniform(t-base);
1063 #elif HAVE_ARC4RANDOM
1064 		t = base + arc4random() % (t-base);
1065 #else
1066 		t = base + random()%(t-base);
1067 #endif
1068 	}
1069 
1070 	/* keep existing flags and fd, but re-add with timeout */
1071 	if(zone->event_added)
1072 		event_del(&zone->zone_handler);
1073 	else	fd = -1;
1074 	zone->timeout.tv_sec = t;
1075 	zone->timeout.tv_usec = 0;
1076 	event_set(&zone->zone_handler, fd, fl, xfrd_handle_zone, zone);
1077 	if(event_base_set(xfrd->event_base, &zone->zone_handler) != 0)
1078 		log_msg(LOG_ERR, "xfrd timer: event_base_set failed");
1079 	if(event_add(&zone->zone_handler, &zone->timeout) != 0)
1080 		log_msg(LOG_ERR, "xfrd timer: event_add failed");
1081 	zone->zone_handler_flags = fl;
1082 	zone->event_added = 1;
1083 }
1084 
1085 void
1086 xfrd_handle_incoming_soa(xfrd_zone_t* zone,
1087 	xfrd_soa_t* soa, time_t acquired)
1088 {
1089 	if(soa == NULL) {
1090 		/* nsd no longer has a zone in memory */
1091 		zone->soa_nsd_acquired = 0;
1092 		xfrd_set_zone_state(zone, xfrd_zone_refreshing);
1093 		xfrd_set_refresh_now(zone);
1094 		return;
1095 	}
1096 	if(zone->soa_nsd_acquired && soa->serial == zone->soa_nsd.serial)
1097 		return;
1098 
1099 	if(zone->soa_disk_acquired && soa->serial == zone->soa_disk.serial)
1100 	{
1101 		/* soa in disk has been loaded in memory */
1102 		log_msg(LOG_INFO, "zone %s serial %u is updated to %u.",
1103 			zone->apex_str, (unsigned)ntohl(zone->soa_nsd.serial),
1104 			(unsigned)ntohl(soa->serial));
1105 		zone->soa_nsd = zone->soa_disk;
1106 		zone->soa_nsd_acquired = zone->soa_disk_acquired;
1107 		xfrd->write_zonefile_needed = 1;
1108 		if(xfrd_time() - zone->soa_disk_acquired
1109 			< (time_t)ntohl(zone->soa_disk.refresh))
1110 		{
1111 			/* zone ok, wait for refresh time */
1112 			xfrd_set_zone_state(zone, xfrd_zone_ok);
1113 			zone->round_num = -1;
1114 			xfrd_set_timer_refresh(zone);
1115 		} else if(xfrd_time() - zone->soa_disk_acquired
1116 			< (time_t)ntohl(zone->soa_disk.expire))
1117 		{
1118 			/* zone refreshing */
1119 			xfrd_set_zone_state(zone, xfrd_zone_refreshing);
1120 			xfrd_set_refresh_now(zone);
1121 		}
1122 		if(xfrd_time() - zone->soa_disk_acquired
1123 			>= (time_t)ntohl(zone->soa_disk.expire)) {
1124 			/* zone expired */
1125 			xfrd_set_zone_state(zone, xfrd_zone_expired);
1126 			xfrd_set_refresh_now(zone);
1127 		}
1128 
1129 		if(zone->soa_notified_acquired != 0 &&
1130 			(zone->soa_notified.serial == 0 ||
1131 		   	compare_serial(ntohl(zone->soa_disk.serial),
1132 				ntohl(zone->soa_notified.serial)) >= 0))
1133 		{	/* read was in response to this notification */
1134 			zone->soa_notified_acquired = 0;
1135 		}
1136 		if(zone->soa_notified_acquired && zone->state == xfrd_zone_ok)
1137 		{
1138 			/* refresh because of notification */
1139 			xfrd_set_zone_state(zone, xfrd_zone_refreshing);
1140 			xfrd_set_refresh_now(zone);
1141 		}
1142 		xfrd_send_notify(xfrd->notify_zones, zone->apex, &zone->soa_nsd);
1143 		return;
1144 	}
1145 
1146 	/* user must have manually provided zone data */
1147 	DEBUG(DEBUG_XFRD,1, (LOG_INFO,
1148 		"xfrd: zone %s serial %u from zonefile. refreshing",
1149 		zone->apex_str, (unsigned)ntohl(soa->serial)));
1150 	zone->soa_nsd = *soa;
1151 	zone->soa_disk = *soa;
1152 	zone->soa_nsd_acquired = acquired;
1153 	zone->soa_disk_acquired = acquired;
1154 	if(zone->soa_notified_acquired != 0 &&
1155 		(zone->soa_notified.serial == 0 ||
1156 	   	compare_serial(ntohl(zone->soa_disk.serial),
1157 			ntohl(zone->soa_notified.serial)) >= 0))
1158 	{	/* user provided in response to this notification */
1159 		zone->soa_notified_acquired = 0;
1160 	}
1161 	xfrd_set_zone_state(zone, xfrd_zone_refreshing);
1162 	xfrd_set_refresh_now(zone);
1163 	xfrd_send_notify(xfrd->notify_zones, zone->apex, &zone->soa_nsd);
1164 }
1165 
1166 void
1167 xfrd_send_expire_notification(xfrd_zone_t* zone)
1168 {
1169 	task_new_expire(xfrd->nsd->task[xfrd->nsd->mytask], xfrd->last_task,
1170 		zone->apex, zone->state == xfrd_zone_expired);
1171 	xfrd_set_reload_timeout();
1172 }
1173 
1174 int
1175 xfrd_udp_read_packet(buffer_type* packet, int fd)
1176 {
1177 	ssize_t received;
1178 
1179 	/* read the data */
1180 	buffer_clear(packet);
1181 	received = recvfrom(fd, buffer_begin(packet), buffer_remaining(packet),
1182 		0, NULL, NULL);
1183 	if(received == -1) {
1184 		log_msg(LOG_ERR, "xfrd: recvfrom failed: %s",
1185 			strerror(errno));
1186 		return 0;
1187 	}
1188 	buffer_set_limit(packet, received);
1189 	return 1;
1190 }
1191 
1192 void
1193 xfrd_udp_release(xfrd_zone_t* zone)
1194 {
1195 	assert(zone->udp_waiting == 0);
1196 	if(zone->event_added)
1197 		event_del(&zone->zone_handler);
1198 	if(zone->zone_handler.ev_fd != -1) {
1199 		close(zone->zone_handler.ev_fd);
1200 	}
1201 	zone->zone_handler.ev_fd = -1;
1202 	zone->zone_handler_flags = 0;
1203 	zone->event_added = 0;
1204 	/* see if there are waiting zones */
1205 	if(xfrd->udp_use_num == XFRD_MAX_UDP)
1206 	{
1207 		while(xfrd->udp_waiting_first) {
1208 			/* snip off waiting list */
1209 			xfrd_zone_t* wz = xfrd->udp_waiting_first;
1210 			assert(wz->udp_waiting);
1211 			wz->udp_waiting = 0;
1212 			xfrd->udp_waiting_first = wz->udp_waiting_next;
1213 			if(wz->udp_waiting_next)
1214 				wz->udp_waiting_next->udp_waiting_prev = NULL;
1215 			if(xfrd->udp_waiting_last == wz)
1216 				xfrd->udp_waiting_last = NULL;
1217 			/* see if this zone needs udp connection */
1218 			if(wz->tcp_conn == -1) {
1219 				int fd = xfrd_send_ixfr_request_udp(wz);
1220 				if(fd != -1) {
1221 					if(wz->event_added)
1222 						event_del(&wz->zone_handler);
1223 					event_set(&wz->zone_handler, fd,
1224 						EV_READ|EV_TIMEOUT|EV_PERSIST,
1225 						xfrd_handle_zone, wz);
1226 					if(event_base_set(xfrd->event_base,
1227 						&wz->zone_handler) != 0)
1228 						log_msg(LOG_ERR, "cannot set event_base for ixfr");
1229 					if(event_add(&wz->zone_handler, &wz->timeout) != 0)
1230 						log_msg(LOG_ERR, "cannot add event for ixfr");
1231 					wz->zone_handler_flags = EV_READ|EV_TIMEOUT|EV_PERSIST;
1232 					wz->event_added = 1;
1233 					return;
1234 				} else {
1235 					/* make this zone do something with
1236 					 * this failure to act */
1237 					xfrd_set_refresh_now(wz);
1238 				}
1239 			}
1240 		}
1241 	}
1242 	/* no waiting zones */
1243 	if(xfrd->udp_use_num > 0)
1244 		xfrd->udp_use_num--;
1245 }
1246 
1247 static void
1248 xfrd_udp_read(xfrd_zone_t* zone)
1249 {
1250 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s read udp data", zone->apex_str));
1251 	if(!xfrd_udp_read_packet(xfrd->packet, zone->zone_handler.ev_fd)) {
1252 		zone->master->bad_xfr_count++;
1253 		if (zone->master->bad_xfr_count > 2) {
1254 			zone->master->ixfr_disabled = time(NULL);
1255 			zone->master->bad_xfr_count = 0;
1256 		}
1257 		/* drop packet */
1258 		xfrd_udp_release(zone);
1259 		/* query next server */
1260 		xfrd_make_request(zone);
1261 		return;
1262 	}
1263 	switch(xfrd_handle_received_xfr_packet(zone, xfrd->packet)) {
1264 		case xfrd_packet_tcp:
1265 			xfrd_set_timer(zone, xfrd->tcp_set->tcp_timeout);
1266 			xfrd_udp_release(zone);
1267 			xfrd_tcp_obtain(xfrd->tcp_set, zone);
1268 			break;
1269 		case xfrd_packet_transfer:
1270 		case xfrd_packet_newlease:
1271 			/* nothing more to do */
1272 			assert(zone->round_num == -1);
1273 			xfrd_udp_release(zone);
1274 			break;
1275 		case xfrd_packet_notimpl:
1276 			zone->master->ixfr_disabled = time(NULL);
1277 			/* drop packet */
1278 			xfrd_udp_release(zone);
1279 			/* query next server */
1280 			xfrd_make_request(zone);
1281 			break;
1282 		case xfrd_packet_more:
1283 		case xfrd_packet_drop:
1284 			/* drop packet */
1285 			xfrd_udp_release(zone);
1286 			/* query next server */
1287 			xfrd_make_request(zone);
1288 			break;
1289 		case xfrd_packet_bad:
1290 		default:
1291 			zone->master->bad_xfr_count++;
1292 			if (zone->master->bad_xfr_count > 2) {
1293 				zone->master->ixfr_disabled = time(NULL);
1294 				zone->master->bad_xfr_count = 0;
1295 			}
1296 			/* drop packet */
1297 			xfrd_udp_release(zone);
1298 			/* query next server */
1299 			xfrd_make_request(zone);
1300 			break;
1301 	}
1302 }
1303 
1304 int
1305 xfrd_send_udp(acl_options_t* acl, buffer_type* packet, acl_options_t* ifc)
1306 {
1307 #ifdef INET6
1308 	struct sockaddr_storage to;
1309 #else
1310 	struct sockaddr_in to;
1311 #endif /* INET6 */
1312 	int fd, family;
1313 
1314 	/* this will set the remote port to acl->port or TCP_PORT */
1315 	socklen_t to_len = xfrd_acl_sockaddr_to(acl, &to);
1316 
1317 	/* get the address family of the remote host */
1318 	if(acl->is_ipv6) {
1319 #ifdef INET6
1320 		family = PF_INET6;
1321 #else
1322 		return -1;
1323 #endif /* INET6 */
1324 	} else {
1325 		family = PF_INET;
1326 	}
1327 
1328 	fd = socket(family, SOCK_DGRAM, IPPROTO_UDP);
1329 	if(fd == -1) {
1330 		log_msg(LOG_ERR, "xfrd: cannot create udp socket to %s: %s",
1331 			acl->ip_address_spec, strerror(errno));
1332 		return -1;
1333 	}
1334 
1335 	/* bind it */
1336 	if (!xfrd_bind_local_interface(fd, ifc, acl, 0)) {
1337 		log_msg(LOG_ERR, "xfrd: cannot bind outgoing interface '%s' to "
1338 				 "udp socket: No matching ip addresses found",
1339 			ifc->ip_address_spec);
1340 		close(fd);
1341 		return -1;
1342 	}
1343 
1344 	/* send it (udp) */
1345 	if(sendto(fd,
1346 		buffer_current(packet),
1347 		buffer_remaining(packet), 0,
1348 		(struct sockaddr*)&to, to_len) == -1)
1349 	{
1350 		log_msg(LOG_ERR, "xfrd: sendto %s failed %s",
1351 			acl->ip_address_spec, strerror(errno));
1352 		close(fd);
1353 		return -1;
1354 	}
1355 	return fd;
1356 }
1357 
1358 int
1359 xfrd_bind_local_interface(int sockd, acl_options_t* ifc, acl_options_t* acl,
1360 	int tcp)
1361 {
1362 #ifdef SO_LINGER
1363 	struct linger linger = {1, 0};
1364 #endif
1365 	socklen_t frm_len;
1366 #ifdef INET6
1367 	struct sockaddr_storage frm;
1368 #else
1369 	struct sockaddr_in frm;
1370 #endif /* INET6 */
1371 	int ret = 1;
1372 
1373 	if (!ifc) /* no outgoing interface set */
1374 		return 1;
1375 
1376 	while (ifc) {
1377 		if (ifc->is_ipv6 != acl->is_ipv6) {
1378 			/* check if we have a matching address family */
1379 			ifc = ifc->next;
1380 			continue;
1381 		}
1382 
1383 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: bind() %s to %s socket",
1384 			ifc->ip_address_spec, tcp? "tcp":"udp"));
1385 		ret = 0;
1386 		frm_len = xfrd_acl_sockaddr_frm(ifc, &frm);
1387 
1388 		if (tcp) {
1389 #ifdef SO_REUSEADDR
1390 			if (setsockopt(sockd, SOL_SOCKET, SO_REUSEADDR, &frm,
1391 				frm_len) < 0) {
1392 				VERBOSITY(2, (LOG_WARNING, "xfrd: setsockopt "
1393 			     "SO_REUSEADDR failed: %s", strerror(errno)));
1394 			}
1395 #else
1396 			VERBOSITY(2, (LOG_WARNING, "xfrd: setsockopt SO_REUSEADDR "
1397 			     "failed: SO_REUSEADDR not defined"));
1398 #endif /* SO_REUSEADDR */
1399 
1400 			if (ifc->port != 0) {
1401 #ifdef SO_LINGER
1402 				if (setsockopt(sockd, SOL_SOCKET, SO_LINGER,
1403 					&linger, sizeof(linger)) < 0) {
1404 					VERBOSITY(2, (LOG_WARNING, "xfrd: setsockopt "
1405 				     "SO_LINGER failed: %s", strerror(errno)));
1406 				}
1407 #else
1408 				VERBOSITY(2, (LOG_WARNING, "xfrd: setsockopt SO_LINGER "
1409 					"failed: SO_LINGER not defined"));
1410 #endif /* SO_LINGER */
1411 			}
1412 		}
1413 
1414 		/* found one */
1415 		if(bind(sockd, (struct sockaddr*)&frm, frm_len) >= 0) {
1416 			DEBUG(DEBUG_XFRD,2, (LOG_INFO, "xfrd: bind() %s to %s "
1417 						       "socket was successful",
1418 			ifc->ip_address_spec, tcp? "tcp":"udp"));
1419 			return 1;
1420 		}
1421 
1422 		DEBUG(DEBUG_XFRD,2, (LOG_INFO, "xfrd: bind() %s to %s socket"
1423 					       "failed: %s",
1424 			ifc->ip_address_spec, tcp? "tcp":"udp",
1425 			strerror(errno)));
1426 
1427 		log_msg(LOG_WARNING, "xfrd: could not bind source address:port to "
1428 		     "socket: %s", strerror(errno));
1429 		/* try another */
1430 		ifc = ifc->next;
1431 	}
1432 	return ret;
1433 }
1434 
1435 void
1436 xfrd_tsig_sign_request(buffer_type* packet, tsig_record_type* tsig,
1437 	acl_options_t* acl)
1438 {
1439 	tsig_algorithm_type* algo;
1440 	assert(acl->key_options && acl->key_options->tsig_key);
1441 	algo = tsig_get_algorithm_by_name(acl->key_options->algorithm);
1442 	if(!algo) {
1443 		log_msg(LOG_ERR, "tsig unknown algorithm %s",
1444 			acl->key_options->algorithm);
1445 		return;
1446 	}
1447 	assert(algo);
1448 	tsig_init_record(tsig, algo, acl->key_options->tsig_key);
1449 	tsig_init_query(tsig, ID(packet));
1450 	tsig_prepare(tsig);
1451 	tsig_update(tsig, packet, buffer_position(packet));
1452 	tsig_sign(tsig);
1453 	tsig_append_rr(tsig, packet);
1454 	ARCOUNT_SET(packet, ARCOUNT(packet) + 1);
1455 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "appending tsig to packet"));
1456 	/* prepare for validating tsigs */
1457 	tsig_prepare(tsig);
1458 }
1459 
1460 static int
1461 xfrd_send_ixfr_request_udp(xfrd_zone_t* zone)
1462 {
1463 	int fd;
1464 
1465 	/* make sure we have a master to query the ixfr request to */
1466 	assert(zone->master);
1467 
1468 	if(zone->tcp_conn != -1) {
1469 		/* tcp is using the zone_handler.fd */
1470 		log_msg(LOG_ERR, "xfrd: %s tried to send udp whilst tcp engaged",
1471 			zone->apex_str);
1472 		return -1;
1473 	}
1474 	xfrd_setup_packet(xfrd->packet, TYPE_IXFR, CLASS_IN, zone->apex,
1475 		qid_generate());
1476 	zone->query_id = ID(xfrd->packet);
1477 	/* delete old xfr file? */
1478 	if(zone->msg_seq_nr)
1479 		xfrd_unlink_xfrfile(xfrd->nsd, zone->xfrfilenumber);
1480 	zone->msg_seq_nr = 0;
1481 	zone->msg_rr_count = 0;
1482 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "sent query with ID %d", zone->query_id));
1483         NSCOUNT_SET(xfrd->packet, 1);
1484 	xfrd_write_soa_buffer(xfrd->packet, zone->apex, &zone->soa_disk);
1485 	/* if we have tsig keys, sign the ixfr query */
1486 	if(zone->master->key_options && zone->master->key_options->tsig_key) {
1487 		xfrd_tsig_sign_request(xfrd->packet, &zone->tsig, zone->master);
1488 	}
1489 	buffer_flip(xfrd->packet);
1490 	xfrd_set_timer(zone, XFRD_UDP_TIMEOUT);
1491 
1492 	if((fd = xfrd_send_udp(zone->master, xfrd->packet,
1493 		zone->zone_options->pattern->outgoing_interface)) == -1)
1494 		return -1;
1495 
1496 	DEBUG(DEBUG_XFRD,1, (LOG_INFO,
1497 		"xfrd sent udp request for ixfr=%u for zone %s to %s",
1498 		(unsigned)ntohl(zone->soa_disk.serial),
1499 		zone->apex_str, zone->master->ip_address_spec));
1500 	return fd;
1501 }
1502 
1503 static int xfrd_parse_soa_info(buffer_type* packet, xfrd_soa_t* soa)
1504 {
1505 	if(!buffer_available(packet, 10))
1506 		return 0;
1507 	soa->type = htons(buffer_read_u16(packet));
1508 	soa->klass = htons(buffer_read_u16(packet));
1509 	soa->ttl = htonl(buffer_read_u32(packet));
1510 	if(ntohs(soa->type) != TYPE_SOA || ntohs(soa->klass) != CLASS_IN)
1511 	{
1512 		return 0;
1513 	}
1514 
1515 	if(!buffer_available(packet, buffer_read_u16(packet)) /* rdata length */ ||
1516 		!(soa->prim_ns[0] = dname_make_wire_from_packet(soa->prim_ns+1, packet, 1)) ||
1517 		!(soa->email[0] = dname_make_wire_from_packet(soa->email+1, packet, 1)))
1518 	{
1519 		return 0;
1520 	}
1521 	soa->rdata_count = 7; /* rdata in SOA */
1522 	soa->serial = htonl(buffer_read_u32(packet));
1523 	soa->refresh = htonl(buffer_read_u32(packet));
1524 	soa->retry = htonl(buffer_read_u32(packet));
1525 	soa->expire = htonl(buffer_read_u32(packet));
1526 	soa->minimum = htonl(buffer_read_u32(packet));
1527 
1528 	return 1;
1529 }
1530 
1531 
1532 /*
1533  * Check the RRs in an IXFR/AXFR reply.
1534  * returns 0 on error, 1 on correct parseable packet.
1535  * done = 1 if the last SOA in an IXFR/AXFR has been seen.
1536  * soa then contains that soa info.
1537  * (soa contents is modified by the routine)
1538  */
1539 static int
1540 xfrd_xfr_check_rrs(xfrd_zone_t* zone, buffer_type* packet, size_t count,
1541 	int *done, xfrd_soa_t* soa, region_type* temp)
1542 {
1543 	/* first RR has already been checked */
1544 	uint32_t tmp_serial = 0;
1545 	uint16_t type, rrlen;
1546 	size_t i, soapos, mempos;
1547 	const dname_type* dname;
1548 	domain_table_type* owners;
1549 	rdata_atom_type* rdatas;
1550 
1551 	for(i=0; i<count; ++i,++zone->msg_rr_count)
1552 	{
1553 		if (*done) {
1554 			DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr has "
1555 				"trailing garbage", zone->apex_str));
1556 			return 0;
1557 		}
1558 		region_free_all(temp);
1559 		owners = domain_table_create(temp);
1560 		/* check the dname for errors */
1561 		dname = dname_make_from_packet(temp, packet, 1, 1);
1562 		if(!dname) {
1563 			DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr unable "
1564 				"to parse owner name", zone->apex_str));
1565 			return 0;
1566 		}
1567 		if(!buffer_available(packet, 10)) {
1568 			DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr hdr "
1569 				"too small", zone->apex_str));
1570 			return 0;
1571 		}
1572 		soapos = buffer_position(packet);
1573 		type = buffer_read_u16(packet);
1574 		(void)buffer_read_u16(packet); /* class */
1575 		(void)buffer_read_u32(packet); /* ttl */
1576 		rrlen = buffer_read_u16(packet);
1577 		if(!buffer_available(packet, rrlen)) {
1578 			DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr pkt "
1579 				"too small", zone->apex_str));
1580 			return 0;
1581 		}
1582 		mempos = buffer_position(packet);
1583 		if(rdata_wireformat_to_rdata_atoms(temp, owners, type, rrlen,
1584 			packet, &rdatas) == -1) {
1585 			DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr unable "
1586 				"to parse rdata", zone->apex_str));
1587 			return 0;
1588 		}
1589 		if(type == TYPE_SOA) {
1590 			/* check the SOAs */
1591 			buffer_set_position(packet, soapos);
1592 			if(!xfrd_parse_soa_info(packet, soa)) {
1593 				DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr "
1594 					"unable to parse soainfo", zone->apex_str));
1595 				return 0;
1596 			}
1597 			if(zone->msg_rr_count == 1 &&
1598 				ntohl(soa->serial) != zone->msg_new_serial) {
1599 				/* 2nd RR is SOA with lower serial, this is an IXFR */
1600 				zone->msg_is_ixfr = 1;
1601 				if(!zone->soa_disk_acquired) {
1602 					DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr "
1603 						"got ixfr but need axfr", zone->apex_str));
1604 					return 0; /* got IXFR but need AXFR */
1605 				}
1606 				if(ntohl(soa->serial) != ntohl(zone->soa_disk.serial)) {
1607 					DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr "
1608 						"bad start serial", zone->apex_str));
1609 					return 0; /* bad start serial in IXFR */
1610 				}
1611 				zone->msg_old_serial = ntohl(soa->serial);
1612 				tmp_serial = ntohl(soa->serial);
1613 			}
1614 			else if(ntohl(soa->serial) == zone->msg_new_serial) {
1615 				/* saw another SOA of new serial. */
1616 				if(zone->msg_is_ixfr == 1) {
1617 					zone->msg_is_ixfr = 2; /* seen middle SOA in ixfr */
1618 				} else {
1619 					/* 2nd SOA for AXFR or 3rd newSOA for IXFR */
1620 					*done = 1;
1621 				}
1622 			}
1623 			else if (zone->msg_is_ixfr) {
1624 				/* some additional checks */
1625 				if(ntohl(soa->serial) > zone->msg_new_serial) {
1626 					DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr "
1627 						"bad middle serial", zone->apex_str));
1628 					return 0; /* bad middle serial in IXFR */
1629 				}
1630 				if(ntohl(soa->serial) < tmp_serial) {
1631 					DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s xfr "
1632 						"serial decreasing not allowed", zone->apex_str));
1633 					return 0; /* middle serial decreases in IXFR */
1634 				}
1635 				/* serial ok, update tmp serial */
1636 				tmp_serial = ntohl(soa->serial);
1637 			}
1638 		}
1639 		buffer_set_position(packet, mempos);
1640 		buffer_skip(packet, rrlen);
1641 	}
1642 	/* packet seems to have a valid DNS RR structure */
1643 	return 1;
1644 }
1645 
1646 static int
1647 xfrd_xfr_process_tsig(xfrd_zone_t* zone, buffer_type* packet)
1648 {
1649 	int have_tsig = 0;
1650 	assert(zone && zone->master && zone->master->key_options
1651 		&& zone->master->key_options->tsig_key && packet);
1652 	if(!tsig_find_rr(&zone->tsig, packet)) {
1653 		log_msg(LOG_ERR, "xfrd: zone %s, from %s: malformed tsig RR",
1654 			zone->apex_str, zone->master->ip_address_spec);
1655 		return 0;
1656 	}
1657 	if(zone->tsig.status == TSIG_OK) {
1658 		have_tsig = 1;
1659 		if (zone->tsig.error_code != TSIG_ERROR_NOERROR) {
1660 			log_msg(LOG_ERR, "xfrd: zone %s, from %s: tsig error "
1661 				"(%s)", zone->apex_str,
1662 				zone->master->ip_address_spec,
1663 				tsig_error(zone->tsig.error_code));
1664 		}
1665 	}
1666 	if(have_tsig) {
1667 		/* strip the TSIG resource record off... */
1668 		buffer_set_limit(packet, zone->tsig.position);
1669 		ARCOUNT_SET(packet, ARCOUNT(packet) - 1);
1670 	}
1671 
1672 	/* keep running the TSIG hash */
1673 	tsig_update(&zone->tsig, packet, buffer_limit(packet));
1674 	if(have_tsig) {
1675 		if (!tsig_verify(&zone->tsig)) {
1676 			log_msg(LOG_ERR, "xfrd: zone %s, from %s: bad tsig signature",
1677 				zone->apex_str, zone->master->ip_address_spec);
1678 			return 0;
1679 		}
1680 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s, from %s: good tsig signature",
1681 			zone->apex_str, zone->master->ip_address_spec));
1682 		/* prepare for next tsigs */
1683 		tsig_prepare(&zone->tsig);
1684 	}
1685 	else if(zone->tsig.updates_since_last_prepare > XFRD_TSIG_MAX_UNSIGNED) {
1686 		/* we allow a number of non-tsig signed packets */
1687 		log_msg(LOG_INFO, "xfrd: zone %s, from %s: too many consecutive "
1688 			"packets without TSIG", zone->apex_str,
1689 			zone->master->ip_address_spec);
1690 		return 0;
1691 	}
1692 
1693 	if(!have_tsig && zone->msg_seq_nr == 0) {
1694 		log_msg(LOG_ERR, "xfrd: zone %s, from %s: no tsig in first packet of reply",
1695 			zone->apex_str, zone->master->ip_address_spec);
1696 		return 0;
1697 	}
1698 	return 1;
1699 }
1700 
1701 /* parse the received packet. returns xfrd packet result code. */
1702 static enum xfrd_packet_result
1703 xfrd_parse_received_xfr_packet(xfrd_zone_t* zone, buffer_type* packet,
1704 	xfrd_soa_t* soa)
1705 {
1706 	size_t rr_count;
1707 	size_t qdcount = QDCOUNT(packet);
1708 	size_t ancount = ANCOUNT(packet), ancount_todo;
1709 	size_t nscount = NSCOUNT(packet);
1710 	int done = 0;
1711 	region_type* tempregion = NULL;
1712 
1713 	/* has to be axfr / ixfr reply */
1714 	if(!buffer_available(packet, QHEADERSZ)) {
1715 		log_msg(LOG_INFO, "packet too small");
1716 		return xfrd_packet_bad;
1717 	}
1718 
1719 	/* only check ID in first response message. Could also check that
1720 	 * AA bit and QR bit are set, but not needed.
1721 	 */
1722 	DEBUG(DEBUG_XFRD,2, (LOG_INFO,
1723 		"got query with ID %d and %d needed", ID(packet), zone->query_id));
1724 	if(ID(packet) != zone->query_id) {
1725 		log_msg(LOG_ERR, "xfrd: zone %s received bad query id from %s, "
1726 				 "dropped",
1727 			zone->apex_str, zone->master->ip_address_spec);
1728 		return xfrd_packet_bad;
1729 	}
1730 	/* check RCODE in all response messages */
1731 	if(RCODE(packet) != RCODE_OK) {
1732 		log_msg(LOG_ERR, "xfrd: zone %s received error code %s from "
1733 				 "%s",
1734 			zone->apex_str, rcode2str(RCODE(packet)),
1735 			zone->master->ip_address_spec);
1736 		if (RCODE(packet) == RCODE_IMPL ||
1737 			RCODE(packet) == RCODE_FORMAT) {
1738 			return xfrd_packet_notimpl;
1739 		}
1740 		if (RCODE(packet) != RCODE_NOTAUTH) {
1741 			/* RFC 2845: If NOTAUTH, client should do TSIG checking */
1742 			return xfrd_packet_drop;
1743 		}
1744 	}
1745 	/* check TSIG */
1746 	if(zone->master->key_options) {
1747 		if(!xfrd_xfr_process_tsig(zone, packet)) {
1748 			DEBUG(DEBUG_XFRD,1, (LOG_ERR, "dropping xfr reply due "
1749 				"to bad TSIG"));
1750 			return xfrd_packet_bad;
1751 		}
1752 	}
1753 	if (RCODE(packet) == RCODE_NOTAUTH) {
1754 		return xfrd_packet_drop;
1755 	}
1756 
1757 	buffer_skip(packet, QHEADERSZ);
1758 
1759 	/* skip question section */
1760 	for(rr_count = 0; rr_count < qdcount; ++rr_count) {
1761 		if (!packet_skip_rr(packet, 1)) {
1762 			log_msg(LOG_ERR, "xfrd: zone %s, from %s: bad RR in "
1763 					 		 "question section",
1764 				zone->apex_str, zone->master->ip_address_spec);
1765 			return xfrd_packet_bad;
1766 		}
1767 	}
1768 	if(zone->msg_rr_count == 0 && ancount == 0) {
1769 		if(zone->tcp_conn == -1 && TC(packet)) {
1770 			DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: TC flagged"));
1771 			return xfrd_packet_tcp;
1772 		}
1773 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: too short xfr packet: no "
1774 					       			   "answer"));
1775 		/* if IXFR is unknown, fallback to AXFR (if allowed) */
1776 		if (nscount == 1) {
1777 			if(!packet_skip_dname(packet) || !xfrd_parse_soa_info(packet, soa)) {
1778 				DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s, from %s: "
1779 					"no SOA begins authority section",
1780 					zone->apex_str, zone->master->ip_address_spec));
1781 				return xfrd_packet_bad;
1782 			}
1783 			return xfrd_packet_notimpl;
1784 		}
1785 		return xfrd_packet_bad;
1786 	}
1787 	ancount_todo = ancount;
1788 
1789 	tempregion = region_create(xalloc, free);
1790 	if(zone->msg_rr_count == 0) {
1791 		const dname_type* soaname = dname_make_from_packet(tempregion,
1792 			packet, 1, 1);
1793 		if(!soaname) { /* parse failure */
1794 			DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s, from %s: "
1795 				"parse error in SOA record",
1796 				zone->apex_str, zone->master->ip_address_spec));
1797 			region_destroy(tempregion);
1798 			return xfrd_packet_bad;
1799 		}
1800 		if(dname_compare(soaname, zone->apex) != 0) { /* wrong name */
1801 			DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s, from %s: "
1802 				"wrong SOA record",
1803 				zone->apex_str, zone->master->ip_address_spec));
1804 			region_destroy(tempregion);
1805 			return xfrd_packet_bad;
1806 		}
1807 
1808 		/* parse the first RR, see if it is a SOA */
1809 		if(!xfrd_parse_soa_info(packet, soa))
1810 		{
1811 			DEBUG(DEBUG_XFRD,1, (LOG_ERR, "xfrd: zone %s, from %s: "
1812 						      "bad SOA rdata",
1813 				zone->apex_str, zone->master->ip_address_spec));
1814 			region_destroy(tempregion);
1815 			return xfrd_packet_bad;
1816 		}
1817 		if(zone->soa_disk_acquired != 0 &&
1818 			zone->state != xfrd_zone_expired /* if expired - accept anything */ &&
1819 			compare_serial(ntohl(soa->serial), ntohl(zone->soa_disk.serial)) < 0) {
1820 			DEBUG(DEBUG_XFRD,1, (LOG_INFO,
1821 				"xfrd: zone %s ignoring old serial from %s",
1822 				zone->apex_str, zone->master->ip_address_spec));
1823 			VERBOSITY(1, (LOG_INFO,
1824 				"xfrd: zone %s ignoring old serial from %s",
1825 				zone->apex_str, zone->master->ip_address_spec));
1826 			region_destroy(tempregion);
1827 			return xfrd_packet_bad;
1828 		}
1829 		if(zone->soa_disk_acquired != 0 && zone->soa_disk.serial == soa->serial) {
1830 			DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s got "
1831 						       "update indicating "
1832 						       "current serial",
1833 				zone->apex_str));
1834 			/* (even if notified) the lease on the current soa is renewed */
1835 			zone->soa_disk_acquired = xfrd_time();
1836 			if(zone->soa_nsd.serial == soa->serial)
1837 				zone->soa_nsd_acquired = xfrd_time();
1838 			xfrd_set_zone_state(zone, xfrd_zone_ok);
1839  			DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s is ok",
1840 				zone->apex_str));
1841 			if(zone->soa_notified_acquired == 0) {
1842 				/* not notified or anything, so stop asking around */
1843 				zone->round_num = -1; /* next try start a new round */
1844 				xfrd_set_timer_refresh(zone);
1845 				region_destroy(tempregion);
1846 				return xfrd_packet_newlease;
1847 			}
1848 			/* try next master */
1849 			region_destroy(tempregion);
1850 			return xfrd_packet_drop;
1851 		}
1852 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "IXFR reply has ok serial (have \
1853 %u, reply %u).", (unsigned)ntohl(zone->soa_disk.serial), (unsigned)ntohl(soa->serial)));
1854 		/* serial is newer than soa_disk */
1855 		if(ancount == 1) {
1856 			/* single record means it is like a notify */
1857 			(void)xfrd_handle_incoming_notify(zone, soa);
1858 		}
1859 		else if(zone->soa_notified_acquired && zone->soa_notified.serial &&
1860 			compare_serial(ntohl(zone->soa_notified.serial), ntohl(soa->serial)) < 0) {
1861 			/* this AXFR/IXFR notifies me that an even newer serial exists */
1862 			zone->soa_notified.serial = soa->serial;
1863 		}
1864 		zone->msg_new_serial = ntohl(soa->serial);
1865 		zone->msg_rr_count = 1;
1866 		zone->msg_is_ixfr = 0;
1867 		if(zone->soa_disk_acquired)
1868 			zone->msg_old_serial = ntohl(zone->soa_disk.serial);
1869 		else zone->msg_old_serial = 0;
1870 		ancount_todo = ancount - 1;
1871 	}
1872 
1873 	if(zone->tcp_conn == -1 && TC(packet)) {
1874 		DEBUG(DEBUG_XFRD,1, (LOG_INFO,
1875 			"xfrd: zone %s received TC from %s. retry tcp.",
1876 			zone->apex_str, zone->master->ip_address_spec));
1877 		region_destroy(tempregion);
1878 		return xfrd_packet_tcp;
1879 	}
1880 
1881 	if(zone->tcp_conn == -1 && ancount < 2) {
1882 		/* too short to be a real ixfr/axfr data transfer: need at */
1883 		/* least two RRs in the answer section. */
1884 		/* The serial is newer, so try tcp to this master. */
1885 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: udp reply is short. Try "
1886 					       			   "tcp anyway."));
1887 		region_destroy(tempregion);
1888 		return xfrd_packet_tcp;
1889 	}
1890 
1891 	if(!xfrd_xfr_check_rrs(zone, packet, ancount_todo, &done, soa,
1892 		tempregion))
1893 	{
1894 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s sent bad xfr "
1895 					       			   "reply.", zone->apex_str));
1896 		region_destroy(tempregion);
1897 		return xfrd_packet_bad;
1898 	}
1899 	region_destroy(tempregion);
1900 	if(zone->tcp_conn == -1 && done == 0) {
1901 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: udp reply incomplete"));
1902 		return xfrd_packet_bad;
1903 	}
1904 	if(done == 0)
1905 		return xfrd_packet_more;
1906 	if(zone->master->key_options) {
1907 		if(zone->tsig.updates_since_last_prepare != 0) {
1908 			log_msg(LOG_INFO, "xfrd: last packet of reply has no "
1909 					 		  "TSIG");
1910 			return xfrd_packet_bad;
1911 		}
1912 	}
1913 	return xfrd_packet_transfer;
1914 }
1915 
1916 const char*
1917 xfrd_pretty_time(time_t v)
1918 {
1919 	struct tm* tm = localtime(&v);
1920 	static char buf[64];
1921 	if(!strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", tm))
1922 		snprintf(buf, sizeof(buf), "strftime-err-%u", (unsigned)v);
1923 	return buf;
1924 }
1925 
1926 enum xfrd_packet_result
1927 xfrd_handle_received_xfr_packet(xfrd_zone_t* zone, buffer_type* packet)
1928 {
1929 	xfrd_soa_t soa;
1930 	enum xfrd_packet_result res;
1931         uint64_t xfrfile_size;
1932 
1933 	/* parse and check the packet - see if it ends the xfr */
1934 	switch((res=xfrd_parse_received_xfr_packet(zone, packet, &soa)))
1935 	{
1936 		case xfrd_packet_more:
1937 		case xfrd_packet_transfer:
1938 			/* continue with commit */
1939 			break;
1940 		case xfrd_packet_newlease:
1941 			return xfrd_packet_newlease;
1942 		case xfrd_packet_tcp:
1943 			return xfrd_packet_tcp;
1944 		case xfrd_packet_notimpl:
1945 		case xfrd_packet_bad:
1946 		case xfrd_packet_drop:
1947 		default:
1948 		{
1949 			/* rollback */
1950 			if(zone->msg_seq_nr > 0) {
1951 				/* do not process xfr - if only one part simply ignore it. */
1952 				/* delete file with previous parts of commit */
1953 				xfrd_unlink_xfrfile(xfrd->nsd, zone->xfrfilenumber);
1954 				VERBOSITY(1, (LOG_INFO, "xfrd: zone %s "
1955 					"reverted transfer %u from %s",
1956 					zone->apex_str, zone->msg_rr_count?
1957 					(int)zone->msg_new_serial:0,
1958 					zone->master->ip_address_spec));
1959 				zone->msg_seq_nr = 0;
1960 			} else if (res == xfrd_packet_bad) {
1961 				VERBOSITY(1, (LOG_INFO, "xfrd: zone %s "
1962 					"bad transfer %u from %s",
1963 					zone->apex_str, zone->msg_rr_count?
1964 					(int)zone->msg_new_serial:0,
1965 					zone->master->ip_address_spec));
1966 			}
1967 			if (res == xfrd_packet_notimpl)
1968 				return res;
1969 			else
1970 				return xfrd_packet_bad;
1971 		}
1972 	}
1973 
1974 	/* dump reply on disk to diff file */
1975 	/* if first part, get new filenumber.  Numbers can wrap around, 64bit
1976 	 * is enough so we do not collide with older-transfers-in-progress */
1977 	if(zone->msg_seq_nr == 0)
1978 		zone->xfrfilenumber = xfrd->xfrfilenumber++;
1979 	diff_write_packet(dname_to_string(zone->apex,0),
1980 		zone->zone_options->pattern->pname,
1981 		zone->msg_old_serial, zone->msg_new_serial, zone->msg_seq_nr,
1982 		buffer_begin(packet), buffer_limit(packet), xfrd->nsd,
1983 		zone->xfrfilenumber);
1984 	VERBOSITY(3, (LOG_INFO,
1985 		"xfrd: zone %s written received XFR packet from %s with serial %u to "
1986 		"disk", zone->apex_str, zone->master->ip_address_spec,
1987 		(int)zone->msg_new_serial));
1988 	zone->msg_seq_nr++;
1989 
1990         xfrfile_size = xfrd_get_xfrfile_size(xfrd->nsd, zone->xfrfilenumber);
1991 	if( zone->zone_options->pattern->size_limit_xfr != 0 &&
1992 	    xfrfile_size > zone->zone_options->pattern->size_limit_xfr ) {
1993             /*	    xfrd_unlink_xfrfile(xfrd->nsd, zone->xfrfilenumber);
1994                     xfrd_set_reload_timeout(); */
1995             log_msg(LOG_INFO, "xfrd : transfered zone data was too large %llu", (long long unsigned)xfrfile_size);
1996 	    return xfrd_packet_bad;
1997 	}
1998 	if(res == xfrd_packet_more) {
1999 		/* wait for more */
2000 		return xfrd_packet_more;
2001 	}
2002 
2003 	/* done. we are completely sure of this */
2004 	buffer_clear(packet);
2005 	buffer_printf(packet, "received update to serial %u at %s from %s",
2006 		(unsigned)zone->msg_new_serial, xfrd_pretty_time(xfrd_time()),
2007 		zone->master->ip_address_spec);
2008 	if(zone->master->key_options) {
2009 		buffer_printf(packet, " TSIG verified with key %s",
2010 			zone->master->key_options->name);
2011 	}
2012 	buffer_flip(packet);
2013 	diff_write_commit(zone->apex_str, zone->msg_old_serial,
2014 		zone->msg_new_serial, zone->msg_seq_nr, 1,
2015 		(char*)buffer_begin(packet), xfrd->nsd, zone->xfrfilenumber);
2016 	VERBOSITY(1, (LOG_INFO, "xfrd: zone %s committed \"%s\"",
2017 		zone->apex_str, (char*)buffer_begin(packet)));
2018 	/* reset msg seq nr, so if that is nonnull we know xfr file exists */
2019 	zone->msg_seq_nr = 0;
2020 	/* now put apply_xfr task on the tasklist */
2021 	if(!task_new_apply_xfr(xfrd->nsd->task[xfrd->nsd->mytask],
2022 		xfrd->last_task, zone->apex, zone->msg_old_serial,
2023 		zone->msg_new_serial, zone->xfrfilenumber)) {
2024 		/* delete the file and pretend transfer was bad to continue */
2025 		xfrd_unlink_xfrfile(xfrd->nsd, zone->xfrfilenumber);
2026 		xfrd_set_reload_timeout();
2027 		return xfrd_packet_bad;
2028 	}
2029 	/* update the disk serial no. */
2030 	zone->soa_disk_acquired = xfrd_time();
2031 	zone->soa_disk = soa;
2032 	if(zone->soa_notified_acquired && (
2033 		zone->soa_notified.serial == 0 ||
2034 		compare_serial(htonl(zone->soa_disk.serial),
2035 		htonl(zone->soa_notified.serial)) >= 0))
2036 	{
2037 		zone->soa_notified_acquired = 0;
2038 	}
2039 	if(!zone->soa_notified_acquired) {
2040 		/* do not set expired zone to ok:
2041 		 * it would cause nsd to start answering
2042 		 * bad data, since the zone is not loaded yet.
2043 		 * if nsd does not reload < retry time, more
2044 		 * queries (for even newer versions) are made.
2045 		 * For expired zone after reload it is set ok (SOAINFO ipc). */
2046 		if(zone->state != xfrd_zone_expired)
2047 			xfrd_set_zone_state(zone, xfrd_zone_ok);
2048 		DEBUG(DEBUG_XFRD,1, (LOG_INFO,
2049 			"xfrd: zone %s is waiting for reload",
2050 			zone->apex_str));
2051 		zone->round_num = -1; /* next try start anew */
2052 		xfrd_set_timer_refresh(zone);
2053 		xfrd_set_reload_timeout();
2054 		return xfrd_packet_transfer;
2055 	} else {
2056 		/* try to get an even newer serial */
2057 		/* pretend it was bad to continue queries */
2058 		xfrd_set_reload_timeout();
2059 		return xfrd_packet_bad;
2060 	}
2061 }
2062 
2063 static void
2064 xfrd_set_reload_timeout()
2065 {
2066 	if(xfrd->nsd->options->xfrd_reload_timeout == -1)
2067 		return; /* automatic reload disabled. */
2068 	if(xfrd->reload_timeout.tv_sec == 0 ||
2069 		xfrd_time() >= (time_t)xfrd->reload_timeout.tv_sec ) {
2070 		/* no reload wait period (or it passed), do it right away */
2071 		xfrd_set_reload_now(xfrd);
2072 		/* start reload wait period */
2073 		xfrd->reload_timeout.tv_sec = xfrd_time() +
2074 			xfrd->nsd->options->xfrd_reload_timeout;
2075 		xfrd->reload_timeout.tv_usec = 0;
2076 		return;
2077 	}
2078 	/* cannot reload now, set that after the timeout a reload has to happen */
2079 	if(xfrd->reload_added == 0) {
2080 		struct timeval tv;
2081 		tv.tv_sec = xfrd->reload_timeout.tv_sec - xfrd_time();
2082 		tv.tv_usec = 0;
2083 		if(tv.tv_sec > xfrd->nsd->options->xfrd_reload_timeout)
2084 			tv.tv_sec = xfrd->nsd->options->xfrd_reload_timeout;
2085 		event_set(&xfrd->reload_handler, -1, EV_TIMEOUT,
2086 			xfrd_handle_reload, xfrd);
2087 		if(event_base_set(xfrd->event_base, &xfrd->reload_handler) != 0)
2088 			log_msg(LOG_ERR, "cannot set reload event base");
2089 		if(event_add(&xfrd->reload_handler, &tv) != 0)
2090 			log_msg(LOG_ERR, "cannot add reload event");
2091 		xfrd->reload_added = 1;
2092 	}
2093 }
2094 
2095 static void
2096 xfrd_handle_reload(int ATTR_UNUSED(fd), short event, void* ATTR_UNUSED(arg))
2097 {
2098 	/* reload timeout */
2099 	assert(event & EV_TIMEOUT);
2100 	(void)event;
2101 	/* timeout wait period after this request is sent */
2102 	xfrd->reload_added = 0;
2103 	xfrd->reload_timeout.tv_sec = xfrd_time() +
2104 		xfrd->nsd->options->xfrd_reload_timeout;
2105 	xfrd_set_reload_now(xfrd);
2106 }
2107 
2108 void
2109 xfrd_handle_notify_and_start_xfr(xfrd_zone_t* zone, xfrd_soa_t* soa)
2110 {
2111 	if(xfrd_handle_incoming_notify(zone, soa)) {
2112 		if(zone->zone_handler.ev_fd == -1 && zone->tcp_conn == -1 &&
2113 			!zone->tcp_waiting && !zone->udp_waiting) {
2114 			xfrd_set_refresh_now(zone);
2115 		}
2116 		/* zones with no content start expbackoff again; this is also
2117 		 * for nsd-control started transfer commands, and also when
2118 		 * the master apparently sends notifies (is back up) */
2119 		if(zone->soa_disk_acquired == 0)
2120 			zone->fresh_xfr_timeout = XFRD_TRANSFER_TIMEOUT_START;
2121 	}
2122 }
2123 
2124 void
2125 xfrd_handle_passed_packet(buffer_type* packet,
2126 	int acl_num, int acl_num_xfr)
2127 {
2128 	uint8_t qnamebuf[MAXDOMAINLEN];
2129 	uint16_t qtype, qclass;
2130 	const dname_type* dname;
2131 	region_type* tempregion = region_create(xalloc, free);
2132 	xfrd_zone_t* zone;
2133 
2134 	buffer_skip(packet, QHEADERSZ);
2135 	if(!packet_read_query_section(packet, qnamebuf, &qtype, &qclass)) {
2136 		region_destroy(tempregion);
2137 		return; /* drop bad packet */
2138 	}
2139 
2140 	dname = dname_make(tempregion, qnamebuf, 1);
2141 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: got passed packet for %s, acl "
2142 		   "%d", dname_to_string(dname,0), acl_num));
2143 
2144 	/* find the zone */
2145 	zone = (xfrd_zone_t*)rbtree_search(xfrd->zones, dname);
2146 	if(!zone) {
2147 		/* this could be because the zone has been deleted meanwhile */
2148 		DEBUG(DEBUG_XFRD, 1, (LOG_INFO, "xfrd: incoming packet for "
2149 			"unknown zone %s", dname_to_string(dname,0)));
2150 		region_destroy(tempregion);
2151 		return; /* drop packet for unknown zone */
2152 	}
2153 	region_destroy(tempregion);
2154 
2155 	/* handle */
2156 	if(OPCODE(packet) == OPCODE_NOTIFY) {
2157 		xfrd_soa_t soa;
2158 		int have_soa = 0;
2159 		int next;
2160 		/* get serial from a SOA */
2161 		if(ANCOUNT(packet) == 1 && packet_skip_dname(packet) &&
2162 			xfrd_parse_soa_info(packet, &soa)) {
2163 				have_soa = 1;
2164 		}
2165 		xfrd_handle_notify_and_start_xfr(zone, have_soa?&soa:NULL);
2166 		/* First, see if our notifier has a match in provide-xfr */
2167 		if (acl_find_num(zone->zone_options->pattern->request_xfr,
2168 				acl_num_xfr))
2169 			next = acl_num_xfr;
2170 		else /* If not, find master that matches notifiers ACL entry */
2171 			next = find_same_master_notify(zone, acl_num);
2172 		if(next != -1) {
2173 			zone->next_master = next;
2174 			DEBUG(DEBUG_XFRD,1, (LOG_INFO,
2175 				"xfrd: notify set next master to query %d",
2176 				next));
2177 		}
2178 	}
2179 	else {
2180 		/* ignore other types of messages */
2181 	}
2182 }
2183 
2184 static int
2185 xfrd_handle_incoming_notify(xfrd_zone_t* zone, xfrd_soa_t* soa)
2186 {
2187 	if(soa && zone->soa_disk_acquired && zone->state != xfrd_zone_expired &&
2188 	   compare_serial(ntohl(soa->serial),ntohl(zone->soa_disk.serial)) <= 0)
2189 	{
2190 		DEBUG(DEBUG_XFRD,1, (LOG_INFO,
2191 			"xfrd: ignored notify %s %u old serial, zone valid "
2192 			"(soa disk serial %u)", zone->apex_str,
2193 			(unsigned)ntohl(soa->serial),
2194 			(unsigned)ntohl(zone->soa_disk.serial)));
2195 		return 0; /* ignore notify with old serial, we have a valid zone */
2196 	}
2197 	if(soa == 0) {
2198 		zone->soa_notified.serial = 0;
2199 	}
2200 	else if (zone->soa_notified_acquired == 0 ||
2201 		 zone->soa_notified.serial == 0 ||
2202 		 compare_serial(ntohl(soa->serial),
2203 			ntohl(zone->soa_notified.serial)) > 0)
2204 	{
2205 		zone->soa_notified = *soa;
2206 	}
2207 	zone->soa_notified_acquired = xfrd_time();
2208 	if(zone->state == xfrd_zone_ok) {
2209 		xfrd_set_zone_state(zone, xfrd_zone_refreshing);
2210 	}
2211 	/* transfer right away */
2212 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "Handle incoming notify for zone %s",
2213 		zone->apex_str));
2214 	return 1;
2215 }
2216 
2217 static int
2218 find_same_master_notify(xfrd_zone_t* zone, int acl_num_nfy)
2219 {
2220 	acl_options_t* nfy_acl = acl_find_num(zone->zone_options->pattern->
2221 		allow_notify, acl_num_nfy);
2222 	int num = 0;
2223 	acl_options_t* master = zone->zone_options->pattern->request_xfr;
2224 	if(!nfy_acl)
2225 		return -1;
2226 	while(master)
2227 	{
2228 		if(acl_addr_matches_host(nfy_acl, master))
2229 			return num;
2230 		master = master->next;
2231 		num++;
2232 	}
2233 	return -1;
2234 }
2235 
2236 void
2237 xfrd_check_failed_updates()
2238 {
2239 	/* see if updates have not come through */
2240 	xfrd_zone_t* zone;
2241 	RBTREE_FOR(zone, xfrd_zone_t*, xfrd->zones)
2242 	{
2243 		/* zone has a disk soa, and no nsd soa or a different nsd soa */
2244 		if(zone->soa_disk_acquired != 0 &&
2245 			(zone->soa_nsd_acquired == 0 ||
2246 			zone->soa_disk.serial != zone->soa_nsd.serial))
2247 		{
2248 			if(zone->soa_disk_acquired <
2249 				xfrd->reload_cmd_last_sent)
2250 			{
2251 				/* this zone should have been loaded, since its disk
2252 				   soa time is before the time of the reload cmd. */
2253 				xfrd_soa_t dumped_soa = zone->soa_disk;
2254 				log_msg(LOG_ERR, "xfrd: zone %s: soa serial %u "
2255 						 		 "update failed, restarting "
2256 						 		 "transfer (notified zone)",
2257 					zone->apex_str, (unsigned)ntohl(zone->soa_disk.serial));
2258 				/* revert the soa; it has not been acquired properly */
2259 				zone->soa_disk_acquired = zone->soa_nsd_acquired;
2260 				zone->soa_disk = zone->soa_nsd;
2261 				/* pretend we are notified with disk soa.
2262 				   This will cause a refetch of the data, and reload. */
2263 				xfrd_handle_incoming_notify(zone, &dumped_soa);
2264 				xfrd_set_timer_refresh(zone);
2265 			} else if(zone->soa_disk_acquired >= xfrd->reload_cmd_last_sent) {
2266 				/* this zone still has to be loaded,
2267 				   make sure reload is set to be sent. */
2268 				if(xfrd->need_to_send_reload == 0 &&
2269 					xfrd->reload_added == 0) {
2270 					log_msg(LOG_ERR, "xfrd: zone %s: needs "
2271 									 "to be loaded. reload lost? "
2272 									 "try again", zone->apex_str);
2273 					xfrd_set_reload_timeout();
2274 				}
2275 			}
2276 		}
2277 	}
2278 }
2279 
2280 void
2281 xfrd_prepare_zones_for_reload()
2282 {
2283 	xfrd_zone_t* zone;
2284 	RBTREE_FOR(zone, xfrd_zone_t*, xfrd->zones)
2285 	{
2286 		/* zone has a disk soa, and no nsd soa or a different nsd soa */
2287 		if(zone->soa_disk_acquired != 0 &&
2288 			(zone->soa_nsd_acquired == 0 ||
2289 			zone->soa_disk.serial != zone->soa_nsd.serial))
2290 		{
2291 			if(zone->soa_disk_acquired == xfrd_time()) {
2292 				/* antedate by one second.
2293 				 * this makes sure that the zone time is before
2294 				 * reload, so that check_failed_zones() is
2295 				 * certain of the result.
2296 				 */
2297 				zone->soa_disk_acquired--;
2298 			}
2299 		}
2300 	}
2301 }
2302 
2303 struct buffer*
2304 xfrd_get_temp_buffer()
2305 {
2306 	return xfrd->packet;
2307 }
2308 
2309 #ifdef BIND8_STATS
2310 /** process stat info task */
2311 static void
2312 xfrd_process_stat_info_task(xfrd_state_t* xfrd, struct task_list_d* task)
2313 {
2314 	size_t i;
2315 	stc_t* p = (void*)task->zname + sizeof(struct nsdst);
2316 	stats_add(&xfrd->nsd->st, (struct nsdst*)task->zname);
2317 	for(i=0; i<xfrd->nsd->child_count; i++) {
2318 		xfrd->nsd->children[i].query_count += *p++;
2319 	}
2320 	/* got total, now see if users are interested in these statistics */
2321 #ifdef HAVE_SSL
2322 	daemon_remote_process_stats(xfrd->nsd->rc);
2323 #endif
2324 }
2325 #endif /* BIND8_STATS */
2326 
2327 #ifdef USE_ZONE_STATS
2328 /** process zonestat inc task */
2329 static void
2330 xfrd_process_zonestat_inc_task(xfrd_state_t* xfrd, struct task_list_d* task)
2331 {
2332 	xfrd->zonestat_safe = (unsigned)task->oldserial;
2333 	zonestat_remap(xfrd->nsd, 0, xfrd->zonestat_safe*sizeof(struct nsdst));
2334 	xfrd->nsd->zonestatsize[0] = xfrd->zonestat_safe;
2335 	zonestat_remap(xfrd->nsd, 1, xfrd->zonestat_safe*sizeof(struct nsdst));
2336 	xfrd->nsd->zonestatsize[1] = xfrd->zonestat_safe;
2337 }
2338 #endif /* USE_ZONE_STATS */
2339 
2340 static void
2341 xfrd_handle_taskresult(xfrd_state_t* xfrd, struct task_list_d* task)
2342 {
2343 #ifndef BIND8_STATS
2344 	(void)xfrd;
2345 #endif
2346 	switch(task->task_type) {
2347 	case task_soa_info:
2348 		xfrd_process_soa_info_task(task);
2349 		break;
2350 #ifdef BIND8_STATS
2351 	case task_stat_info:
2352 		xfrd_process_stat_info_task(xfrd, task);
2353 		break;
2354 #endif /* BIND8_STATS */
2355 #ifdef USE_ZONE_STATS
2356 	case task_zonestat_inc:
2357 		xfrd_process_zonestat_inc_task(xfrd, task);
2358 		break;
2359 #endif
2360 	default:
2361 		log_msg(LOG_WARNING, "unhandled task result in xfrd from "
2362 			"reload type %d", (int)task->task_type);
2363 	}
2364 }
2365 
2366 void xfrd_process_task_result(xfrd_state_t* xfrd, struct udb_base* taskudb)
2367 {
2368 	udb_ptr t;
2369 	/* remap it for usage */
2370 	task_remap(taskudb);
2371 	/* process the task-results in the taskudb */
2372 	udb_ptr_new(&t, taskudb, udb_base_get_userdata(taskudb));
2373 	while(!udb_ptr_is_null(&t)) {
2374 		xfrd_handle_taskresult(xfrd, TASKLIST(&t));
2375 		udb_ptr_set_rptr(&t, taskudb, &TASKLIST(&t)->next);
2376 	}
2377 	udb_ptr_unlink(&t, taskudb);
2378 	/* clear the udb so it can be used by xfrd to make new tasks for
2379 	 * reload, this happens when the reload signal is sent, and thus
2380 	 * the taskudbs are swapped */
2381 	task_clear(taskudb);
2382 }
2383 
2384 void xfrd_set_reload_now(xfrd_state_t* xfrd)
2385 {
2386 	xfrd->need_to_send_reload = 1;
2387 	if(!(xfrd->ipc_handler_flags&EV_WRITE)) {
2388 		ipc_xfrd_set_listening(xfrd, EV_PERSIST|EV_READ|EV_WRITE);
2389 	}
2390 }
2391 
2392 static void
2393 xfrd_handle_write_timer(int ATTR_UNUSED(fd), short event, void* ATTR_UNUSED(arg))
2394 {
2395 	/* timeout for write events */
2396 	assert(event & EV_TIMEOUT);
2397 	(void)event;
2398 	if(xfrd->nsd->options->zonefiles_write == 0)
2399 		return;
2400 	/* call reload to write changed zonefiles */
2401 	if(!xfrd->write_zonefile_needed) {
2402 		DEBUG(DEBUG_XFRD,2, (LOG_INFO, "zonefiles write timer (nothing)"));
2403 		xfrd_write_timer_set();
2404 		return;
2405 	}
2406 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "zonefiles write timer"));
2407 	task_new_write_zonefiles(xfrd->nsd->task[xfrd->nsd->mytask],
2408 		xfrd->last_task, NULL);
2409 	xfrd_set_reload_now(xfrd);
2410 	xfrd->write_zonefile_needed = 0;
2411 	xfrd_write_timer_set();
2412 }
2413 
2414 static void xfrd_write_timer_set()
2415 {
2416 	struct timeval tv;
2417 	if(xfrd->nsd->options->zonefiles_write == 0)
2418 		return;
2419 	tv.tv_sec = xfrd->nsd->options->zonefiles_write;
2420 	tv.tv_usec = 0;
2421 	event_set(&xfrd->write_timer, -1, EV_TIMEOUT,
2422 		xfrd_handle_write_timer, xfrd);
2423 	if(event_base_set(xfrd->event_base, &xfrd->write_timer) != 0)
2424 		log_msg(LOG_ERR, "xfrd write timer: event_base_set failed");
2425 	if(event_add(&xfrd->write_timer, &tv) != 0)
2426 		log_msg(LOG_ERR, "xfrd write timer: event_add failed");
2427 }
2428 
2429 static void xfrd_handle_child_timer(int ATTR_UNUSED(fd), short event,
2430 	void* ATTR_UNUSED(arg))
2431 {
2432 	assert(event & EV_TIMEOUT);
2433 	(void)event;
2434 	/* only used to wakeup the process to reap children, note the
2435 	 * event is no longer registered */
2436 	xfrd->child_timer_added = 0;
2437 }
2438