xref: /openbsd/usr.sbin/nsd/remote.c (revision 6a6b9a23)
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 #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, nsd_options_t* cfg)
487 {
488 	assert(cfg->control_enable && cfg->control_port);
489 	if(cfg->control_interface) {
490 		ip_address_option_t* 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_t* xfrd, char* arg,
768 	zone_options_t** 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_t* 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_t* 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_t* xfrd, char* arg)
815 {
816 	zone_options_t* 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_t* xfrd, char* arg)
828 {
829 	zone_options_t* 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_t* xfrd, char* arg)
841 {
842 	zone_options_t* zo;
843 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
844 		return;
845 	if(zo) {
846 		struct notify_zone_t* n = (struct notify_zone_t*)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_t* n;
856 		RBTREE_FOR(n, struct notify_zone_t*, 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_t* xfrd, char* arg)
866 {
867 	zone_options_t* zo;
868 	xfrd_zone_t* zone;
869 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
870 		return;
871 	if(zo) {
872 		zone = (xfrd_zone_t*)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_t*, 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_t* 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_t* xfrd, char* arg)
907 {
908 	zone_options_t* zo;
909 	xfrd_zone_t* zone;
910 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
911 		return;
912 	if(zo) {
913 		zone = (xfrd_zone_t*)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_t*, 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_t* 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_t* xfrd, zone_options_t* zo)
946 {
947 	xfrd_zone_t* xz = (xfrd_zone_t*)rbtree_search(xfrd->zones,
948 		(const dname_type*)zo->node.key);
949 	struct notify_zone_t* nz = (struct notify_zone_t*)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) {
962 			if(!ssl_printf(ssl, "	notify: \"sent try %d "
963 				"to %s with serial %u\"\n", nz->notify_retry,
964 				nz->notify_current->ip_address_spec,
965 				(unsigned)ntohl(nz->current_soa->serial)))
966 				return 0;
967 		}
968 	}
969 	if(!xz) {
970 		if(!ssl_printf(ssl, "	state: master\n"))
971 			return 0;
972 		return 1;
973 	}
974 	if(!ssl_printf(ssl, "	state: %s\n",
975 		(xz->state == xfrd_zone_ok)?"ok":(
976 		(xz->state == xfrd_zone_expired)?"expired":"refreshing")))
977 		return 0;
978 	if(!print_soa_status(ssl, "served-serial", &xz->soa_nsd,
979 		xz->soa_nsd_acquired))
980 		return 0;
981 	if(!print_soa_status(ssl, "commit-serial", &xz->soa_disk,
982 		xz->soa_disk_acquired))
983 		return 0;
984 	if(xz->round_num != -1) {
985 		if(!print_soa_status(ssl, "notified-serial", &xz->soa_notified,
986 			xz->soa_notified_acquired))
987 			return 0;
988 	}
989 
990 	/* UDP */
991 	if(xz->udp_waiting) {
992 		if(!ssl_printf(ssl, "	transfer: \"waiting-for-UDP-fd\"\n"))
993 			return 0;
994 	} else if(xz->zone_handler.ev_fd != -1 && xz->tcp_conn == -1) {
995 		if(!ssl_printf(ssl, "	transfer: \"sent UDP to %s\"\n",
996 			xz->master->ip_address_spec))
997 			return 0;
998 	}
999 
1000 	/* TCP */
1001 	if(xz->tcp_waiting) {
1002 		if(!ssl_printf(ssl, "	transfer: \"waiting-for-TCP-fd\"\n"))
1003 			return 0;
1004 	} else if(xz->tcp_conn != -1) {
1005 		if(!ssl_printf(ssl, "	transfer: \"TCP connected to %s\"\n",
1006 			xz->master->ip_address_spec))
1007 			return 0;
1008 	}
1009 
1010 	return 1;
1011 }
1012 
1013 /** do the zonestatus command */
1014 static void
1015 do_zonestatus(SSL* ssl, xfrd_state_t* xfrd, char* arg)
1016 {
1017 	zone_options_t* zo;
1018 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
1019 		return;
1020 	if(zo) (void)print_zonestatus(ssl, xfrd, zo);
1021 	else {
1022 		RBTREE_FOR(zo, zone_options_t*,
1023 			xfrd->nsd->options->zone_options) {
1024 			if(!print_zonestatus(ssl, xfrd, zo))
1025 				return;
1026 		}
1027 	}
1028 }
1029 
1030 /** do the verbosity command */
1031 static void
1032 do_verbosity(SSL* ssl, char* str)
1033 {
1034 	int val = atoi(str);
1035 	if(strcmp(str, "") == 0) {
1036 		ssl_printf(ssl, "verbosity %d\n", verbosity);
1037 		return;
1038 	}
1039 	if(val == 0 && strcmp(str, "0") != 0) {
1040 		ssl_printf(ssl, "error in verbosity number syntax: %s\n", str);
1041 		return;
1042 	}
1043 	verbosity = val;
1044 	task_new_set_verbosity(xfrd->nsd->task[xfrd->nsd->mytask],
1045 		xfrd->last_task, val);
1046 	xfrd_set_reload_now(xfrd);
1047 	send_ok(ssl);
1048 }
1049 
1050 /** find second argument, modifies string */
1051 static int
1052 find_arg2(SSL* ssl, char* arg, char** arg2)
1053 {
1054 	char* as = strrchr(arg, ' ');
1055 	if(as) {
1056 		as[0]=0;
1057 		*arg2 = as+1;
1058 		while(isspace((unsigned char)*as) && as > arg)
1059 			as--;
1060 		as[0]=0;
1061 		return 1;
1062 	}
1063 	ssl_printf(ssl, "error could not find next argument "
1064 		"after %s\n", arg);
1065 	return 0;
1066 }
1067 
1068 /** do the status command */
1069 static void
1070 do_status(SSL* ssl, xfrd_state_t* xfrd)
1071 {
1072 	if(!ssl_printf(ssl, "version: %s\n", PACKAGE_VERSION))
1073 		return;
1074 	if(!ssl_printf(ssl, "verbosity: %d\n", verbosity))
1075 		return;
1076 #ifdef RATELIMIT
1077 	if(!ssl_printf(ssl, "ratelimit: %d\n",
1078 		(int)xfrd->nsd->options->rrl_ratelimit))
1079 		return;
1080 #else
1081 	(void)xfrd;
1082 #endif
1083 }
1084 
1085 /** do the stats command */
1086 static void
1087 do_stats(struct daemon_remote* rc, int peek, struct rc_state* rs)
1088 {
1089 #ifdef BIND8_STATS
1090 	/* queue up to get stats after a reload is done (to gather statistics
1091 	 * from the servers) */
1092 	assert(!rs->in_stats_list);
1093 	if(peek) rs->in_stats_list = 2;
1094 	else	rs->in_stats_list = 1;
1095 	rs->stats_next = rc->stats_list;
1096 	rc->stats_list = rs;
1097 	/* block the tcp waiting for the reload */
1098 	event_del(&rs->c);
1099 	rs->event_added = 0;
1100 	/* force a reload */
1101 	xfrd_set_reload_now(xfrd);
1102 #else
1103 	(void)rc; (void)peek;
1104 	(void)ssl_printf(rs->ssl, "error no stats enabled at compile time\n");
1105 #endif /* BIND8_STATS */
1106 }
1107 
1108 /** see if we have more zonestatistics entries and it has to be incremented */
1109 static void
1110 zonestat_inc_ifneeded(xfrd_state_t* xfrd)
1111 {
1112 #ifdef USE_ZONE_STATS
1113 	if(xfrd->nsd->options->zonestatnames->count != xfrd->zonestat_safe)
1114 		task_new_zonestat_inc(xfrd->nsd->task[xfrd->nsd->mytask],
1115 			xfrd->last_task,
1116 			xfrd->nsd->options->zonestatnames->count);
1117 #else
1118 	(void)xfrd;
1119 #endif /* USE_ZONE_STATS */
1120 }
1121 
1122 /** perform the addzone command for one zone */
1123 static int
1124 perform_addzone(SSL* ssl, xfrd_state_t* xfrd, char* arg)
1125 {
1126 	const dname_type* dname;
1127 	zone_options_t* zopt;
1128 	char* arg2 = NULL;
1129 	if(!find_arg2(ssl, arg, &arg2))
1130 		return 0;
1131 
1132 	/* if we add it to the xfrd now, then xfrd could download AXFR and
1133 	 * store it and the NSD-reload would see it in the difffile before
1134 	 * it sees the add-config task.
1135 	 */
1136 	/* thus: AXFRs and IXFRs must store the pattern name in the
1137 	 * difffile, so that it can be added when the AXFR or IXFR is seen.
1138 	 */
1139 
1140 	/* check that the pattern exists */
1141 	if(!rbtree_search(xfrd->nsd->options->patterns, arg2)) {
1142 		(void)ssl_printf(ssl, "error pattern %s does not exist\n",
1143 			arg2);
1144 		return 0;
1145 	}
1146 
1147 	dname = dname_parse(xfrd->region, arg);
1148 	if(!dname) {
1149 		(void)ssl_printf(ssl, "error cannot parse zone name\n");
1150 		return 0;
1151 	}
1152 
1153 	/* see if zone is a duplicate */
1154 	if( (zopt=zone_options_find(xfrd->nsd->options, dname)) ) {
1155 		region_recycle(xfrd->region, (void*)dname,
1156 			dname_total_size(dname));
1157 		(void)ssl_printf(ssl, "zone %s already exists\n", arg);
1158 		return 1;
1159 	}
1160 	region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
1161 	dname = NULL;
1162 
1163 	/* add to zonelist and adds to config in memory */
1164 	zopt = zone_list_add(xfrd->nsd->options, arg, arg2);
1165 	if(!zopt) {
1166 		/* also dname parse error here */
1167 		(void)ssl_printf(ssl, "error could not add zonelist entry\n");
1168 		return 0;
1169 	}
1170 	/* make addzone task and schedule reload */
1171 	task_new_add_zone(xfrd->nsd->task[xfrd->nsd->mytask],
1172 		xfrd->last_task, arg, arg2,
1173 		getzonestatid(xfrd->nsd->options, zopt));
1174 	zonestat_inc_ifneeded(xfrd);
1175 	xfrd_set_reload_now(xfrd);
1176 	/* add to xfrd - notify (for master and slaves) */
1177 	init_notify_send(xfrd->notify_zones, xfrd->region, zopt);
1178 	/* add to xfrd - slave */
1179 	if(zone_is_slave(zopt)) {
1180 		xfrd_init_slave_zone(xfrd, zopt);
1181 	}
1182 	return 1;
1183 }
1184 
1185 /** perform the delzone command for one zone */
1186 static int
1187 perform_delzone(SSL* ssl, xfrd_state_t* xfrd, char* arg)
1188 {
1189 	const dname_type* dname;
1190 	zone_options_t* zopt;
1191 
1192 	dname = dname_parse(xfrd->region, arg);
1193 	if(!dname) {
1194 		(void)ssl_printf(ssl, "error cannot parse zone name\n");
1195 		return 0;
1196 	}
1197 
1198 	/* see if we have the zone in question */
1199 	zopt = zone_options_find(xfrd->nsd->options, dname);
1200 	if(!zopt) {
1201 		region_recycle(xfrd->region, (void*)dname,
1202 			dname_total_size(dname));
1203 		/* nothing to do */
1204 		if(!ssl_printf(ssl, "warning zone %s not present\n", arg))
1205 			return 0;
1206 		return 1;
1207 	}
1208 
1209 	/* see if it can be deleted */
1210 	if(zopt->part_of_config) {
1211 		region_recycle(xfrd->region, (void*)dname,
1212 			dname_total_size(dname));
1213 		(void)ssl_printf(ssl, "error zone defined in nsd.conf, "
1214 			"cannot delete it in this manner: remove it from "
1215 			"nsd.conf yourself and repattern\n");
1216 		return 0;
1217 	}
1218 
1219 	/* create deletion task */
1220 	task_new_del_zone(xfrd->nsd->task[xfrd->nsd->mytask],
1221 		xfrd->last_task, dname);
1222 	xfrd_set_reload_now(xfrd);
1223 	/* delete it in xfrd */
1224 	if(zone_is_slave(zopt)) {
1225 		xfrd_del_slave_zone(xfrd, dname);
1226 	}
1227 	xfrd_del_notify(xfrd, dname);
1228 	/* delete from config */
1229 	zone_list_del(xfrd->nsd->options, zopt);
1230 
1231 	region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
1232 	return 1;
1233 }
1234 
1235 /** do the addzone command */
1236 static void
1237 do_addzone(SSL* ssl, xfrd_state_t* xfrd, char* arg)
1238 {
1239 	if(!perform_addzone(ssl, xfrd, arg))
1240 		return;
1241 	send_ok(ssl);
1242 }
1243 
1244 /** do the delzone command */
1245 static void
1246 do_delzone(SSL* ssl, xfrd_state_t* xfrd, char* arg)
1247 {
1248 	if(!perform_delzone(ssl, xfrd, arg))
1249 		return;
1250 	send_ok(ssl);
1251 }
1252 
1253 /** do the addzones command */
1254 static void
1255 do_addzones(SSL* ssl, xfrd_state_t* xfrd)
1256 {
1257 	char buf[2048];
1258 	int num = 0;
1259 	while(ssl_read_line(ssl, buf, sizeof(buf))) {
1260 		if(buf[0] == 0x04 && buf[1] == 0)
1261 			break; /* end of transmission */
1262 		if(!perform_addzone(ssl, xfrd, buf)) {
1263 			if(!ssl_printf(ssl, "error for input line '%s'\n",
1264 				buf))
1265 				return;
1266 		} else {
1267 			if(!ssl_printf(ssl, "added: %s\n", buf))
1268 				return;
1269 			num++;
1270 		}
1271 	}
1272 	(void)ssl_printf(ssl, "added %d zones\n", num);
1273 }
1274 
1275 /** do the delzones command */
1276 static void
1277 do_delzones(SSL* ssl, xfrd_state_t* xfrd)
1278 {
1279 	char buf[2048];
1280 	int num = 0;
1281 	while(ssl_read_line(ssl, buf, sizeof(buf))) {
1282 		if(buf[0] == 0x04 && buf[1] == 0)
1283 			break; /* end of transmission */
1284 		if(!perform_delzone(ssl, xfrd, buf)) {
1285 			if(!ssl_printf(ssl, "error for input line '%s'\n",
1286 				buf))
1287 				return;
1288 		} else {
1289 			if(!ssl_printf(ssl, "removed: %s\n", buf))
1290 				return;
1291 			num++;
1292 		}
1293 	}
1294 	(void)ssl_printf(ssl, "deleted %d zones\n", num);
1295 }
1296 
1297 
1298 /** remove TSIG key from config and add task so that reload does too */
1299 static void remove_key(xfrd_state_t* xfrd, const char* kname)
1300 {
1301 	/* add task before deletion because the name string could be deleted */
1302 	task_new_del_key(xfrd->nsd->task[xfrd->nsd->mytask], xfrd->last_task,
1303 		kname);
1304 	key_options_remove(xfrd->nsd->options, kname);
1305 	xfrd_set_reload_now(xfrd); /* this is executed when the current control
1306 		command ends, thus the entire config changes are bunched up */
1307 }
1308 
1309 /** add TSIG key to config and add task so that reload does too */
1310 static void add_key(xfrd_state_t* xfrd, key_options_t* k)
1311 {
1312 	key_options_add_modify(xfrd->nsd->options, k);
1313 	task_new_add_key(xfrd->nsd->task[xfrd->nsd->mytask], xfrd->last_task,
1314 		k);
1315 	xfrd_set_reload_now(xfrd);
1316 }
1317 
1318 /** check if keys have changed */
1319 static void repat_keys(xfrd_state_t* xfrd, nsd_options_t* newopt)
1320 {
1321 	nsd_options_t* oldopt = xfrd->nsd->options;
1322 	key_options_t* k;
1323 	/* find deleted keys */
1324 	k = (key_options_t*)rbtree_first(oldopt->keys);
1325 	while((rbnode_t*)k != RBTREE_NULL) {
1326 		key_options_t* next = (key_options_t*)rbtree_next(
1327 			(rbnode_t*)k);
1328 		if(!key_options_find(newopt, k->name))
1329 			remove_key(xfrd, k->name);
1330 		k = next;
1331 	}
1332 	/* find added or changed keys */
1333 	RBTREE_FOR(k, key_options_t*, newopt->keys) {
1334 		key_options_t* origk = key_options_find(oldopt, k->name);
1335 		if(!origk)
1336 			add_key(xfrd, k);
1337 		else if(!key_options_equal(k, origk))
1338 			add_key(xfrd, k);
1339 	}
1340 }
1341 
1342 /** find zone given the implicit pattern */
1343 static const dname_type*
1344 parse_implicit_name(xfrd_state_t* xfrd,const char* pname)
1345 {
1346 	if(strncmp(pname, PATTERN_IMPLICIT_MARKER,
1347 		strlen(PATTERN_IMPLICIT_MARKER)) != 0)
1348 		return NULL;
1349 	return dname_parse(xfrd->region, pname +
1350 		strlen(PATTERN_IMPLICIT_MARKER));
1351 }
1352 
1353 /** remove cfgzone and add task so that reload does too */
1354 static void
1355 remove_cfgzone(xfrd_state_t* xfrd, const char* pname)
1356 {
1357 	/* dname and find the zone for the implicit pattern */
1358 	zone_options_t* zopt = NULL;
1359 	const dname_type* dname = parse_implicit_name(xfrd, pname);
1360 	if(!dname) {
1361 		/* should have a parseable name, but it did not */
1362 		return;
1363 	}
1364 
1365 	/* find the zone entry for the implicit pattern */
1366 	zopt = zone_options_find(xfrd->nsd->options, dname);
1367 	if(!zopt) {
1368 		/* this should not happen; implicit pattern has zone entry */
1369 		region_recycle(xfrd->region, (void*)dname,
1370 			dname_total_size(dname));
1371 		return;
1372 	}
1373 
1374 	/* create deletion task */
1375 	task_new_del_zone(xfrd->nsd->task[xfrd->nsd->mytask],
1376 		xfrd->last_task, dname);
1377 	xfrd_set_reload_now(xfrd);
1378 	/* delete it in xfrd */
1379 	if(zone_is_slave(zopt)) {
1380 		xfrd_del_slave_zone(xfrd, dname);
1381 	}
1382 	xfrd_del_notify(xfrd, dname);
1383 
1384 	/* delete from zoneoptions */
1385 	zone_options_delete(xfrd->nsd->options, zopt);
1386 
1387 	/* recycle parsed dname */
1388 	region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
1389 }
1390 
1391 /** add cfgzone and add task so that reload does too */
1392 static void
1393 add_cfgzone(xfrd_state_t* xfrd, const char* pname)
1394 {
1395 	/* add to our zonelist */
1396 	zone_options_t* zopt = zone_options_create(xfrd->nsd->options->region);
1397 	if(!zopt)
1398 		return;
1399 	zopt->part_of_config = 1;
1400 	zopt->name = region_strdup(xfrd->nsd->options->region,
1401 		pname + strlen(PATTERN_IMPLICIT_MARKER));
1402 	zopt->pattern = pattern_options_find(xfrd->nsd->options, pname);
1403 	if(!zopt->name || !zopt->pattern)
1404 		return;
1405 	if(!nsd_options_insert_zone(xfrd->nsd->options, zopt)) {
1406 		log_msg(LOG_ERR, "bad domain name or duplicate zone '%s' "
1407 			"pattern %s", zopt->name, pname);
1408 	}
1409 
1410 	/* make addzone task and schedule reload */
1411 	task_new_add_zone(xfrd->nsd->task[xfrd->nsd->mytask],
1412 		xfrd->last_task, zopt->name, pname,
1413 		getzonestatid(xfrd->nsd->options, zopt));
1414 	/* zonestat_inc is done after the entire config file has been done */
1415 	xfrd_set_reload_now(xfrd);
1416 	/* add to xfrd - notify (for master and slaves) */
1417 	init_notify_send(xfrd->notify_zones, xfrd->region, zopt);
1418 	/* add to xfrd - slave */
1419 	if(zone_is_slave(zopt)) {
1420 		xfrd_init_slave_zone(xfrd, zopt);
1421 	}
1422 }
1423 
1424 /** remove pattern and add task so that reload does too */
1425 static void
1426 remove_pat(xfrd_state_t* xfrd, const char* name)
1427 {
1428 	/* add task before deletion, because name-string could be deleted */
1429 	task_new_del_pattern(xfrd->nsd->task[xfrd->nsd->mytask],
1430 		xfrd->last_task, name);
1431 	pattern_options_remove(xfrd->nsd->options, name);
1432 	xfrd_set_reload_now(xfrd);
1433 }
1434 
1435 /** add pattern and add task so that reload does too */
1436 static void
1437 add_pat(xfrd_state_t* xfrd, pattern_options_t* p)
1438 {
1439 	pattern_options_add_modify(xfrd->nsd->options, p);
1440 	task_new_add_pattern(xfrd->nsd->task[xfrd->nsd->mytask],
1441 		xfrd->last_task, p);
1442 	xfrd_set_reload_now(xfrd);
1443 }
1444 
1445 /** interrupt zones that are using changed or removed patterns */
1446 static void
1447 repat_interrupt_zones(xfrd_state_t* xfrd, nsd_options_t* newopt)
1448 {
1449 	/* if masterlist changed:
1450 	 *   interrupt slave zone (UDP or TCP) transfers.
1451 	 *   slave zones reset master to start of list.
1452 	 */
1453 	xfrd_zone_t* xz;
1454 	struct notify_zone_t* nz;
1455 	RBTREE_FOR(xz, xfrd_zone_t*, xfrd->zones) {
1456 		pattern_options_t* oldp = xz->zone_options->pattern;
1457 		pattern_options_t* newp = pattern_options_find(newopt,
1458 			oldp->pname);
1459 		if(!newp || !acl_list_equal(oldp->request_xfr,
1460 			newp->request_xfr)) {
1461 			/* interrupt transfer */
1462 			if(xz->tcp_conn != -1) {
1463 				xfrd_tcp_release(xfrd->tcp_set, xz);
1464 				xfrd_set_refresh_now(xz);
1465 			} else if(xz->zone_handler.ev_fd != -1) {
1466 				xfrd_udp_release(xz);
1467 				xfrd_set_refresh_now(xz);
1468 			}
1469 			xz->master = 0;
1470 			xz->master_num = 0;
1471 			xz->next_master = -1;
1472 			xz->round_num = -1; /* fresh set of retries */
1473 		}
1474 	}
1475 	/* if notify list changed:
1476 	 *   interrupt notify that is busy.
1477 	 *   reset notify to start of list.  (clear all other reset_notify)
1478 	 */
1479 	RBTREE_FOR(nz, struct notify_zone_t*, xfrd->notify_zones) {
1480 		pattern_options_t* oldp = nz->options->pattern;
1481 		pattern_options_t* newp = pattern_options_find(newopt,
1482 			oldp->pname);
1483 		if(!newp || !acl_list_equal(oldp->notify, newp->notify)) {
1484 			/* interrupt notify */
1485 			if(nz->notify_send_enable) {
1486 				notify_disable(nz);
1487 				/* set to restart the notify after the
1488 				 * pattern has been changed. */
1489 				nz->notify_restart = 2;
1490 			} else {
1491 				nz->notify_restart = 1;
1492 			}
1493 		} else {
1494 			nz->notify_restart = 0;
1495 		}
1496 	}
1497 }
1498 
1499 /** for notify, after the pattern changes, restart the affected notifies */
1500 static void
1501 repat_interrupt_notify_start(xfrd_state_t* xfrd)
1502 {
1503 	struct notify_zone_t* nz;
1504 	RBTREE_FOR(nz, struct notify_zone_t*, xfrd->notify_zones) {
1505 		if(nz->notify_restart) {
1506 			if(nz->notify_current)
1507 				nz->notify_current = nz->options->pattern->notify;
1508 			if(nz->notify_restart == 2) {
1509 				if(nz->notify_restart)
1510 					xfrd_notify_start(nz, xfrd);
1511 			}
1512 		}
1513 	}
1514 }
1515 
1516 /** check if patterns have changed */
1517 static void
1518 repat_patterns(xfrd_state_t* xfrd, nsd_options_t* newopt)
1519 {
1520 	/* zones that use changed patterns must have:
1521 	 * - their AXFR/IXFR interrupted: try again, acl may have changed.
1522 	 *   if the old master/key still exists, OK, fix master-numptrs and
1523 	 *   keep going.  Otherwise, stop xfer and reset TSIG.
1524 	 * - send NOTIFY reset to start of NOTIFY list (and TSIG reset).
1525 	 */
1526 	nsd_options_t* oldopt = xfrd->nsd->options;
1527 	pattern_options_t* p;
1528 	int search_zones = 0;
1529 
1530 	repat_interrupt_zones(xfrd, newopt);
1531 	/* find deleted patterns */
1532 	p = (pattern_options_t*)rbtree_first(oldopt->patterns);
1533 	while((rbnode_t*)p != RBTREE_NULL) {
1534 		pattern_options_t* next = (pattern_options_t*)rbtree_next(
1535 			(rbnode_t*)p);
1536 		if(!pattern_options_find(newopt, p->pname)) {
1537 			if(p->implicit) {
1538 				/* first remove its zone */
1539 				VERBOSITY(1, (LOG_INFO, "zone removed from config: %s", p->pname + strlen(PATTERN_IMPLICIT_MARKER)));
1540 				remove_cfgzone(xfrd, p->pname);
1541 			}
1542 			remove_pat(xfrd, p->pname);
1543 		}
1544 		p = next;
1545 	}
1546 	/* find added or changed patterns */
1547 	RBTREE_FOR(p, pattern_options_t*, newopt->patterns) {
1548 		pattern_options_t* origp = pattern_options_find(oldopt,
1549 			p->pname);
1550 		if(!origp) {
1551 			/* no zones can use it, no zone_interrupt needed */
1552 			add_pat(xfrd, p);
1553 			if(p->implicit) {
1554 				VERBOSITY(1, (LOG_INFO, "zone added to config: %s", p->pname + strlen(PATTERN_IMPLICIT_MARKER)));
1555 				add_cfgzone(xfrd, p->pname);
1556 			}
1557 		} else if(!pattern_options_equal(p, origp)) {
1558 			uint8_t newstate = 0;
1559 			if (p->request_xfr && !origp->request_xfr) {
1560 				newstate = REPAT_SLAVE;
1561 			} else if (!p->request_xfr && origp->request_xfr) {
1562 				newstate = REPAT_MASTER;
1563 			}
1564 			add_pat(xfrd, p);
1565 			if (p->implicit && newstate) {
1566 				const dname_type* dname =
1567 					parse_implicit_name(xfrd, p->pname);
1568 				if (dname) {
1569 					if (newstate == REPAT_SLAVE) {
1570 						zone_options_t* zopt =
1571 							zone_options_find(
1572 							oldopt, dname);
1573 						if (zopt) {
1574 							xfrd_init_slave_zone(
1575 								xfrd, zopt);
1576 						}
1577 					} else if (newstate == REPAT_MASTER) {
1578 						xfrd_del_slave_zone(xfrd,
1579 							dname);
1580 					}
1581 					region_recycle(xfrd->region,
1582 						(void*)dname,
1583 						dname_total_size(dname));
1584 				}
1585 			} else if(!p->implicit && newstate) {
1586 				/* search all zones with this pattern */
1587 				search_zones = 1;
1588 				origp->xfrd_flags = newstate;
1589 			}
1590 		}
1591 	}
1592 	if (search_zones) {
1593 		zone_options_t* zone_opt;
1594 		/* search in oldopt because 1) it contains zonelist zones,
1595 		 * and 2) you need oldopt(existing) to call xfrd_init */
1596 		RBTREE_FOR(zone_opt, zone_options_t*, oldopt->zone_options) {
1597 			pattern_options_t* oldp = zone_opt->pattern;
1598 			if (!oldp->implicit) {
1599 				if (oldp->xfrd_flags == REPAT_SLAVE) {
1600 					/* xfrd needs stable reference so get
1601 					 * it from the oldopt(modified) tree */
1602 					xfrd_init_slave_zone(xfrd, zone_opt);
1603 				} else if (oldp->xfrd_flags == REPAT_MASTER) {
1604 					xfrd_del_slave_zone(xfrd,
1605 						(const dname_type*)
1606 						zone_opt->node.key);
1607 				}
1608 				oldp->xfrd_flags = 0;
1609 			}
1610 		}
1611 	}
1612 	repat_interrupt_notify_start(xfrd);
1613 }
1614 
1615 /** true if options are different that can be set via repat. */
1616 static int
1617 repat_options_changed(xfrd_state_t* xfrd, nsd_options_t* newopt)
1618 {
1619 #ifdef RATELIMIT
1620 	if(xfrd->nsd->options->rrl_ratelimit != newopt->rrl_ratelimit)
1621 		return 1;
1622 	if(xfrd->nsd->options->rrl_whitelist_ratelimit != newopt->rrl_whitelist_ratelimit)
1623 		return 1;
1624 	if(xfrd->nsd->options->rrl_slip != newopt->rrl_slip)
1625 		return 1;
1626 #else
1627 	(void)xfrd; (void)newopt;
1628 #endif
1629 	return 0;
1630 }
1631 
1632 /** check if global options have changed */
1633 static void
1634 repat_options(xfrd_state_t* xfrd, nsd_options_t* newopt)
1635 {
1636 	if(repat_options_changed(xfrd, newopt)) {
1637 		/* update our options */
1638 #ifdef RATELIMIT
1639 		xfrd->nsd->options->rrl_ratelimit = newopt->rrl_ratelimit;
1640 		xfrd->nsd->options->rrl_whitelist_ratelimit = newopt->rrl_whitelist_ratelimit;
1641 		xfrd->nsd->options->rrl_slip = newopt->rrl_slip;
1642 #endif
1643 		task_new_opt_change(xfrd->nsd->task[xfrd->nsd->mytask],
1644 			xfrd->last_task, newopt);
1645 		xfrd_set_reload_now(xfrd);
1646 	}
1647 }
1648 
1649 /** print errors over ssl, gets pointer-to-pointer to ssl, so it can set
1650  * the pointer to NULL on failure and stop printing */
1651 static void
1652 print_ssl_cfg_err(void* arg, const char* str)
1653 {
1654 	SSL** ssl = (SSL**)arg;
1655 	if(!*ssl) return;
1656 	if(!ssl_printf(*ssl, "%s", str))
1657 		*ssl = NULL; /* failed, stop printing */
1658 }
1659 
1660 /** do the repattern command: reread config file and apply keys, patterns */
1661 static void
1662 do_repattern(SSL* ssl, xfrd_state_t* xfrd)
1663 {
1664 	region_type* region = region_create(xalloc, free);
1665 	nsd_options_t* opt;
1666 	const char* cfgfile = xfrd->nsd->options->configfile;
1667 
1668 	/* check chroot and configfile, if possible to reread */
1669 	if(xfrd->nsd->chrootdir) {
1670 		size_t l = strlen(xfrd->nsd->chrootdir);
1671 		while(l>0 && xfrd->nsd->chrootdir[l-1] == '/')
1672 			--l;
1673 		if(strncmp(xfrd->nsd->chrootdir, cfgfile, l) != 0) {
1674 			ssl_printf(ssl, "error %s is not relative to %s: "
1675 				"chroot prevents reread of config\n",
1676 				cfgfile, xfrd->nsd->chrootdir);
1677 			region_destroy(region);
1678 			return;
1679 		}
1680 		cfgfile += l;
1681 	}
1682 
1683 	ssl_printf(ssl, "reconfig start, read %s\n", cfgfile);
1684 	opt = nsd_options_create(region);
1685 	if(!parse_options_file(opt, cfgfile, &print_ssl_cfg_err, &ssl)) {
1686 		/* error already printed */
1687 		region_destroy(region);
1688 		return;
1689 	}
1690 	/* check for differences in TSIG keys and patterns, and apply,
1691 	 * first the keys, so that pattern->keyptr can be set right. */
1692 	repat_keys(xfrd, opt);
1693 	repat_patterns(xfrd, opt);
1694 	repat_options(xfrd, opt);
1695 	zonestat_inc_ifneeded(xfrd);
1696 	send_ok(ssl);
1697 	region_destroy(region);
1698 }
1699 
1700 /** do the serverpid command: printout pid of server process */
1701 static void
1702 do_serverpid(SSL* ssl, xfrd_state_t* xfrd)
1703 {
1704 	(void)ssl_printf(ssl, "%u\n", (unsigned)xfrd->reload_pid);
1705 }
1706 
1707 /** check for name with end-of-string, space or tab after it */
1708 static int
1709 cmdcmp(char* p, const char* cmd, size_t len)
1710 {
1711 	return strncmp(p,cmd,len)==0 && (p[len]==0||p[len]==' '||p[len]=='\t');
1712 }
1713 
1714 /** execute a remote control command */
1715 static void
1716 execute_cmd(struct daemon_remote* rc, SSL* ssl, char* cmd, struct rc_state* rs)
1717 {
1718 	char* p = skipwhite(cmd);
1719 	/* compare command */
1720 	if(cmdcmp(p, "stop", 4)) {
1721 		do_stop(ssl, rc->xfrd);
1722 	} else if(cmdcmp(p, "reload", 6)) {
1723 		do_reload(ssl, rc->xfrd, skipwhite(p+6));
1724 	} else if(cmdcmp(p, "write", 5)) {
1725 		do_write(ssl, rc->xfrd, skipwhite(p+5));
1726 	} else if(cmdcmp(p, "status", 6)) {
1727 		do_status(ssl, rc->xfrd);
1728 	} else if(cmdcmp(p, "stats_noreset", 13)) {
1729 		do_stats(rc, 1, rs);
1730 	} else if(cmdcmp(p, "stats", 5)) {
1731 		do_stats(rc, 0, rs);
1732 	} else if(cmdcmp(p, "log_reopen", 10)) {
1733 		do_log_reopen(ssl, rc->xfrd);
1734 	} else if(cmdcmp(p, "addzone", 7)) {
1735 		do_addzone(ssl, rc->xfrd, skipwhite(p+7));
1736 	} else if(cmdcmp(p, "delzone", 7)) {
1737 		do_delzone(ssl, rc->xfrd, skipwhite(p+7));
1738 	} else if(cmdcmp(p, "addzones", 8)) {
1739 		do_addzones(ssl, rc->xfrd);
1740 	} else if(cmdcmp(p, "delzones", 8)) {
1741 		do_delzones(ssl, rc->xfrd);
1742 	} else if(cmdcmp(p, "notify", 6)) {
1743 		do_notify(ssl, rc->xfrd, skipwhite(p+6));
1744 	} else if(cmdcmp(p, "transfer", 8)) {
1745 		do_transfer(ssl, rc->xfrd, skipwhite(p+8));
1746 	} else if(cmdcmp(p, "force_transfer", 14)) {
1747 		do_force_transfer(ssl, rc->xfrd, skipwhite(p+14));
1748 	} else if(cmdcmp(p, "zonestatus", 10)) {
1749 		do_zonestatus(ssl, rc->xfrd, skipwhite(p+10));
1750 	} else if(cmdcmp(p, "verbosity", 9)) {
1751 		do_verbosity(ssl, skipwhite(p+9));
1752 	} else if(cmdcmp(p, "repattern", 9)) {
1753 		do_repattern(ssl, rc->xfrd);
1754 	} else if(cmdcmp(p, "reconfig", 8)) {
1755 		do_repattern(ssl, rc->xfrd);
1756 	} else if(cmdcmp(p, "serverpid", 9)) {
1757 		do_serverpid(ssl, rc->xfrd);
1758 	} else {
1759 		(void)ssl_printf(ssl, "error unknown command '%s'\n", p);
1760 	}
1761 }
1762 
1763 /** handle remote control request */
1764 static void
1765 handle_req(struct daemon_remote* rc, struct rc_state* s, SSL* ssl)
1766 {
1767 	int r;
1768 	char pre[10];
1769 	char magic[8];
1770 	char buf[1024];
1771 	if (fcntl(s->c.ev_fd, F_SETFL, 0) == -1) { /* set blocking */
1772 		log_msg(LOG_ERR, "cannot fcntl rc: %s", strerror(errno));
1773 	}
1774 
1775 	/* try to read magic UBCT[version]_space_ string */
1776 	ERR_clear_error();
1777 	if((r=SSL_read(ssl, magic, (int)sizeof(magic)-1)) <= 0) {
1778 		if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN)
1779 			return;
1780 		log_crypto_err("could not SSL_read");
1781 		return;
1782 	}
1783 	magic[7] = 0;
1784 	if( r != 7 || strncmp(magic, "NSDCT", 5) != 0) {
1785 		VERBOSITY(2, (LOG_INFO, "control connection has bad header"));
1786 		/* probably wrong tool connected, ignore it completely */
1787 		return;
1788 	}
1789 
1790 	/* read the command line */
1791 	if(!ssl_read_line(ssl, buf, sizeof(buf))) {
1792 		return;
1793 	}
1794 	snprintf(pre, sizeof(pre), "NSDCT%d ", NSD_CONTROL_VERSION);
1795 	if(strcmp(magic, pre) != 0) {
1796 		VERBOSITY(2, (LOG_INFO, "control connection had bad "
1797 			"version %s, cmd: %s", magic, buf));
1798 		ssl_printf(ssl, "error version mismatch\n");
1799 		return;
1800 	}
1801 	VERBOSITY(2, (LOG_INFO, "control cmd: %s", buf));
1802 
1803 	/* figure out what to do */
1804 	execute_cmd(rc, ssl, buf, s);
1805 }
1806 
1807 static void
1808 remote_control_callback(int fd, short event, void* arg)
1809 {
1810 	struct rc_state* s = (struct rc_state*)arg;
1811 	struct daemon_remote* rc = s->rc;
1812 	int r;
1813 	if( (event&EV_TIMEOUT) ) {
1814 		log_msg(LOG_ERR, "remote control timed out");
1815 		clean_point(rc, s);
1816 		return;
1817 	}
1818 	/* (continue to) setup the SSL connection */
1819 	ERR_clear_error();
1820 	r = SSL_do_handshake(s->ssl);
1821 	if(r != 1) {
1822 		int r2 = SSL_get_error(s->ssl, r);
1823 		if(r2 == SSL_ERROR_WANT_READ) {
1824 			if(s->shake_state == rc_hs_read) {
1825 				/* try again later */
1826 				return;
1827 			}
1828 			s->shake_state = rc_hs_read;
1829 			event_del(&s->c);
1830 			event_set(&s->c, fd, EV_PERSIST|EV_TIMEOUT|EV_READ,
1831 				remote_control_callback, s);
1832 			if(event_base_set(xfrd->event_base, &s->c) != 0)
1833 				log_msg(LOG_ERR, "remote_accept: cannot set event_base");
1834 			if(event_add(&s->c, &s->tval) != 0)
1835 				log_msg(LOG_ERR, "remote_accept: cannot add event");
1836 			return;
1837 		} else if(r2 == SSL_ERROR_WANT_WRITE) {
1838 			if(s->shake_state == rc_hs_write) {
1839 				/* try again later */
1840 				return;
1841 			}
1842 			s->shake_state = rc_hs_write;
1843 			event_del(&s->c);
1844 			event_set(&s->c, fd, EV_PERSIST|EV_TIMEOUT|EV_WRITE,
1845 				remote_control_callback, s);
1846 			if(event_base_set(xfrd->event_base, &s->c) != 0)
1847 				log_msg(LOG_ERR, "remote_accept: cannot set event_base");
1848 			if(event_add(&s->c, &s->tval) != 0)
1849 				log_msg(LOG_ERR, "remote_accept: cannot add event");
1850 			return;
1851 		} else {
1852 			if(r == 0)
1853 				log_msg(LOG_ERR, "remote control connection closed prematurely");
1854 			log_crypto_err("remote control failed ssl");
1855 			clean_point(rc, s);
1856 			return;
1857 		}
1858 	}
1859 	s->shake_state = rc_none;
1860 
1861 	/* once handshake has completed, check authentication */
1862 	if(SSL_get_verify_result(s->ssl) == X509_V_OK) {
1863 		X509* x = SSL_get_peer_certificate(s->ssl);
1864 		if(!x) {
1865 			VERBOSITY(2, (LOG_INFO, "remote control connection "
1866 				"provided no client certificate"));
1867 			clean_point(rc, s);
1868 			return;
1869 		}
1870 		VERBOSITY(3, (LOG_INFO, "remote control connection authenticated"));
1871 		X509_free(x);
1872 	} else {
1873 		VERBOSITY(2, (LOG_INFO, "remote control connection failed to "
1874 			"authenticate with client certificate"));
1875 		clean_point(rc, s);
1876 		return;
1877 	}
1878 
1879 	/* if OK start to actually handle the request */
1880 	handle_req(rc, s, s->ssl);
1881 
1882 	if(!s->in_stats_list) {
1883 		VERBOSITY(3, (LOG_INFO, "remote control operation completed"));
1884 		clean_point(rc, s);
1885 	}
1886 }
1887 
1888 #ifdef BIND8_STATS
1889 static const char*
1890 opcode2str(int o)
1891 {
1892 	switch(o) {
1893 		case OPCODE_QUERY: return "QUERY";
1894 		case OPCODE_IQUERY: return "IQUERY";
1895 		case OPCODE_STATUS: return "STATUS";
1896 		case OPCODE_NOTIFY: return "NOTIFY";
1897 		case OPCODE_UPDATE: return "UPDATE";
1898 		default: return "OTHER";
1899 	}
1900 }
1901 
1902 /** print long number */
1903 static int
1904 print_longnum(SSL* ssl, char* desc, uint64_t x)
1905 {
1906 	if(x > (uint64_t)1024*1024*1024) {
1907 		/* more than a Gb */
1908 		size_t front = (size_t)(x / (uint64_t)1000000);
1909 		size_t back = (size_t)(x % (uint64_t)1000000);
1910 		return ssl_printf(ssl, "%s%u%6.6u\n", desc,
1911 			(unsigned)front, (unsigned)back);
1912 	} else {
1913 		return ssl_printf(ssl, "%s%u\n", desc, (unsigned)x);
1914 	}
1915 }
1916 
1917 /* print one block of statistics.  n is name and d is delimiter */
1918 static void
1919 print_stat_block(SSL* ssl, char* n, char* d, struct nsdst* st)
1920 {
1921 	const char* rcstr[] = {"NOERROR", "FORMERR", "SERVFAIL", "NXDOMAIN",
1922 	    "NOTIMP", "REFUSED", "YXDOMAIN", "YXRRSET", "NXRRSET", "NOTAUTH",
1923 	    "NOTZONE", "RCODE11", "RCODE12", "RCODE13", "RCODE14", "RCODE15",
1924 	    "BADVERS"
1925 	};
1926 	size_t i;
1927 	for(i=0; i<= 255; i++) {
1928 		if(inhibit_zero && st->qtype[i] == 0 &&
1929 			strncmp(rrtype_to_string(i), "TYPE", 4) == 0)
1930 			continue;
1931 		if(!ssl_printf(ssl, "%s%snum.type.%s=%u\n", n, d,
1932 			rrtype_to_string(i), (unsigned)st->qtype[i]))
1933 			return;
1934 	}
1935 
1936 	/* opcode */
1937 	for(i=0; i<6; i++) {
1938 		if(inhibit_zero && st->opcode[i] == 0 && i != OPCODE_QUERY)
1939 			continue;
1940 		if(!ssl_printf(ssl, "%s%snum.opcode.%s=%u\n", n, d,
1941 			opcode2str(i), (unsigned)st->opcode[i]))
1942 			return;
1943 	}
1944 
1945 	/* qclass */
1946 	for(i=0; i<4; i++) {
1947 		if(inhibit_zero && st->qclass[i] == 0 && i != CLASS_IN)
1948 			continue;
1949 		if(!ssl_printf(ssl, "%s%snum.class.%s=%u\n", n, d,
1950 			rrclass_to_string(i), (unsigned)st->qclass[i]))
1951 			return;
1952 	}
1953 
1954 	/* rcode */
1955 	for(i=0; i<17; i++) {
1956 		if(inhibit_zero && st->rcode[i] == 0 &&
1957 			i > RCODE_YXDOMAIN) /* NSD does not use larger */
1958 			continue;
1959 		if(!ssl_printf(ssl, "%s%snum.rcode.%s=%u\n", n, d, rcstr[i],
1960 			(unsigned)st->rcode[i]))
1961 			return;
1962 	}
1963 
1964 	/* edns */
1965 	if(!ssl_printf(ssl, "%s%snum.edns=%u\n", n, d, (unsigned)st->edns))
1966 		return;
1967 
1968 	/* ednserr */
1969 	if(!ssl_printf(ssl, "%s%snum.ednserr=%u\n", n, d,
1970 		(unsigned)st->ednserr))
1971 		return;
1972 
1973 	/* qudp */
1974 	if(!ssl_printf(ssl, "%s%snum.udp=%u\n", n, d, (unsigned)st->qudp))
1975 		return;
1976 	/* qudp6 */
1977 	if(!ssl_printf(ssl, "%s%snum.udp6=%u\n", n, d, (unsigned)st->qudp6))
1978 		return;
1979 	/* ctcp */
1980 	if(!ssl_printf(ssl, "%s%snum.tcp=%u\n", n, d, (unsigned)st->ctcp))
1981 		return;
1982 	/* ctcp6 */
1983 	if(!ssl_printf(ssl, "%s%snum.tcp6=%u\n", n, d, (unsigned)st->ctcp6))
1984 		return;
1985 
1986 	/* nona */
1987 	if(!ssl_printf(ssl, "%s%snum.answer_wo_aa=%u\n", n, d,
1988 		(unsigned)st->nona))
1989 		return;
1990 
1991 	/* rxerr */
1992 	if(!ssl_printf(ssl, "%s%snum.rxerr=%u\n", n, d, (unsigned)st->rxerr))
1993 		return;
1994 
1995 	/* txerr */
1996 	if(!ssl_printf(ssl, "%s%snum.txerr=%u\n", n, d, (unsigned)st->txerr))
1997 		return;
1998 
1999 	/* number of requested-axfr, number of times axfr served to clients */
2000 	if(!ssl_printf(ssl, "%s%snum.raxfr=%u\n", n, d, (unsigned)st->raxfr))
2001 		return;
2002 
2003 	/* truncated */
2004 	if(!ssl_printf(ssl, "%s%snum.truncated=%u\n", n, d,
2005 		(unsigned)st->truncated))
2006 		return;
2007 
2008 	/* dropped */
2009 	if(!ssl_printf(ssl, "%s%snum.dropped=%u\n", n, d,
2010 		(unsigned)st->dropped))
2011 		return;
2012 }
2013 
2014 #ifdef USE_ZONE_STATS
2015 static void
2016 resize_zonestat(xfrd_state_t* xfrd, size_t num)
2017 {
2018 	struct nsdst** a = xalloc_array_zero(num, sizeof(struct nsdst*));
2019 	if(xfrd->zonestat_clear_num != 0)
2020 		memcpy(a, xfrd->zonestat_clear, xfrd->zonestat_clear_num
2021 			* sizeof(struct nsdst*));
2022 	free(xfrd->zonestat_clear);
2023 	xfrd->zonestat_clear = a;
2024 	xfrd->zonestat_clear_num = num;
2025 }
2026 
2027 static void
2028 zonestat_print(SSL* ssl, xfrd_state_t* xfrd, int clear)
2029 {
2030 	struct zonestatname* n;
2031 	struct nsdst stat0, stat1;
2032 	RBTREE_FOR(n, struct zonestatname*, xfrd->nsd->options->zonestatnames){
2033 		char* name = (char*)n->node.key;
2034 		if(n->id >= xfrd->zonestat_safe)
2035 			continue; /* newly allocated and reload has not yet
2036 				done and replied with new size */
2037 		if(name == NULL || name[0]==0)
2038 			continue; /* empty name, do not output */
2039 		/* the statistics are stored in two blocks, during reload
2040 		 * the newly forked processes get the other block to use,
2041 		 * these blocks are mmapped and are currently in use to
2042 		 * add statistics to */
2043 		memcpy(&stat0, &xfrd->nsd->zonestat[0][n->id], sizeof(stat0));
2044 		memcpy(&stat1, &xfrd->nsd->zonestat[1][n->id], sizeof(stat1));
2045 		stats_add(&stat0, &stat1);
2046 
2047 		/* save a copy of current (cumulative) stats in stat1 */
2048 		memcpy(&stat1, &stat0, sizeof(stat1));
2049 		/* subtract last total of stats that was 'cleared' */
2050 		if(n->id < xfrd->zonestat_clear_num &&
2051 			xfrd->zonestat_clear[n->id])
2052 			stats_subtract(&stat0, xfrd->zonestat_clear[n->id]);
2053 		if(clear) {
2054 			/* extend storage array if needed */
2055 			if(n->id >= xfrd->zonestat_clear_num) {
2056 				if(n->id+1 < xfrd->nsd->options->zonestatnames->count)
2057 					resize_zonestat(xfrd, xfrd->nsd->options->zonestatnames->count);
2058 				else
2059 					resize_zonestat(xfrd, n->id+1);
2060 			}
2061 			if(!xfrd->zonestat_clear[n->id])
2062 				xfrd->zonestat_clear[n->id] = xalloc(
2063 					sizeof(struct nsdst));
2064 			/* store last total of stats */
2065 			memcpy(xfrd->zonestat_clear[n->id], &stat1,
2066 				sizeof(struct nsdst));
2067 		}
2068 
2069 		/* stat0 contains the details that we want to print */
2070 		if(!ssl_printf(ssl, "%s%snum.queries=%u\n", name, ".",
2071 			(unsigned)(stat0.qudp + stat0.qudp6 + stat0.ctcp +
2072 				stat0.ctcp6)))
2073 			return;
2074 		print_stat_block(ssl, name, ".", &stat0);
2075 	}
2076 }
2077 #endif /* USE_ZONE_STATS */
2078 
2079 static void
2080 print_stats(SSL* ssl, xfrd_state_t* xfrd, struct timeval* now, int clear)
2081 {
2082 	size_t i;
2083 	stc_t total = 0;
2084 	struct timeval elapsed, uptime;
2085 
2086 	/* per CPU and total */
2087 	for(i=0; i<xfrd->nsd->child_count; i++) {
2088 		if(!ssl_printf(ssl, "server%d.queries=%u\n", (int)i,
2089 			(unsigned)xfrd->nsd->children[i].query_count))
2090 			return;
2091 		total += xfrd->nsd->children[i].query_count;
2092 	}
2093 	if(!ssl_printf(ssl, "num.queries=%u\n", (unsigned)total))
2094 		return;
2095 
2096 	/* time elapsed and uptime (in seconds) */
2097 	timeval_subtract(&uptime, now, &xfrd->nsd->rc->boot_time);
2098 	timeval_subtract(&elapsed, now, &xfrd->nsd->rc->stats_time);
2099 	if(!ssl_printf(ssl, "time.boot=%u.%6.6u\n",
2100 		(unsigned)uptime.tv_sec, (unsigned)uptime.tv_usec))
2101 		return;
2102 	if(!ssl_printf(ssl, "time.elapsed=%u.%6.6u\n",
2103 		(unsigned)elapsed.tv_sec, (unsigned)elapsed.tv_usec))
2104 		return;
2105 
2106 	/* mem info, database on disksize */
2107 	if(!print_longnum(ssl, "size.db.disk=", xfrd->nsd->st.db_disk))
2108 		return;
2109 	if(!print_longnum(ssl, "size.db.mem=", xfrd->nsd->st.db_mem))
2110 		return;
2111 	if(!print_longnum(ssl, "size.xfrd.mem=", region_get_mem(xfrd->region)))
2112 		return;
2113 	if(!print_longnum(ssl, "size.config.disk=",
2114 		xfrd->nsd->options->zonelist_off))
2115 		return;
2116 	if(!print_longnum(ssl, "size.config.mem=", region_get_mem(
2117 		xfrd->nsd->options->region)))
2118 		return;
2119 	print_stat_block(ssl, "", "", &xfrd->nsd->st);
2120 
2121 	/* zone statistics */
2122 	if(!ssl_printf(ssl, "zone.master=%u\n",
2123 		(unsigned)(xfrd->notify_zones->count - xfrd->zones->count)))
2124 		return;
2125 	if(!ssl_printf(ssl, "zone.slave=%u\n", (unsigned)xfrd->zones->count))
2126 		return;
2127 #ifdef USE_ZONE_STATS
2128 	zonestat_print(ssl, xfrd, clear); /* per-zone statistics */
2129 #else
2130 	(void)clear;
2131 #endif
2132 }
2133 
2134 static void
2135 clear_stats(xfrd_state_t* xfrd)
2136 {
2137 	size_t i;
2138 	uint64_t dbd = xfrd->nsd->st.db_disk;
2139 	uint64_t dbm = xfrd->nsd->st.db_mem;
2140 	for(i=0; i<xfrd->nsd->child_count; i++) {
2141 		xfrd->nsd->children[i].query_count = 0;
2142 	}
2143 	memset(&xfrd->nsd->st, 0, sizeof(struct nsdst));
2144 	/* zonestats are cleared by storing the cumulative value that
2145 	 * was last printed in the zonestat_clear array, and subtracting
2146 	 * that before the next stats printout */
2147 	xfrd->nsd->st.db_disk = dbd;
2148 	xfrd->nsd->st.db_mem = dbm;
2149 }
2150 
2151 void
2152 daemon_remote_process_stats(struct daemon_remote* rc)
2153 {
2154 	struct rc_state* s;
2155 	struct timeval now;
2156 	if(!rc) return;
2157 	if(gettimeofday(&now, NULL) == -1)
2158 		log_msg(LOG_ERR, "gettimeofday: %s", strerror(errno));
2159 	/* pop one and give it stats */
2160 	while((s = rc->stats_list)) {
2161 		assert(s->in_stats_list);
2162 		print_stats(s->ssl, rc->xfrd, &now, (s->in_stats_list == 1));
2163 		if(s->in_stats_list == 1) {
2164 			clear_stats(rc->xfrd);
2165 			rc->stats_time = now;
2166 		}
2167 		VERBOSITY(3, (LOG_INFO, "remote control stats printed"));
2168 		rc->stats_list = s->next;
2169 		s->in_stats_list = 0;
2170 		clean_point(rc, s);
2171 	}
2172 }
2173 #endif /* BIND8_STATS */
2174 
2175 #endif /* HAVE_SSL */
2176