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