xref: /openbsd/usr.sbin/nsd/remote.c (revision cecf84d4)
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 #ifdef HAVE_SSL
47 
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 #include <ctype.h>
58 #include <unistd.h>
59 #include <assert.h>
60 #include <fcntl.h>
61 #ifndef USE_MINI_EVENT
62 #  ifdef HAVE_EVENT_H
63 #    include <event.h>
64 #  else
65 #    include <event2/event.h>
66 #    include "event2/event_struct.h"
67 #    include "event2/event_compat.h"
68 #  endif
69 #else
70 #  include "mini_event.h"
71 #endif
72 #include "remote.h"
73 #include "util.h"
74 #include "xfrd.h"
75 #include "xfrd-notify.h"
76 #include "xfrd-tcp.h"
77 #include "nsd.h"
78 #include "options.h"
79 #include "difffile.h"
80 #include "xfrd.h"
81 #include "ipc.h"
82 
83 #ifdef HAVE_SYS_TYPES_H
84 #  include <sys/types.h>
85 #endif
86 #ifdef HAVE_NETDB_H
87 #include <netdb.h>
88 #endif
89 
90 /** number of seconds timeout on incoming remote control handshake */
91 #define REMOTE_CONTROL_TCP_TIMEOUT 120
92 
93 /** repattern to master or slave */
94 #define REPAT_SLAVE  1
95 #define REPAT_MASTER 2
96 
97 /** if you want zero to be inhibited in stats output.
98  * it omits zeroes for types that have no acronym and unused-rcodes */
99 const int inhibit_zero = 1;
100 
101 /**
102  * a busy control command connection, SSL state
103  * Defined here to keep the definition private, and keep SSL out of the .h
104  */
105 struct rc_state {
106 	/** the next item in list */
107 	struct rc_state* next, *prev;
108 	/* if the event was added to the event_base */
109 	int event_added;
110 	/** the commpoint */
111 	struct event c;
112 	/** timeout for this state */
113 	struct timeval tval;
114 	/** in the handshake part */
115 	enum { rc_none, rc_hs_read, rc_hs_write } shake_state;
116 	/** the ssl state */
117 	SSL* ssl;
118 	/** the rc this is part of */
119 	struct daemon_remote* rc;
120 	/** stats list next item */
121 	struct rc_state* stats_next;
122 	/** stats list indicator (0 is not part of stats list, 1 is stats,
123 	 * 2 is stats_noreset. */
124 	int in_stats_list;
125 };
126 
127 /**
128  * list of events for accepting connections
129  */
130 struct acceptlist {
131 	struct acceptlist* next;
132 	int event_added;
133 	struct event c;
134 };
135 
136 /**
137  * The remote control state.
138  */
139 struct daemon_remote {
140 	/** the master process for this remote control */
141 	struct xfrd_state* xfrd;
142 	/** commpoints for accepting remote control connections */
143 	struct acceptlist* accept_list;
144 	/** number of active commpoints that are handling remote control */
145 	int active;
146 	/** max active commpoints */
147 	int max_active;
148 	/** current commpoints busy; double linked, malloced */
149 	struct rc_state* busy_list;
150 	/** commpoints waiting for stats to complete (also in busy_list) */
151 	struct rc_state* stats_list;
152 	/** last time stats was reported */
153 	struct timeval stats_time, boot_time;
154 	/** the SSL context for creating new SSL streams */
155 	SSL_CTX* ctx;
156 };
157 
158 /**
159  * Print fixed line of text over ssl connection in blocking mode
160  * @param ssl: print to
161  * @param text: the text.
162  * @return false on connection failure.
163  */
164 static int ssl_print_text(SSL* ssl, const char* text);
165 
166 /**
167  * printf style printing to the ssl connection
168  * @param ssl: the SSL connection to print to. Blocking.
169  * @param format: printf style format string.
170  * @return success or false on a network failure.
171  */
172 static int ssl_printf(SSL* ssl, const char* format, ...)
173         ATTR_FORMAT(printf, 2, 3);
174 
175 /**
176  * Read until \n is encountered
177  * If SSL signals EOF, the string up to then is returned (without \n).
178  * @param ssl: the SSL connection to read from. blocking.
179  * @param buf: buffer to read to.
180  * @param max: size of buffer.
181  * @return false on connection failure.
182  */
183 static int ssl_read_line(SSL* ssl, char* buf, size_t max);
184 
185 /** perform the accept of a new remote control connection */
186 static void
187 remote_accept_callback(int fd, short event, void* arg);
188 
189 /** perform remote control */
190 static void
191 remote_control_callback(int fd, short event, void* arg);
192 
193 
194 /** ---- end of private defines ---- **/
195 
196 
197 /** log ssl crypto err */
198 static void
199 log_crypto_err(const char* str)
200 {
201 	/* error:[error code]:[library name]:[function name]:[reason string] */
202 	char buf[128];
203 	unsigned long e;
204 	ERR_error_string_n(ERR_get_error(), buf, sizeof(buf));
205 	log_msg(LOG_ERR, "%s crypto %s", str, buf);
206 	while( (e=ERR_get_error()) ) {
207 		ERR_error_string_n(e, buf, sizeof(buf));
208 		log_msg(LOG_ERR, "and additionally crypto %s", buf);
209 	}
210 }
211 
212 #ifdef BIND8_STATS
213 /** subtract timers and the values do not overflow or become negative */
214 static void
215 timeval_subtract(struct timeval* d, const struct timeval* end,
216 	const struct timeval* start)
217 {
218 #ifndef S_SPLINT_S
219 	time_t end_usec = end->tv_usec;
220 	d->tv_sec = end->tv_sec - start->tv_sec;
221 	if(end_usec < start->tv_usec) {
222 		end_usec += 1000000;
223 		d->tv_sec--;
224 	}
225 	d->tv_usec = end_usec - start->tv_usec;
226 #endif
227 }
228 #endif /* BIND8_STATS */
229 
230 struct daemon_remote*
231 daemon_remote_create(nsd_options_t* cfg)
232 {
233 	char* s_cert;
234 	char* s_key;
235 	struct daemon_remote* rc = (struct daemon_remote*)xalloc_zero(
236 		sizeof(*rc));
237 	rc->max_active = 10;
238 	assert(cfg->control_enable);
239 
240 	/* init SSL library */
241 	ERR_load_crypto_strings();
242 	ERR_load_SSL_strings();
243 	OpenSSL_add_all_algorithms();
244 	(void)SSL_library_init();
245 
246 	if(!RAND_status()) {
247 		/* try to seed it */
248 		unsigned char buf[256];
249 		unsigned int v, seed=(unsigned)time(NULL) ^ (unsigned)getpid();
250 		size_t i;
251 		v = seed;
252 		for(i=0; i<256/sizeof(v); i++) {
253 			memmove(buf+i*sizeof(v), &v, sizeof(v));
254 			v = v*seed + (unsigned int)i;
255 		}
256 		RAND_seed(buf, 256);
257 		log_msg(LOG_WARNING, "warning: no entropy, seeding openssl PRNG with time");
258 	}
259 
260 	rc->ctx = SSL_CTX_new(SSLv23_server_method());
261 	if(!rc->ctx) {
262 		log_crypto_err("could not SSL_CTX_new");
263 		free(rc);
264 		return NULL;
265 	}
266 	/* no SSLv2, SSLv3 because has defects */
267 	if(!(SSL_CTX_set_options(rc->ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)){
268 		log_crypto_err("could not set SSL_OP_NO_SSLv2");
269 		daemon_remote_delete(rc);
270 		return NULL;
271 	}
272 	if(!(SSL_CTX_set_options(rc->ctx, SSL_OP_NO_SSLv3) & SSL_OP_NO_SSLv3)){
273 		log_crypto_err("could not set SSL_OP_NO_SSLv3");
274 		daemon_remote_delete(rc);
275 		return NULL;
276 	}
277 	s_cert = cfg->server_cert_file;
278 	s_key = cfg->server_key_file;
279 	VERBOSITY(2, (LOG_INFO, "setup SSL certificates"));
280 	if (!SSL_CTX_use_certificate_file(rc->ctx,s_cert,SSL_FILETYPE_PEM)) {
281 		log_msg(LOG_ERR, "Error for server-cert-file: %s", s_cert);
282 		log_crypto_err("Error in SSL_CTX use_certificate_file");
283 		goto setup_error;
284 	}
285 	if(!SSL_CTX_use_PrivateKey_file(rc->ctx,s_key,SSL_FILETYPE_PEM)) {
286 		log_msg(LOG_ERR, "Error for server-key-file: %s", s_key);
287 		log_crypto_err("Error in SSL_CTX use_PrivateKey_file");
288 		goto setup_error;
289 	}
290 	if(!SSL_CTX_check_private_key(rc->ctx)) {
291 		log_msg(LOG_ERR, "Error for server-key-file: %s", s_key);
292 		log_crypto_err("Error in SSL_CTX check_private_key");
293 		goto setup_error;
294 	}
295 	if(!SSL_CTX_load_verify_locations(rc->ctx, s_cert, NULL)) {
296 		log_crypto_err("Error setting up SSL_CTX verify locations");
297 	setup_error:
298 		daemon_remote_delete(rc);
299 		return NULL;
300 	}
301 	SSL_CTX_set_client_CA_list(rc->ctx, SSL_load_client_CA_file(s_cert));
302 	SSL_CTX_set_verify(rc->ctx, SSL_VERIFY_PEER, NULL);
303 
304 	/* and try to open the ports */
305 	if(!daemon_remote_open_ports(rc, cfg)) {
306 		log_msg(LOG_ERR, "could not open remote control port");
307 		goto setup_error;
308 	}
309 
310 	if(gettimeofday(&rc->boot_time, NULL) == -1)
311 		log_msg(LOG_ERR, "gettimeofday: %s", strerror(errno));
312 	rc->stats_time = rc->boot_time;
313 
314 	return rc;
315 }
316 
317 void daemon_remote_close(struct daemon_remote* rc)
318 {
319 	struct rc_state* p, *np;
320 	struct acceptlist* h, *nh;
321 	if(!rc) return;
322 
323 	/* close listen sockets */
324 	h = rc->accept_list;
325 	while(h) {
326 		nh = h->next;
327 		if(h->event_added)
328 			event_del(&h->c);
329 		close(h->c.ev_fd);
330 		free(h);
331 		h = nh;
332 	}
333 	rc->accept_list = NULL;
334 
335 	/* close busy connection sockets */
336 	p = rc->busy_list;
337 	while(p) {
338 		np = p->next;
339 		if(p->event_added)
340 			event_del(&p->c);
341 		if(p->ssl)
342 			SSL_free(p->ssl);
343 		close(p->c.ev_fd);
344 		free(p);
345 		p = np;
346 	}
347 	rc->busy_list = NULL;
348 	rc->active = 0;
349 }
350 
351 void daemon_remote_delete(struct daemon_remote* rc)
352 {
353 	if(!rc) return;
354 	daemon_remote_close(rc);
355 	if(rc->ctx) {
356 		SSL_CTX_free(rc->ctx);
357 	}
358 	free(rc);
359 }
360 
361 static int
362 create_tcp_accept_sock(struct addrinfo* addr, int* noproto)
363 {
364 #if defined(SO_REUSEADDR) || (defined(INET6) && (defined(IPV6_V6ONLY) || defined(IPV6_USE_MIN_MTU) || defined(IPV6_MTU)))
365 	int on = 1;
366 #endif
367 	int s;
368 	*noproto = 0;
369 	if ((s = socket(addr->ai_family, addr->ai_socktype, 0)) == -1) {
370 #if defined(INET6)
371 		if (addr->ai_family == AF_INET6 &&
372 			errno == EAFNOSUPPORT) {
373 			*noproto = 1;
374 			log_msg(LOG_WARNING, "fallback to TCP4, no IPv6: not supported");
375 			return -1;
376 		}
377 #endif /* INET6 */
378 		log_msg(LOG_ERR, "can't create a socket: %s", strerror(errno));
379 		return -1;
380 	}
381 #ifdef  SO_REUSEADDR
382 	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) {
383 		log_msg(LOG_ERR, "setsockopt(..., SO_REUSEADDR, ...) failed: %s", strerror(errno));
384 	}
385 #endif /* SO_REUSEADDR */
386 #if defined(INET6) && defined(IPV6_V6ONLY)
387 	if (addr->ai_family == AF_INET6 &&
388 		setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0)
389 	{
390 		log_msg(LOG_ERR, "setsockopt(..., IPV6_V6ONLY, ...) failed: %s", strerror(errno));
391 		return -1;
392 	}
393 #endif
394 	/* set it nonblocking */
395 	/* (StevensUNP p463), if tcp listening socket is blocking, then
396 	   it may block in accept, even if select() says readable. */
397 	if (fcntl(s, F_SETFL, O_NONBLOCK) == -1) {
398 		log_msg(LOG_ERR, "cannot fcntl tcp: %s", strerror(errno));
399 	}
400 	/* Bind it... */
401 	if (bind(s, (struct sockaddr *)addr->ai_addr, addr->ai_addrlen) != 0) {
402 		log_msg(LOG_ERR, "can't bind tcp socket: %s", strerror(errno));
403 		return -1;
404 	}
405 	/* Listen to it... */
406 	if (listen(s, TCP_BACKLOG_REMOTE) == -1) {
407 		log_msg(LOG_ERR, "can't listen: %s", strerror(errno));
408 		return -1;
409 	}
410 	return s;
411 }
412 
413 /**
414  * Add and open a new control port
415  * @param rc: rc with result list.
416  * @param ip: ip str
417  * @param nr: port nr
418  * @param noproto_is_err: if lack of protocol support is an error.
419  * @return false on failure.
420  */
421 static int
422 add_open(struct daemon_remote* rc, const char* ip, int nr, int noproto_is_err)
423 {
424 	struct addrinfo hints;
425 	struct addrinfo* res;
426 	struct acceptlist* hl;
427 	int noproto;
428 	int fd, r;
429 	char port[15];
430 	snprintf(port, sizeof(port), "%d", nr);
431 	port[sizeof(port)-1]=0;
432 	memset(&hints, 0, sizeof(hints));
433 	hints.ai_socktype = SOCK_STREAM;
434 	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
435 	if((r = getaddrinfo(ip, port, &hints, &res)) != 0 || !res) {
436                 log_msg(LOG_ERR, "control interface %s:%s getaddrinfo: %s %s",
437 			ip?ip:"default", port, gai_strerror(r),
438 #ifdef EAI_SYSTEM
439 			r==EAI_SYSTEM?(char*)strerror(errno):""
440 #else
441 			""
442 #endif
443 			);
444 		return 0;
445 	}
446 
447 	/* open fd */
448 	fd = create_tcp_accept_sock(res, &noproto);
449 	freeaddrinfo(res);
450 	if(fd == -1 && noproto) {
451 		if(!noproto_is_err)
452 			return 1; /* return success, but do nothing */
453 		log_msg(LOG_ERR, "cannot open control interface %s %d : "
454 			"protocol not supported", ip, nr);
455 		return 0;
456 	}
457 	if(fd == -1) {
458 		log_msg(LOG_ERR, "cannot open control interface %s %d", ip, nr);
459 		return 0;
460 	}
461 
462 	/* alloc */
463 	hl = (struct acceptlist*)xalloc_zero(sizeof(*hl));
464 	hl->next = rc->accept_list;
465 	rc->accept_list = hl;
466 
467 	hl->c.ev_fd = fd;
468 	hl->event_added = 0;
469 	return 1;
470 }
471 
472 int
473 daemon_remote_open_ports(struct daemon_remote* rc, nsd_options_t* cfg)
474 {
475 	assert(cfg->control_enable && cfg->control_port);
476 	if(cfg->control_interface) {
477 		ip_address_option_t* p;
478 		for(p = cfg->control_interface; p; p = p->next) {
479 			if(!add_open(rc, p->address, cfg->control_port, 1)) {
480 				return 0;
481 			}
482 		}
483 	} else {
484 		/* defaults */
485 		if(cfg->do_ip6 && !add_open(rc, "::1", cfg->control_port, 0)) {
486 			return 0;
487 		}
488 		if(cfg->do_ip4 &&
489 			!add_open(rc, "127.0.0.1", cfg->control_port, 1)) {
490 			return 0;
491 		}
492 	}
493 	return 1;
494 }
495 
496 void
497 daemon_remote_attach(struct daemon_remote* rc, struct xfrd_state* xfrd)
498 {
499 	int fd;
500 	struct acceptlist* p;
501 	if(!rc) return;
502 	rc->xfrd = xfrd;
503 	for(p = rc->accept_list; p; p = p->next) {
504 		/* add event */
505 		fd = p->c.ev_fd;
506 		event_set(&p->c, fd, EV_PERSIST|EV_READ, remote_accept_callback,
507 			rc);
508 		if(event_base_set(xfrd->event_base, &p->c) != 0)
509 			log_msg(LOG_ERR, "remote: cannot set event_base");
510 		if(event_add(&p->c, NULL) != 0)
511 			log_msg(LOG_ERR, "remote: cannot add event");
512 		p->event_added = 1;
513 	}
514 }
515 
516 static void
517 remote_accept_callback(int fd, short event, void* arg)
518 {
519 	struct daemon_remote *rc = (struct daemon_remote*)arg;
520 #ifdef INET6
521 	struct sockaddr_storage addr;
522 #else
523 	struct sockaddr_in addr;
524 #endif
525 	socklen_t addrlen;
526 	int newfd;
527 	struct rc_state* n;
528 
529 	if (!(event & EV_READ)) {
530 		return;
531 	}
532 
533 	/* perform the accept */
534 	addrlen = sizeof(addr);
535 	newfd = accept(fd, (struct sockaddr*)&addr, &addrlen);
536 	if(newfd == -1) {
537 		if (    errno != EINTR
538 			&& errno != EWOULDBLOCK
539 #ifdef ECONNABORTED
540 			&& errno != ECONNABORTED
541 #endif /* ECONNABORTED */
542 #ifdef EPROTO
543 			&& errno != EPROTO
544 #endif /* EPROTO */
545 			) {
546 			log_msg(LOG_ERR, "accept failed: %s", strerror(errno));
547 		}
548 		return;
549 	}
550 
551 	/* create new commpoint unless we are servicing already */
552 	if(rc->active >= rc->max_active) {
553 		log_msg(LOG_WARNING, "drop incoming remote control: "
554 			"too many connections");
555 	close_exit:
556 		close(newfd);
557 		return;
558 	}
559 	if (fcntl(newfd, F_SETFL, O_NONBLOCK) == -1) {
560 		log_msg(LOG_ERR, "fcntl failed: %s", strerror(errno));
561 		goto close_exit;
562 	}
563 
564 	/* setup state to service the remote control command */
565 	n = (struct rc_state*)calloc(1, sizeof(*n));
566 	if(!n) {
567 		log_msg(LOG_ERR, "out of memory");
568 		goto close_exit;
569 	}
570 
571 	n->tval.tv_sec = REMOTE_CONTROL_TCP_TIMEOUT;
572 	n->tval.tv_usec = 0L;
573 
574 	event_set(&n->c, newfd, EV_PERSIST|EV_TIMEOUT|EV_READ,
575 		remote_control_callback, n);
576 	if(event_base_set(xfrd->event_base, &n->c) != 0) {
577 		log_msg(LOG_ERR, "remote_accept: cannot set event_base");
578 		free(n);
579 		goto close_exit;
580 	}
581 	if(event_add(&n->c, &n->tval) != 0) {
582 		log_msg(LOG_ERR, "remote_accept: cannot add event");
583 		free(n);
584 		goto close_exit;
585 	}
586 	n->event_added = 1;
587 
588 	if(2 <= verbosity) {
589 		char s[128];
590 		addr2str(&addr, s, sizeof(s));
591 		VERBOSITY(2, (LOG_INFO, "new control connection from %s", s));
592 	}
593 
594 	n->shake_state = rc_hs_read;
595 	n->ssl = SSL_new(rc->ctx);
596 	if(!n->ssl) {
597 		log_crypto_err("could not SSL_new");
598 		event_del(&n->c);
599 		free(n);
600 		goto close_exit;
601 	}
602 	SSL_set_accept_state(n->ssl);
603         (void)SSL_set_mode(n->ssl, SSL_MODE_AUTO_RETRY);
604 	if(!SSL_set_fd(n->ssl, newfd)) {
605 		log_crypto_err("could not SSL_set_fd");
606 		event_del(&n->c);
607 		SSL_free(n->ssl);
608 		free(n);
609 		goto close_exit;
610 	}
611 
612 	n->rc = rc;
613 	n->stats_next = NULL;
614 	n->in_stats_list = 0;
615 	n->prev = NULL;
616 	n->next = rc->busy_list;
617 	if(n->next) n->next->prev = n;
618 	rc->busy_list = n;
619 	rc->active ++;
620 
621 	/* perform the first nonblocking read already, for windows,
622 	 * so it can return wouldblock. could be faster too. */
623 	remote_control_callback(newfd, EV_READ, n);
624 }
625 
626 /** delete from list */
627 static void
628 state_list_remove_elem(struct rc_state** list, struct rc_state* todel)
629 {
630 	if(todel->prev) todel->prev->next = todel->next;
631 	else	*list = todel->next;
632 	if(todel->next) todel->next->prev = todel->prev;
633 }
634 
635 /** delete from stats list */
636 static void
637 stats_list_remove_elem(struct rc_state** list, struct rc_state* todel)
638 {
639 	while(*list) {
640 		if( (*list) == todel) {
641 			*list = (*list)->stats_next;
642 			return;
643 		}
644 		list = &(*list)->stats_next;
645 	}
646 }
647 
648 /** decrease active count and remove commpoint from busy list */
649 static void
650 clean_point(struct daemon_remote* rc, struct rc_state* s)
651 {
652 	if(s->in_stats_list)
653 		stats_list_remove_elem(&rc->stats_list, s);
654 	state_list_remove_elem(&rc->busy_list, s);
655 	rc->active --;
656 	if(s->event_added)
657 		event_del(&s->c);
658 	if(s->ssl) {
659 		SSL_shutdown(s->ssl);
660 		SSL_free(s->ssl);
661 	}
662 	close(s->c.ev_fd);
663 	free(s);
664 }
665 
666 static int
667 ssl_print_text(SSL* ssl, const char* text)
668 {
669 	int r;
670 	if(!ssl)
671 		return 0;
672 	ERR_clear_error();
673 	if((r=SSL_write(ssl, text, (int)strlen(text))) <= 0) {
674 		if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
675 			VERBOSITY(2, (LOG_WARNING, "in SSL_write, peer "
676 				"closed connection"));
677 			return 0;
678 		}
679 		log_crypto_err("could not SSL_write");
680 		return 0;
681 	}
682 	return 1;
683 }
684 
685 /** print text over the ssl connection */
686 static int
687 ssl_print_vmsg(SSL* ssl, const char* format, va_list args)
688 {
689 	char msg[1024];
690 	vsnprintf(msg, sizeof(msg), format, args);
691 	return ssl_print_text(ssl, msg);
692 }
693 
694 /** printf style printing to the ssl connection */
695 static int
696 ssl_printf(SSL* ssl, const char* format, ...)
697 {
698 	va_list args;
699 	int ret;
700 	va_start(args, format);
701 	ret = ssl_print_vmsg(ssl, format, args);
702 	va_end(args);
703 	return ret;
704 }
705 
706 static int
707 ssl_read_line(SSL* ssl, char* buf, size_t max)
708 {
709 	int r;
710 	size_t len = 0;
711 	if(!ssl)
712 		return 0;
713 	while(len < max) {
714 		ERR_clear_error();
715 		if((r=SSL_read(ssl, buf+len, 1)) <= 0) {
716 			if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
717 				buf[len] = 0;
718 				return 1;
719 			}
720 			log_crypto_err("could not SSL_read");
721 			return 0;
722 		}
723 		if(buf[len] == '\n') {
724 			/* return string without \n */
725 			buf[len] = 0;
726 			return 1;
727 		}
728 		len++;
729 	}
730 	buf[max-1] = 0;
731 	log_msg(LOG_ERR, "control line too long (%d): %s", (int)max, buf);
732 	return 0;
733 }
734 
735 /** skip whitespace, return new pointer into string */
736 static char*
737 skipwhite(char* str)
738 {
739 	/* EOS \0 is not a space */
740 	while( isspace((unsigned char)*str) )
741 		str++;
742 	return str;
743 }
744 
745 /** send the OK to the control client */
746 static void
747 send_ok(SSL* ssl)
748 {
749 	(void)ssl_printf(ssl, "ok\n");
750 }
751 
752 /** get zone argument (if any) or NULL, false on error */
753 static int
754 get_zone_arg(SSL* ssl, xfrd_state_t* xfrd, char* arg,
755 	zone_options_t** zo)
756 {
757 	const dname_type* dname;
758 	if(!arg[0]) {
759 		/* no argument present, return NULL */
760 		*zo = NULL;
761 		return 1;
762 	}
763 	dname = dname_parse(xfrd->region, arg);
764 	if(!dname) {
765 		ssl_printf(ssl, "error cannot parse zone name '%s'\n", arg);
766 		*zo = NULL;
767 		return 0;
768 	}
769 	*zo = zone_options_find(xfrd->nsd->options, dname);
770 	region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
771 	if(!*zo) {
772 		ssl_printf(ssl, "error zone %s not configured\n", arg);
773 		return 0;
774 	}
775 	return 1;
776 }
777 
778 /** do the stop command */
779 static void
780 do_stop(SSL* ssl, xfrd_state_t* xfrd)
781 {
782 	xfrd->need_to_send_shutdown = 1;
783 
784 	if(!(xfrd->ipc_handler_flags&EV_WRITE)) {
785 		ipc_xfrd_set_listening(xfrd, EV_PERSIST|EV_READ|EV_WRITE);
786 	}
787 
788 	send_ok(ssl);
789 }
790 
791 /** do the log_reopen command, it only needs reload_now */
792 static void
793 do_log_reopen(SSL* ssl, xfrd_state_t* xfrd)
794 {
795 	xfrd_set_reload_now(xfrd);
796 	send_ok(ssl);
797 }
798 
799 /** do the reload command */
800 static void
801 do_reload(SSL* ssl, xfrd_state_t* xfrd, char* arg)
802 {
803 	zone_options_t* zo;
804 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
805 		return;
806 	task_new_check_zonefiles(xfrd->nsd->task[xfrd->nsd->mytask],
807 		xfrd->last_task, zo?(const dname_type*)zo->node.key:NULL);
808 	xfrd_set_reload_now(xfrd);
809 	send_ok(ssl);
810 }
811 
812 /** do the write command */
813 static void
814 do_write(SSL* ssl, xfrd_state_t* xfrd, char* arg)
815 {
816 	zone_options_t* zo;
817 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
818 		return;
819 	task_new_write_zonefiles(xfrd->nsd->task[xfrd->nsd->mytask],
820 		xfrd->last_task, zo?(const dname_type*)zo->node.key:NULL);
821 	xfrd_set_reload_now(xfrd);
822 	send_ok(ssl);
823 }
824 
825 /** do the notify command */
826 static void
827 do_notify(SSL* ssl, xfrd_state_t* xfrd, char* arg)
828 {
829 	zone_options_t* zo;
830 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
831 		return;
832 	if(zo) {
833 		struct notify_zone_t* n = (struct notify_zone_t*)rbtree_search(
834 			xfrd->notify_zones, (const dname_type*)zo->node.key);
835 		if(n) {
836 			xfrd_notify_start(n);
837 			send_ok(ssl);
838 		} else {
839 			ssl_printf(ssl, "error zone does not have notify\n");
840 		}
841 	} else {
842 		struct notify_zone_t* n;
843 		RBTREE_FOR(n, struct notify_zone_t*, xfrd->notify_zones) {
844 			xfrd_notify_start(n);
845 		}
846 		send_ok(ssl);
847 	}
848 }
849 
850 /** do the transfer command */
851 static void
852 do_transfer(SSL* ssl, xfrd_state_t* xfrd, char* arg)
853 {
854 	zone_options_t* zo;
855 	xfrd_zone_t* zone;
856 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
857 		return;
858 	if(zo) {
859 		zone = (xfrd_zone_t*)rbtree_search(xfrd->zones, (const
860 			dname_type*)zo->node.key);
861 		if(zone) {
862 			xfrd_handle_notify_and_start_xfr(zone, NULL);
863 			send_ok(ssl);
864 		} else {
865 			ssl_printf(ssl, "error zone not slave\n");
866 		}
867 	} else {
868 		RBTREE_FOR(zone, xfrd_zone_t*, xfrd->zones) {
869 			xfrd_handle_notify_and_start_xfr(zone, NULL);
870 		}
871 		ssl_printf(ssl, "ok, %u zones\n", (unsigned)xfrd->zones->count);
872 	}
873 }
874 
875 /** force transfer a zone */
876 static void
877 force_transfer_zone(xfrd_zone_t* zone)
878 {
879 	/* if in TCP transaction, stop it immediately. */
880 	if(zone->tcp_conn != -1)
881 		xfrd_tcp_release(xfrd->tcp_set, zone);
882 	else if(zone->zone_handler.ev_fd != -1)
883 		xfrd_udp_release(zone);
884 	/* pretend we not longer have it and force any
885 	 * zone to be downloaded (even same serial, w AXFR) */
886 	zone->soa_disk_acquired = 0;
887 	zone->soa_nsd_acquired = 0;
888 	xfrd_handle_notify_and_start_xfr(zone, NULL);
889 }
890 
891 /** do the force transfer command */
892 static void
893 do_force_transfer(SSL* ssl, xfrd_state_t* xfrd, char* arg)
894 {
895 	zone_options_t* zo;
896 	xfrd_zone_t* zone;
897 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
898 		return;
899 	if(zo) {
900 		zone = (xfrd_zone_t*)rbtree_search(xfrd->zones, (const
901 			dname_type*)zo->node.key);
902 		if(zone) {
903 			force_transfer_zone(zone);
904 			send_ok(ssl);
905 		} else {
906 			ssl_printf(ssl, "error zone not slave\n");
907 		}
908 	} else {
909 		RBTREE_FOR(zone, xfrd_zone_t*, xfrd->zones) {
910 			force_transfer_zone(zone);
911 		}
912 		ssl_printf(ssl, "ok, %u zones\n", (unsigned)xfrd->zones->count);
913 	}
914 }
915 
916 static int
917 print_soa_status(SSL* ssl, const char* str, xfrd_soa_t* soa, time_t acq)
918 {
919 	if(acq) {
920 		if(!ssl_printf(ssl, "	%s: \"%u since %s\"\n", str,
921 			(unsigned)ntohl(soa->serial), xfrd_pretty_time(acq)))
922 			return 0;
923 	} else {
924 		if(!ssl_printf(ssl, "	%s: none\n", str))
925 			return 0;
926 	}
927 	return 1;
928 }
929 
930 /** print zonestatus for one domain */
931 static int
932 print_zonestatus(SSL* ssl, xfrd_state_t* xfrd, zone_options_t* zo)
933 {
934 	xfrd_zone_t* xz = (xfrd_zone_t*)rbtree_search(xfrd->zones,
935 		(const dname_type*)zo->node.key);
936 	struct notify_zone_t* nz = (struct notify_zone_t*)rbtree_search(
937 		xfrd->notify_zones, (const dname_type*)zo->node.key);
938 	if(!ssl_printf(ssl, "zone:	%s\n", zo->name))
939 		return 0;
940 	if(!zo->part_of_config) {
941 		if(!ssl_printf(ssl, "	pattern: %s\n", zo->pattern->pname))
942 			return 0;
943 	}
944 	if(nz) {
945 		if(nz->is_waiting) {
946 			if(!ssl_printf(ssl, "	notify: \"waiting-for-fd\"\n"))
947 				return 0;
948 		} else if(nz->notify_send_enable) {
949 			if(!ssl_printf(ssl, "	notify: \"sent try %d "
950 				"to %s with serial %u\"\n", nz->notify_retry,
951 				nz->notify_current->ip_address_spec,
952 				(unsigned)ntohl(nz->current_soa->serial)))
953 				return 0;
954 		}
955 	}
956 	if(!xz) {
957 		if(!ssl_printf(ssl, "	state: master\n"))
958 			return 0;
959 		return 1;
960 	}
961 	if(!ssl_printf(ssl, "	state: %s\n",
962 		(xz->state == xfrd_zone_ok)?"ok":(
963 		(xz->state == xfrd_zone_expired)?"expired":"refreshing")))
964 		return 0;
965 	if(!print_soa_status(ssl, "served-serial", &xz->soa_nsd,
966 		xz->soa_nsd_acquired))
967 		return 0;
968 	if(!print_soa_status(ssl, "commit-serial", &xz->soa_disk,
969 		xz->soa_disk_acquired))
970 		return 0;
971 	if(xz->round_num != -1) {
972 		if(!print_soa_status(ssl, "notified-serial", &xz->soa_notified,
973 			xz->soa_notified_acquired))
974 			return 0;
975 	}
976 
977 	/* UDP */
978 	if(xz->udp_waiting) {
979 		if(!ssl_printf(ssl, "	transfer: \"waiting-for-UDP-fd\"\n"))
980 			return 0;
981 	} else if(xz->zone_handler.ev_fd != -1 && xz->tcp_conn == -1) {
982 		if(!ssl_printf(ssl, "	transfer: \"sent UDP to %s\"\n",
983 			xz->master->ip_address_spec))
984 			return 0;
985 	}
986 
987 	/* TCP */
988 	if(xz->tcp_waiting) {
989 		if(!ssl_printf(ssl, "	transfer: \"waiting-for-TCP-fd\"\n"))
990 			return 0;
991 	} else if(xz->tcp_conn != -1) {
992 		if(!ssl_printf(ssl, "	transfer: \"TCP connected to %s\"\n",
993 			xz->master->ip_address_spec))
994 			return 0;
995 	}
996 
997 	return 1;
998 }
999 
1000 /** do the zonestatus command */
1001 static void
1002 do_zonestatus(SSL* ssl, xfrd_state_t* xfrd, char* arg)
1003 {
1004 	zone_options_t* zo;
1005 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
1006 		return;
1007 	if(zo) (void)print_zonestatus(ssl, xfrd, zo);
1008 	else {
1009 		RBTREE_FOR(zo, zone_options_t*,
1010 			xfrd->nsd->options->zone_options) {
1011 			if(!print_zonestatus(ssl, xfrd, zo))
1012 				return;
1013 		}
1014 	}
1015 }
1016 
1017 /** do the verbosity command */
1018 static void
1019 do_verbosity(SSL* ssl, char* str)
1020 {
1021 	int val = atoi(str);
1022 	if(strcmp(str, "") == 0) {
1023 		ssl_printf(ssl, "verbosity %d\n", verbosity);
1024 		return;
1025 	}
1026 	if(val == 0 && strcmp(str, "0") != 0) {
1027 		ssl_printf(ssl, "error in verbosity number syntax: %s\n", str);
1028 		return;
1029 	}
1030 	verbosity = val;
1031 	task_new_set_verbosity(xfrd->nsd->task[xfrd->nsd->mytask],
1032 		xfrd->last_task, val);
1033 	xfrd_set_reload_now(xfrd);
1034 	send_ok(ssl);
1035 }
1036 
1037 /** find second argument, modifies string */
1038 static int
1039 find_arg2(SSL* ssl, char* arg, char** arg2)
1040 {
1041 	char* as = strrchr(arg, ' ');
1042 	if(as) {
1043 		as[0]=0;
1044 		*arg2 = as+1;
1045 		while(isspace((unsigned char)*as) && as > arg)
1046 			as--;
1047 		as[0]=0;
1048 		return 1;
1049 	}
1050 	ssl_printf(ssl, "error could not find next argument "
1051 		"after %s\n", arg);
1052 	return 0;
1053 }
1054 
1055 /** do the status command */
1056 static void
1057 do_status(SSL* ssl, xfrd_state_t* xfrd)
1058 {
1059 	if(!ssl_printf(ssl, "version: %s\n", PACKAGE_VERSION))
1060 		return;
1061 	if(!ssl_printf(ssl, "verbosity: %d\n", verbosity))
1062 		return;
1063 #ifdef RATELIMIT
1064 	if(!ssl_printf(ssl, "ratelimit: %d\n",
1065 		(int)xfrd->nsd->options->rrl_ratelimit))
1066 		return;
1067 #else
1068 	(void)xfrd;
1069 #endif
1070 }
1071 
1072 /** do the stats command */
1073 static void
1074 do_stats(struct daemon_remote* rc, int peek, struct rc_state* rs)
1075 {
1076 #ifdef BIND8_STATS
1077 	/* queue up to get stats after a reload is done (to gather statistics
1078 	 * from the servers) */
1079 	assert(!rs->in_stats_list);
1080 	if(peek) rs->in_stats_list = 2;
1081 	else	rs->in_stats_list = 1;
1082 	rs->stats_next = rc->stats_list;
1083 	rc->stats_list = rs;
1084 	/* block the tcp waiting for the reload */
1085 	event_del(&rs->c);
1086 	rs->event_added = 0;
1087 	/* force a reload */
1088 	xfrd_set_reload_now(xfrd);
1089 #else
1090 	(void)rc; (void)peek;
1091 	(void)ssl_printf(rs->ssl, "error no stats enabled at compile time\n");
1092 #endif /* BIND8_STATS */
1093 }
1094 
1095 /** see if we have more zonestatistics entries and it has to be incremented */
1096 static void
1097 zonestat_inc_ifneeded(xfrd_state_t* xfrd)
1098 {
1099 #ifdef USE_ZONE_STATS
1100 	if(xfrd->nsd->options->zonestatnames->count != xfrd->zonestat_safe)
1101 		task_new_zonestat_inc(xfrd->nsd->task[xfrd->nsd->mytask],
1102 			xfrd->last_task,
1103 			xfrd->nsd->options->zonestatnames->count);
1104 #else
1105 	(void)xfrd;
1106 #endif /* USE_ZONE_STATS */
1107 }
1108 
1109 /** do the addzone command */
1110 static void
1111 do_addzone(SSL* ssl, xfrd_state_t* xfrd, char* arg)
1112 {
1113 	const dname_type* dname;
1114 	zone_options_t* zopt;
1115 	char* arg2 = NULL;
1116 	if(!find_arg2(ssl, arg, &arg2))
1117 		return;
1118 
1119 	/* if we add it to the xfrd now, then xfrd could download AXFR and
1120 	 * store it and the NSD-reload would see it in the difffile before
1121 	 * it sees the add-config task.
1122 	 */
1123 	/* thus: AXFRs and IXFRs must store the pattern name in the
1124 	 * difffile, so that it can be added when the AXFR or IXFR is seen.
1125 	 */
1126 
1127 	/* check that the pattern exists */
1128 	if(!rbtree_search(xfrd->nsd->options->patterns, arg2)) {
1129 		(void)ssl_printf(ssl, "error pattern %s does not exist\n",
1130 			arg2);
1131 		return;
1132 	}
1133 
1134 	dname = dname_parse(xfrd->region, arg);
1135 	if(!dname) {
1136 		(void)ssl_printf(ssl, "error cannot parse zone name\n");
1137 		return;
1138 	}
1139 
1140 	/* see if zone is a duplicate */
1141 	if( (zopt=zone_options_find(xfrd->nsd->options, dname)) ) {
1142 		region_recycle(xfrd->region, (void*)dname,
1143 			dname_total_size(dname));
1144 		(void)ssl_printf(ssl, "zone %s already exists\n", arg);
1145 		send_ok(ssl); /* a nop operation */
1146 		return;
1147 	}
1148 	region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
1149 	dname = NULL;
1150 
1151 	/* add to zonelist and adds to config in memory */
1152 	zopt = zone_list_add(xfrd->nsd->options, arg, arg2);
1153 	if(!zopt) {
1154 		/* also dname parse error here */
1155 		(void)ssl_printf(ssl, "error could not add zonelist entry\n");
1156 		return;
1157 	}
1158 	/* make addzone task and schedule reload */
1159 	task_new_add_zone(xfrd->nsd->task[xfrd->nsd->mytask],
1160 		xfrd->last_task, arg, arg2,
1161 		getzonestatid(xfrd->nsd->options, zopt));
1162 	zonestat_inc_ifneeded(xfrd);
1163 	xfrd_set_reload_now(xfrd);
1164 	/* add to xfrd - notify (for master and slaves) */
1165 	init_notify_send(xfrd->notify_zones, xfrd->region, zopt);
1166 	/* add to xfrd - slave */
1167 	if(zone_is_slave(zopt)) {
1168 		xfrd_init_slave_zone(xfrd, zopt);
1169 	}
1170 
1171 	send_ok(ssl);
1172 }
1173 
1174 /** do the delzone command */
1175 static void
1176 do_delzone(SSL* ssl, xfrd_state_t* xfrd, char* arg)
1177 {
1178 	const dname_type* dname;
1179 	zone_options_t* zopt;
1180 
1181 	dname = dname_parse(xfrd->region, arg);
1182 	if(!dname) {
1183 		(void)ssl_printf(ssl, "error cannot parse zone name\n");
1184 		return;
1185 	}
1186 
1187 	/* see if we have the zone in question */
1188 	zopt = zone_options_find(xfrd->nsd->options, dname);
1189 	if(!zopt) {
1190 		region_recycle(xfrd->region, (void*)dname,
1191 			dname_total_size(dname));
1192 		/* nothing to do */
1193 		if(!ssl_printf(ssl, "warning zone %s not present\n", arg))
1194 			return;
1195 		send_ok(ssl);
1196 		return;
1197 	}
1198 
1199 	/* see if it can be deleted */
1200 	if(zopt->part_of_config) {
1201 		region_recycle(xfrd->region, (void*)dname,
1202 			dname_total_size(dname));
1203 		(void)ssl_printf(ssl, "error zone defined in nsd.conf, "
1204 			"cannot delete it in this manner: remove it from "
1205 			"nsd.conf yourself and repattern\n");
1206 		return;
1207 	}
1208 
1209 	/* create deletion task */
1210 	task_new_del_zone(xfrd->nsd->task[xfrd->nsd->mytask],
1211 		xfrd->last_task, dname);
1212 	xfrd_set_reload_now(xfrd);
1213 	/* delete it in xfrd */
1214 	if(zone_is_slave(zopt)) {
1215 		xfrd_del_slave_zone(xfrd, dname);
1216 	}
1217 	xfrd_del_notify(xfrd, dname);
1218 	/* delete from config */
1219 	zone_list_del(xfrd->nsd->options, zopt);
1220 
1221 	region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
1222 	send_ok(ssl);
1223 }
1224 
1225 /** remove TSIG key from config and add task so that reload does too */
1226 static void remove_key(xfrd_state_t* xfrd, const char* kname)
1227 {
1228 	/* add task before deletion because the name string could be deleted */
1229 	task_new_del_key(xfrd->nsd->task[xfrd->nsd->mytask], xfrd->last_task,
1230 		kname);
1231 	key_options_remove(xfrd->nsd->options, kname);
1232 	xfrd_set_reload_now(xfrd); /* this is executed when the current control
1233 		command ends, thus the entire config changes are bunched up */
1234 }
1235 
1236 /** add TSIG key to config and add task so that reload does too */
1237 static void add_key(xfrd_state_t* xfrd, key_options_t* k)
1238 {
1239 	key_options_add_modify(xfrd->nsd->options, k);
1240 	task_new_add_key(xfrd->nsd->task[xfrd->nsd->mytask], xfrd->last_task,
1241 		k);
1242 	xfrd_set_reload_now(xfrd);
1243 }
1244 
1245 /** check if keys have changed */
1246 static void repat_keys(xfrd_state_t* xfrd, nsd_options_t* newopt)
1247 {
1248 	nsd_options_t* oldopt = xfrd->nsd->options;
1249 	key_options_t* k;
1250 	/* find deleted keys */
1251 	k = (key_options_t*)rbtree_first(oldopt->keys);
1252 	while((rbnode_t*)k != RBTREE_NULL) {
1253 		key_options_t* next = (key_options_t*)rbtree_next(
1254 			(rbnode_t*)k);
1255 		if(!key_options_find(newopt, k->name))
1256 			remove_key(xfrd, k->name);
1257 		k = next;
1258 	}
1259 	/* find added or changed keys */
1260 	RBTREE_FOR(k, key_options_t*, newopt->keys) {
1261 		key_options_t* origk = key_options_find(oldopt, k->name);
1262 		if(!origk)
1263 			add_key(xfrd, k);
1264 		else if(!key_options_equal(k, origk))
1265 			add_key(xfrd, k);
1266 	}
1267 }
1268 
1269 /** find zone given the implicit pattern */
1270 static const dname_type*
1271 parse_implicit_name(xfrd_state_t* xfrd,const char* pname)
1272 {
1273 	if(strncmp(pname, PATTERN_IMPLICIT_MARKER,
1274 		strlen(PATTERN_IMPLICIT_MARKER)) != 0)
1275 		return NULL;
1276 	return dname_parse(xfrd->region, pname +
1277 		strlen(PATTERN_IMPLICIT_MARKER));
1278 }
1279 
1280 /** remove cfgzone and add task so that reload does too */
1281 static void
1282 remove_cfgzone(xfrd_state_t* xfrd, const char* pname)
1283 {
1284 	/* dname and find the zone for the implicit pattern */
1285 	zone_options_t* zopt = NULL;
1286 	const dname_type* dname = parse_implicit_name(xfrd, pname);
1287 	if(!dname) {
1288 		/* should have a parseable name, but it did not */
1289 		return;
1290 	}
1291 
1292 	/* find the zone entry for the implicit pattern */
1293 	zopt = zone_options_find(xfrd->nsd->options, dname);
1294 	if(!zopt) {
1295 		/* this should not happen; implicit pattern has zone entry */
1296 		region_recycle(xfrd->region, (void*)dname,
1297 			dname_total_size(dname));
1298 		return;
1299 	}
1300 
1301 	/* create deletion task */
1302 	task_new_del_zone(xfrd->nsd->task[xfrd->nsd->mytask],
1303 		xfrd->last_task, dname);
1304 	xfrd_set_reload_now(xfrd);
1305 	/* delete it in xfrd */
1306 	if(zone_is_slave(zopt)) {
1307 		xfrd_del_slave_zone(xfrd, dname);
1308 	}
1309 	xfrd_del_notify(xfrd, dname);
1310 
1311 	/* delete from zoneoptions */
1312 	zone_options_delete(xfrd->nsd->options, zopt);
1313 
1314 	/* recycle parsed dname */
1315 	region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
1316 }
1317 
1318 /** add cfgzone and add task so that reload does too */
1319 static void
1320 add_cfgzone(xfrd_state_t* xfrd, const char* pname)
1321 {
1322 	/* add to our zonelist */
1323 	zone_options_t* zopt = zone_options_create(xfrd->nsd->options->region);
1324 	if(!zopt)
1325 		return;
1326 	zopt->part_of_config = 1;
1327 	zopt->name = region_strdup(xfrd->nsd->options->region,
1328 		pname + strlen(PATTERN_IMPLICIT_MARKER));
1329 	zopt->pattern = pattern_options_find(xfrd->nsd->options, pname);
1330 	if(!zopt->name || !zopt->pattern)
1331 		return;
1332 	if(!nsd_options_insert_zone(xfrd->nsd->options, zopt)) {
1333 		log_msg(LOG_ERR, "bad domain name or duplicate zone '%s' "
1334 			"pattern %s", zopt->name, pname);
1335 	}
1336 
1337 	/* make addzone task and schedule reload */
1338 	task_new_add_zone(xfrd->nsd->task[xfrd->nsd->mytask],
1339 		xfrd->last_task, zopt->name, pname,
1340 		getzonestatid(xfrd->nsd->options, zopt));
1341 	/* zonestat_inc is done after the entire config file has been done */
1342 	xfrd_set_reload_now(xfrd);
1343 	/* add to xfrd - notify (for master and slaves) */
1344 	init_notify_send(xfrd->notify_zones, xfrd->region, zopt);
1345 	/* add to xfrd - slave */
1346 	if(zone_is_slave(zopt)) {
1347 		xfrd_init_slave_zone(xfrd, zopt);
1348 	}
1349 }
1350 
1351 /** remove pattern and add task so that reload does too */
1352 static void
1353 remove_pat(xfrd_state_t* xfrd, const char* name)
1354 {
1355 	/* add task before deletion, because name-string could be deleted */
1356 	task_new_del_pattern(xfrd->nsd->task[xfrd->nsd->mytask],
1357 		xfrd->last_task, name);
1358 	pattern_options_remove(xfrd->nsd->options, name);
1359 	xfrd_set_reload_now(xfrd);
1360 }
1361 
1362 /** add pattern and add task so that reload does too */
1363 static void
1364 add_pat(xfrd_state_t* xfrd, pattern_options_t* p)
1365 {
1366 	pattern_options_add_modify(xfrd->nsd->options, p);
1367 	task_new_add_pattern(xfrd->nsd->task[xfrd->nsd->mytask],
1368 		xfrd->last_task, p);
1369 	xfrd_set_reload_now(xfrd);
1370 }
1371 
1372 /** interrupt zones that are using changed or removed patterns */
1373 static void
1374 repat_interrupt_zones(xfrd_state_t* xfrd, nsd_options_t* newopt)
1375 {
1376 	/* if masterlist changed:
1377 	 *   interrupt slave zone (UDP or TCP) transfers.
1378 	 *   slave zones reset master to start of list.
1379 	 */
1380 	xfrd_zone_t* xz;
1381 	struct notify_zone_t* nz;
1382 	RBTREE_FOR(xz, xfrd_zone_t*, xfrd->zones) {
1383 		pattern_options_t* oldp = xz->zone_options->pattern;
1384 		pattern_options_t* newp = pattern_options_find(newopt,
1385 			oldp->pname);
1386 		if(!newp || !acl_list_equal(oldp->request_xfr,
1387 			newp->request_xfr)) {
1388 			/* interrupt transfer */
1389 			if(xz->tcp_conn != -1) {
1390 				xfrd_tcp_release(xfrd->tcp_set, xz);
1391 				xfrd_set_refresh_now(xz);
1392 			} else if(xz->zone_handler.ev_fd != -1) {
1393 				xfrd_udp_release(xz);
1394 				xfrd_set_refresh_now(xz);
1395 			}
1396 			xz->master = 0;
1397 			xz->master_num = 0;
1398 			xz->next_master = -1;
1399 			xz->round_num = 0; /* fresh set of retries */
1400 		}
1401 	}
1402 	/* if notify list changed:
1403 	 *   interrupt notify that is busy.
1404 	 *   reset notify to start of list.  (clear all other reset_notify)
1405 	 */
1406 	RBTREE_FOR(nz, struct notify_zone_t*, xfrd->notify_zones) {
1407 		pattern_options_t* oldp = nz->options->pattern;
1408 		pattern_options_t* newp = pattern_options_find(newopt,
1409 			oldp->pname);
1410 		if(!newp || !acl_list_equal(oldp->notify, newp->notify)) {
1411 			/* interrupt notify */
1412 			if(nz->notify_send_enable) {
1413 				notify_disable(nz);
1414 				/* set to restart the notify after the
1415 				 * pattern has been changed. */
1416 				nz->notify_restart = 2;
1417 			} else {
1418 				nz->notify_restart = 1;
1419 			}
1420 		} else {
1421 			nz->notify_restart = 0;
1422 		}
1423 	}
1424 }
1425 
1426 /** for notify, after the pattern changes, restart the affected notifies */
1427 static void
1428 repat_interrupt_notify_start(xfrd_state_t* xfrd)
1429 {
1430 	struct notify_zone_t* nz;
1431 	RBTREE_FOR(nz, struct notify_zone_t*, xfrd->notify_zones) {
1432 		if(nz->notify_restart) {
1433 			if(nz->notify_current)
1434 				nz->notify_current = nz->options->pattern->notify;
1435 			if(nz->notify_restart == 2) {
1436 				if(nz->notify_restart)
1437 					xfrd_notify_start(nz);
1438 			}
1439 		}
1440 	}
1441 }
1442 
1443 /** check if patterns have changed */
1444 static void
1445 repat_patterns(xfrd_state_t* xfrd, nsd_options_t* newopt)
1446 {
1447 	/* zones that use changed patterns must have:
1448 	 * - their AXFR/IXFR interrupted: try again, acl may have changed.
1449 	 *   if the old master/key still exists, OK, fix master-numptrs and
1450 	 *   keep going.  Otherwise, stop xfer and reset TSIG.
1451 	 * - send NOTIFY reset to start of NOTIFY list (and TSIG reset).
1452 	 */
1453 	nsd_options_t* oldopt = xfrd->nsd->options;
1454 	pattern_options_t* p;
1455 	int search_zones = 0;
1456 
1457 	repat_interrupt_zones(xfrd, newopt);
1458 	/* find deleted patterns */
1459 	p = (pattern_options_t*)rbtree_first(oldopt->patterns);
1460 	while((rbnode_t*)p != RBTREE_NULL) {
1461 		pattern_options_t* next = (pattern_options_t*)rbtree_next(
1462 			(rbnode_t*)p);
1463 		if(!pattern_options_find(newopt, p->pname)) {
1464 			if(p->implicit) {
1465 				/* first remove its zone */
1466 				VERBOSITY(1, (LOG_INFO, "zone removed from config: %s", p->pname + strlen(PATTERN_IMPLICIT_MARKER)));
1467 				remove_cfgzone(xfrd, p->pname);
1468 			}
1469 			remove_pat(xfrd, p->pname);
1470 		}
1471 		p = next;
1472 	}
1473 	/* find added or changed patterns */
1474 	RBTREE_FOR(p, pattern_options_t*, newopt->patterns) {
1475 		pattern_options_t* origp = pattern_options_find(oldopt,
1476 			p->pname);
1477 		if(!origp) {
1478 			/* no zones can use it, no zone_interrupt needed */
1479 			add_pat(xfrd, p);
1480 			if(p->implicit) {
1481 				VERBOSITY(1, (LOG_INFO, "zone added to config: %s", p->pname + strlen(PATTERN_IMPLICIT_MARKER)));
1482 				add_cfgzone(xfrd, p->pname);
1483 			}
1484 		} else if(!pattern_options_equal(p, origp)) {
1485 			uint8_t newstate = 0;
1486 			if (p->request_xfr && !origp->request_xfr) {
1487 				newstate = REPAT_SLAVE;
1488 			} else if (!p->request_xfr && origp->request_xfr) {
1489 				newstate = REPAT_MASTER;
1490 			}
1491 			add_pat(xfrd, p);
1492 			if (p->implicit && newstate) {
1493 				const dname_type* dname =
1494 					parse_implicit_name(xfrd, p->pname);
1495 				if (dname) {
1496 					if (newstate == REPAT_SLAVE) {
1497 						zone_options_t* zopt =
1498 							zone_options_find(
1499 							oldopt, dname);
1500 						if (zopt) {
1501 							xfrd_init_slave_zone(
1502 								xfrd, zopt);
1503 						}
1504 					} else if (newstate == REPAT_MASTER) {
1505 						xfrd_del_slave_zone(xfrd,
1506 							dname);
1507 					}
1508 					region_recycle(xfrd->region,
1509 						(void*)dname,
1510 						dname_total_size(dname));
1511 				}
1512 			} else if(!p->implicit && newstate) {
1513 				/* search all zones with this pattern */
1514 				search_zones = 1;
1515 				origp->xfrd_flags = newstate;
1516 			}
1517 		}
1518 	}
1519 	if (search_zones) {
1520 		zone_options_t* zone_opt;
1521 		/* search in oldopt because 1) it contains zonelist zones,
1522 		 * and 2) you need oldopt(existing) to call xfrd_init */
1523 		RBTREE_FOR(zone_opt, zone_options_t*, oldopt->zone_options) {
1524 			pattern_options_t* oldp = zone_opt->pattern;
1525 			if (!oldp->implicit) {
1526 				if (oldp->xfrd_flags == REPAT_SLAVE) {
1527 					/* xfrd needs stable reference so get
1528 					 * it from the oldopt(modified) tree */
1529 					xfrd_init_slave_zone(xfrd, zone_opt);
1530 				} else if (oldp->xfrd_flags == REPAT_MASTER) {
1531 					xfrd_del_slave_zone(xfrd,
1532 						(const dname_type*)
1533 						zone_opt->node.key);
1534 				}
1535 				oldp->xfrd_flags = 0;
1536 			}
1537 		}
1538 	}
1539 	repat_interrupt_notify_start(xfrd);
1540 }
1541 
1542 /** true if options are different that can be set via repat. */
1543 static int
1544 repat_options_changed(xfrd_state_t* xfrd, nsd_options_t* newopt)
1545 {
1546 #ifdef RATELIMIT
1547 	if(xfrd->nsd->options->rrl_ratelimit != newopt->rrl_ratelimit)
1548 		return 1;
1549 	if(xfrd->nsd->options->rrl_whitelist_ratelimit != newopt->rrl_whitelist_ratelimit)
1550 		return 1;
1551 	if(xfrd->nsd->options->rrl_slip != newopt->rrl_slip)
1552 		return 1;
1553 #else
1554 	(void)xfrd; (void)newopt;
1555 #endif
1556 	return 0;
1557 }
1558 
1559 /** check if global options have changed */
1560 static void
1561 repat_options(xfrd_state_t* xfrd, nsd_options_t* newopt)
1562 {
1563 	if(repat_options_changed(xfrd, newopt)) {
1564 		/* update our options */
1565 #ifdef RATELIMIT
1566 		xfrd->nsd->options->rrl_ratelimit = newopt->rrl_ratelimit;
1567 		xfrd->nsd->options->rrl_whitelist_ratelimit = newopt->rrl_whitelist_ratelimit;
1568 		xfrd->nsd->options->rrl_slip = newopt->rrl_slip;
1569 #endif
1570 		task_new_opt_change(xfrd->nsd->task[xfrd->nsd->mytask],
1571 			xfrd->last_task, newopt);
1572 		xfrd_set_reload_now(xfrd);
1573 	}
1574 }
1575 
1576 /** print errors over ssl, gets pointer-to-pointer to ssl, so it can set
1577  * the pointer to NULL on failure and stop printing */
1578 static void
1579 print_ssl_cfg_err(void* arg, const char* str)
1580 {
1581 	SSL** ssl = (SSL**)arg;
1582 	if(!*ssl) return;
1583 	if(!ssl_printf(*ssl, "%s", str))
1584 		*ssl = NULL; /* failed, stop printing */
1585 }
1586 
1587 /** do the repattern command: reread config file and apply keys, patterns */
1588 static void
1589 do_repattern(SSL* ssl, xfrd_state_t* xfrd)
1590 {
1591 	region_type* region = region_create(xalloc, free);
1592 	nsd_options_t* opt;
1593 	const char* cfgfile = xfrd->nsd->options->configfile;
1594 
1595 	/* check chroot and configfile, if possible to reread */
1596 	if(xfrd->nsd->chrootdir) {
1597 		size_t l = strlen(xfrd->nsd->chrootdir);
1598 		while(l>0 && xfrd->nsd->chrootdir[l-1] == '/')
1599 			--l;
1600 		if(strncmp(xfrd->nsd->chrootdir, cfgfile, l) != 0) {
1601 			ssl_printf(ssl, "error %s is not relative to %s: "
1602 				"chroot prevents reread of config\n",
1603 				cfgfile, xfrd->nsd->chrootdir);
1604 			region_destroy(region);
1605 			return;
1606 		}
1607 		cfgfile += l;
1608 	}
1609 
1610 	ssl_printf(ssl, "reconfig start, read %s\n", cfgfile);
1611 	opt = nsd_options_create(region);
1612 	if(!parse_options_file(opt, cfgfile, &print_ssl_cfg_err, &ssl)) {
1613 		/* error already printed */
1614 		region_destroy(region);
1615 		return;
1616 	}
1617 	/* check for differences in TSIG keys and patterns, and apply,
1618 	 * first the keys, so that pattern->keyptr can be set right. */
1619 	repat_keys(xfrd, opt);
1620 	repat_patterns(xfrd, opt);
1621 	repat_options(xfrd, opt);
1622 	zonestat_inc_ifneeded(xfrd);
1623 	send_ok(ssl);
1624 	region_destroy(region);
1625 }
1626 
1627 /** do the serverpid command: printout pid of server process */
1628 static void
1629 do_serverpid(SSL* ssl, xfrd_state_t* xfrd)
1630 {
1631 	(void)ssl_printf(ssl, "%u\n", (unsigned)xfrd->reload_pid);
1632 }
1633 
1634 /** check for name with end-of-string, space or tab after it */
1635 static int
1636 cmdcmp(char* p, const char* cmd, size_t len)
1637 {
1638 	return strncmp(p,cmd,len)==0 && (p[len]==0||p[len]==' '||p[len]=='\t');
1639 }
1640 
1641 /** execute a remote control command */
1642 static void
1643 execute_cmd(struct daemon_remote* rc, SSL* ssl, char* cmd, struct rc_state* rs)
1644 {
1645 	char* p = skipwhite(cmd);
1646 	/* compare command */
1647 	if(cmdcmp(p, "stop", 4)) {
1648 		do_stop(ssl, rc->xfrd);
1649 	} else if(cmdcmp(p, "reload", 6)) {
1650 		do_reload(ssl, rc->xfrd, skipwhite(p+6));
1651 	} else if(cmdcmp(p, "write", 5)) {
1652 		do_write(ssl, rc->xfrd, skipwhite(p+5));
1653 	} else if(cmdcmp(p, "status", 6)) {
1654 		do_status(ssl, rc->xfrd);
1655 	} else if(cmdcmp(p, "stats_noreset", 13)) {
1656 		do_stats(rc, 1, rs);
1657 	} else if(cmdcmp(p, "stats", 5)) {
1658 		do_stats(rc, 0, rs);
1659 	} else if(cmdcmp(p, "log_reopen", 10)) {
1660 		do_log_reopen(ssl, rc->xfrd);
1661 	} else if(cmdcmp(p, "addzone", 7)) {
1662 		do_addzone(ssl, rc->xfrd, skipwhite(p+7));
1663 	} else if(cmdcmp(p, "delzone", 7)) {
1664 		do_delzone(ssl, rc->xfrd, skipwhite(p+7));
1665 	} else if(cmdcmp(p, "notify", 6)) {
1666 		do_notify(ssl, rc->xfrd, skipwhite(p+6));
1667 	} else if(cmdcmp(p, "transfer", 8)) {
1668 		do_transfer(ssl, rc->xfrd, skipwhite(p+8));
1669 	} else if(cmdcmp(p, "force_transfer", 14)) {
1670 		do_force_transfer(ssl, rc->xfrd, skipwhite(p+14));
1671 	} else if(cmdcmp(p, "zonestatus", 10)) {
1672 		do_zonestatus(ssl, rc->xfrd, skipwhite(p+10));
1673 	} else if(cmdcmp(p, "verbosity", 9)) {
1674 		do_verbosity(ssl, skipwhite(p+9));
1675 	} else if(cmdcmp(p, "repattern", 9)) {
1676 		do_repattern(ssl, rc->xfrd);
1677 	} else if(cmdcmp(p, "reconfig", 8)) {
1678 		do_repattern(ssl, rc->xfrd);
1679 	} else if(cmdcmp(p, "serverpid", 9)) {
1680 		do_serverpid(ssl, rc->xfrd);
1681 	} else {
1682 		(void)ssl_printf(ssl, "error unknown command '%s'\n", p);
1683 	}
1684 }
1685 
1686 /** handle remote control request */
1687 static void
1688 handle_req(struct daemon_remote* rc, struct rc_state* s, SSL* ssl)
1689 {
1690 	int r;
1691 	char pre[10];
1692 	char magic[8];
1693 	char buf[1024];
1694 	if (fcntl(s->c.ev_fd, F_SETFL, 0) == -1) { /* set blocking */
1695 		log_msg(LOG_ERR, "cannot fcntl rc: %s", strerror(errno));
1696 	}
1697 
1698 	/* try to read magic UBCT[version]_space_ string */
1699 	ERR_clear_error();
1700 	if((r=SSL_read(ssl, magic, (int)sizeof(magic)-1)) <= 0) {
1701 		if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN)
1702 			return;
1703 		log_crypto_err("could not SSL_read");
1704 		return;
1705 	}
1706 	magic[7] = 0;
1707 	if( r != 7 || strncmp(magic, "NSDCT", 5) != 0) {
1708 		VERBOSITY(2, (LOG_INFO, "control connection has bad header"));
1709 		/* probably wrong tool connected, ignore it completely */
1710 		return;
1711 	}
1712 
1713 	/* read the command line */
1714 	if(!ssl_read_line(ssl, buf, sizeof(buf))) {
1715 		return;
1716 	}
1717 	snprintf(pre, sizeof(pre), "NSDCT%d ", NSD_CONTROL_VERSION);
1718 	if(strcmp(magic, pre) != 0) {
1719 		VERBOSITY(2, (LOG_INFO, "control connection had bad "
1720 			"version %s, cmd: %s", magic, buf));
1721 		ssl_printf(ssl, "error version mismatch\n");
1722 		return;
1723 	}
1724 	VERBOSITY(2, (LOG_INFO, "control cmd: %s", buf));
1725 
1726 	/* figure out what to do */
1727 	execute_cmd(rc, ssl, buf, s);
1728 }
1729 
1730 static void
1731 remote_control_callback(int fd, short event, void* arg)
1732 {
1733 	struct rc_state* s = (struct rc_state*)arg;
1734 	struct daemon_remote* rc = s->rc;
1735 	int r;
1736 	if( (event&EV_TIMEOUT) ) {
1737 		log_msg(LOG_ERR, "remote control timed out");
1738 		clean_point(rc, s);
1739 		return;
1740 	}
1741 	/* (continue to) setup the SSL connection */
1742 	ERR_clear_error();
1743 	r = SSL_do_handshake(s->ssl);
1744 	if(r != 1) {
1745 		int r2 = SSL_get_error(s->ssl, r);
1746 		if(r2 == SSL_ERROR_WANT_READ) {
1747 			if(s->shake_state == rc_hs_read) {
1748 				/* try again later */
1749 				return;
1750 			}
1751 			s->shake_state = rc_hs_read;
1752 			event_del(&s->c);
1753 			event_set(&s->c, fd, EV_PERSIST|EV_TIMEOUT|EV_READ,
1754 				remote_control_callback, s);
1755 			if(event_base_set(xfrd->event_base, &s->c) != 0)
1756 				log_msg(LOG_ERR, "remote_accept: cannot set event_base");
1757 			if(event_add(&s->c, &s->tval) != 0)
1758 				log_msg(LOG_ERR, "remote_accept: cannot add event");
1759 			return;
1760 		} else if(r2 == SSL_ERROR_WANT_WRITE) {
1761 			if(s->shake_state == rc_hs_write) {
1762 				/* try again later */
1763 				return;
1764 			}
1765 			s->shake_state = rc_hs_write;
1766 			event_del(&s->c);
1767 			event_set(&s->c, fd, EV_PERSIST|EV_TIMEOUT|EV_WRITE,
1768 				remote_control_callback, s);
1769 			if(event_base_set(xfrd->event_base, &s->c) != 0)
1770 				log_msg(LOG_ERR, "remote_accept: cannot set event_base");
1771 			if(event_add(&s->c, &s->tval) != 0)
1772 				log_msg(LOG_ERR, "remote_accept: cannot add event");
1773 			return;
1774 		} else {
1775 			if(r == 0)
1776 				log_msg(LOG_ERR, "remote control connection closed prematurely");
1777 			log_crypto_err("remote control failed ssl");
1778 			clean_point(rc, s);
1779 			return;
1780 		}
1781 	}
1782 	s->shake_state = rc_none;
1783 
1784 	/* once handshake has completed, check authentication */
1785 	if(SSL_get_verify_result(s->ssl) == X509_V_OK) {
1786 		X509* x = SSL_get_peer_certificate(s->ssl);
1787 		if(!x) {
1788 			VERBOSITY(2, (LOG_INFO, "remote control connection "
1789 				"provided no client certificate"));
1790 			clean_point(rc, s);
1791 			return;
1792 		}
1793 		VERBOSITY(3, (LOG_INFO, "remote control connection authenticated"));
1794 		X509_free(x);
1795 	} else {
1796 		VERBOSITY(2, (LOG_INFO, "remote control connection failed to "
1797 			"authenticate with client certificate"));
1798 		clean_point(rc, s);
1799 		return;
1800 	}
1801 
1802 	/* if OK start to actually handle the request */
1803 	handle_req(rc, s, s->ssl);
1804 
1805 	if(!s->in_stats_list) {
1806 		VERBOSITY(3, (LOG_INFO, "remote control operation completed"));
1807 		clean_point(rc, s);
1808 	}
1809 }
1810 
1811 #ifdef BIND8_STATS
1812 static const char*
1813 opcode2str(int o)
1814 {
1815 	switch(o) {
1816 		case OPCODE_QUERY: return "QUERY";
1817 		case OPCODE_IQUERY: return "IQUERY";
1818 		case OPCODE_STATUS: return "STATUS";
1819 		case OPCODE_NOTIFY: return "NOTIFY";
1820 		case OPCODE_UPDATE: return "UPDATE";
1821 		default: return "OTHER";
1822 	}
1823 }
1824 
1825 /** print long number */
1826 static int
1827 print_longnum(SSL* ssl, char* desc, uint64_t x)
1828 {
1829 	if(x > (uint64_t)1024*1024*1024) {
1830 		/* more than a Gb */
1831 		size_t front = (size_t)(x / (uint64_t)1000000);
1832 		size_t back = (size_t)(x % (uint64_t)1000000);
1833 		return ssl_printf(ssl, "%s%u%6.6u\n", desc,
1834 			(unsigned)front, (unsigned)back);
1835 	} else {
1836 		return ssl_printf(ssl, "%s%u\n", desc, (unsigned)x);
1837 	}
1838 }
1839 
1840 /* print one block of statistics.  n is name and d is delimiter */
1841 static void
1842 print_stat_block(SSL* ssl, char* n, char* d, struct nsdst* st)
1843 {
1844 	const char* rcstr[] = {"NOERROR", "FORMERR", "SERVFAIL", "NXDOMAIN",
1845 	    "NOTIMP", "REFUSED", "YXDOMAIN", "YXRRSET", "NXRRSET", "NOTAUTH",
1846 	    "NOTZONE", "RCODE11", "RCODE12", "RCODE13", "RCODE14", "RCODE15",
1847 	    "BADVERS"
1848 	};
1849 	size_t i;
1850 	for(i=0; i<= 255; i++) {
1851 		if(inhibit_zero && st->qtype[i] == 0 &&
1852 			strncmp(rrtype_to_string(i), "TYPE", 4) == 0)
1853 			continue;
1854 		if(!ssl_printf(ssl, "%s%snum.type.%s=%u\n", n, d,
1855 			rrtype_to_string(i), (unsigned)st->qtype[i]))
1856 			return;
1857 	}
1858 
1859 	/* opcode */
1860 	for(i=0; i<6; i++) {
1861 		if(inhibit_zero && st->opcode[i] == 0 && i != OPCODE_QUERY)
1862 			continue;
1863 		if(!ssl_printf(ssl, "%s%snum.opcode.%s=%u\n", n, d,
1864 			opcode2str(i), (unsigned)st->opcode[i]))
1865 			return;
1866 	}
1867 
1868 	/* qclass */
1869 	for(i=0; i<4; i++) {
1870 		if(inhibit_zero && st->qclass[i] == 0 && i != CLASS_IN)
1871 			continue;
1872 		if(!ssl_printf(ssl, "%s%snum.class.%s=%u\n", n, d,
1873 			rrclass_to_string(i), (unsigned)st->qclass[i]))
1874 			return;
1875 	}
1876 
1877 	/* rcode */
1878 	for(i=0; i<17; i++) {
1879 		if(inhibit_zero && st->rcode[i] == 0 &&
1880 			i > RCODE_YXDOMAIN) /* NSD does not use larger */
1881 			continue;
1882 		if(!ssl_printf(ssl, "%s%snum.rcode.%s=%u\n", n, d, rcstr[i],
1883 			(unsigned)st->rcode[i]))
1884 			return;
1885 	}
1886 
1887 	/* edns */
1888 	if(!ssl_printf(ssl, "%s%snum.edns=%u\n", n, d, (unsigned)st->edns))
1889 		return;
1890 
1891 	/* ednserr */
1892 	if(!ssl_printf(ssl, "%s%snum.ednserr=%u\n", n, d,
1893 		(unsigned)st->ednserr))
1894 		return;
1895 
1896 	/* qudp */
1897 	if(!ssl_printf(ssl, "%s%snum.udp=%u\n", n, d, (unsigned)st->qudp))
1898 		return;
1899 	/* qudp6 */
1900 	if(!ssl_printf(ssl, "%s%snum.udp6=%u\n", n, d, (unsigned)st->qudp6))
1901 		return;
1902 	/* ctcp */
1903 	if(!ssl_printf(ssl, "%s%snum.tcp=%u\n", n, d, (unsigned)st->ctcp))
1904 		return;
1905 	/* ctcp6 */
1906 	if(!ssl_printf(ssl, "%s%snum.tcp6=%u\n", n, d, (unsigned)st->ctcp6))
1907 		return;
1908 
1909 	/* nona */
1910 	if(!ssl_printf(ssl, "%s%snum.answer_wo_aa=%u\n", n, d,
1911 		(unsigned)st->nona))
1912 		return;
1913 
1914 	/* rxerr */
1915 	if(!ssl_printf(ssl, "%s%snum.rxerr=%u\n", n, d, (unsigned)st->rxerr))
1916 		return;
1917 
1918 	/* txerr */
1919 	if(!ssl_printf(ssl, "%s%snum.txerr=%u\n", n, d, (unsigned)st->txerr))
1920 		return;
1921 
1922 	/* number of requested-axfr, number of times axfr served to clients */
1923 	if(!ssl_printf(ssl, "%s%snum.raxfr=%u\n", n, d, (unsigned)st->raxfr))
1924 		return;
1925 
1926 	/* truncated */
1927 	if(!ssl_printf(ssl, "%s%snum.truncated=%u\n", n, d,
1928 		(unsigned)st->truncated))
1929 		return;
1930 
1931 	/* dropped */
1932 	if(!ssl_printf(ssl, "%s%snum.dropped=%u\n", n, d,
1933 		(unsigned)st->dropped))
1934 		return;
1935 }
1936 
1937 #ifdef USE_ZONE_STATS
1938 static void
1939 resize_zonestat(xfrd_state_t* xfrd, size_t num)
1940 {
1941 	struct nsdst** a = xalloc_zero(num * sizeof(struct nsdst*));
1942 	if(xfrd->zonestat_clear_num != 0)
1943 		memcpy(a, xfrd->zonestat_clear, xfrd->zonestat_clear_num
1944 			* sizeof(struct nsdst*));
1945 	free(xfrd->zonestat_clear);
1946 	xfrd->zonestat_clear = a;
1947 	xfrd->zonestat_clear_num = num;
1948 }
1949 
1950 static void
1951 zonestat_print(SSL* ssl, xfrd_state_t* xfrd, int clear)
1952 {
1953 	struct zonestatname* n;
1954 	struct nsdst stat0, stat1;
1955 	RBTREE_FOR(n, struct zonestatname*, xfrd->nsd->options->zonestatnames){
1956 		char* name = (char*)n->node.key;
1957 		if(n->id >= xfrd->zonestat_safe)
1958 			continue; /* newly allocated and reload has not yet
1959 				done and replied with new size */
1960 		if(name == NULL || name[0]==0)
1961 			continue; /* empty name, do not output */
1962 		/* the statistics are stored in two blocks, during reload
1963 		 * the newly forked processes get the other block to use,
1964 		 * these blocks are mmapped and are currently in use to
1965 		 * add statistics to */
1966 		memcpy(&stat0, &xfrd->nsd->zonestat[0][n->id], sizeof(stat0));
1967 		memcpy(&stat1, &xfrd->nsd->zonestat[1][n->id], sizeof(stat1));
1968 		stats_add(&stat0, &stat1);
1969 
1970 		/* save a copy of current (cumulative) stats in stat1 */
1971 		memcpy(&stat1, &stat0, sizeof(stat1));
1972 		/* subtract last total of stats that was 'cleared' */
1973 		if(n->id < xfrd->zonestat_clear_num &&
1974 			xfrd->zonestat_clear[n->id])
1975 			stats_subtract(&stat0, xfrd->zonestat_clear[n->id]);
1976 		if(clear) {
1977 			/* extend storage array if needed */
1978 			if(n->id >= xfrd->zonestat_clear_num) {
1979 				if(n->id+1 < xfrd->nsd->options->zonestatnames->count)
1980 					resize_zonestat(xfrd, xfrd->nsd->options->zonestatnames->count);
1981 				else
1982 					resize_zonestat(xfrd, n->id+1);
1983 			}
1984 			if(!xfrd->zonestat_clear[n->id])
1985 				xfrd->zonestat_clear[n->id] = xalloc(
1986 					sizeof(struct nsdst));
1987 			/* store last total of stats */
1988 			memcpy(xfrd->zonestat_clear[n->id], &stat1,
1989 				sizeof(struct nsdst));
1990 		}
1991 
1992 		/* stat0 contains the details that we want to print */
1993 		if(!ssl_printf(ssl, "%s%snum.queries=%u\n", name, ".",
1994 			(unsigned)(stat0.qudp + stat0.qudp6 + stat0.ctcp +
1995 				stat0.ctcp6)))
1996 			return;
1997 		print_stat_block(ssl, name, ".", &stat0);
1998 	}
1999 }
2000 #endif /* USE_ZONE_STATS */
2001 
2002 static void
2003 print_stats(SSL* ssl, xfrd_state_t* xfrd, struct timeval* now, int clear)
2004 {
2005 	size_t i;
2006 	stc_t total = 0;
2007 	struct timeval elapsed, uptime;
2008 
2009 	/* per CPU and total */
2010 	for(i=0; i<xfrd->nsd->child_count; i++) {
2011 		if(!ssl_printf(ssl, "server%d.queries=%u\n", (int)i,
2012 			(unsigned)xfrd->nsd->children[i].query_count))
2013 			return;
2014 		total += xfrd->nsd->children[i].query_count;
2015 	}
2016 	if(!ssl_printf(ssl, "num.queries=%u\n", (unsigned)total))
2017 		return;
2018 
2019 	/* time elapsed and uptime (in seconds) */
2020 	timeval_subtract(&uptime, now, &xfrd->nsd->rc->boot_time);
2021 	timeval_subtract(&elapsed, now, &xfrd->nsd->rc->stats_time);
2022 	if(!ssl_printf(ssl, "time.boot=%u.%6.6u\n",
2023 		(unsigned)uptime.tv_sec, (unsigned)uptime.tv_usec))
2024 		return;
2025 	if(!ssl_printf(ssl, "time.elapsed=%u.%6.6u\n",
2026 		(unsigned)elapsed.tv_sec, (unsigned)elapsed.tv_usec))
2027 		return;
2028 
2029 	/* mem info, database on disksize */
2030 	if(!print_longnum(ssl, "size.db.disk=", xfrd->nsd->st.db_disk))
2031 		return;
2032 	if(!print_longnum(ssl, "size.db.mem=", xfrd->nsd->st.db_mem))
2033 		return;
2034 	if(!print_longnum(ssl, "size.xfrd.mem=", region_get_mem(xfrd->region)))
2035 		return;
2036 	if(!print_longnum(ssl, "size.config.disk=",
2037 		xfrd->nsd->options->zonelist_off))
2038 		return;
2039 	if(!print_longnum(ssl, "size.config.mem=", region_get_mem(
2040 		xfrd->nsd->options->region)))
2041 		return;
2042 	print_stat_block(ssl, "", "", &xfrd->nsd->st);
2043 
2044 	/* zone statistics */
2045 	if(!ssl_printf(ssl, "zone.master=%u\n",
2046 		(unsigned)(xfrd->notify_zones->count - xfrd->zones->count)))
2047 		return;
2048 	if(!ssl_printf(ssl, "zone.slave=%u\n", (unsigned)xfrd->zones->count))
2049 		return;
2050 #ifdef USE_ZONE_STATS
2051 	zonestat_print(ssl, xfrd, clear); /* per-zone statistics */
2052 #else
2053 	(void)clear;
2054 #endif
2055 }
2056 
2057 static void
2058 clear_stats(xfrd_state_t* xfrd)
2059 {
2060 	size_t i;
2061 	uint64_t dbd = xfrd->nsd->st.db_disk;
2062 	uint64_t dbm = xfrd->nsd->st.db_mem;
2063 	for(i=0; i<xfrd->nsd->child_count; i++) {
2064 		xfrd->nsd->children[i].query_count = 0;
2065 	}
2066 	memset(&xfrd->nsd->st, 0, sizeof(struct nsdst));
2067 	/* zonestats are cleared by storing the cumulative value that
2068 	 * was last printed in the zonestat_clear array, and subtracting
2069 	 * that before the next stats printout */
2070 	xfrd->nsd->st.db_disk = dbd;
2071 	xfrd->nsd->st.db_mem = dbm;
2072 }
2073 
2074 void
2075 daemon_remote_process_stats(struct daemon_remote* rc)
2076 {
2077 	struct rc_state* s;
2078 	struct timeval now;
2079 	if(!rc) return;
2080 	if(gettimeofday(&now, NULL) == -1)
2081 		log_msg(LOG_ERR, "gettimeofday: %s", strerror(errno));
2082 	/* pop one and give it stats */
2083 	while((s = rc->stats_list)) {
2084 		assert(s->in_stats_list);
2085 		print_stats(s->ssl, rc->xfrd, &now, (s->in_stats_list == 1));
2086 		if(s->in_stats_list == 1) {
2087 			clear_stats(rc->xfrd);
2088 			rc->stats_time = now;
2089 		}
2090 		VERBOSITY(3, (LOG_INFO, "remote control stats printed"));
2091 		rc->stats_list = s->next;
2092 		s->in_stats_list = 0;
2093 		clean_point(rc, s);
2094 	}
2095 }
2096 #endif /* BIND8_STATS */
2097 
2098 #endif /* HAVE_SSL */
2099