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