xref: /openbsd/usr.sbin/nsd/remote.c (revision 3efee2e1)
1 /*
2  * remote.c - remote control for the NSD daemon.
3  *
4  * Copyright (c) 2008, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /**
37  * \file
38  *
39  * This file contains the remote control functionality for the daemon.
40  * The remote control can be performed using either the commandline
41  * nsd-control tool, or a TLS capable web browser.
42  * The channel is secured using TLSv1, and certificates.
43  * Both the server and the client(control tool) have their own keys.
44  */
45 #include "config.h"
46 
47 #ifdef HAVE_SSL
48 #ifdef HAVE_OPENSSL_SSL_H
49 #include <openssl/ssl.h>
50 #endif
51 #ifdef HAVE_OPENSSL_ERR_H
52 #include <openssl/err.h>
53 #endif
54 #ifdef HAVE_OPENSSL_RAND_H
55 #include <openssl/rand.h>
56 #endif
57 #endif /* HAVE_SSL */
58 #include <ctype.h>
59 #include <unistd.h>
60 #include <assert.h>
61 #include <fcntl.h>
62 #include <errno.h>
63 #ifndef USE_MINI_EVENT
64 #  ifdef HAVE_EVENT_H
65 #    include <event.h>
66 #  else
67 #    include <event2/event.h>
68 #    include "event2/event_struct.h"
69 #    include "event2/event_compat.h"
70 #  endif
71 #else
72 #  include "mini_event.h"
73 #endif
74 #include "remote.h"
75 #include "util.h"
76 #include "xfrd.h"
77 #include "xfrd-notify.h"
78 #include "xfrd-tcp.h"
79 #include "nsd.h"
80 #include "options.h"
81 #include "difffile.h"
82 #include "ipc.h"
83 
84 #ifdef HAVE_SYS_TYPES_H
85 #  include <sys/types.h>
86 #endif
87 #ifdef HAVE_SYS_STAT_H
88 #  include <sys/stat.h>
89 #endif
90 #ifdef HAVE_NETDB_H
91 #  include <netdb.h>
92 #endif
93 #ifdef HAVE_SYS_UN_H
94 #  include <sys/un.h>
95 #endif
96 #ifndef AF_LOCAL
97 #define AF_LOCAL AF_UNIX
98 #endif
99 
100 /** number of seconds timeout on incoming remote control handshake */
101 #define REMOTE_CONTROL_TCP_TIMEOUT 120
102 
103 /** repattern to master or slave */
104 #define REPAT_SLAVE  1
105 #define REPAT_MASTER 2
106 
107 /** if you want zero to be inhibited in stats output.
108  * it omits zeroes for types that have no acronym and unused-rcodes */
109 const int inhibit_zero = 1;
110 
111 /**
112  * a busy control command connection, SSL state
113  * Defined here to keep the definition private, and keep SSL out of the .h
114  */
115 struct rc_state {
116 	/** the next item in list */
117 	struct rc_state* next, *prev;
118 	/* if the event was added to the event_base */
119 	int event_added;
120 	/** the commpoint */
121 	struct event c;
122 	/** timeout for this state */
123 	struct timeval tval;
124 	/** in the handshake part */
125 	enum { rc_none, rc_hs_read, rc_hs_write } shake_state;
126 #ifdef HAVE_SSL
127 	/** the ssl state */
128 	SSL* ssl;
129 #endif
130 	/** file descriptor */
131 	int fd;
132 	/** the rc this is part of */
133 	struct daemon_remote* rc;
134 	/** stats list next item */
135 	struct rc_state* stats_next;
136 	/** stats list indicator (0 is not part of stats list, 1 is stats,
137 	 * 2 is stats_noreset. */
138 	int in_stats_list;
139 };
140 
141 /**
142  * list of events for accepting connections
143  */
144 struct acceptlist {
145 	struct acceptlist* next;
146 	int event_added;
147 	struct event c;
148 	char* ident;
149 	struct daemon_remote* rc;
150 };
151 
152 /**
153  * The remote control state.
154  */
155 struct daemon_remote {
156 	/** the master process for this remote control */
157 	struct xfrd_state* xfrd;
158 	/** commpoints for accepting remote control connections */
159 	struct acceptlist* accept_list;
160 	/* if certificates are used */
161 	int use_cert;
162 	/** number of active commpoints that are handling remote control */
163 	int active;
164 	/** max active commpoints */
165 	int max_active;
166 	/** current commpoints busy; double linked, malloced */
167 	struct rc_state* busy_list;
168 	/** commpoints waiting for stats to complete (also in busy_list) */
169 	struct rc_state* stats_list;
170 	/** last time stats was reported */
171 	struct timeval stats_time, boot_time;
172 #ifdef HAVE_SSL
173 	/** the SSL context for creating new SSL streams */
174 	SSL_CTX* ctx;
175 #endif
176 };
177 
178 /**
179  * Connection to print to, either SSL or plain over fd
180  */
181 struct remote_stream {
182 #ifdef HAVE_SSL
183 	/** SSL structure, nonNULL if using SSL */
184 	SSL* ssl;
185 #endif
186 	/** file descriptor for plain transfer */
187 	int fd;
188 };
189 typedef struct remote_stream RES;
190 
191 /**
192  * Print fixed line of text over ssl connection in blocking mode
193  * @param res: print to
194  * @param text: the text.
195  * @return false on connection failure.
196  */
197 static int ssl_print_text(RES* res, const char* text);
198 
199 /**
200  * printf style printing to the ssl connection
201  * @param res: the RES connection to print to. Blocking.
202  * @param format: printf style format string.
203  * @return success or false on a network failure.
204  */
205 static int ssl_printf(RES* res, const char* format, ...)
206         ATTR_FORMAT(printf, 2, 3);
207 
208 /**
209  * Read until \n is encountered
210  * If stream signals EOF, the string up to then is returned (without \n).
211  * @param res: the RES connection to read from. blocking.
212  * @param buf: buffer to read to.
213  * @param max: size of buffer.
214  * @return false on connection failure.
215  */
216 static int ssl_read_line(RES* res, char* buf, size_t max);
217 
218 /** perform the accept of a new remote control connection */
219 static void
220 remote_accept_callback(int fd, short event, void* arg);
221 
222 /** perform remote control */
223 static void
224 remote_control_callback(int fd, short event, void* arg);
225 
226 
227 /** ---- end of private defines ---- **/
228 
229 #ifdef HAVE_SSL
230 /** log ssl crypto err */
231 static void
232 log_crypto_err(const char* str)
233 {
234 	/* error:[error code]:[library name]:[function name]:[reason string] */
235 	char buf[128];
236 	unsigned long e;
237 	ERR_error_string_n(ERR_get_error(), buf, sizeof(buf));
238 	log_msg(LOG_ERR, "%s crypto %s", str, buf);
239 	while( (e=ERR_get_error()) ) {
240 		ERR_error_string_n(e, buf, sizeof(buf));
241 		log_msg(LOG_ERR, "and additionally crypto %s", buf);
242 	}
243 }
244 #endif /* HAVE_SSL */
245 
246 #ifdef BIND8_STATS
247 /** subtract timers and the values do not overflow or become negative */
248 static void
249 timeval_subtract(struct timeval* d, const struct timeval* end,
250 	const struct timeval* start)
251 {
252 #ifndef S_SPLINT_S
253 	time_t end_usec = end->tv_usec;
254 	d->tv_sec = end->tv_sec - start->tv_sec;
255 	if(end_usec < start->tv_usec) {
256 		end_usec += 1000000;
257 		d->tv_sec--;
258 	}
259 	d->tv_usec = end_usec - start->tv_usec;
260 #endif
261 }
262 #endif /* BIND8_STATS */
263 
264 #ifdef HAVE_SSL
265 static int
266 remote_setup_ctx(struct daemon_remote* rc, struct nsd_options* cfg)
267 {
268 	char* s_cert = cfg->server_cert_file;
269 	char* s_key = cfg->server_key_file;
270 	rc->ctx = server_tls_ctx_setup(s_key, s_cert, s_cert);
271 	if(!rc->ctx) {
272 		log_msg(LOG_ERR, "could not setup remote control TLS context");
273 		return 0;
274 	}
275 	return 1;
276 }
277 #endif /* HAVE_SSL */
278 
279 struct daemon_remote*
280 daemon_remote_create(struct nsd_options* cfg)
281 {
282 	struct daemon_remote* rc = (struct daemon_remote*)xalloc_zero(
283 		sizeof(*rc));
284 	rc->max_active = 10;
285 	assert(cfg->control_enable);
286 
287 	if(options_remote_is_address(cfg)) {
288 #ifdef HAVE_SSL
289 		if(!remote_setup_ctx(rc, cfg)) {
290 			daemon_remote_delete(rc);
291 			return NULL;
292 		}
293 		rc->use_cert = 1;
294 #else
295 		log_msg(LOG_ERR, "Could not setup remote control: NSD was compiled without SSL.");
296 #endif /* HAVE_SSL */
297 	} else {
298 		struct ip_address_option* o;
299 #ifdef HAVE_SSL
300 		rc->ctx = NULL;
301 #endif
302 		rc->use_cert = 0;
303 		for(o = cfg->control_interface; o; o = o->next) {
304 			if(o->address && o->address[0] != '/')
305 				log_msg(LOG_WARNING, "control-interface %s is not using TLS, but plain transfer, because first control-interface in config file is a local socket (starts with a /).", o->address);
306 		}
307 	}
308 
309 	/* and try to open the ports */
310 	if(!daemon_remote_open_ports(rc, cfg)) {
311 		log_msg(LOG_ERR, "could not open remote control port");
312 		daemon_remote_delete(rc);
313 		return NULL;
314 	}
315 
316 	if(gettimeofday(&rc->boot_time, NULL) == -1)
317 		log_msg(LOG_ERR, "gettimeofday: %s", strerror(errno));
318 	rc->stats_time = rc->boot_time;
319 
320 	return rc;
321 }
322 
323 void daemon_remote_close(struct daemon_remote* rc)
324 {
325 	struct rc_state* p, *np;
326 	struct acceptlist* h, *nh;
327 	if(!rc) return;
328 
329 	/* close listen sockets */
330 	h = rc->accept_list;
331 	while(h) {
332 		nh = h->next;
333 		if(h->event_added)
334 			event_del(&h->c);
335 		close(h->c.ev_fd);
336 		free(h->ident);
337 		free(h);
338 		h = nh;
339 	}
340 	rc->accept_list = NULL;
341 
342 	/* close busy connection sockets */
343 	p = rc->busy_list;
344 	while(p) {
345 		np = p->next;
346 		if(p->event_added)
347 			event_del(&p->c);
348 #ifdef HAVE_SSL
349 		if(p->ssl)
350 			SSL_free(p->ssl);
351 #endif
352 		close(p->c.ev_fd);
353 		free(p);
354 		p = np;
355 	}
356 	rc->busy_list = NULL;
357 	rc->active = 0;
358 }
359 
360 void daemon_remote_delete(struct daemon_remote* rc)
361 {
362 	if(!rc) return;
363 	daemon_remote_close(rc);
364 #ifdef HAVE_SSL
365 	if(rc->ctx) {
366 		SSL_CTX_free(rc->ctx);
367 	}
368 #endif
369 	free(rc);
370 }
371 
372 static int
373 create_tcp_accept_sock(struct addrinfo* addr, int* noproto)
374 {
375 #if defined(SO_REUSEADDR) || (defined(INET6) && (defined(IPV6_V6ONLY) || defined(IPV6_USE_MIN_MTU) || defined(IPV6_MTU)))
376 	int on = 1;
377 #endif
378 	int s;
379 	*noproto = 0;
380 	if ((s = socket(addr->ai_family, addr->ai_socktype, 0)) == -1) {
381 #if defined(INET6)
382 		if (addr->ai_family == AF_INET6 &&
383 			errno == EAFNOSUPPORT) {
384 			*noproto = 1;
385 			log_msg(LOG_WARNING, "fallback to TCP4, no IPv6: not supported");
386 			return -1;
387 		}
388 #endif /* INET6 */
389 		log_msg(LOG_ERR, "can't create a socket: %s", strerror(errno));
390 		return -1;
391 	}
392 #ifdef  SO_REUSEADDR
393 	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) {
394 		log_msg(LOG_ERR, "setsockopt(..., SO_REUSEADDR, ...) failed: %s", strerror(errno));
395 	}
396 #endif /* SO_REUSEADDR */
397 #if defined(INET6) && defined(IPV6_V6ONLY)
398 	if (addr->ai_family == AF_INET6 &&
399 		setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0)
400 	{
401 		log_msg(LOG_ERR, "setsockopt(..., IPV6_V6ONLY, ...) failed: %s", strerror(errno));
402 		close(s);
403 		return -1;
404 	}
405 #endif
406 	/* set it nonblocking */
407 	/* (StevensUNP p463), if tcp listening socket is blocking, then
408 	   it may block in accept, even if select() says readable. */
409 	if (fcntl(s, F_SETFL, O_NONBLOCK) == -1) {
410 		log_msg(LOG_ERR, "cannot fcntl tcp: %s", strerror(errno));
411 	}
412 	/* Bind it... */
413 	if (bind(s, (struct sockaddr *)addr->ai_addr, addr->ai_addrlen) != 0) {
414 		log_msg(LOG_ERR, "can't bind tcp socket: %s", strerror(errno));
415 		close(s);
416 		return -1;
417 	}
418 	/* Listen to it... */
419 	if (listen(s, TCP_BACKLOG_REMOTE) == -1) {
420 		log_msg(LOG_ERR, "can't listen: %s", strerror(errno));
421 		close(s);
422 		return -1;
423 	}
424 	return s;
425 }
426 
427 /**
428  * Add and open a new control port
429  * @param rc: rc with result list.
430  * @param ip: ip str
431  * @param nr: port nr
432  * @param noproto_is_err: if lack of protocol support is an error.
433  * @return false on failure.
434  */
435 static int
436 add_open(struct daemon_remote* rc, struct nsd_options* cfg, const char* ip,
437 	int nr, int noproto_is_err)
438 {
439 	struct addrinfo hints;
440 	struct addrinfo* res;
441 	struct acceptlist* hl;
442 	int noproto = 0;
443 	int fd, r;
444 	char port[15];
445 	snprintf(port, sizeof(port), "%d", nr);
446 	port[sizeof(port)-1]=0;
447 	memset(&hints, 0, sizeof(hints));
448 	assert(ip);
449 
450 	if(ip[0] == '/') {
451 		/* This looks like a local socket */
452 		fd = create_local_accept_sock(ip, &noproto);
453 		/*
454 		 * Change socket ownership and permissions so users other
455 		 * than root can access it provided they are in the same
456 		 * group as the user we run as.
457 		 */
458 		if(fd != -1) {
459 #ifdef HAVE_CHOWN
460 			if(chmod(ip, (mode_t)(S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)) == -1) {
461 				VERBOSITY(3, (LOG_INFO, "cannot chmod control socket %s: %s", ip, strerror(errno)));
462 			}
463 			if (cfg->username && cfg->username[0] &&
464 				nsd.uid != (uid_t)-1) {
465 				if(chown(ip, nsd.uid, nsd.gid) == -1)
466 					VERBOSITY(2, (LOG_INFO, "cannot chown %u.%u %s: %s",
467 					  (unsigned)nsd.uid, (unsigned)nsd.gid,
468 					  ip, strerror(errno)));
469 			}
470 #else
471 			(void)cfg;
472 #endif
473 		}
474 	} else {
475 		hints.ai_socktype = SOCK_STREAM;
476 		hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
477 		/* if we had no interface ip name, "default" is what we
478 		 * would do getaddrinfo for. */
479 		if((r = getaddrinfo(ip, port, &hints, &res)) != 0 || !res) {
480 			log_msg(LOG_ERR, "control interface %s:%s getaddrinfo: %s %s",
481 				ip, port, gai_strerror(r),
482 #ifdef EAI_SYSTEM
483 				r==EAI_SYSTEM?(char*)strerror(errno):""
484 #else
485 				""
486 #endif
487 				);
488 			return 0;
489 		}
490 
491 		/* open fd */
492 		fd = create_tcp_accept_sock(res, &noproto);
493 		freeaddrinfo(res);
494 	}
495 
496 	if(fd == -1 && noproto) {
497 		if(!noproto_is_err)
498 			return 1; /* return success, but do nothing */
499 		log_msg(LOG_ERR, "cannot open control interface %s %d : "
500 			"protocol not supported", ip, nr);
501 		return 0;
502 	}
503 	if(fd == -1) {
504 		log_msg(LOG_ERR, "cannot open control interface %s %d", ip, nr);
505 		return 0;
506 	}
507 
508 	/* alloc */
509 	hl = (struct acceptlist*)xalloc_zero(sizeof(*hl));
510 	hl->rc = rc;
511 	hl->ident = strdup(ip);
512 	if(!hl->ident) {
513 		log_msg(LOG_ERR, "malloc failure");
514 		close(fd);
515 		free(hl);
516 		return 0;
517 	}
518 	hl->next = rc->accept_list;
519 	rc->accept_list = hl;
520 
521 	hl->c.ev_fd = fd;
522 	hl->event_added = 0;
523 	return 1;
524 }
525 
526 int
527 daemon_remote_open_ports(struct daemon_remote* rc, struct nsd_options* cfg)
528 {
529 	assert(cfg->control_enable && cfg->control_port);
530 	if(cfg->control_interface) {
531 		ip_address_option_type* p;
532 		for(p = cfg->control_interface; p; p = p->next) {
533 			if(!add_open(rc, cfg, p->address, cfg->control_port, 1)) {
534 				return 0;
535 			}
536 		}
537 	} else {
538 		/* defaults */
539 		if(cfg->do_ip6 && !add_open(rc, cfg, "::1", cfg->control_port, 0)) {
540 			return 0;
541 		}
542 		if(cfg->do_ip4 &&
543 			!add_open(rc, cfg, "127.0.0.1", cfg->control_port, 1)) {
544 			return 0;
545 		}
546 	}
547 	return 1;
548 }
549 
550 void
551 daemon_remote_attach(struct daemon_remote* rc, struct xfrd_state* xfrd)
552 {
553 	int fd;
554 	struct acceptlist* p;
555 	if(!rc) return;
556 	rc->xfrd = xfrd;
557 	for(p = rc->accept_list; p; p = p->next) {
558 		/* add event */
559 		fd = p->c.ev_fd;
560 		memset(&p->c, 0, sizeof(p->c));
561 		event_set(&p->c, fd, EV_PERSIST|EV_READ, remote_accept_callback,
562 			p);
563 		if(event_base_set(xfrd->event_base, &p->c) != 0)
564 			log_msg(LOG_ERR, "remote: cannot set event_base");
565 		if(event_add(&p->c, NULL) != 0)
566 			log_msg(LOG_ERR, "remote: cannot add event");
567 		p->event_added = 1;
568 	}
569 }
570 
571 static void
572 remote_accept_callback(int fd, short event, void* arg)
573 {
574 	struct acceptlist *hl = (struct acceptlist*)arg;
575 	struct daemon_remote *rc = hl->rc;
576 #ifdef INET6
577 	struct sockaddr_storage addr;
578 #else
579 	struct sockaddr_in addr;
580 #endif
581 	socklen_t addrlen;
582 	int newfd;
583 	struct rc_state* n;
584 
585 	if (!(event & EV_READ)) {
586 		return;
587 	}
588 
589 	/* perform the accept */
590 	addrlen = sizeof(addr);
591 #ifndef HAVE_ACCEPT4
592 	newfd = accept(fd, (struct sockaddr*)&addr, &addrlen);
593 #else
594 	newfd = accept4(fd, (struct sockaddr*)&addr, &addrlen, SOCK_NONBLOCK);
595 #endif
596 	if(newfd == -1) {
597 		if (    errno != EINTR
598 			&& errno != EWOULDBLOCK
599 #ifdef ECONNABORTED
600 			&& errno != ECONNABORTED
601 #endif /* ECONNABORTED */
602 #ifdef EPROTO
603 			&& errno != EPROTO
604 #endif /* EPROTO */
605 			) {
606 			log_msg(LOG_ERR, "accept failed: %s", strerror(errno));
607 		}
608 		return;
609 	}
610 
611 	/* create new commpoint unless we are servicing already */
612 	if(rc->active >= rc->max_active) {
613 		log_msg(LOG_WARNING, "drop incoming remote control: "
614 			"too many connections");
615 	close_exit:
616 		close(newfd);
617 		return;
618 	}
619 
620 #ifndef HAVE_ACCEPT4
621 	if (fcntl(newfd, F_SETFL, O_NONBLOCK) == -1) {
622 		log_msg(LOG_ERR, "fcntl failed: %s", strerror(errno));
623 		goto close_exit;
624 	}
625 #endif
626 
627 	/* setup state to service the remote control command */
628 	n = (struct rc_state*)calloc(1, sizeof(*n));
629 	if(!n) {
630 		log_msg(LOG_ERR, "out of memory");
631 		goto close_exit;
632 	}
633 
634 	n->tval.tv_sec = REMOTE_CONTROL_TCP_TIMEOUT;
635 	n->tval.tv_usec = 0L;
636 	n->fd = newfd;
637 
638 	memset(&n->c, 0, sizeof(n->c));
639 	event_set(&n->c, newfd, EV_PERSIST|EV_TIMEOUT|EV_READ,
640 		remote_control_callback, n);
641 	if(event_base_set(xfrd->event_base, &n->c) != 0) {
642 		log_msg(LOG_ERR, "remote_accept: cannot set event_base");
643 		free(n);
644 		goto close_exit;
645 	}
646 	if(event_add(&n->c, &n->tval) != 0) {
647 		log_msg(LOG_ERR, "remote_accept: cannot add event");
648 		free(n);
649 		goto close_exit;
650 	}
651 	n->event_added = 1;
652 
653 	if(2 <= verbosity) {
654 		if(hl->ident && hl->ident[0] == '/') {
655 			VERBOSITY(2, (LOG_INFO, "new control connection from %s", hl->ident));
656 		} else {
657 			char s[128];
658 			addr2str(&addr, s, sizeof(s));
659 			VERBOSITY(2, (LOG_INFO, "new control connection from %s", s));
660 		}
661 	}
662 
663 #ifdef HAVE_SSL
664 	if(rc->ctx) {
665 		n->shake_state = rc_hs_read;
666 		n->ssl = SSL_new(rc->ctx);
667 		if(!n->ssl) {
668 			log_crypto_err("could not SSL_new");
669 			event_del(&n->c);
670 			free(n);
671 			goto close_exit;
672 		}
673 		SSL_set_accept_state(n->ssl);
674 		(void)SSL_set_mode(n->ssl, SSL_MODE_AUTO_RETRY);
675 		if(!SSL_set_fd(n->ssl, newfd)) {
676 			log_crypto_err("could not SSL_set_fd");
677 			event_del(&n->c);
678 			SSL_free(n->ssl);
679 			free(n);
680 			goto close_exit;
681 		}
682 	} else {
683 		n->ssl = NULL;
684 	}
685 #endif /* HAVE_SSL */
686 
687 	n->rc = rc;
688 	n->stats_next = NULL;
689 	n->in_stats_list = 0;
690 	n->prev = NULL;
691 	n->next = rc->busy_list;
692 	if(n->next) n->next->prev = n;
693 	rc->busy_list = n;
694 	rc->active ++;
695 
696 	/* perform the first nonblocking read already, for windows,
697 	 * so it can return wouldblock. could be faster too. */
698 	remote_control_callback(newfd, EV_READ, n);
699 }
700 
701 /** delete from list */
702 static void
703 state_list_remove_elem(struct rc_state** list, struct rc_state* todel)
704 {
705 	if(todel->prev) todel->prev->next = todel->next;
706 	else	*list = todel->next;
707 	if(todel->next) todel->next->prev = todel->prev;
708 }
709 
710 /** delete from stats list */
711 static void
712 stats_list_remove_elem(struct rc_state** list, struct rc_state* todel)
713 {
714 	struct rc_state* prev = NULL;
715 	struct rc_state* n = *list;
716 	while(n) {
717 		/* delete this one? */
718 		if(n == todel) {
719 			if(prev) prev->next = n->next;
720 			else	(*list) = n->next;
721 			/* go on and delete further elements */
722 			/* prev = prev; */
723 			n = n->next;
724 			continue;
725 		}
726 
727 		/* go to the next element */
728 		prev = n;
729 		n = n->next;
730 	}
731 }
732 
733 /** decrease active count and remove commpoint from busy list */
734 static void
735 clean_point(struct daemon_remote* rc, struct rc_state* s)
736 {
737 	if(s->in_stats_list)
738 		stats_list_remove_elem(&rc->stats_list, s);
739 	state_list_remove_elem(&rc->busy_list, s);
740 	rc->active --;
741 	if(s->event_added)
742 		event_del(&s->c);
743 #ifdef HAVE_SSL
744 	if(s->ssl) {
745 		SSL_shutdown(s->ssl);
746 		SSL_free(s->ssl);
747 	}
748 #endif /* HAVE_SSL */
749 	close(s->c.ev_fd);
750 	free(s);
751 }
752 
753 static int
754 ssl_print_text(RES* res, const char* text)
755 {
756 	if(!res)
757 		return 0;
758 #ifdef HAVE_SSL
759 	if(res->ssl) {
760 		int r;
761 		ERR_clear_error();
762 		if((r=SSL_write(res->ssl, text, (int)strlen(text))) <= 0) {
763 			if(SSL_get_error(res->ssl, r) == SSL_ERROR_ZERO_RETURN) {
764 				VERBOSITY(2, (LOG_WARNING, "in SSL_write, peer "
765 					"closed connection"));
766 				return 0;
767 			}
768 			log_crypto_err("could not SSL_write");
769 			return 0;
770 		}
771 	} else {
772 #endif /* HAVE_SSL */
773 		if(write_socket(res->fd, text, strlen(text)) <= 0) {
774 			log_msg(LOG_ERR, "could not write: %s",
775 				strerror(errno));
776 			return 0;
777 		}
778 #ifdef HAVE_SSL
779 	}
780 #endif /* HAVE_SSL */
781 	return 1;
782 }
783 
784 /** print text over the ssl connection */
785 static int
786 ssl_print_vmsg(RES* ssl, const char* format, va_list args)
787 {
788 	char msg[1024];
789 	vsnprintf(msg, sizeof(msg), format, args);
790 	return ssl_print_text(ssl, msg);
791 }
792 
793 /** printf style printing to the ssl connection */
794 static int
795 ssl_printf(RES* ssl, const char* format, ...)
796 {
797 	va_list args;
798 	int ret;
799 	va_start(args, format);
800 	ret = ssl_print_vmsg(ssl, format, args);
801 	va_end(args);
802 	return ret;
803 }
804 
805 static int
806 ssl_read_line(RES* res, char* buf, size_t max)
807 {
808 	size_t len = 0;
809 	if(!res)
810 		return 0;
811 	while(len < max) {
812 		buf[len] = 0; /* terminate for safety and please checkers */
813 		/* this byte is written if we read a byte from the input */
814 #ifdef HAVE_SSL
815 		if(res->ssl) {
816 			int r;
817 			ERR_clear_error();
818 			if((r=SSL_read(res->ssl, buf+len, 1)) <= 0) {
819 				if(SSL_get_error(res->ssl, r) == SSL_ERROR_ZERO_RETURN) {
820 					buf[len] = 0;
821 					return 1;
822 				}
823 				log_crypto_err("could not SSL_read");
824 				return 0;
825 			}
826 		} else {
827 #endif /* HAVE_SSL */
828 			while(1) {
829 				ssize_t rr = read(res->fd, buf+len, 1);
830 				if(rr <= 0) {
831 					if(rr == 0) {
832 						buf[len] = 0;
833 						return 1;
834 					}
835 					if(errno == EINTR || errno == EAGAIN)
836 						continue;
837 					log_msg(LOG_ERR, "could not read: %s",
838 						strerror(errno));
839 					return 0;
840 				}
841 				break;
842 			}
843 #ifdef HAVE_SSL
844 		}
845 #endif /* HAVE_SSL */
846 		if(buf[len] == '\n') {
847 			/* return string without \n */
848 			buf[len] = 0;
849 			return 1;
850 		}
851 		len++;
852 	}
853 	buf[max-1] = 0;
854 	log_msg(LOG_ERR, "control line too long (%d): %s", (int)max, buf);
855 	return 0;
856 }
857 
858 /** skip whitespace, return new pointer into string */
859 static char*
860 skipwhite(char* str)
861 {
862 	/* EOS \0 is not a space */
863 	while( isspace((unsigned char)*str) )
864 		str++;
865 	return str;
866 }
867 
868 /** send the OK to the control client */
869 static void
870 send_ok(RES* ssl)
871 {
872 	(void)ssl_printf(ssl, "ok\n");
873 }
874 
875 /** get zone argument (if any) or NULL, false on error */
876 static int
877 get_zone_arg(RES* ssl, xfrd_state_type* xfrd, char* arg,
878 	struct zone_options** zo)
879 {
880 	const dname_type* dname;
881 	if(!arg[0]) {
882 		/* no argument present, return NULL */
883 		*zo = NULL;
884 		return 1;
885 	}
886 	dname = dname_parse(xfrd->region, arg);
887 	if(!dname) {
888 		(void)ssl_printf(ssl, "error cannot parse zone name '%s'\n", arg);
889 		*zo = NULL;
890 		return 0;
891 	}
892 	*zo = zone_options_find(xfrd->nsd->options, dname);
893 	region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
894 	if(!*zo) {
895 		(void)ssl_printf(ssl, "error zone %s not configured\n", arg);
896 		return 0;
897 	}
898 	return 1;
899 }
900 
901 /** do the stop command */
902 static void
903 do_stop(RES* ssl, xfrd_state_type* xfrd)
904 {
905 	xfrd->need_to_send_shutdown = 1;
906 
907 	if(!(xfrd->ipc_handler_flags&EV_WRITE)) {
908 		ipc_xfrd_set_listening(xfrd, EV_PERSIST|EV_READ|EV_WRITE);
909 	}
910 
911 	send_ok(ssl);
912 }
913 
914 /** do the log_reopen command, it only needs reload_now */
915 static void
916 do_log_reopen(RES* ssl, xfrd_state_type* xfrd)
917 {
918 	xfrd_set_reload_now(xfrd);
919 	send_ok(ssl);
920 }
921 
922 /** do the reload command */
923 static void
924 do_reload(RES* ssl, xfrd_state_type* xfrd, char* arg)
925 {
926 	struct zone_options* zo;
927 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
928 		return;
929 	task_new_check_zonefiles(xfrd->nsd->task[xfrd->nsd->mytask],
930 		xfrd->last_task, zo?(const dname_type*)zo->node.key:NULL);
931 	xfrd_set_reload_now(xfrd);
932 	send_ok(ssl);
933 }
934 
935 /** do the write command */
936 static void
937 do_write(RES* ssl, xfrd_state_type* xfrd, char* arg)
938 {
939 	struct zone_options* zo;
940 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
941 		return;
942 	task_new_write_zonefiles(xfrd->nsd->task[xfrd->nsd->mytask],
943 		xfrd->last_task, zo?(const dname_type*)zo->node.key:NULL);
944 	xfrd_set_reload_now(xfrd);
945 	send_ok(ssl);
946 }
947 
948 /** do the notify command */
949 static void
950 do_notify(RES* ssl, xfrd_state_type* xfrd, char* arg)
951 {
952 	struct zone_options* zo;
953 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
954 		return;
955 	if(zo) {
956 		struct notify_zone* n = (struct notify_zone*)rbtree_search(
957 			xfrd->notify_zones, (const dname_type*)zo->node.key);
958 		if(n) {
959 			xfrd_notify_start(n, xfrd);
960 			send_ok(ssl);
961 		} else {
962 			(void)ssl_printf(ssl, "error zone does not have notify\n");
963 		}
964 	} else {
965 		struct notify_zone* n;
966 		RBTREE_FOR(n, struct notify_zone*, xfrd->notify_zones) {
967 			xfrd_notify_start(n, xfrd);
968 		}
969 		send_ok(ssl);
970 	}
971 }
972 
973 /** do the transfer command */
974 static void
975 do_transfer(RES* ssl, xfrd_state_type* xfrd, char* arg)
976 {
977 	struct zone_options* zo;
978 	xfrd_zone_type* zone;
979 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
980 		return;
981 	if(zo) {
982 		zone = (xfrd_zone_type*)rbtree_search(xfrd->zones, (const
983 			dname_type*)zo->node.key);
984 		if(zone) {
985 			xfrd_handle_notify_and_start_xfr(zone, NULL);
986 			send_ok(ssl);
987 		} else {
988 			(void)ssl_printf(ssl, "error zone not slave\n");
989 		}
990 	} else {
991 		RBTREE_FOR(zone, xfrd_zone_type*, xfrd->zones) {
992 			xfrd_handle_notify_and_start_xfr(zone, NULL);
993 		}
994 		(void)ssl_printf(ssl, "ok, %lu zones\n", (unsigned long)xfrd->zones->count);
995 	}
996 }
997 
998 /** force transfer a zone */
999 static void
1000 force_transfer_zone(xfrd_zone_type* zone)
1001 {
1002 	/* if in TCP transaction, stop it immediately. */
1003 	if(zone->tcp_conn != -1)
1004 		xfrd_tcp_release(xfrd->tcp_set, zone);
1005 	else if(zone->zone_handler.ev_fd != -1)
1006 		xfrd_udp_release(zone);
1007 	/* pretend we not longer have it and force any
1008 	 * zone to be downloaded (even same serial, w AXFR) */
1009 	zone->soa_disk_acquired = 0;
1010 	zone->soa_nsd_acquired = 0;
1011 	xfrd_handle_notify_and_start_xfr(zone, NULL);
1012 }
1013 
1014 /** do the force transfer command */
1015 static void
1016 do_force_transfer(RES* ssl, xfrd_state_type* xfrd, char* arg)
1017 {
1018 	struct zone_options* zo;
1019 	xfrd_zone_type* zone;
1020 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
1021 		return;
1022 	if(zo) {
1023 		zone = (xfrd_zone_type*)rbtree_search(xfrd->zones, (const
1024 			dname_type*)zo->node.key);
1025 		if(zone) {
1026 			force_transfer_zone(zone);
1027 			send_ok(ssl);
1028 		} else {
1029 			(void)ssl_printf(ssl, "error zone not slave\n");
1030 		}
1031 	} else {
1032 		RBTREE_FOR(zone, xfrd_zone_type*, xfrd->zones) {
1033 			force_transfer_zone(zone);
1034 		}
1035 		(void)ssl_printf(ssl, "ok, %lu zones\n", (unsigned long)xfrd->zones->count);
1036 	}
1037 }
1038 
1039 static int
1040 print_soa_status(RES* ssl, const char* str, xfrd_soa_type* soa, time_t acq)
1041 {
1042 	if(acq) {
1043 		if(!ssl_printf(ssl, "	%s: \"%u since %s\"\n", str,
1044 			(unsigned)ntohl(soa->serial), xfrd_pretty_time(acq)))
1045 			return 0;
1046 	} else {
1047 		if(!ssl_printf(ssl, "	%s: none\n", str))
1048 			return 0;
1049 	}
1050 	return 1;
1051 }
1052 
1053 /** print zonestatus for one domain */
1054 static int
1055 print_zonestatus(RES* ssl, xfrd_state_type* xfrd, struct zone_options* zo)
1056 {
1057 	xfrd_zone_type* xz = (xfrd_zone_type*)rbtree_search(xfrd->zones,
1058 		(const dname_type*)zo->node.key);
1059 	struct notify_zone* nz = (struct notify_zone*)rbtree_search(
1060 		xfrd->notify_zones, (const dname_type*)zo->node.key);
1061 	if(!ssl_printf(ssl, "zone:	%s\n", zo->name))
1062 		return 0;
1063 	if(!zo->part_of_config) {
1064 		if(!ssl_printf(ssl, "	pattern: %s\n", zo->pattern->pname))
1065 			return 0;
1066 	}
1067 	if(nz) {
1068 		if(nz->is_waiting) {
1069 			if(!ssl_printf(ssl, "	notify: \"waiting-for-fd\"\n"))
1070 				return 0;
1071 		} else if(nz->notify_send_enable || nz->notify_send6_enable) {
1072 			int i;
1073 			if(!ssl_printf(ssl, "	notify: \"send"))
1074 				return 0;
1075 			for(i=0; i<NOTIFY_CONCURRENT_MAX; i++) {
1076 				if(!nz->pkts[i].dest) continue;
1077 				if(!ssl_printf(ssl, " %s",
1078 					nz->pkts[i].dest->ip_address_spec))
1079 					return 0;
1080 			}
1081 			if(!ssl_printf(ssl, " with serial %u\"\n",
1082 				(unsigned)ntohl(nz->current_soa->serial)))
1083 				return 0;
1084 		}
1085 	}
1086 	if(!xz) {
1087 		if(!ssl_printf(ssl, "	state: master\n"))
1088 			return 0;
1089 		return 1;
1090 	}
1091 	if(!ssl_printf(ssl, "	state: %s\n",
1092 		(xz->state == xfrd_zone_ok)?"ok":(
1093 		(xz->state == xfrd_zone_expired)?"expired":"refreshing")))
1094 		return 0;
1095 	if(!print_soa_status(ssl, "served-serial", &xz->soa_nsd,
1096 		xz->soa_nsd_acquired))
1097 		return 0;
1098 	if(!print_soa_status(ssl, "commit-serial", &xz->soa_disk,
1099 		xz->soa_disk_acquired))
1100 		return 0;
1101 	if(xz->round_num != -1) {
1102 		if(!print_soa_status(ssl, "notified-serial", &xz->soa_notified,
1103 			xz->soa_notified_acquired))
1104 			return 0;
1105 	} else if(xz->event_added) {
1106 		if(!ssl_printf(ssl, "\twait: \"%lu sec between attempts\"\n",
1107 			(unsigned long)xz->timeout.tv_sec))
1108 			return 0;
1109 	}
1110 
1111 	/* UDP */
1112 	if(xz->udp_waiting) {
1113 		if(!ssl_printf(ssl, "	transfer: \"waiting-for-UDP-fd\"\n"))
1114 			return 0;
1115 	} else if(xz->zone_handler.ev_fd != -1 && xz->tcp_conn == -1) {
1116 		if(!ssl_printf(ssl, "	transfer: \"sent UDP to %s\"\n",
1117 			xz->master->ip_address_spec))
1118 			return 0;
1119 	}
1120 
1121 	/* TCP */
1122 	if(xz->tcp_waiting) {
1123 		if(!ssl_printf(ssl, "	transfer: \"waiting-for-TCP-fd\"\n"))
1124 			return 0;
1125 	} else if(xz->tcp_conn != -1) {
1126 		if(!ssl_printf(ssl, "	transfer: \"TCP connected to %s\"\n",
1127 			xz->master->ip_address_spec))
1128 			return 0;
1129 	}
1130 
1131 	return 1;
1132 }
1133 
1134 /** do the zonestatus command */
1135 static void
1136 do_zonestatus(RES* ssl, xfrd_state_type* xfrd, char* arg)
1137 {
1138 	struct zone_options* zo;
1139 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
1140 		return;
1141 	if(zo) (void)print_zonestatus(ssl, xfrd, zo);
1142 	else {
1143 		RBTREE_FOR(zo, struct zone_options*,
1144 			xfrd->nsd->options->zone_options) {
1145 			if(!print_zonestatus(ssl, xfrd, zo))
1146 				return;
1147 		}
1148 	}
1149 }
1150 
1151 /** do the verbosity command */
1152 static void
1153 do_verbosity(RES* ssl, char* str)
1154 {
1155 	int val = atoi(str);
1156 	if(strcmp(str, "") == 0) {
1157 		(void)ssl_printf(ssl, "verbosity %d\n", verbosity);
1158 		return;
1159 	}
1160 	if(val == 0 && strcmp(str, "0") != 0) {
1161 		(void)ssl_printf(ssl, "error in verbosity number syntax: %s\n", str);
1162 		return;
1163 	}
1164 	verbosity = val;
1165 	task_new_set_verbosity(xfrd->nsd->task[xfrd->nsd->mytask],
1166 		xfrd->last_task, val);
1167 	xfrd_set_reload_now(xfrd);
1168 	send_ok(ssl);
1169 }
1170 
1171 /** find second argument, modifies string */
1172 static int
1173 find_arg2(RES* ssl, char* arg, char** arg2)
1174 {
1175 	char* as = strrchr(arg, ' ');
1176 	if(as) {
1177 		as[0]=0;
1178 		*arg2 = as+1;
1179 		while(isspace((unsigned char)*as) && as > arg)
1180 			as--;
1181 		as[0]=0;
1182 		return 1;
1183 	}
1184 	*arg2 = NULL;
1185 	(void)ssl_printf(ssl, "error could not find next argument "
1186 		"after %s\n", arg);
1187 	return 0;
1188 }
1189 
1190 /** find second and third arguments, modifies string,
1191  * does not print error for missing arg3 so that if it does not find an
1192  * arg3, the caller can use two arguments. */
1193 static int
1194 find_arg3(RES* ssl, char* arg, char** arg2, char** arg3)
1195 {
1196 	if(find_arg2(ssl, arg, arg2)) {
1197 		char* as;
1198 		*arg3 = *arg2;
1199 		as = strrchr(arg, ' ');
1200 		if(as) {
1201 			as[0]=0;
1202 			*arg2 = as+1;
1203 			while(isspace((unsigned char)*as) && as > arg)
1204 				as--;
1205 			as[0]=0;
1206 			return 1;
1207 		}
1208 	}
1209 	*arg3 = NULL;
1210 	return 0;
1211 }
1212 
1213 /** do the status command */
1214 static void
1215 do_status(RES* ssl, xfrd_state_type* xfrd)
1216 {
1217 	if(!ssl_printf(ssl, "version: %s\n", PACKAGE_VERSION))
1218 		return;
1219 	if(!ssl_printf(ssl, "verbosity: %d\n", verbosity))
1220 		return;
1221 #ifdef RATELIMIT
1222 	if(!ssl_printf(ssl, "ratelimit: %d\n",
1223 		(int)xfrd->nsd->options->rrl_ratelimit))
1224 		return;
1225 #else
1226 	(void)xfrd;
1227 #endif
1228 }
1229 
1230 /** do the stats command */
1231 static void
1232 do_stats(struct daemon_remote* rc, int peek, struct rc_state* rs)
1233 {
1234 #ifdef BIND8_STATS
1235 	/* queue up to get stats after a reload is done (to gather statistics
1236 	 * from the servers) */
1237 	assert(!rs->in_stats_list);
1238 	if(peek) rs->in_stats_list = 2;
1239 	else	rs->in_stats_list = 1;
1240 	rs->stats_next = rc->stats_list;
1241 	rc->stats_list = rs;
1242 	/* block the tcp waiting for the reload */
1243 	event_del(&rs->c);
1244 	rs->event_added = 0;
1245 	/* force a reload */
1246 	xfrd_set_reload_now(xfrd);
1247 #else
1248 	RES res;
1249 	res.ssl = rs->ssl;
1250 	res.fd = rs->fd;
1251 	(void)rc; (void)peek;
1252 	(void)ssl_printf(&res, "error no stats enabled at compile time\n");
1253 #endif /* BIND8_STATS */
1254 }
1255 
1256 /** see if we have more zonestatistics entries and it has to be incremented */
1257 static void
1258 zonestat_inc_ifneeded(xfrd_state_type* xfrd)
1259 {
1260 #ifdef USE_ZONE_STATS
1261 	if(xfrd->nsd->options->zonestatnames->count != xfrd->zonestat_safe)
1262 		task_new_zonestat_inc(xfrd->nsd->task[xfrd->nsd->mytask],
1263 			xfrd->last_task,
1264 			xfrd->nsd->options->zonestatnames->count);
1265 #else
1266 	(void)xfrd;
1267 #endif /* USE_ZONE_STATS */
1268 }
1269 
1270 /** perform the changezone command for one zone */
1271 static int
1272 perform_changezone(RES* ssl, xfrd_state_type* xfrd, char* arg)
1273 {
1274 	const dname_type* dname;
1275 	struct zone_options* zopt;
1276 	char* arg2 = NULL;
1277 	if(!find_arg2(ssl, arg, &arg2))
1278 		return 0;
1279 
1280 	/* if we add it to the xfrd now, then xfrd could download AXFR and
1281 	 * store it and the NSD-reload would see it in the difffile before
1282 	 * it sees the add-config task.
1283 	 */
1284 	/* thus: AXFRs and IXFRs must store the pattern name in the
1285 	 * difffile, so that it can be added when the AXFR or IXFR is seen.
1286 	 */
1287 
1288 	/* check that the pattern exists */
1289 	if(!rbtree_search(xfrd->nsd->options->patterns, arg2)) {
1290 		(void)ssl_printf(ssl, "error pattern %s does not exist\n",
1291 			arg2);
1292 		return 0;
1293 	}
1294 
1295 	dname = dname_parse(xfrd->region, arg);
1296 	if(!dname) {
1297 		(void)ssl_printf(ssl, "error cannot parse zone name\n");
1298 		return 0;
1299 	}
1300 
1301 	/* see if zone is a duplicate */
1302 	if( (zopt=zone_options_find(xfrd->nsd->options, dname)) ) {
1303 		if(zopt->part_of_config) {
1304 			(void)ssl_printf(ssl, "error zone defined in nsd.conf, "
1305 			  "cannot delete it in this manner: remove it from "
1306 			  "nsd.conf yourself and repattern\n");
1307 			region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
1308 			dname = NULL;
1309 			return 0;
1310 		}
1311 		/* found the zone, now delete it */
1312 		/* create deletion task */
1313 		/* this deletion task is processed before the addition task,
1314 		 * that is created below, in the same reload process, causing
1315 		 * a seamless change from one to the other, with no downtime
1316 		 * for the zone. */
1317 		task_new_del_zone(xfrd->nsd->task[xfrd->nsd->mytask],
1318 			xfrd->last_task, dname);
1319 		xfrd_set_reload_now(xfrd);
1320 		/* delete it in xfrd */
1321 		if(zone_is_slave(zopt)) {
1322 			xfrd_del_slave_zone(xfrd, dname);
1323 		}
1324 		xfrd_del_notify(xfrd, dname);
1325 		/* delete from config */
1326 		zone_list_del(xfrd->nsd->options, zopt);
1327 	} else {
1328 		(void)ssl_printf(ssl, "zone %s did not exist, creating", arg);
1329 	}
1330 	region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
1331 	dname = NULL;
1332 
1333 	/* add to zonelist and adds to config in memory */
1334 	zopt = zone_list_add(xfrd->nsd->options, arg, arg2);
1335 	if(!zopt) {
1336 		/* also dname parse error here */
1337 		(void)ssl_printf(ssl, "error could not add zonelist entry\n");
1338 		return 0;
1339 	}
1340 	/* make addzone task and schedule reload */
1341 	task_new_add_zone(xfrd->nsd->task[xfrd->nsd->mytask],
1342 		xfrd->last_task, arg, arg2,
1343 		getzonestatid(xfrd->nsd->options, zopt));
1344 	zonestat_inc_ifneeded(xfrd);
1345 	xfrd_set_reload_now(xfrd);
1346 	/* add to xfrd - notify (for master and slaves) */
1347 	init_notify_send(xfrd->notify_zones, xfrd->region, zopt);
1348 	/* add to xfrd - slave */
1349 	if(zone_is_slave(zopt)) {
1350 		xfrd_init_slave_zone(xfrd, zopt);
1351 	}
1352 	return 1;
1353 }
1354 
1355 /** perform the addzone command for one zone */
1356 static int
1357 perform_addzone(RES* ssl, xfrd_state_type* xfrd, char* arg)
1358 {
1359 	const dname_type* dname;
1360 	struct zone_options* zopt;
1361 	char* arg2 = NULL;
1362 	if(!find_arg2(ssl, arg, &arg2))
1363 		return 0;
1364 
1365 	/* if we add it to the xfrd now, then xfrd could download AXFR and
1366 	 * store it and the NSD-reload would see it in the difffile before
1367 	 * it sees the add-config task.
1368 	 */
1369 	/* thus: AXFRs and IXFRs must store the pattern name in the
1370 	 * difffile, so that it can be added when the AXFR or IXFR is seen.
1371 	 */
1372 
1373 	/* check that the pattern exists */
1374 	if(!rbtree_search(xfrd->nsd->options->patterns, arg2)) {
1375 		(void)ssl_printf(ssl, "error pattern %s does not exist\n",
1376 			arg2);
1377 		return 0;
1378 	}
1379 
1380 	dname = dname_parse(xfrd->region, arg);
1381 	if(!dname) {
1382 		(void)ssl_printf(ssl, "error cannot parse zone name\n");
1383 		return 0;
1384 	}
1385 
1386 	/* see if zone is a duplicate */
1387 	if( zone_options_find(xfrd->nsd->options, dname) ) {
1388 		region_recycle(xfrd->region, (void*)dname,
1389 			dname_total_size(dname));
1390 		(void)ssl_printf(ssl, "zone %s already exists\n", arg);
1391 		return 1;
1392 	}
1393 	region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
1394 	dname = NULL;
1395 
1396 	/* add to zonelist and adds to config in memory */
1397 	zopt = zone_list_add(xfrd->nsd->options, arg, arg2);
1398 	if(!zopt) {
1399 		/* also dname parse error here */
1400 		(void)ssl_printf(ssl, "error could not add zonelist entry\n");
1401 		return 0;
1402 	}
1403 	/* make addzone task and schedule reload */
1404 	task_new_add_zone(xfrd->nsd->task[xfrd->nsd->mytask],
1405 		xfrd->last_task, arg, arg2,
1406 		getzonestatid(xfrd->nsd->options, zopt));
1407 	zonestat_inc_ifneeded(xfrd);
1408 	xfrd_set_reload_now(xfrd);
1409 	/* add to xfrd - notify (for master and slaves) */
1410 	init_notify_send(xfrd->notify_zones, xfrd->region, zopt);
1411 	/* add to xfrd - slave */
1412 	if(zone_is_slave(zopt)) {
1413 		xfrd_init_slave_zone(xfrd, zopt);
1414 	}
1415 	return 1;
1416 }
1417 
1418 /** perform the delzone command for one zone */
1419 static int
1420 perform_delzone(RES* ssl, xfrd_state_type* xfrd, char* arg)
1421 {
1422 	const dname_type* dname;
1423 	struct zone_options* zopt;
1424 
1425 	dname = dname_parse(xfrd->region, arg);
1426 	if(!dname) {
1427 		(void)ssl_printf(ssl, "error cannot parse zone name\n");
1428 		return 0;
1429 	}
1430 
1431 	/* see if we have the zone in question */
1432 	zopt = zone_options_find(xfrd->nsd->options, dname);
1433 	if(!zopt) {
1434 		region_recycle(xfrd->region, (void*)dname,
1435 			dname_total_size(dname));
1436 		/* nothing to do */
1437 		(void)ssl_printf(ssl, "warning zone %s not present\n", arg);
1438 		return 0;
1439 	}
1440 
1441 	/* see if it can be deleted */
1442 	if(zopt->part_of_config) {
1443 		region_recycle(xfrd->region, (void*)dname,
1444 			dname_total_size(dname));
1445 		(void)ssl_printf(ssl, "error zone defined in nsd.conf, "
1446 			"cannot delete it in this manner: remove it from "
1447 			"nsd.conf yourself and repattern\n");
1448 		return 0;
1449 	}
1450 
1451 	/* create deletion task */
1452 	task_new_del_zone(xfrd->nsd->task[xfrd->nsd->mytask],
1453 		xfrd->last_task, dname);
1454 	xfrd_set_reload_now(xfrd);
1455 	/* delete it in xfrd */
1456 	if(zone_is_slave(zopt)) {
1457 		xfrd_del_slave_zone(xfrd, dname);
1458 	}
1459 	xfrd_del_notify(xfrd, dname);
1460 	/* delete from config */
1461 	zone_list_del(xfrd->nsd->options, zopt);
1462 
1463 	region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
1464 	return 1;
1465 }
1466 
1467 /** do the addzone command */
1468 static void
1469 do_addzone(RES* ssl, xfrd_state_type* xfrd, char* arg)
1470 {
1471 	if(!perform_addzone(ssl, xfrd, arg))
1472 		return;
1473 	send_ok(ssl);
1474 }
1475 
1476 /** do the delzone command */
1477 static void
1478 do_delzone(RES* ssl, xfrd_state_type* xfrd, char* arg)
1479 {
1480 	if(!perform_delzone(ssl, xfrd, arg))
1481 		return;
1482 	send_ok(ssl);
1483 }
1484 
1485 /** do the changezone command */
1486 static void
1487 do_changezone(RES* ssl, xfrd_state_type* xfrd, char* arg)
1488 {
1489 	if(!perform_changezone(ssl, xfrd, arg))
1490 		return;
1491 	send_ok(ssl);
1492 }
1493 
1494 /** do the addzones command */
1495 static void
1496 do_addzones(RES* ssl, xfrd_state_type* xfrd)
1497 {
1498 	char buf[2048];
1499 	int num = 0;
1500 	while(ssl_read_line(ssl, buf, sizeof(buf))) {
1501 		if(buf[0] == 0x04 && buf[1] == 0)
1502 			break; /* end of transmission */
1503 		if(!perform_addzone(ssl, xfrd, buf)) {
1504 			if(!ssl_printf(ssl, "error for input line '%s'\n",
1505 				buf))
1506 				return;
1507 		} else {
1508 			if(!ssl_printf(ssl, "added: %s\n", buf))
1509 				return;
1510 			num++;
1511 		}
1512 	}
1513 	(void)ssl_printf(ssl, "added %d zones\n", num);
1514 }
1515 
1516 /** do the delzones command */
1517 static void
1518 do_delzones(RES* ssl, xfrd_state_type* xfrd)
1519 {
1520 	char buf[2048];
1521 	int num = 0;
1522 	while(ssl_read_line(ssl, buf, sizeof(buf))) {
1523 		if(buf[0] == 0x04 && buf[1] == 0)
1524 			break; /* end of transmission */
1525 		if(!perform_delzone(ssl, xfrd, buf)) {
1526 			if(!ssl_printf(ssl, "error for input line '%s'\n",
1527 				buf))
1528 				return;
1529 		} else {
1530 			if(!ssl_printf(ssl, "removed: %s\n", buf))
1531 				return;
1532 			num++;
1533 		}
1534 	}
1535 	(void)ssl_printf(ssl, "deleted %d zones\n", num);
1536 }
1537 
1538 
1539 /** remove TSIG key from config and add task so that reload does too */
1540 static void remove_key(xfrd_state_type* xfrd, const char* kname)
1541 {
1542 	/* add task before deletion because the name string could be deleted */
1543 	task_new_del_key(xfrd->nsd->task[xfrd->nsd->mytask], xfrd->last_task,
1544 		kname);
1545 	key_options_remove(xfrd->nsd->options, kname);
1546 	xfrd_set_reload_now(xfrd); /* this is executed when the current control
1547 		command ends, thus the entire config changes are bunched up */
1548 }
1549 
1550 /** add TSIG key to config and add task so that reload does too */
1551 static void add_key(xfrd_state_type* xfrd, struct key_options* k)
1552 {
1553 	key_options_add_modify(xfrd->nsd->options, k);
1554 	task_new_add_key(xfrd->nsd->task[xfrd->nsd->mytask], xfrd->last_task,
1555 		k);
1556 	xfrd_set_reload_now(xfrd);
1557 }
1558 
1559 /** check if keys have changed */
1560 static void repat_keys(xfrd_state_type* xfrd, struct nsd_options* newopt)
1561 {
1562 	struct nsd_options* oldopt = xfrd->nsd->options;
1563 	struct key_options* k;
1564 	/* find deleted keys */
1565 	k = (struct key_options*)rbtree_first(oldopt->keys);
1566 	while((rbnode_type*)k != RBTREE_NULL) {
1567 		struct key_options* next = (struct key_options*)rbtree_next(
1568 			(rbnode_type*)k);
1569 		if(!key_options_find(newopt, k->name))
1570 			remove_key(xfrd, k->name);
1571 		k = next;
1572 	}
1573 	/* find added or changed keys */
1574 	RBTREE_FOR(k, struct key_options*, newopt->keys) {
1575 		struct key_options* origk = key_options_find(oldopt, k->name);
1576 		if(!origk)
1577 			add_key(xfrd, k);
1578 		else if(!key_options_equal(k, origk))
1579 			add_key(xfrd, k);
1580 	}
1581 }
1582 
1583 /** find zone given the implicit pattern */
1584 static const dname_type*
1585 parse_implicit_name(xfrd_state_type* xfrd,const char* pname)
1586 {
1587 	if(strncmp(pname, PATTERN_IMPLICIT_MARKER,
1588 		strlen(PATTERN_IMPLICIT_MARKER)) != 0)
1589 		return NULL;
1590 	return dname_parse(xfrd->region, pname +
1591 		strlen(PATTERN_IMPLICIT_MARKER));
1592 }
1593 
1594 /** remove cfgzone and add task so that reload does too */
1595 static void
1596 remove_cfgzone(xfrd_state_type* xfrd, const char* pname)
1597 {
1598 	/* dname and find the zone for the implicit pattern */
1599 	struct zone_options* zopt = NULL;
1600 	const dname_type* dname = parse_implicit_name(xfrd, pname);
1601 	if(!dname) {
1602 		/* should have a parseable name, but it did not */
1603 		return;
1604 	}
1605 
1606 	/* find the zone entry for the implicit pattern */
1607 	zopt = zone_options_find(xfrd->nsd->options, dname);
1608 	if(!zopt) {
1609 		/* this should not happen; implicit pattern has zone entry */
1610 		region_recycle(xfrd->region, (void*)dname,
1611 			dname_total_size(dname));
1612 		return;
1613 	}
1614 
1615 	/* create deletion task */
1616 	task_new_del_zone(xfrd->nsd->task[xfrd->nsd->mytask],
1617 		xfrd->last_task, dname);
1618 	xfrd_set_reload_now(xfrd);
1619 	/* delete it in xfrd */
1620 	if(zone_is_slave(zopt)) {
1621 		xfrd_del_slave_zone(xfrd, dname);
1622 	}
1623 	xfrd_del_notify(xfrd, dname);
1624 
1625 	/* delete from zoneoptions */
1626 	zone_options_delete(xfrd->nsd->options, zopt);
1627 
1628 	/* recycle parsed dname */
1629 	region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
1630 }
1631 
1632 /** add cfgzone and add task so that reload does too */
1633 static void
1634 add_cfgzone(xfrd_state_type* xfrd, const char* pname)
1635 {
1636 	/* add to our zonelist */
1637 	struct zone_options* zopt = zone_options_create(
1638 		xfrd->nsd->options->region);
1639 	if(!zopt)
1640 		return;
1641 	zopt->part_of_config = 1;
1642 	zopt->name = region_strdup(xfrd->nsd->options->region,
1643 		pname + strlen(PATTERN_IMPLICIT_MARKER));
1644 	zopt->pattern = pattern_options_find(xfrd->nsd->options, pname);
1645 	if(!zopt->name || !zopt->pattern)
1646 		return;
1647 	if(!nsd_options_insert_zone(xfrd->nsd->options, zopt)) {
1648 		log_msg(LOG_ERR, "bad domain name or duplicate zone '%s' "
1649 			"pattern %s", zopt->name, pname);
1650 	}
1651 
1652 	/* make addzone task and schedule reload */
1653 	task_new_add_zone(xfrd->nsd->task[xfrd->nsd->mytask],
1654 		xfrd->last_task, zopt->name, pname,
1655 		getzonestatid(xfrd->nsd->options, zopt));
1656 	/* zonestat_inc is done after the entire config file has been done */
1657 	xfrd_set_reload_now(xfrd);
1658 	/* add to xfrd - notify (for master and slaves) */
1659 	init_notify_send(xfrd->notify_zones, xfrd->region, zopt);
1660 	/* add to xfrd - slave */
1661 	if(zone_is_slave(zopt)) {
1662 		xfrd_init_slave_zone(xfrd, zopt);
1663 	}
1664 }
1665 
1666 /** remove pattern and add task so that reload does too */
1667 static void
1668 remove_pat(xfrd_state_type* xfrd, const char* name)
1669 {
1670 	/* add task before deletion, because name-string could be deleted */
1671 	task_new_del_pattern(xfrd->nsd->task[xfrd->nsd->mytask],
1672 		xfrd->last_task, name);
1673 	pattern_options_remove(xfrd->nsd->options, name);
1674 	xfrd_set_reload_now(xfrd);
1675 }
1676 
1677 /** add pattern and add task so that reload does too */
1678 static void
1679 add_pat(xfrd_state_type* xfrd, struct pattern_options* p)
1680 {
1681 	pattern_options_add_modify(xfrd->nsd->options, p);
1682 	task_new_add_pattern(xfrd->nsd->task[xfrd->nsd->mytask],
1683 		xfrd->last_task, p);
1684 	xfrd_set_reload_now(xfrd);
1685 }
1686 
1687 /** interrupt zones that are using changed or removed patterns */
1688 static void
1689 repat_interrupt_zones(xfrd_state_type* xfrd, struct nsd_options* newopt)
1690 {
1691 	/* if masterlist changed:
1692 	 *   interrupt slave zone (UDP or TCP) transfers.
1693 	 *   slave zones reset master to start of list.
1694 	 */
1695 	xfrd_zone_type* xz;
1696 	struct notify_zone* nz;
1697 	RBTREE_FOR(xz, xfrd_zone_type*, xfrd->zones) {
1698 		struct pattern_options* oldp = xz->zone_options->pattern;
1699 		struct pattern_options* newp = pattern_options_find(newopt,
1700 			oldp->pname);
1701 		if(!newp || !acl_list_equal(oldp->request_xfr,
1702 			newp->request_xfr)) {
1703 			/* interrupt transfer */
1704 			if(xz->tcp_conn != -1) {
1705 				xfrd_tcp_release(xfrd->tcp_set, xz);
1706 				xfrd_set_refresh_now(xz);
1707 			} else if(xz->zone_handler.ev_fd != -1) {
1708 				xfrd_udp_release(xz);
1709 				xfrd_set_refresh_now(xz);
1710 			}
1711 			xz->master = 0;
1712 			xz->master_num = 0;
1713 			xz->next_master = -1;
1714 			xz->round_num = -1; /* fresh set of retries */
1715 		}
1716 	}
1717 	/* if notify list changed:
1718 	 *   interrupt notify that is busy.
1719 	 *   reset notify to start of list.  (clear all other reset_notify)
1720 	 */
1721 	RBTREE_FOR(nz, struct notify_zone*, xfrd->notify_zones) {
1722 		struct pattern_options* oldp = nz->options->pattern;
1723 		struct pattern_options* newp = pattern_options_find(newopt,
1724 			oldp->pname);
1725 		if(!newp || !acl_list_equal(oldp->notify, newp->notify)) {
1726 			/* interrupt notify */
1727 			if(nz->notify_send_enable) {
1728 				notify_disable(nz);
1729 				/* set to restart the notify after the
1730 				 * pattern has been changed. */
1731 				nz->notify_restart = 2;
1732 			} else {
1733 				nz->notify_restart = 1;
1734 			}
1735 		} else {
1736 			nz->notify_restart = 0;
1737 		}
1738 	}
1739 }
1740 
1741 /** for notify, after the pattern changes, restart the affected notifies */
1742 static void
1743 repat_interrupt_notify_start(xfrd_state_type* xfrd)
1744 {
1745 	struct notify_zone* nz;
1746 	RBTREE_FOR(nz, struct notify_zone*, xfrd->notify_zones) {
1747 		if(nz->notify_restart) {
1748 			if(nz->notify_current)
1749 				nz->notify_current = nz->options->pattern->notify;
1750 			if(nz->notify_restart == 2) {
1751 				if(nz->notify_restart)
1752 					xfrd_notify_start(nz, xfrd);
1753 			}
1754 		}
1755 	}
1756 }
1757 
1758 /** check if patterns have changed */
1759 static void
1760 repat_patterns(xfrd_state_type* xfrd, struct nsd_options* newopt)
1761 {
1762 	/* zones that use changed patterns must have:
1763 	 * - their AXFR/IXFR interrupted: try again, acl may have changed.
1764 	 *   if the old master/key still exists, OK, fix master-numptrs and
1765 	 *   keep going.  Otherwise, stop xfer and reset TSIG.
1766 	 * - send NOTIFY reset to start of NOTIFY list (and TSIG reset).
1767 	 */
1768 	struct nsd_options* oldopt = xfrd->nsd->options;
1769 	struct pattern_options* p;
1770 	int search_zones = 0;
1771 
1772 	repat_interrupt_zones(xfrd, newopt);
1773 	/* find deleted patterns */
1774 	p = (struct pattern_options*)rbtree_first(oldopt->patterns);
1775 	while((rbnode_type*)p != RBTREE_NULL) {
1776 		struct pattern_options* next = (struct pattern_options*)
1777 			rbtree_next((rbnode_type*)p);
1778 		if(!pattern_options_find(newopt, p->pname)) {
1779 			if(p->implicit) {
1780 				/* first remove its zone */
1781 				VERBOSITY(1, (LOG_INFO, "zone removed from config: %s", p->pname + strlen(PATTERN_IMPLICIT_MARKER)));
1782 				remove_cfgzone(xfrd, p->pname);
1783 			}
1784 			remove_pat(xfrd, p->pname);
1785 		}
1786 		p = next;
1787 	}
1788 	/* find added or changed patterns */
1789 	RBTREE_FOR(p, struct pattern_options*, newopt->patterns) {
1790 		struct pattern_options* origp = pattern_options_find(oldopt,
1791 			p->pname);
1792 		if(!origp) {
1793 			/* no zones can use it, no zone_interrupt needed */
1794 			add_pat(xfrd, p);
1795 			if(p->implicit) {
1796 				VERBOSITY(1, (LOG_INFO, "zone added to config: %s", p->pname + strlen(PATTERN_IMPLICIT_MARKER)));
1797 				add_cfgzone(xfrd, p->pname);
1798 			}
1799 		} else if(!pattern_options_equal(p, origp)) {
1800 			uint8_t newstate = 0;
1801 			if (p->request_xfr && !origp->request_xfr) {
1802 				newstate = REPAT_SLAVE;
1803 			} else if (!p->request_xfr && origp->request_xfr) {
1804 				newstate = REPAT_MASTER;
1805 			}
1806 			add_pat(xfrd, p);
1807 			if (p->implicit && newstate) {
1808 				const dname_type* dname =
1809 					parse_implicit_name(xfrd, p->pname);
1810 				if (dname) {
1811 					if (newstate == REPAT_SLAVE) {
1812 						struct zone_options* zopt =
1813 							zone_options_find(
1814 							oldopt, dname);
1815 						if (zopt) {
1816 							xfrd_init_slave_zone(
1817 								xfrd, zopt);
1818 						}
1819 					} else if (newstate == REPAT_MASTER) {
1820 						xfrd_del_slave_zone(xfrd,
1821 							dname);
1822 					}
1823 					region_recycle(xfrd->region,
1824 						(void*)dname,
1825 						dname_total_size(dname));
1826 				}
1827 			} else if(!p->implicit && newstate) {
1828 				/* search all zones with this pattern */
1829 				search_zones = 1;
1830 				origp->xfrd_flags = newstate;
1831 			}
1832 		}
1833 	}
1834 	if (search_zones) {
1835 		struct zone_options* zone_opt;
1836 		/* search in oldopt because 1) it contains zonelist zones,
1837 		 * and 2) you need oldopt(existing) to call xfrd_init */
1838 		RBTREE_FOR(zone_opt, struct zone_options*, oldopt->zone_options) {
1839 			struct pattern_options* oldp = zone_opt->pattern;
1840 			if (!oldp->implicit) {
1841 				if (oldp->xfrd_flags == REPAT_SLAVE) {
1842 					/* xfrd needs stable reference so get
1843 					 * it from the oldopt(modified) tree */
1844 					xfrd_init_slave_zone(xfrd, zone_opt);
1845 				} else if (oldp->xfrd_flags == REPAT_MASTER) {
1846 					xfrd_del_slave_zone(xfrd,
1847 						(const dname_type*)
1848 						zone_opt->node.key);
1849 				}
1850 				oldp->xfrd_flags = 0;
1851 			}
1852 		}
1853 	}
1854 	repat_interrupt_notify_start(xfrd);
1855 }
1856 
1857 /** true if options are different that can be set via repat. */
1858 static int
1859 repat_options_changed(xfrd_state_type* xfrd, struct nsd_options* newopt)
1860 {
1861 #ifdef RATELIMIT
1862 	if(xfrd->nsd->options->rrl_ratelimit != newopt->rrl_ratelimit)
1863 		return 1;
1864 	if(xfrd->nsd->options->rrl_whitelist_ratelimit != newopt->rrl_whitelist_ratelimit)
1865 		return 1;
1866 	if(xfrd->nsd->options->rrl_slip != newopt->rrl_slip)
1867 		return 1;
1868 #else
1869 	(void)xfrd; (void)newopt;
1870 #endif
1871 	return 0;
1872 }
1873 
1874 /** check if global options have changed */
1875 static void
1876 repat_options(xfrd_state_type* xfrd, struct nsd_options* newopt)
1877 {
1878 	if(repat_options_changed(xfrd, newopt)) {
1879 		/* update our options */
1880 #ifdef RATELIMIT
1881 		xfrd->nsd->options->rrl_ratelimit = newopt->rrl_ratelimit;
1882 		xfrd->nsd->options->rrl_whitelist_ratelimit = newopt->rrl_whitelist_ratelimit;
1883 		xfrd->nsd->options->rrl_slip = newopt->rrl_slip;
1884 #endif
1885 		task_new_opt_change(xfrd->nsd->task[xfrd->nsd->mytask],
1886 			xfrd->last_task, newopt);
1887 		xfrd_set_reload_now(xfrd);
1888 	}
1889 }
1890 
1891 /** print errors over ssl, gets pointer-to-pointer to ssl, so it can set
1892  * the pointer to NULL on failure and stop printing */
1893 static void
1894 print_ssl_cfg_err(void* arg, const char* str)
1895 {
1896 	RES** ssl = (RES**)arg;
1897 	if(!*ssl) return;
1898 	if(!ssl_printf(*ssl, "%s", str))
1899 		*ssl = NULL; /* failed, stop printing */
1900 }
1901 
1902 /** do the repattern command: reread config file and apply keys, patterns */
1903 static void
1904 do_repattern(RES* ssl, xfrd_state_type* xfrd)
1905 {
1906 	region_type* region = region_create(xalloc, free);
1907 	struct nsd_options* opt;
1908 	const char* cfgfile = xfrd->nsd->options->configfile;
1909 
1910 	/* check chroot and configfile, if possible to reread */
1911 	if(xfrd->nsd->chrootdir) {
1912 		size_t l = strlen(xfrd->nsd->chrootdir);
1913 		while(l>0 && xfrd->nsd->chrootdir[l-1] == '/')
1914 			--l;
1915 		if(strncmp(xfrd->nsd->chrootdir, cfgfile, l) != 0) {
1916 			(void)ssl_printf(ssl, "error %s is not relative to %s: "
1917 				"chroot prevents reread of config\n",
1918 				cfgfile, xfrd->nsd->chrootdir);
1919 			region_destroy(region);
1920 			return;
1921 		}
1922 		cfgfile += l;
1923 	}
1924 
1925 	(void)ssl_printf(ssl, "reconfig start, read %s\n", cfgfile);
1926 	opt = nsd_options_create(region);
1927 	if(!parse_options_file(opt, cfgfile, &print_ssl_cfg_err, &ssl)) {
1928 		/* error already printed */
1929 		region_destroy(region);
1930 		return;
1931 	}
1932 	/* check for differences in TSIG keys and patterns, and apply,
1933 	 * first the keys, so that pattern->keyptr can be set right. */
1934 	repat_keys(xfrd, opt);
1935 	repat_patterns(xfrd, opt);
1936 	repat_options(xfrd, opt);
1937 	zonestat_inc_ifneeded(xfrd);
1938 	send_ok(ssl);
1939 	region_destroy(region);
1940 }
1941 
1942 /** do the serverpid command: printout pid of server process */
1943 static void
1944 do_serverpid(RES* ssl, xfrd_state_type* xfrd)
1945 {
1946 	(void)ssl_printf(ssl, "%u\n", (unsigned)xfrd->reload_pid);
1947 }
1948 
1949 /** do the print_tsig command: printout tsig info */
1950 static void
1951 do_print_tsig(RES* ssl, xfrd_state_type* xfrd, char* arg)
1952 {
1953 	if(*arg == '\0') {
1954 		struct key_options* key;
1955 		RBTREE_FOR(key, struct key_options*, xfrd->nsd->options->keys) {
1956 			if(!ssl_printf(ssl, "key: name: \"%s\" secret: \"%s\" algorithm: %s\n", key->name, key->secret, key->algorithm))
1957 				return;
1958 		}
1959 		return;
1960 	} else {
1961 		struct key_options* key_opts = key_options_find(xfrd->nsd->options, arg);
1962 		if(!key_opts) {
1963 			(void)ssl_printf(ssl, "error: no such key with name: %s\n", arg);
1964 			return;
1965 		} else {
1966 			(void)ssl_printf(ssl, "key: name: \"%s\" secret: \"%s\" algorithm: %s\n", arg, key_opts->secret, key_opts->algorithm);
1967 		}
1968 	}
1969 }
1970 
1971 /** do the update_tsig command: change existing tsig to new secret */
1972 static void
1973 do_update_tsig(RES* ssl, xfrd_state_type* xfrd, char* arg)
1974 {
1975 	struct region* region = xfrd->nsd->options->region;
1976 	char* arg2 = NULL;
1977 	uint8_t data[65536]; /* 64K */
1978 	struct key_options* key_opt;
1979 
1980 	if(*arg == '\0') {
1981 		(void)ssl_printf(ssl, "error: missing argument (keyname)\n");
1982 		return;
1983 	}
1984 	if(!find_arg2(ssl, arg, &arg2)) {
1985 		(void)ssl_printf(ssl, "error: missing argument (secret)\n");
1986 		return;
1987 	}
1988 	key_opt = key_options_find(xfrd->nsd->options, arg);
1989 	if(!key_opt) {
1990 		(void)ssl_printf(ssl, "error: no such key with name: %s\n", arg);
1991 		memset(arg2, 0xdd, strlen(arg2));
1992 		return;
1993 	}
1994 	if(__b64_pton(arg2, data, sizeof(data)) == -1) {
1995 		(void)ssl_printf(ssl, "error: the secret: %s is not in b64 format\n", arg2);
1996 		memset(data, 0xdd, sizeof(data)); /* wipe secret */
1997 		memset(arg2, 0xdd, strlen(arg2));
1998 		return;
1999 	}
2000 	log_msg(LOG_INFO, "changing secret provided with the key: %s with old secret %s and algo: %s\n", arg, key_opt->secret, key_opt->algorithm);
2001 	if(key_opt->secret) {
2002 		/* wipe old secret */
2003 		memset(key_opt->secret, 0xdd, strlen(key_opt->secret));
2004 		region_recycle(region, key_opt->secret,
2005 			strlen(key_opt->secret)+1);
2006 	}
2007 	key_opt->secret = region_strdup(region, arg2);
2008 	log_msg(LOG_INFO, "the key: %s has new secret %s and algorithm: %s\n", arg, key_opt->secret, key_opt->algorithm);
2009 	/* wipe secret from temp parse buffer */
2010 	memset(arg2, 0xdd, strlen(arg2));
2011 	memset(data, 0xdd, sizeof(data));
2012 
2013 	key_options_desetup(region, key_opt);
2014 	key_options_setup(region, key_opt);
2015 	task_new_add_key(xfrd->nsd->task[xfrd->nsd->mytask], xfrd->last_task,
2016 		key_opt);
2017 	xfrd_set_reload_now(xfrd);
2018 
2019 	send_ok(ssl);
2020 }
2021 
2022 /** do the add tsig command, add new key with name, secret and algo given */
2023 static void
2024 do_add_tsig(RES* ssl, xfrd_state_type* xfrd, char* arg)
2025 {
2026 	char* arg2 = NULL;
2027 	char* arg3 = NULL;
2028 	uint8_t data[65536]; /* 64KB */
2029 	uint8_t dname[MAXDOMAINLEN+1];
2030 	char algo[256];
2031 	region_type* region = xfrd->nsd->options->region;
2032 	struct key_options* new_key_opt;
2033 
2034 	if(*arg == '\0') {
2035 		(void)ssl_printf(ssl, "error: missing argument (keyname)\n");
2036 		return;
2037 	}
2038 	if(!find_arg3(ssl, arg, &arg2, &arg3)) {
2039 		strlcpy(algo, "hmac-sha256", sizeof(algo));
2040 	} else {
2041 		strlcpy(algo, arg3, sizeof(algo));
2042 	}
2043 	if(!arg2) {
2044 		(void)ssl_printf(ssl, "error: missing argument (secret)\n");
2045 		return;
2046 	}
2047 	if(key_options_find(xfrd->nsd->options, arg)) {
2048 		(void)ssl_printf(ssl, "error: key %s already exists\n", arg);
2049 		memset(arg2, 0xdd, strlen(arg2));
2050 		return;
2051 	}
2052 	if(__b64_pton(arg2, data, sizeof(data)) == -1) {
2053 		(void)ssl_printf(ssl, "error: the secret: %s is not in b64 format\n", arg2);
2054 		memset(data, 0xdd, sizeof(data)); /* wipe secret */
2055 		memset(arg2, 0xdd, strlen(arg2));
2056 		return;
2057 	}
2058 	memset(data, 0xdd, sizeof(data)); /* wipe secret from temp buffer */
2059 	if(!dname_parse_wire(dname, arg)) {
2060 		(void)ssl_printf(ssl, "error: could not parse key name: %s\n", arg);
2061 		memset(arg2, 0xdd, strlen(arg2));
2062 		return;
2063 	}
2064 	if(tsig_get_algorithm_by_name(algo) == NULL) {
2065 		(void)ssl_printf(ssl, "error: unknown algorithm: %s\n", algo);
2066 		memset(arg2, 0xdd, strlen(arg2));
2067 		return;
2068 	}
2069 	log_msg(LOG_INFO, "adding key with name: %s and secret: %s with algo: %s\n", arg, arg2, algo);
2070 	new_key_opt = key_options_create(region);
2071 	new_key_opt->name = region_strdup(region, arg);
2072 	new_key_opt->secret = region_strdup(region, arg2);
2073 	new_key_opt->algorithm = region_strdup(region, algo);
2074 	add_key(xfrd, new_key_opt);
2075 
2076 	/* wipe secret from temp buffer */
2077 	memset(arg2, 0xdd, strlen(arg2));
2078 	send_ok(ssl);
2079 }
2080 
2081 /** set acl entries to use the given TSIG key */
2082 static void
2083 zopt_set_acl_to_tsig(struct acl_options* acl, struct region* region,
2084 	const char* key_name, struct key_options* key_opt)
2085 {
2086 	while(acl) {
2087 		if(acl->blocked) {
2088 			acl = acl->next;
2089 			continue;
2090 		}
2091 		acl->nokey = 0;
2092 		if(acl->key_name)
2093 			region_recycle(region, (void*)acl->key_name,
2094 				strlen(acl->key_name)+1);
2095 		acl->key_name = region_strdup(region, key_name);
2096 		acl->key_options = key_opt;
2097 		acl = acl->next;
2098 	}
2099 }
2100 
2101 /** do the assoc_tsig command: associate the zone to use the tsig name */
2102 static void
2103 do_assoc_tsig(RES* ssl, xfrd_state_type* xfrd, char* arg)
2104 {
2105 	region_type* region = xfrd->nsd->options->region;
2106 	char* arg2 = NULL;
2107 	struct zone_options* zone;
2108 	struct key_options* key_opt;
2109 
2110 	if(*arg == '\0') {
2111 		(void)ssl_printf(ssl, "error: missing argument (zonename)\n");
2112 		return;
2113 	}
2114 	if(!find_arg2(ssl, arg, &arg2)) {
2115 		(void)ssl_printf(ssl, "error: missing argument (keyname)\n");
2116 		return;
2117 	}
2118 
2119 	if(!get_zone_arg(ssl, xfrd, arg, &zone))
2120 		return;
2121 	if(!zone) {
2122 		(void)ssl_printf(ssl, "error: missing argument (zone)\n");
2123 		return;
2124 	}
2125 	key_opt = key_options_find(xfrd->nsd->options, arg2);
2126 	if(!key_opt) {
2127 		(void)ssl_printf(ssl, "error: key: %s does not exist\n", arg2);
2128 		return;
2129 	}
2130 
2131 	zopt_set_acl_to_tsig(zone->pattern->allow_notify, region, arg2,
2132 		key_opt);
2133 	zopt_set_acl_to_tsig(zone->pattern->notify, region, arg2, key_opt);
2134 	zopt_set_acl_to_tsig(zone->pattern->request_xfr, region, arg2,
2135 		key_opt);
2136 	zopt_set_acl_to_tsig(zone->pattern->provide_xfr, region, arg2,
2137 		key_opt);
2138 	zopt_set_acl_to_tsig(zone->pattern->allow_query, region, arg2,
2139 		key_opt);
2140 
2141 	task_new_add_pattern(xfrd->nsd->task[xfrd->nsd->mytask],
2142 		xfrd->last_task, zone->pattern);
2143 	xfrd_set_reload_now(xfrd);
2144 
2145 	send_ok(ssl);
2146 }
2147 
2148 /** see if TSIG key is used in the acl */
2149 static int
2150 acl_contains_tsig_key(struct acl_options* acl, const char* name)
2151 {
2152 	while(acl) {
2153 		if(acl->key_name && strcmp(acl->key_name, name) == 0)
2154 			return 1;
2155 		acl = acl->next;
2156 	}
2157 	return 0;
2158 }
2159 
2160 /** do the del_tsig command, remove an (unused) tsig */
2161 static void
2162 do_del_tsig(RES* ssl, xfrd_state_type* xfrd, char* arg) {
2163 	int used_key = 0;
2164 	struct zone_options* zone;
2165 	struct key_options* key_opt;
2166 
2167 	if(*arg == '\0') {
2168 		(void)ssl_printf(ssl, "error: missing argument (keyname)\n");
2169 		return;
2170 	}
2171 	key_opt = key_options_find(xfrd->nsd->options, arg);
2172 	if(!key_opt) {
2173 		(void)ssl_printf(ssl, "key %s does not exist, nothing to be deleted\n", arg);
2174 		return;
2175 	}
2176 	RBTREE_FOR(zone, struct zone_options*, xfrd->nsd->options->zone_options)
2177 	{
2178 		if(acl_contains_tsig_key(zone->pattern->allow_notify, arg) ||
2179 		   acl_contains_tsig_key(zone->pattern->notify, arg) ||
2180 		   acl_contains_tsig_key(zone->pattern->request_xfr, arg) ||
2181 		   acl_contains_tsig_key(zone->pattern->provide_xfr, arg) ||
2182 		   acl_contains_tsig_key(zone->pattern->allow_query, arg)) {
2183 			if(!ssl_printf(ssl, "zone %s uses key %s\n",
2184 				zone->name, arg))
2185 				return;
2186 			used_key = 1;
2187 			break;
2188 		}
2189 	}
2190 
2191 	if(used_key) {
2192 		(void)ssl_printf(ssl, "error: key: %s is in use and cannot be deleted\n", arg);
2193 		return;
2194 	} else {
2195 		remove_key(xfrd, arg);
2196 		log_msg(LOG_INFO, "key: %s is successfully deleted\n", arg);
2197 	}
2198 
2199 	send_ok(ssl);
2200 }
2201 
2202 /* returns `0` on failure */
2203 static int
2204 cookie_secret_file_dump(RES* ssl, nsd_type const* nsd) {
2205 	char const* secret_file = nsd->options->cookie_secret_file;
2206 	char secret_hex[NSD_COOKIE_SECRET_SIZE * 2 + 1];
2207 	FILE* f;
2208 	size_t i;
2209 	assert( secret_file != NULL );
2210 
2211 	/* open write only and truncate */
2212 	if((f = fopen(secret_file, "w")) == NULL ) {
2213 		(void)ssl_printf(ssl, "unable to open cookie secret file %s: %s",
2214 		                 secret_file, strerror(errno));
2215 		return 0;
2216 	}
2217 	for(i = 0; i < nsd->cookie_count; i++) {
2218 		struct cookie_secret const* cs = &nsd->cookie_secrets[i];
2219 		ssize_t const len = hex_ntop(cs->cookie_secret, NSD_COOKIE_SECRET_SIZE,
2220 			secret_hex, sizeof(secret_hex));
2221 		(void)len; /* silence unused variable warning with -DNDEBUG */
2222 		assert( len == NSD_COOKIE_SECRET_SIZE * 2 );
2223 		secret_hex[NSD_COOKIE_SECRET_SIZE * 2] = '\0';
2224 		fprintf(f, "%s\n", secret_hex);
2225 	}
2226 	explicit_bzero(secret_hex, sizeof(secret_hex));
2227 	fclose(f);
2228 	return 1;
2229 }
2230 
2231 static void
2232 do_activate_cookie_secret(RES* ssl, xfrd_state_type* xrfd, char* arg) {
2233 	nsd_type* nsd = xrfd->nsd;
2234 	(void)arg;
2235 
2236 	if(nsd->cookie_count <= 1 ) {
2237 		(void)ssl_printf(ssl, "error: no staging cookie secret to activate\n");
2238 		return;
2239 	}
2240 	if(!nsd->options->cookie_secret_file || !nsd->options->cookie_secret_file[0]) {
2241 		(void)ssl_printf(ssl, "error: no cookie secret file configured\n");
2242 		return;
2243 	}
2244 	if(!cookie_secret_file_dump(ssl, nsd)) {
2245 		(void)ssl_printf(ssl, "error: writing to cookie secret file: \"%s\"\n",
2246 				nsd->options->cookie_secret_file);
2247 		return;
2248 	}
2249 	activate_cookie_secret(nsd);
2250 	(void)cookie_secret_file_dump(ssl, nsd);
2251 	task_new_activate_cookie_secret(xfrd->nsd->task[xfrd->nsd->mytask],
2252 	    xfrd->last_task);
2253 	xfrd_set_reload_now(xfrd);
2254 	send_ok(ssl);
2255 }
2256 
2257 static void
2258 do_drop_cookie_secret(RES* ssl, xfrd_state_type* xrfd, char* arg) {
2259 	nsd_type* nsd = xrfd->nsd;
2260 	(void)arg;
2261 
2262 	if(nsd->cookie_count <= 1 ) {
2263 		(void)ssl_printf(ssl, "error: can not drop the currently active cookie secret\n");
2264 		return;
2265 	}
2266 	if(!nsd->options->cookie_secret_file || !nsd->options->cookie_secret_file[0]) {
2267 		(void)ssl_printf(ssl, "error: no cookie secret file configured\n");
2268 		return;
2269 	}
2270 	if(!cookie_secret_file_dump(ssl, nsd)) {
2271 		(void)ssl_printf(ssl, "error: writing to cookie secret file: \"%s\"\n",
2272 				nsd->options->cookie_secret_file);
2273 		return;
2274 	}
2275 	drop_cookie_secret(nsd);
2276 	(void)cookie_secret_file_dump(ssl, nsd);
2277 	task_new_drop_cookie_secret(xfrd->nsd->task[xfrd->nsd->mytask],
2278 	    xfrd->last_task);
2279 	xfrd_set_reload_now(xfrd);
2280 	send_ok(ssl);
2281 }
2282 
2283 static void
2284 do_add_cookie_secret(RES* ssl, xfrd_state_type* xrfd, char* arg) {
2285 	nsd_type* nsd = xrfd->nsd;
2286 	uint8_t secret[NSD_COOKIE_SECRET_SIZE];
2287 
2288 	if(*arg == '\0') {
2289 		(void)ssl_printf(ssl, "error: missing argument (cookie_secret)\n");
2290 		return;
2291 	}
2292 	if(strlen(arg) != 32) {
2293 		explicit_bzero(arg, strlen(arg));
2294 		(void)ssl_printf(ssl, "invalid cookie secret: invalid argument length\n");
2295 		(void)ssl_printf(ssl, "please provide a 128bit hex encoded secret\n");
2296 		return;
2297 	}
2298 	if(hex_pton(arg, secret, NSD_COOKIE_SECRET_SIZE) != NSD_COOKIE_SECRET_SIZE ) {
2299 		explicit_bzero(secret, NSD_COOKIE_SECRET_SIZE);
2300 		explicit_bzero(arg, strlen(arg));
2301 		(void)ssl_printf(ssl, "invalid cookie secret: parse error\n");
2302 		(void)ssl_printf(ssl, "please provide a 128bit hex encoded secret\n");
2303 		return;
2304 	}
2305 	if(!nsd->options->cookie_secret_file || !nsd->options->cookie_secret_file[0]) {
2306 		explicit_bzero(secret, NSD_COOKIE_SECRET_SIZE);
2307 		explicit_bzero(arg, strlen(arg));
2308 		(void)ssl_printf(ssl, "error: no cookie secret file configured\n");
2309 		return;
2310 	}
2311 	if(!cookie_secret_file_dump(ssl, nsd)) {
2312 		explicit_bzero(secret, NSD_COOKIE_SECRET_SIZE);
2313 		explicit_bzero(arg, strlen(arg));
2314 		(void)ssl_printf(ssl, "error: writing to cookie secret file: \"%s\"\n",
2315 				nsd->options->cookie_secret_file);
2316 		return;
2317 	}
2318 	add_cookie_secret(nsd, secret);
2319 	explicit_bzero(secret, NSD_COOKIE_SECRET_SIZE);
2320 	(void)cookie_secret_file_dump(ssl, nsd);
2321 	task_new_add_cookie_secret(xfrd->nsd->task[xfrd->nsd->mytask],
2322 	    xfrd->last_task, arg);
2323 	explicit_bzero(arg, strlen(arg));
2324 	xfrd_set_reload_now(xfrd);
2325 	send_ok(ssl);
2326 }
2327 
2328 static void
2329 do_print_cookie_secrets(RES* ssl, xfrd_state_type* xrfd, char* arg) {
2330 	nsd_type* nsd = xrfd->nsd;
2331 	char secret_hex[NSD_COOKIE_SECRET_SIZE * 2 + 1];
2332 	int i;
2333 	(void)arg;
2334 
2335 	/* (void)ssl_printf(ssl, "cookie_secret_count=%zu\n", nsd->cookie_count); */
2336 	for(i = 0; (size_t)i < nsd->cookie_count; i++) {
2337 		struct cookie_secret const* cs = &nsd->cookie_secrets[i];
2338 		ssize_t const len = hex_ntop(cs->cookie_secret, NSD_COOKIE_SECRET_SIZE,
2339 		                             secret_hex, sizeof(secret_hex));
2340 		(void)len; /* silence unused variable warning with -DNDEBUG */
2341 		assert( len == NSD_COOKIE_SECRET_SIZE * 2 );
2342 		secret_hex[NSD_COOKIE_SECRET_SIZE * 2] = '\0';
2343 		if (i == 0)
2344 			(void)ssl_printf(ssl, "active : %s\n",  secret_hex);
2345 		else if (nsd->cookie_count == 2)
2346 			(void)ssl_printf(ssl, "staging: %s\n",  secret_hex);
2347 		else
2348 			(void)ssl_printf(ssl, "staging[%d]: %s\n", i, secret_hex);
2349 	}
2350 	explicit_bzero(secret_hex, sizeof(secret_hex));
2351 }
2352 
2353 /** check for name with end-of-string, space or tab after it */
2354 static int
2355 cmdcmp(char* p, const char* cmd, size_t len)
2356 {
2357 	return strncmp(p,cmd,len)==0 && (p[len]==0||p[len]==' '||p[len]=='\t');
2358 }
2359 
2360 /** execute a remote control command */
2361 static void
2362 execute_cmd(struct daemon_remote* rc, RES* ssl, char* cmd, struct rc_state* rs)
2363 {
2364 	char* p = skipwhite(cmd);
2365 	/* compare command */
2366 	if(cmdcmp(p, "stop", 4)) {
2367 		do_stop(ssl, rc->xfrd);
2368 	} else if(cmdcmp(p, "reload", 6)) {
2369 		do_reload(ssl, rc->xfrd, skipwhite(p+6));
2370 	} else if(cmdcmp(p, "write", 5)) {
2371 		do_write(ssl, rc->xfrd, skipwhite(p+5));
2372 	} else if(cmdcmp(p, "status", 6)) {
2373 		do_status(ssl, rc->xfrd);
2374 	} else if(cmdcmp(p, "stats_noreset", 13)) {
2375 		do_stats(rc, 1, rs);
2376 	} else if(cmdcmp(p, "stats", 5)) {
2377 		do_stats(rc, 0, rs);
2378 	} else if(cmdcmp(p, "log_reopen", 10)) {
2379 		do_log_reopen(ssl, rc->xfrd);
2380 	} else if(cmdcmp(p, "addzone", 7)) {
2381 		do_addzone(ssl, rc->xfrd, skipwhite(p+7));
2382 	} else if(cmdcmp(p, "delzone", 7)) {
2383 		do_delzone(ssl, rc->xfrd, skipwhite(p+7));
2384 	} else if(cmdcmp(p, "changezone", 10)) {
2385 		do_changezone(ssl, rc->xfrd, skipwhite(p+10));
2386 	} else if(cmdcmp(p, "addzones", 8)) {
2387 		do_addzones(ssl, rc->xfrd);
2388 	} else if(cmdcmp(p, "delzones", 8)) {
2389 		do_delzones(ssl, rc->xfrd);
2390 	} else if(cmdcmp(p, "notify", 6)) {
2391 		do_notify(ssl, rc->xfrd, skipwhite(p+6));
2392 	} else if(cmdcmp(p, "transfer", 8)) {
2393 		do_transfer(ssl, rc->xfrd, skipwhite(p+8));
2394 	} else if(cmdcmp(p, "force_transfer", 14)) {
2395 		do_force_transfer(ssl, rc->xfrd, skipwhite(p+14));
2396 	} else if(cmdcmp(p, "zonestatus", 10)) {
2397 		do_zonestatus(ssl, rc->xfrd, skipwhite(p+10));
2398 	} else if(cmdcmp(p, "verbosity", 9)) {
2399 		do_verbosity(ssl, skipwhite(p+9));
2400 	} else if(cmdcmp(p, "repattern", 9)) {
2401 		do_repattern(ssl, rc->xfrd);
2402 	} else if(cmdcmp(p, "reconfig", 8)) {
2403 		do_repattern(ssl, rc->xfrd);
2404 	} else if(cmdcmp(p, "serverpid", 9)) {
2405 		do_serverpid(ssl, rc->xfrd);
2406 	} else if(cmdcmp(p, "print_tsig", 10)) {
2407 		do_print_tsig(ssl, rc->xfrd, skipwhite(p+10));
2408 	} else if(cmdcmp(p, "update_tsig", 11)) {
2409 		do_update_tsig(ssl, rc->xfrd, skipwhite(p+11));
2410 	} else if(cmdcmp(p, "add_tsig", 8)) {
2411 		do_add_tsig(ssl, rc->xfrd, skipwhite(p+8));
2412 	} else if(cmdcmp(p, "assoc_tsig", 10)) {
2413 		do_assoc_tsig(ssl, rc->xfrd, skipwhite(p+10));
2414 	} else if(cmdcmp(p, "del_tsig", 8)) {
2415 		do_del_tsig(ssl, rc->xfrd, skipwhite(p+8));
2416 	} else if(cmdcmp(p, "add_cookie_secret", 17)) {
2417 		do_add_cookie_secret(ssl, rc->xfrd, skipwhite(p+17));
2418 	} else if(cmdcmp(p, "drop_cookie_secret", 18)) {
2419 		do_drop_cookie_secret(ssl, rc->xfrd, skipwhite(p+18));
2420 	} else if(cmdcmp(p, "print_cookie_secrets", 20)) {
2421 		do_print_cookie_secrets(ssl, rc->xfrd, skipwhite(p+20));
2422 	} else if(cmdcmp(p, "activate_cookie_secret", 22)) {
2423 		do_activate_cookie_secret(ssl, rc->xfrd, skipwhite(p+22));
2424 	} else {
2425 		(void)ssl_printf(ssl, "error unknown command '%s'\n", p);
2426 	}
2427 }
2428 
2429 /** handle remote control request */
2430 static void
2431 handle_req(struct daemon_remote* rc, struct rc_state* s, RES* res)
2432 {
2433 	int r;
2434 	char pre[10];
2435 	char magic[8];
2436 	char buf[1024];
2437 	if (fcntl(s->c.ev_fd, F_SETFL, 0) == -1) { /* set blocking */
2438 		log_msg(LOG_ERR, "cannot fcntl rc: %s", strerror(errno));
2439 	}
2440 
2441 	/* try to read magic UBCT[version]_space_ string */
2442 #ifdef HAVE_SSL
2443 	if(res->ssl) {
2444 		ERR_clear_error();
2445 		if((r=SSL_read(res->ssl, magic, (int)sizeof(magic)-1)) <= 0) {
2446 			if(SSL_get_error(res->ssl, r) == SSL_ERROR_ZERO_RETURN)
2447 				return;
2448 			log_crypto_err("could not SSL_read");
2449 			return;
2450 		}
2451 	} else {
2452 #endif /* HAVE_SSL */
2453 		while(1) {
2454 			ssize_t rr = read(res->fd, magic, sizeof(magic)-1);
2455 			if(rr <= 0) {
2456 				if(rr == 0) return;
2457 				if(errno == EINTR || errno == EAGAIN)
2458 					continue;
2459 				log_msg(LOG_ERR, "could not read: %s", strerror(errno));
2460 				return;
2461 			}
2462 			r = (int)rr;
2463 			break;
2464 		}
2465 #ifdef HAVE_SSL
2466 	}
2467 #endif /* HAVE_SSL */
2468 	magic[7] = 0;
2469 	if( r != 7 || strncmp(magic, "NSDCT", 5) != 0) {
2470 		VERBOSITY(2, (LOG_INFO, "control connection has bad header"));
2471 		/* probably wrong tool connected, ignore it completely */
2472 		return;
2473 	}
2474 
2475 	/* read the command line */
2476 	if(!ssl_read_line(res, buf, sizeof(buf))) {
2477 		return;
2478 	}
2479 	snprintf(pre, sizeof(pre), "NSDCT%d ", NSD_CONTROL_VERSION);
2480 	if(strcmp(magic, pre) != 0) {
2481 		VERBOSITY(2, (LOG_INFO, "control connection had bad "
2482 			"version %s, cmd: %s", magic, buf));
2483 		(void)ssl_printf(res, "error version mismatch\n");
2484 		return;
2485 	}
2486 	/* always log control commands */
2487 	VERBOSITY(0, (LOG_INFO, "control cmd: %s", buf));
2488 
2489 	/* figure out what to do */
2490 	execute_cmd(rc, res, buf, s);
2491 }
2492 
2493 #ifdef HAVE_SSL
2494 /** handle SSL_do_handshake changes to the file descriptor to wait for later */
2495 static void
2496 remote_handshake_later(struct daemon_remote* rc, struct rc_state* s, int fd,
2497 	int r, int r2)
2498 {
2499 	if(r2 == SSL_ERROR_WANT_READ) {
2500 		if(s->shake_state == rc_hs_read) {
2501 			/* try again later */
2502 			return;
2503 		}
2504 		s->shake_state = rc_hs_read;
2505 		event_del(&s->c);
2506 		memset(&s->c, 0, sizeof(s->c));
2507 		event_set(&s->c, fd, EV_PERSIST|EV_TIMEOUT|EV_READ,
2508 			remote_control_callback, s);
2509 		if(event_base_set(xfrd->event_base, &s->c) != 0)
2510 			log_msg(LOG_ERR, "remote_accept: cannot set event_base");
2511 		if(event_add(&s->c, &s->tval) != 0)
2512 			log_msg(LOG_ERR, "remote_accept: cannot add event");
2513 		return;
2514 	} else if(r2 == SSL_ERROR_WANT_WRITE) {
2515 		if(s->shake_state == rc_hs_write) {
2516 			/* try again later */
2517 			return;
2518 		}
2519 		s->shake_state = rc_hs_write;
2520 		event_del(&s->c);
2521 		memset(&s->c, 0, sizeof(s->c));
2522 		event_set(&s->c, fd, EV_PERSIST|EV_TIMEOUT|EV_WRITE,
2523 			remote_control_callback, s);
2524 		if(event_base_set(xfrd->event_base, &s->c) != 0)
2525 			log_msg(LOG_ERR, "remote_accept: cannot set event_base");
2526 		if(event_add(&s->c, &s->tval) != 0)
2527 			log_msg(LOG_ERR, "remote_accept: cannot add event");
2528 		return;
2529 	} else {
2530 		if(r == 0)
2531 			log_msg(LOG_ERR, "remote control connection closed prematurely");
2532 		log_crypto_err("remote control failed ssl");
2533 		clean_point(rc, s);
2534 	}
2535 }
2536 #endif /* HAVE_SSL */
2537 
2538 static void
2539 remote_control_callback(int fd, short event, void* arg)
2540 {
2541 	RES res;
2542 	struct rc_state* s = (struct rc_state*)arg;
2543 	struct daemon_remote* rc = s->rc;
2544 	if( (event&EV_TIMEOUT) ) {
2545 		log_msg(LOG_ERR, "remote control timed out");
2546 		clean_point(rc, s);
2547 		return;
2548 	}
2549 #ifdef HAVE_SSL
2550 	if(s->ssl) {
2551 		/* (continue to) setup the SSL connection */
2552 		int r;
2553 		ERR_clear_error();
2554 		r = SSL_do_handshake(s->ssl);
2555 		if(r != 1) {
2556 			int r2 = SSL_get_error(s->ssl, r);
2557 			remote_handshake_later(rc, s, fd, r, r2);
2558 			return;
2559 		}
2560 		s->shake_state = rc_none;
2561 	}
2562 #endif /* HAVE_SSL */
2563 
2564 	/* once handshake has completed, check authentication */
2565 	if (!rc->use_cert) {
2566 		VERBOSITY(3, (LOG_INFO, "unauthenticated remote control connection"));
2567 #ifdef HAVE_SSL
2568 	} else if(SSL_get_verify_result(s->ssl) == X509_V_OK) {
2569 		X509* x = SSL_get_peer_certificate(s->ssl);
2570 		if(!x) {
2571 			VERBOSITY(2, (LOG_INFO, "remote control connection "
2572 				"provided no client certificate"));
2573 			clean_point(rc, s);
2574 			return;
2575 		}
2576 		VERBOSITY(3, (LOG_INFO, "remote control connection authenticated"));
2577 		X509_free(x);
2578 #endif /* HAVE_SSL */
2579 	} else {
2580 		VERBOSITY(2, (LOG_INFO, "remote control connection failed to "
2581 			"authenticate with client certificate"));
2582 		clean_point(rc, s);
2583 		return;
2584 	}
2585 
2586 	/* if OK start to actually handle the request */
2587 #ifdef HAVE_SSL
2588 	res.ssl = s->ssl;
2589 #endif /* HAVE_SSL */
2590 	res.fd = fd;
2591 	handle_req(rc, s, &res);
2592 
2593 	if(!s->in_stats_list) {
2594 		VERBOSITY(3, (LOG_INFO, "remote control operation completed"));
2595 		clean_point(rc, s);
2596 	}
2597 }
2598 
2599 #ifdef BIND8_STATS
2600 static const char*
2601 opcode2str(int o)
2602 {
2603 	switch(o) {
2604 		case OPCODE_QUERY: return "QUERY";
2605 		case OPCODE_IQUERY: return "IQUERY";
2606 		case OPCODE_STATUS: return "STATUS";
2607 		case OPCODE_NOTIFY: return "NOTIFY";
2608 		case OPCODE_UPDATE: return "UPDATE";
2609 		default: return "OTHER";
2610 	}
2611 }
2612 
2613 /** print long number */
2614 static int
2615 print_longnum(RES* ssl, char* desc, uint64_t x)
2616 {
2617 	if(x > (uint64_t)1024*1024*1024) {
2618 		/* more than a Gb */
2619 		size_t front = (size_t)(x / (uint64_t)1000000);
2620 		size_t back = (size_t)(x % (uint64_t)1000000);
2621 		return ssl_printf(ssl, "%s%lu%6.6lu\n", desc,
2622 			(unsigned long)front, (unsigned long)back);
2623 	} else {
2624 		return ssl_printf(ssl, "%s%lu\n", desc, (unsigned long)x);
2625 	}
2626 }
2627 
2628 /* print one block of statistics.  n is name and d is delimiter */
2629 static void
2630 print_stat_block(RES* ssl, char* n, char* d, struct nsdst* st)
2631 {
2632 	const char* rcstr[] = {"NOERROR", "FORMERR", "SERVFAIL", "NXDOMAIN",
2633 	    "NOTIMP", "REFUSED", "YXDOMAIN", "YXRRSET", "NXRRSET", "NOTAUTH",
2634 	    "NOTZONE", "RCODE11", "RCODE12", "RCODE13", "RCODE14", "RCODE15",
2635 	    "BADVERS"
2636 	};
2637 	size_t i;
2638 	for(i=0; i<= 255; i++) {
2639 		if(inhibit_zero && st->qtype[i] == 0 &&
2640 			strncmp(rrtype_to_string(i), "TYPE", 4) == 0)
2641 			continue;
2642 		if(!ssl_printf(ssl, "%s%snum.type.%s=%lu\n", n, d,
2643 			rrtype_to_string(i), (unsigned long)st->qtype[i]))
2644 			return;
2645 	}
2646 
2647 	/* opcode */
2648 	for(i=0; i<6; i++) {
2649 		if(inhibit_zero && st->opcode[i] == 0 && i != OPCODE_QUERY)
2650 			continue;
2651 		if(!ssl_printf(ssl, "%s%snum.opcode.%s=%lu\n", n, d,
2652 			opcode2str(i), (unsigned long)st->opcode[i]))
2653 			return;
2654 	}
2655 
2656 	/* qclass */
2657 	for(i=0; i<4; i++) {
2658 		if(inhibit_zero && st->qclass[i] == 0 && i != CLASS_IN)
2659 			continue;
2660 		if(!ssl_printf(ssl, "%s%snum.class.%s=%lu\n", n, d,
2661 			rrclass_to_string(i), (unsigned long)st->qclass[i]))
2662 			return;
2663 	}
2664 
2665 	/* rcode */
2666 	for(i=0; i<17; i++) {
2667 		if(inhibit_zero && st->rcode[i] == 0 &&
2668 			i > RCODE_YXDOMAIN) /* NSD does not use larger */
2669 			continue;
2670 		if(!ssl_printf(ssl, "%s%snum.rcode.%s=%lu\n", n, d, rcstr[i],
2671 			(unsigned long)st->rcode[i]))
2672 			return;
2673 	}
2674 
2675 	/* edns */
2676 	if(!ssl_printf(ssl, "%s%snum.edns=%lu\n", n, d, (unsigned long)st->edns))
2677 		return;
2678 
2679 	/* ednserr */
2680 	if(!ssl_printf(ssl, "%s%snum.ednserr=%lu\n", n, d,
2681 		(unsigned long)st->ednserr))
2682 		return;
2683 
2684 	/* qudp */
2685 	if(!ssl_printf(ssl, "%s%snum.udp=%lu\n", n, d, (unsigned long)st->qudp))
2686 		return;
2687 	/* qudp6 */
2688 	if(!ssl_printf(ssl, "%s%snum.udp6=%lu\n", n, d, (unsigned long)st->qudp6))
2689 		return;
2690 	/* ctcp */
2691 	if(!ssl_printf(ssl, "%s%snum.tcp=%lu\n", n, d, (unsigned long)st->ctcp))
2692 		return;
2693 	/* ctcp6 */
2694 	if(!ssl_printf(ssl, "%s%snum.tcp6=%lu\n", n, d, (unsigned long)st->ctcp6))
2695 		return;
2696 	/* ctls */
2697 	if(!ssl_printf(ssl, "%s%snum.tls=%lu\n", n, d, (unsigned long)st->ctls))
2698 		return;
2699 	/* ctls6 */
2700 	if(!ssl_printf(ssl, "%s%snum.tls6=%lu\n", n, d, (unsigned long)st->ctls6))
2701 		return;
2702 
2703 	/* nona */
2704 	if(!ssl_printf(ssl, "%s%snum.answer_wo_aa=%lu\n", n, d,
2705 		(unsigned long)st->nona))
2706 		return;
2707 
2708 	/* rxerr */
2709 	if(!ssl_printf(ssl, "%s%snum.rxerr=%lu\n", n, d, (unsigned long)st->rxerr))
2710 		return;
2711 
2712 	/* txerr */
2713 	if(!ssl_printf(ssl, "%s%snum.txerr=%lu\n", n, d, (unsigned long)st->txerr))
2714 		return;
2715 
2716 	/* number of requested-axfr, number of times axfr served to clients */
2717 	if(!ssl_printf(ssl, "%s%snum.raxfr=%lu\n", n, d, (unsigned long)st->raxfr))
2718 		return;
2719 
2720 	/* number of requested-ixfr, number of times ixfr served to clients */
2721 	if(!ssl_printf(ssl, "%s%snum.rixfr=%lu\n", n, d, (unsigned long)st->rixfr))
2722 		return;
2723 
2724 	/* truncated */
2725 	if(!ssl_printf(ssl, "%s%snum.truncated=%lu\n", n, d,
2726 		(unsigned long)st->truncated))
2727 		return;
2728 
2729 	/* dropped */
2730 	if(!ssl_printf(ssl, "%s%snum.dropped=%lu\n", n, d,
2731 		(unsigned long)st->dropped))
2732 		return;
2733 }
2734 
2735 #ifdef USE_ZONE_STATS
2736 static void
2737 resize_zonestat(xfrd_state_type* xfrd, size_t num)
2738 {
2739 	struct nsdst** a = xalloc_array_zero(num, sizeof(struct nsdst*));
2740 	if(xfrd->zonestat_clear_num != 0)
2741 		memcpy(a, xfrd->zonestat_clear, xfrd->zonestat_clear_num
2742 			* sizeof(struct nsdst*));
2743 	free(xfrd->zonestat_clear);
2744 	xfrd->zonestat_clear = a;
2745 	xfrd->zonestat_clear_num = num;
2746 }
2747 
2748 static void
2749 zonestat_print(RES* ssl, xfrd_state_type* xfrd, int clear)
2750 {
2751 	struct zonestatname* n;
2752 	struct nsdst stat0, stat1;
2753 	RBTREE_FOR(n, struct zonestatname*, xfrd->nsd->options->zonestatnames){
2754 		char* name = (char*)n->node.key;
2755 		if(n->id >= xfrd->zonestat_safe)
2756 			continue; /* newly allocated and reload has not yet
2757 				done and replied with new size */
2758 		if(name == NULL || name[0]==0)
2759 			continue; /* empty name, do not output */
2760 		/* the statistics are stored in two blocks, during reload
2761 		 * the newly forked processes get the other block to use,
2762 		 * these blocks are mmapped and are currently in use to
2763 		 * add statistics to */
2764 		memcpy(&stat0, &xfrd->nsd->zonestat[0][n->id], sizeof(stat0));
2765 		memcpy(&stat1, &xfrd->nsd->zonestat[1][n->id], sizeof(stat1));
2766 		stats_add(&stat0, &stat1);
2767 
2768 		/* save a copy of current (cumulative) stats in stat1 */
2769 		memcpy(&stat1, &stat0, sizeof(stat1));
2770 		/* subtract last total of stats that was 'cleared' */
2771 		if(n->id < xfrd->zonestat_clear_num &&
2772 			xfrd->zonestat_clear[n->id])
2773 			stats_subtract(&stat0, xfrd->zonestat_clear[n->id]);
2774 		if(clear) {
2775 			/* extend storage array if needed */
2776 			if(n->id >= xfrd->zonestat_clear_num) {
2777 				if(n->id+1 < xfrd->nsd->options->zonestatnames->count)
2778 					resize_zonestat(xfrd, xfrd->nsd->options->zonestatnames->count);
2779 				else
2780 					resize_zonestat(xfrd, n->id+1);
2781 			}
2782 			if(!xfrd->zonestat_clear[n->id])
2783 				xfrd->zonestat_clear[n->id] = xalloc(
2784 					sizeof(struct nsdst));
2785 			/* store last total of stats */
2786 			memcpy(xfrd->zonestat_clear[n->id], &stat1,
2787 				sizeof(struct nsdst));
2788 		}
2789 
2790 		/* stat0 contains the details that we want to print */
2791 		if(!ssl_printf(ssl, "%s%snum.queries=%lu\n", name, ".",
2792 			(unsigned long)(stat0.qudp + stat0.qudp6 + stat0.ctcp +
2793 				stat0.ctcp6 + stat0.ctls + stat0.ctls6)))
2794 			return;
2795 		print_stat_block(ssl, name, ".", &stat0);
2796 	}
2797 }
2798 #endif /* USE_ZONE_STATS */
2799 
2800 static void
2801 print_stats(RES* ssl, xfrd_state_type* xfrd, struct timeval* now, int clear)
2802 {
2803 	size_t i;
2804 	stc_type total = 0;
2805 	struct timeval elapsed, uptime;
2806 
2807 	/* per CPU and total */
2808 	for(i=0; i<xfrd->nsd->child_count; i++) {
2809 		if(!ssl_printf(ssl, "server%d.queries=%lu\n", (int)i,
2810 			(unsigned long)xfrd->nsd->children[i].query_count))
2811 			return;
2812 		total += xfrd->nsd->children[i].query_count;
2813 	}
2814 	if(!ssl_printf(ssl, "num.queries=%lu\n", (unsigned long)total))
2815 		return;
2816 
2817 	/* time elapsed and uptime (in seconds) */
2818 	timeval_subtract(&uptime, now, &xfrd->nsd->rc->boot_time);
2819 	timeval_subtract(&elapsed, now, &xfrd->nsd->rc->stats_time);
2820 	if(!ssl_printf(ssl, "time.boot=%lu.%6.6lu\n",
2821 		(unsigned long)uptime.tv_sec, (unsigned long)uptime.tv_usec))
2822 		return;
2823 	if(!ssl_printf(ssl, "time.elapsed=%lu.%6.6lu\n",
2824 		(unsigned long)elapsed.tv_sec, (unsigned long)elapsed.tv_usec))
2825 		return;
2826 
2827 	/* mem info, database on disksize */
2828 	if(!print_longnum(ssl, "size.db.disk=", xfrd->nsd->st.db_disk))
2829 		return;
2830 	if(!print_longnum(ssl, "size.db.mem=", xfrd->nsd->st.db_mem))
2831 		return;
2832 	if(!print_longnum(ssl, "size.xfrd.mem=", region_get_mem(xfrd->region)))
2833 		return;
2834 	if(!print_longnum(ssl, "size.config.disk=",
2835 		xfrd->nsd->options->zonelist_off))
2836 		return;
2837 	if(!print_longnum(ssl, "size.config.mem=", region_get_mem(
2838 		xfrd->nsd->options->region)))
2839 		return;
2840 	print_stat_block(ssl, "", "", &xfrd->nsd->st);
2841 
2842 	/* zone statistics */
2843 	if(!ssl_printf(ssl, "zone.master=%lu\n",
2844 		(unsigned long)(xfrd->notify_zones->count - xfrd->zones->count)))
2845 		return;
2846 	if(!ssl_printf(ssl, "zone.slave=%lu\n", (unsigned long)xfrd->zones->count))
2847 		return;
2848 #ifdef USE_ZONE_STATS
2849 	zonestat_print(ssl, xfrd, clear); /* per-zone statistics */
2850 #else
2851 	(void)clear;
2852 #endif
2853 }
2854 
2855 static void
2856 clear_stats(xfrd_state_type* xfrd)
2857 {
2858 	size_t i;
2859 	uint64_t dbd = xfrd->nsd->st.db_disk;
2860 	uint64_t dbm = xfrd->nsd->st.db_mem;
2861 	for(i=0; i<xfrd->nsd->child_count; i++) {
2862 		xfrd->nsd->children[i].query_count = 0;
2863 	}
2864 	memset(&xfrd->nsd->st, 0, sizeof(struct nsdst));
2865 	/* zonestats are cleared by storing the cumulative value that
2866 	 * was last printed in the zonestat_clear array, and subtracting
2867 	 * that before the next stats printout */
2868 	xfrd->nsd->st.db_disk = dbd;
2869 	xfrd->nsd->st.db_mem = dbm;
2870 }
2871 
2872 void
2873 daemon_remote_process_stats(struct daemon_remote* rc)
2874 {
2875 	RES res;
2876 	struct rc_state* s;
2877 	struct timeval now;
2878 	if(!rc) return;
2879 	if(gettimeofday(&now, NULL) == -1)
2880 		log_msg(LOG_ERR, "gettimeofday: %s", strerror(errno));
2881 	/* pop one and give it stats */
2882 	while((s = rc->stats_list)) {
2883 		assert(s->in_stats_list);
2884 #ifdef HAVE_SSL
2885 		res.ssl = s->ssl;
2886 #endif
2887 		res.fd = s->fd;
2888 		print_stats(&res, rc->xfrd, &now, (s->in_stats_list == 1));
2889 		if(s->in_stats_list == 1) {
2890 			clear_stats(rc->xfrd);
2891 			rc->stats_time = now;
2892 		}
2893 		VERBOSITY(3, (LOG_INFO, "remote control stats printed"));
2894 		rc->stats_list = s->next;
2895 		s->in_stats_list = 0;
2896 		clean_point(rc, s);
2897 	}
2898 }
2899 #endif /* BIND8_STATS */
2900 
2901 int
2902 create_local_accept_sock(const char *path, int* noproto)
2903 {
2904 #ifdef HAVE_SYS_UN_H
2905 	int s;
2906 	struct sockaddr_un usock;
2907 
2908 	VERBOSITY(3, (LOG_INFO, "creating unix socket %s", path));
2909 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
2910 	/* this member exists on BSDs, not Linux */
2911 	usock.sun_len = (unsigned)sizeof(usock);
2912 #endif
2913 	usock.sun_family = AF_LOCAL;
2914 	/* length is 92-108, 104 on FreeBSD */
2915 	(void)strlcpy(usock.sun_path, path, sizeof(usock.sun_path));
2916 
2917 	if ((s = socket(AF_LOCAL, SOCK_STREAM, 0)) == -1) {
2918 		log_msg(LOG_ERR, "Cannot create local socket %s (%s)",
2919 			path, strerror(errno));
2920 		return -1;
2921 	}
2922 
2923 	if (unlink(path) && errno != ENOENT) {
2924 		/* The socket already exists and cannot be removed */
2925 		log_msg(LOG_ERR, "Cannot remove old local socket %s (%s)",
2926 			path, strerror(errno));
2927 		goto err;
2928 	}
2929 
2930 	if (bind(s, (struct sockaddr *)&usock,
2931 		(socklen_t)sizeof(struct sockaddr_un)) == -1) {
2932 		log_msg(LOG_ERR, "Cannot bind local socket %s (%s)",
2933 			path, strerror(errno));
2934 		goto err;
2935 	}
2936 
2937 	if (fcntl(s, F_SETFL, O_NONBLOCK) == -1) {
2938 		log_msg(LOG_ERR, "Cannot set non-blocking mode");
2939 		goto err;
2940 	}
2941 
2942 	if (listen(s, TCP_BACKLOG) == -1) {
2943 		log_msg(LOG_ERR, "can't listen: %s", strerror(errno));
2944 		goto err;
2945 	}
2946 
2947 	(void)noproto; /*unused*/
2948 	return s;
2949 
2950 err:
2951 	close(s);
2952 	return -1;
2953 
2954 #else
2955 	(void)path;
2956 	log_msg(LOG_ERR, "Local sockets are not supported");
2957 	*noproto = 1;
2958 	return -1;
2959 #endif
2960 }
2961