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