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