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