Home | History | Annotate | Line # | Download | only in dist
      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 
     47 #ifdef HAVE_SSL
     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 #endif /* HAVE_SSL */
     58 #include <ctype.h>
     59 #include <unistd.h>
     60 #include <assert.h>
     61 #include <fcntl.h>
     62 #include <errno.h>
     63 #ifndef USE_MINI_EVENT
     64 #  ifdef HAVE_EVENT_H
     65 #    include <event.h>
     66 #  else
     67 #    include <event2/event.h>
     68 #    include "event2/event_struct.h"
     69 #    include "event2/event_compat.h"
     70 #  endif
     71 #else
     72 #  include "mini_event.h"
     73 #endif
     74 #include "util.h"
     75 #include "xfrd.h"
     76 #include "xfrd-catalog-zones.h"
     77 #include "xfrd-notify.h"
     78 #include "xfrd-tcp.h"
     79 #include "nsd.h"
     80 #include "options.h"
     81 #include "difffile.h"
     82 #include "ipc.h"
     83 #include "remote.h"
     84 #include "rdata.h"
     85 
     86 #ifdef USE_METRICS
     87 #include "metrics.h"
     88 #endif /* USE_METRICS */
     89 
     90 #ifdef HAVE_SYS_TYPES_H
     91 #  include <sys/types.h>
     92 #endif
     93 #ifdef HAVE_SYS_STAT_H
     94 #  include <sys/stat.h>
     95 #endif
     96 #ifdef HAVE_NETDB_H
     97 #  include <netdb.h>
     98 #endif
     99 #ifdef HAVE_SYS_UN_H
    100 #  include <sys/un.h>
    101 #endif
    102 #ifndef AF_LOCAL
    103 #define AF_LOCAL AF_UNIX
    104 #endif
    105 
    106 /** number of seconds timeout on incoming remote control handshake */
    107 #define REMOTE_CONTROL_TCP_TIMEOUT 120
    108 
    109 /** repattern to master or slave */
    110 #define REPAT_SLAVE                   1
    111 #define REPAT_MASTER                  2
    112 #define REPAT_CATALOG_CONSUMER        4
    113 #define REPAT_CATALOG_CONSUMER_DEINIT 8
    114 
    115 /** if you want zero to be inhibited in stats output.
    116  * it omits zeroes for types that have no acronym and unused-rcodes */
    117 const int inhibit_zero = 1;
    118 
    119 /**
    120  * a busy control command connection, SSL state
    121  * Defined here to keep the definition private, and keep SSL out of the .h
    122  */
    123 struct rc_state {
    124 	/** the next item in list */
    125 	struct rc_state* next, *prev;
    126 	/* if the event was added to the event_base */
    127 	int event_added;
    128 	/** the commpoint */
    129 	struct event c;
    130 	/** timeout for this state */
    131 	struct timeval tval;
    132 	/** in the handshake part */
    133 	enum { rc_none, rc_hs_read, rc_hs_write } shake_state;
    134 #ifdef HAVE_SSL
    135 	/** the ssl state */
    136 	SSL* ssl;
    137 #endif
    138 	/** file descriptor */
    139 	int fd;
    140 	/** the rc this is part of */
    141 	struct daemon_remote* rc;
    142 	/** stats list next item */
    143 	struct rc_state* stats_next;
    144 };
    145 
    146 /**
    147  * list of events for accepting connections
    148  */
    149 struct acceptlist {
    150 	struct acceptlist* next;
    151 	int event_added;
    152 	struct event c;
    153 	char* ident;
    154 	struct daemon_remote* rc;
    155 };
    156 
    157 /**
    158  * The remote control state.
    159  */
    160 struct daemon_remote {
    161 	/** the master process for this remote control */
    162 	struct xfrd_state* xfrd;
    163 	/** commpoints for accepting remote control connections */
    164 	struct acceptlist* accept_list;
    165 	/* if certificates are used */
    166 	int use_cert;
    167 	/** number of active commpoints that are handling remote control */
    168 	int active;
    169 	/** max active commpoints */
    170 	int max_active;
    171 	/** current commpoints busy; double linked, malloced */
    172 	struct rc_state* busy_list;
    173 	/** last time stats was reported */
    174 	struct timeval stats_time, boot_time;
    175 #ifdef HAVE_SSL
    176 	/** the SSL context for creating new SSL streams */
    177 	SSL_CTX* ctx;
    178 #endif
    179 };
    180 
    181 /**
    182  * Connection to print to, either SSL or plain over fd
    183  */
    184 struct remote_stream {
    185 #ifdef HAVE_SSL
    186 	/** SSL structure, nonNULL if using SSL */
    187 	SSL* ssl;
    188 #endif
    189 	/** file descriptor for plain transfer */
    190 	int fd;
    191 };
    192 typedef struct remote_stream RES;
    193 
    194 /**
    195  * Print fixed line of text over ssl connection in blocking mode
    196  * @param res: print to
    197  * @param text: the text.
    198  * @return false on connection failure.
    199  */
    200 static int ssl_print_text(RES* res, const char* text);
    201 
    202 /**
    203  * printf style printing to the ssl connection
    204  * @param res: the RES connection to print to. Blocking.
    205  * @param format: printf style format string.
    206  * @return success or false on a network failure.
    207  */
    208 static int ssl_printf(RES* res, const char* format, ...)
    209         ATTR_FORMAT(printf, 2, 3);
    210 
    211 /**
    212  * Read until \n is encountered
    213  * If stream signals EOF, the string up to then is returned (without \n).
    214  * @param res: the RES connection to read from. blocking.
    215  * @param buf: buffer to read to.
    216  * @param max: size of buffer.
    217  * @return false on connection failure.
    218  */
    219 static int ssl_read_line(RES* res, char* buf, size_t max);
    220 
    221 /** perform the accept of a new remote control connection */
    222 static void
    223 remote_accept_callback(int fd, short event, void* arg);
    224 
    225 /** perform remote control */
    226 static void
    227 remote_control_callback(int fd, short event, void* arg);
    228 
    229 /** ---- end of private defines ---- **/
    230 
    231 #ifdef HAVE_SSL
    232 /** log ssl crypto err */
    233 static void
    234 log_crypto_err(const char* str)
    235 {
    236 	/* error:[error code]:[library name]:[function name]:[reason string] */
    237 	char buf[128];
    238 	unsigned long e;
    239 	ERR_error_string_n(ERR_get_error(), buf, sizeof(buf));
    240 	log_msg(LOG_ERR, "%s crypto %s", str, buf);
    241 	while( (e=ERR_get_error()) ) {
    242 		ERR_error_string_n(e, buf, sizeof(buf));
    243 		log_msg(LOG_ERR, "and additionally crypto %s", buf);
    244 	}
    245 }
    246 #endif /* HAVE_SSL */
    247 
    248 #ifdef BIND8_STATS
    249 /** subtract timers and the values do not overflow or become negative */
    250 void
    251 timeval_subtract(struct timeval* d, const struct timeval* end,
    252 	const struct timeval* start)
    253 {
    254 #ifndef S_SPLINT_S
    255 	time_t end_usec = end->tv_usec;
    256 	d->tv_sec = end->tv_sec - start->tv_sec;
    257 	if(end_usec < start->tv_usec) {
    258 		end_usec += 1000000;
    259 		d->tv_sec--;
    260 	}
    261 	d->tv_usec = end_usec - start->tv_usec;
    262 #endif
    263 }
    264 #endif /* BIND8_STATS */
    265 
    266 #ifdef HAVE_SSL
    267 static int
    268 remote_setup_ctx(struct daemon_remote* rc, struct nsd_options* cfg)
    269 {
    270 	char* s_cert = cfg->server_cert_file;
    271 	char* s_key = cfg->server_key_file;
    272 	rc->ctx = server_tls_ctx_setup(s_key, s_cert, s_cert);
    273 	if(!rc->ctx) {
    274 		log_msg(LOG_ERR, "could not setup remote control TLS context");
    275 		return 0;
    276 	}
    277 	return 1;
    278 }
    279 #endif /* HAVE_SSL */
    280 
    281 struct daemon_remote*
    282 daemon_remote_create(struct nsd_options* cfg)
    283 {
    284 	struct daemon_remote* rc = (struct daemon_remote*)xalloc_zero(
    285 		sizeof(*rc));
    286 	rc->max_active = 10;
    287 	assert(cfg->control_enable);
    288 
    289 	if(options_remote_is_address(cfg)) {
    290 #ifdef HAVE_SSL
    291 		if(!remote_setup_ctx(rc, cfg)) {
    292 			daemon_remote_delete(rc);
    293 			return NULL;
    294 		}
    295 		rc->use_cert = 1;
    296 #else
    297 		log_msg(LOG_ERR, "Could not setup remote control: NSD was compiled without SSL.");
    298 #endif /* HAVE_SSL */
    299 	} else {
    300 		struct ip_address_option* o;
    301 #ifdef HAVE_SSL
    302 		rc->ctx = NULL;
    303 #endif
    304 		rc->use_cert = 0;
    305 		for(o = cfg->control_interface; o; o = o->next) {
    306 			if(o->address && o->address[0] != '/')
    307 				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);
    308 		}
    309 	}
    310 
    311 	/* and try to open the ports */
    312 	if(!daemon_remote_open_ports(rc, cfg)) {
    313 		log_msg(LOG_ERR, "could not open remote control port");
    314 		daemon_remote_delete(rc);
    315 		return NULL;
    316 	}
    317 
    318 	if(gettimeofday(&rc->boot_time, NULL) == -1)
    319 		log_msg(LOG_ERR, "gettimeofday: %s", strerror(errno));
    320 	rc->stats_time = rc->boot_time;
    321 
    322 	return rc;
    323 }
    324 
    325 void daemon_remote_close(struct daemon_remote* rc)
    326 {
    327 	struct rc_state* p, *np;
    328 	struct acceptlist* h, *nh;
    329 	if(!rc) return;
    330 
    331 	/* close listen sockets */
    332 	h = rc->accept_list;
    333 	while(h) {
    334 		nh = h->next;
    335 		if(h->event_added)
    336 			event_del(&h->c);
    337 		close(h->c.ev_fd);
    338 		free(h->ident);
    339 		free(h);
    340 		h = nh;
    341 	}
    342 	rc->accept_list = NULL;
    343 
    344 	/* close busy connection sockets */
    345 	p = rc->busy_list;
    346 	while(p) {
    347 		np = p->next;
    348 		if(p->event_added)
    349 			event_del(&p->c);
    350 #ifdef HAVE_SSL
    351 		if(p->ssl)
    352 			SSL_free(p->ssl);
    353 #endif
    354 		close(p->c.ev_fd);
    355 		free(p);
    356 		p = np;
    357 	}
    358 	rc->busy_list = NULL;
    359 	rc->active = 0;
    360 }
    361 
    362 void daemon_remote_delete(struct daemon_remote* rc)
    363 {
    364 	if(!rc) return;
    365 	daemon_remote_close(rc);
    366 #ifdef HAVE_SSL
    367 	if(rc->ctx) {
    368 		SSL_CTX_free(rc->ctx);
    369 	}
    370 #endif
    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 		close(s);
    405 		return -1;
    406 	}
    407 #endif
    408 	/* set it nonblocking */
    409 	/* (StevensUNP p463), if tcp listening socket is blocking, then
    410 	   it may block in accept, even if select() says readable. */
    411 	if (fcntl(s, F_SETFL, O_NONBLOCK) == -1) {
    412 		log_msg(LOG_ERR, "cannot fcntl tcp: %s", strerror(errno));
    413 	}
    414 	/* Bind it... */
    415 	if (bind(s, (struct sockaddr *)addr->ai_addr, addr->ai_addrlen) != 0) {
    416 		log_msg(LOG_ERR, "can't bind tcp socket: %s", strerror(errno));
    417 		close(s);
    418 		return -1;
    419 	}
    420 	/* Listen to it... */
    421 	if (listen(s, TCP_BACKLOG_REMOTE) == -1) {
    422 		log_msg(LOG_ERR, "can't listen: %s", strerror(errno));
    423 		close(s);
    424 		return -1;
    425 	}
    426 	return s;
    427 }
    428 
    429 /**
    430  * Add and open a new control port
    431  * @param rc: rc with result list.
    432  * @param ip: ip str
    433  * @param nr: port nr
    434  * @param noproto_is_err: if lack of protocol support is an error.
    435  * @return false on failure.
    436  */
    437 static int
    438 add_open(struct daemon_remote* rc, struct nsd_options* cfg, const char* ip,
    439 	int nr, int noproto_is_err)
    440 {
    441 	struct addrinfo hints;
    442 	struct addrinfo* res;
    443 	struct acceptlist* hl;
    444 	int noproto = 0;
    445 	int fd, r;
    446 	char port[15];
    447 	snprintf(port, sizeof(port), "%d", nr);
    448 	port[sizeof(port)-1]=0;
    449 	memset(&hints, 0, sizeof(hints));
    450 	assert(ip);
    451 
    452 	if(ip[0] == '/') {
    453 		/* This looks like a local socket */
    454 		fd = create_local_accept_sock(ip, &noproto);
    455 		/*
    456 		 * Change socket ownership and permissions so users other
    457 		 * than root can access it provided they are in the same
    458 		 * group as the user we run as.
    459 		 */
    460 		if(fd != -1) {
    461 #ifdef HAVE_CHOWN
    462 			if(chmod(ip, (mode_t)(S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)) == -1) {
    463 				VERBOSITY(3, (LOG_INFO, "cannot chmod control socket %s: %s", ip, strerror(errno)));
    464 			}
    465 			if (cfg->username && cfg->username[0] &&
    466 				nsd.uid != (uid_t)-1) {
    467 				if(chown(ip, nsd.uid, nsd.gid) == -1)
    468 					VERBOSITY(2, (LOG_INFO, "cannot chown %u.%u %s: %s",
    469 					  (unsigned)nsd.uid, (unsigned)nsd.gid,
    470 					  ip, strerror(errno)));
    471 			}
    472 #else
    473 			(void)cfg;
    474 #endif
    475 		}
    476 	} else {
    477 		hints.ai_socktype = SOCK_STREAM;
    478 		hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
    479 		/* if we had no interface ip name, "default" is what we
    480 		 * would do getaddrinfo for. */
    481 		if((r = getaddrinfo(ip, port, &hints, &res)) != 0 || !res) {
    482 			log_msg(LOG_ERR, "control interface %s:%s getaddrinfo: %s %s",
    483 				ip, port, gai_strerror(r),
    484 #ifdef EAI_SYSTEM
    485 				r==EAI_SYSTEM?(char*)strerror(errno):""
    486 #else
    487 				""
    488 #endif
    489 				);
    490 			return 0;
    491 		}
    492 
    493 		/* open fd */
    494 		fd = create_tcp_accept_sock(res, &noproto);
    495 		freeaddrinfo(res);
    496 	}
    497 
    498 	if(fd == -1 && noproto) {
    499 		if(!noproto_is_err)
    500 			return 1; /* return success, but do nothing */
    501 		log_msg(LOG_ERR, "cannot open control interface %s %d : "
    502 			"protocol not supported", ip, nr);
    503 		return 0;
    504 	}
    505 	if(fd == -1) {
    506 		log_msg(LOG_ERR, "cannot open control interface %s %d", ip, nr);
    507 		return 0;
    508 	}
    509 
    510 	/* alloc */
    511 	hl = (struct acceptlist*)xalloc_zero(sizeof(*hl));
    512 	hl->rc = rc;
    513 	hl->ident = strdup(ip);
    514 	if(!hl->ident) {
    515 		log_msg(LOG_ERR, "malloc failure");
    516 		close(fd);
    517 		free(hl);
    518 		return 0;
    519 	}
    520 	hl->next = rc->accept_list;
    521 	rc->accept_list = hl;
    522 
    523 	hl->c.ev_fd = fd;
    524 	hl->event_added = 0;
    525 	return 1;
    526 }
    527 
    528 int
    529 daemon_remote_open_ports(struct daemon_remote* rc, struct nsd_options* cfg)
    530 {
    531 	assert(cfg->control_enable && cfg->control_port);
    532 	if(cfg->control_interface) {
    533 		ip_address_option_type* p;
    534 		for(p = cfg->control_interface; p; p = p->next) {
    535 			if(!add_open(rc, cfg, p->address, cfg->control_port, 1)) {
    536 				return 0;
    537 			}
    538 		}
    539 	} else {
    540 		/* defaults */
    541 		if(cfg->do_ip6 && !add_open(rc, cfg, "::1", cfg->control_port, 0)) {
    542 			return 0;
    543 		}
    544 		if(cfg->do_ip4 &&
    545 			!add_open(rc, cfg, "127.0.0.1", cfg->control_port, 1)) {
    546 			return 0;
    547 		}
    548 	}
    549 	return 1;
    550 }
    551 
    552 void
    553 daemon_remote_attach(struct daemon_remote* rc, struct xfrd_state* xfrd)
    554 {
    555 	int fd;
    556 	struct acceptlist* p;
    557 	if(!rc) return;
    558 	rc->xfrd = xfrd;
    559 	for(p = rc->accept_list; p; p = p->next) {
    560 		/* add event */
    561 		fd = p->c.ev_fd;
    562 		memset(&p->c, 0, sizeof(p->c));
    563 		event_set(&p->c, fd, EV_PERSIST|EV_READ, remote_accept_callback,
    564 			p);
    565 		if(event_base_set(xfrd->event_base, &p->c) != 0)
    566 			log_msg(LOG_ERR, "remote: cannot set event_base");
    567 		if(event_add(&p->c, NULL) != 0)
    568 			log_msg(LOG_ERR, "remote: cannot add event");
    569 		p->event_added = 1;
    570 	}
    571 }
    572 
    573 static void
    574 remote_accept_callback(int fd, short event, void* arg)
    575 {
    576 	struct acceptlist *hl = (struct acceptlist*)arg;
    577 	struct daemon_remote *rc = hl->rc;
    578 #ifdef INET6
    579 	struct sockaddr_storage addr;
    580 #else
    581 	struct sockaddr_in addr;
    582 #endif
    583 	socklen_t addrlen;
    584 	int newfd;
    585 	struct rc_state* n;
    586 
    587 	if (!(event & EV_READ)) {
    588 		return;
    589 	}
    590 
    591 	/* perform the accept */
    592 	addrlen = sizeof(addr);
    593 #ifndef HAVE_ACCEPT4
    594 	newfd = accept(fd, (struct sockaddr*)&addr, &addrlen);
    595 #else
    596 	newfd = accept4(fd, (struct sockaddr*)&addr, &addrlen, SOCK_NONBLOCK);
    597 #endif
    598 	if(newfd == -1) {
    599 		if (    errno != EINTR
    600 			&& errno != EWOULDBLOCK
    601 #ifdef ECONNABORTED
    602 			&& errno != ECONNABORTED
    603 #endif /* ECONNABORTED */
    604 #ifdef EPROTO
    605 			&& errno != EPROTO
    606 #endif /* EPROTO */
    607 			) {
    608 			log_msg(LOG_ERR, "accept failed: %s", strerror(errno));
    609 		}
    610 		return;
    611 	}
    612 
    613 	/* create new commpoint unless we are servicing already */
    614 	if(rc->active >= rc->max_active) {
    615 		log_msg(LOG_WARNING, "drop incoming remote control: "
    616 			"too many connections");
    617 	close_exit:
    618 		close(newfd);
    619 		return;
    620 	}
    621 
    622 #ifndef HAVE_ACCEPT4
    623 	if (fcntl(newfd, F_SETFL, O_NONBLOCK) == -1) {
    624 		log_msg(LOG_ERR, "fcntl failed: %s", strerror(errno));
    625 		goto close_exit;
    626 	}
    627 #endif
    628 
    629 	/* setup state to service the remote control command */
    630 	n = (struct rc_state*)calloc(1, sizeof(*n));
    631 	if(!n) {
    632 		log_msg(LOG_ERR, "out of memory");
    633 		goto close_exit;
    634 	}
    635 
    636 	n->tval.tv_sec = REMOTE_CONTROL_TCP_TIMEOUT;
    637 	n->tval.tv_usec = 0L;
    638 	n->fd = newfd;
    639 
    640 	memset(&n->c, 0, sizeof(n->c));
    641 	event_set(&n->c, newfd, EV_PERSIST|EV_TIMEOUT|EV_READ,
    642 		remote_control_callback, n);
    643 	if(event_base_set(xfrd->event_base, &n->c) != 0) {
    644 		log_msg(LOG_ERR, "remote_accept: cannot set event_base");
    645 		free(n);
    646 		goto close_exit;
    647 	}
    648 	if(event_add(&n->c, &n->tval) != 0) {
    649 		log_msg(LOG_ERR, "remote_accept: cannot add event");
    650 		free(n);
    651 		goto close_exit;
    652 	}
    653 	n->event_added = 1;
    654 
    655 	if(2 <= verbosity) {
    656 		if(hl->ident && hl->ident[0] == '/') {
    657 			VERBOSITY(2, (LOG_INFO, "new control connection from %s", hl->ident));
    658 		} else {
    659 			char s[128];
    660 			addr2str(&addr, s, sizeof(s));
    661 			VERBOSITY(2, (LOG_INFO, "new control connection from %s", s));
    662 		}
    663 	}
    664 
    665 #ifdef HAVE_SSL
    666 	if(rc->ctx) {
    667 		n->shake_state = rc_hs_read;
    668 		n->ssl = SSL_new(rc->ctx);
    669 		if(!n->ssl) {
    670 			log_crypto_err("could not SSL_new");
    671 			if(n->event_added)
    672 				event_del(&n->c);
    673 			free(n);
    674 			goto close_exit;
    675 		}
    676 		SSL_set_accept_state(n->ssl);
    677 		(void)SSL_set_mode(n->ssl, SSL_MODE_AUTO_RETRY);
    678 		if(!SSL_set_fd(n->ssl, newfd)) {
    679 			log_crypto_err("could not SSL_set_fd");
    680 			if(n->event_added)
    681 				event_del(&n->c);
    682 			SSL_free(n->ssl);
    683 			free(n);
    684 			goto close_exit;
    685 		}
    686 	} else {
    687 		n->ssl = NULL;
    688 	}
    689 #endif /* HAVE_SSL */
    690 
    691 	n->rc = rc;
    692 	n->stats_next = NULL;
    693 	n->prev = NULL;
    694 	n->next = rc->busy_list;
    695 	if(n->next) n->next->prev = n;
    696 	rc->busy_list = n;
    697 	rc->active ++;
    698 
    699 	/* perform the first nonblocking read already, for windows,
    700 	 * so it can return wouldblock. could be faster too. */
    701 	remote_control_callback(newfd, EV_READ, n);
    702 }
    703 
    704 /** delete from list */
    705 static void
    706 state_list_remove_elem(struct rc_state** list, struct rc_state* todel)
    707 {
    708 	if(todel->prev) todel->prev->next = todel->next;
    709 	else	*list = todel->next;
    710 	if(todel->next) todel->next->prev = todel->prev;
    711 }
    712 
    713 /** decrease active count and remove commpoint from busy list */
    714 static void
    715 clean_point(struct daemon_remote* rc, struct rc_state* s)
    716 {
    717 	state_list_remove_elem(&rc->busy_list, s);
    718 	rc->active --;
    719 	if(s->event_added)
    720 		event_del(&s->c);
    721 #ifdef HAVE_SSL
    722 	if(s->ssl) {
    723 		SSL_shutdown(s->ssl);
    724 		SSL_free(s->ssl);
    725 	}
    726 #endif /* HAVE_SSL */
    727 	close(s->c.ev_fd);
    728 	free(s);
    729 }
    730 
    731 static int
    732 ssl_print_text(RES* res, const char* text)
    733 {
    734 	if(!res)
    735 		return 0;
    736 #ifdef HAVE_SSL
    737 	if(res->ssl) {
    738 		int r;
    739 		ERR_clear_error();
    740 		if((r=SSL_write(res->ssl, text, (int)strlen(text))) <= 0) {
    741 			if(SSL_get_error(res->ssl, r) == SSL_ERROR_ZERO_RETURN) {
    742 				VERBOSITY(2, (LOG_WARNING, "in SSL_write, peer "
    743 					"closed connection"));
    744 				return 0;
    745 			}
    746 			log_crypto_err("could not SSL_write");
    747 			return 0;
    748 		}
    749 	} else {
    750 #endif /* HAVE_SSL */
    751 		if(write_socket(res->fd, text, strlen(text)) <= 0) {
    752 			log_msg(LOG_ERR, "could not write: %s",
    753 				strerror(errno));
    754 			return 0;
    755 		}
    756 #ifdef HAVE_SSL
    757 	}
    758 #endif /* HAVE_SSL */
    759 	return 1;
    760 }
    761 
    762 /** print text over the ssl connection */
    763 static int
    764 ssl_print_vmsg(RES* ssl, const char* format, va_list args)
    765 {
    766 	char msg[1024];
    767 	vsnprintf(msg, sizeof(msg), format, args);
    768 	return ssl_print_text(ssl, msg);
    769 }
    770 
    771 /** printf style printing to the ssl connection */
    772 static int
    773 ssl_printf(RES* ssl, const char* format, ...)
    774 {
    775 	va_list args;
    776 	int ret;
    777 	va_start(args, format);
    778 	ret = ssl_print_vmsg(ssl, format, args);
    779 	va_end(args);
    780 	return ret;
    781 }
    782 
    783 static int
    784 ssl_read_line(RES* res, char* buf, size_t max)
    785 {
    786 	size_t len = 0;
    787 	if(!res)
    788 		return 0;
    789 	while(len < max) {
    790 		buf[len] = 0; /* terminate for safety and please checkers */
    791 		/* this byte is written if we read a byte from the input */
    792 #ifdef HAVE_SSL
    793 		if(res->ssl) {
    794 			int r;
    795 			ERR_clear_error();
    796 			if((r=SSL_read(res->ssl, buf+len, 1)) <= 0) {
    797 				if(SSL_get_error(res->ssl, r) == SSL_ERROR_ZERO_RETURN) {
    798 					buf[len] = 0;
    799 					return 1;
    800 				}
    801 				log_crypto_err("could not SSL_read");
    802 				return 0;
    803 			}
    804 		} else {
    805 #endif /* HAVE_SSL */
    806 			while(1) {
    807 				ssize_t rr = read(res->fd, buf+len, 1);
    808 				if(rr <= 0) {
    809 					if(rr == 0) {
    810 						buf[len] = 0;
    811 						return 1;
    812 					}
    813 					if(errno == EINTR || errno == EAGAIN)
    814 						continue;
    815 					log_msg(LOG_ERR, "could not read: %s",
    816 						strerror(errno));
    817 					return 0;
    818 				}
    819 				break;
    820 			}
    821 #ifdef HAVE_SSL
    822 		}
    823 #endif /* HAVE_SSL */
    824 		if(buf[len] == '\n') {
    825 			/* return string without \n */
    826 			buf[len] = 0;
    827 			return 1;
    828 		}
    829 		len++;
    830 	}
    831 	buf[max-1] = 0;
    832 	log_msg(LOG_ERR, "control line too long (%d): %s", (int)max, buf);
    833 	return 0;
    834 }
    835 
    836 /** skip whitespace, return new pointer into string */
    837 static char*
    838 skipwhite(char* str)
    839 {
    840 	/* EOS \0 is not a space */
    841 	while( isspace((unsigned char)*str) )
    842 		str++;
    843 	return str;
    844 }
    845 
    846 /** send the OK to the control client */
    847 static void
    848 send_ok(RES* ssl)
    849 {
    850 	(void)ssl_printf(ssl, "ok\n");
    851 }
    852 
    853 /** get zone argument (if any) or NULL, false on error */
    854 static int
    855 get_zone_arg(RES* ssl, xfrd_state_type* xfrd, char* arg,
    856 	struct zone_options** zo)
    857 {
    858 	const dname_type* dname;
    859 	if(!arg[0]) {
    860 		/* no argument present, return NULL */
    861 		*zo = NULL;
    862 		return 1;
    863 	}
    864 	dname = dname_parse(xfrd->region, arg);
    865 	if(!dname) {
    866 		(void)ssl_printf(ssl, "error cannot parse zone name '%s'\n", arg);
    867 		*zo = NULL;
    868 		return 0;
    869 	}
    870 	*zo = zone_options_find(xfrd->nsd->options, dname);
    871 	region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
    872 	if(!*zo) {
    873 		(void)ssl_printf(ssl, "error zone %s not configured\n", arg);
    874 		return 0;
    875 	}
    876 	return 1;
    877 }
    878 
    879 /** do the stop command */
    880 static void
    881 do_stop(RES* ssl, xfrd_state_type* xfrd)
    882 {
    883 	xfrd->need_to_send_shutdown = 1;
    884 
    885 	if(!(xfrd->ipc_handler_flags&EV_WRITE)) {
    886 		ipc_xfrd_set_listening(xfrd, EV_PERSIST|EV_READ|EV_WRITE);
    887 	}
    888 
    889 	send_ok(ssl);
    890 }
    891 
    892 /** do the log_reopen command, it only needs reload_now */
    893 static void
    894 do_log_reopen(RES* ssl, xfrd_state_type* xfrd)
    895 {
    896 	xfrd_set_reload_now(xfrd);
    897 	send_ok(ssl);
    898 }
    899 
    900 /** do the reload command */
    901 static void
    902 do_reload(RES* ssl, xfrd_state_type* xfrd, char* arg)
    903 {
    904 	struct zone_options* zo;
    905 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
    906 		return;
    907 	task_new_check_zonefiles(xfrd->nsd->task[xfrd->nsd->mytask],
    908 		xfrd->last_task, zo?(const dname_type*)zo->node.key:NULL);
    909 	xfrd_set_reload_now(xfrd);
    910 	send_ok(ssl);
    911 }
    912 
    913 /** do the write command */
    914 static void
    915 do_write(RES* ssl, xfrd_state_type* xfrd, char* arg)
    916 {
    917 	struct zone_options* zo;
    918 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
    919 		return;
    920 	task_new_write_zonefiles(xfrd->nsd->task[xfrd->nsd->mytask],
    921 		xfrd->last_task, zo?(const dname_type*)zo->node.key:NULL);
    922 	xfrd_set_reload_now(xfrd);
    923 	send_ok(ssl);
    924 }
    925 
    926 /** do the notify command */
    927 static void
    928 do_notify(RES* ssl, xfrd_state_type* xfrd, char* arg)
    929 {
    930 	struct zone_options* zo;
    931 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
    932 		return;
    933 	if(zo) {
    934 		struct notify_zone* n = (struct notify_zone*)rbtree_search(
    935 			xfrd->notify_zones, (const dname_type*)zo->node.key);
    936 		if(n) {
    937 			xfrd_notify_start(n, xfrd);
    938 			send_ok(ssl);
    939 		} else {
    940 			(void)ssl_printf(ssl, "error zone does not have notify\n");
    941 		}
    942 	} else {
    943 		struct notify_zone* n;
    944 		RBTREE_FOR(n, struct notify_zone*, xfrd->notify_zones) {
    945 			xfrd_notify_start(n, xfrd);
    946 		}
    947 		send_ok(ssl);
    948 	}
    949 }
    950 
    951 /** do the transfer command */
    952 static void
    953 do_transfer(RES* ssl, xfrd_state_type* xfrd, char* arg)
    954 {
    955 	struct zone_options* zo;
    956 	xfrd_zone_type* zone;
    957 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
    958 		return;
    959 	if(zo) {
    960 		zone = (xfrd_zone_type*)rbtree_search(xfrd->zones, (const
    961 			dname_type*)zo->node.key);
    962 		if(zone) {
    963 			xfrd_handle_notify_and_start_xfr(zone, NULL);
    964 			send_ok(ssl);
    965 		} else {
    966 			(void)ssl_printf(ssl, "error zone not secondary\n");
    967 		}
    968 	} else {
    969 		RBTREE_FOR(zone, xfrd_zone_type*, xfrd->zones) {
    970 			xfrd_handle_notify_and_start_xfr(zone, NULL);
    971 		}
    972 		(void)ssl_printf(ssl, "ok, %lu zones\n", (unsigned long)xfrd->zones->count);
    973 	}
    974 }
    975 
    976 /** force transfer a zone */
    977 static void
    978 force_transfer_zone(xfrd_zone_type* zone)
    979 {
    980 	/* if in TCP transaction, stop it immediately. */
    981 	if(zone->tcp_conn != -1)
    982 		xfrd_tcp_release(xfrd->tcp_set, zone);
    983 	else if(zone->zone_handler.ev_fd != -1)
    984 		xfrd_udp_release(zone);
    985 	/* pretend we not longer have it and force any
    986 	 * zone to be downloaded (even same serial, w AXFR) */
    987 	zone->soa_disk_acquired = 0;
    988 	zone->soa_nsd_acquired = 0;
    989 	xfrd_handle_notify_and_start_xfr(zone, NULL);
    990 }
    991 
    992 /** do the force transfer command */
    993 static void
    994 do_force_transfer(RES* ssl, xfrd_state_type* xfrd, char* arg)
    995 {
    996 	struct zone_options* zo;
    997 	xfrd_zone_type* zone;
    998 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
    999 		return;
   1000 	if(zo) {
   1001 		zone = (xfrd_zone_type*)rbtree_search(xfrd->zones, (const
   1002 			dname_type*)zo->node.key);
   1003 		if(zone) {
   1004 			force_transfer_zone(zone);
   1005 			send_ok(ssl);
   1006 		} else {
   1007 			(void)ssl_printf(ssl, "error zone not secondary\n");
   1008 		}
   1009 	} else {
   1010 		RBTREE_FOR(zone, xfrd_zone_type*, xfrd->zones) {
   1011 			force_transfer_zone(zone);
   1012 		}
   1013 		(void)ssl_printf(ssl, "ok, %lu zones\n", (unsigned long)xfrd->zones->count);
   1014 	}
   1015 }
   1016 
   1017 static int
   1018 print_soa_status(RES* ssl, const char* str, xfrd_soa_type* soa, time_t acq)
   1019 {
   1020 	if(acq) {
   1021 		if(!ssl_printf(ssl, "	%s: \"%u since %s\"\n", str,
   1022 			(unsigned)ntohl(soa->serial), xfrd_pretty_time(acq)))
   1023 			return 0;
   1024 	} else {
   1025 		if(!ssl_printf(ssl, "	%s: none\n", str))
   1026 			return 0;
   1027 	}
   1028 	return 1;
   1029 }
   1030 
   1031 /** print zonestatus for one domain */
   1032 static int
   1033 print_zonestatus(RES* ssl, xfrd_state_type* xfrd, struct zone_options* zo)
   1034 {
   1035 	xfrd_zone_type* xz = (xfrd_zone_type*)rbtree_search(xfrd->zones,
   1036 		(const dname_type*)zo->node.key);
   1037 	struct notify_zone* nz = (struct notify_zone*)rbtree_search(
   1038 		xfrd->notify_zones, (const dname_type*)zo->node.key);
   1039 	if(!ssl_printf(ssl, "zone:	%s\n", zo->name))
   1040 		return 0;
   1041 	if(!zo->part_of_config) {
   1042 		if(!ssl_printf(ssl, "	pattern: %s\n", zo->pattern->pname))
   1043 			return 0;
   1044 	}
   1045 	if(zone_is_catalog_consumer(zo)) {
   1046 		uint32_t serial = 0;
   1047 		zone_type* zone = namedb_find_zone(xfrd->nsd->db,
   1048 				(const dname_type*)zo->node.key);
   1049 		struct xfrd_catalog_consumer_zone* consumer_zone =
   1050 			(struct xfrd_catalog_consumer_zone*)
   1051 			rbtree_search( xfrd->catalog_consumer_zones
   1052 			             , zo->node.key);
   1053 
   1054 		if(!ssl_printf(ssl, "	catalog: consumer"))
   1055 			return 0;
   1056 		if(zone && zone->soa_rrset && zone->soa_rrset->rrs
   1057 		&& retrieve_soa_rdata_serial(zone->soa_rrset->rrs[0],
   1058 			&serial)) {
   1059 			if(!ssl_printf(ssl, " (serial: %u, # members: %zu)\n",
   1060 					serial,
   1061 					  consumer_zone
   1062 					? consumer_zone->member_ids.count : 0))
   1063 				return 0;
   1064 
   1065 		} else if(!ssl_printf(ssl, "\n"))
   1066 			return 0;
   1067 		if(invalid_catalog_consumer_zone(zo)) {
   1068 			if(!ssl_printf(ssl, "	catalog-invalid: %s\n",
   1069 					invalid_catalog_consumer_zone(zo)))
   1070 				return 0;
   1071 		}
   1072 	}
   1073 	if(zone_is_catalog_producer(zo)) {
   1074 		struct xfrd_catalog_producer_zone* producer_zone =
   1075 			(struct xfrd_catalog_producer_zone*)
   1076 			rbtree_search( xfrd->catalog_producer_zones
   1077 			             , zo->node.key);
   1078 		if(!ssl_printf(ssl, "	catalog: producer"))
   1079 			return 0;
   1080 		if(producer_zone) {
   1081 			if(!ssl_printf(ssl, " (serial: %u, # members: %zu)\n",
   1082 					(unsigned)producer_zone->serial,
   1083 				       	producer_zone->member_ids.count))
   1084 				return 0;
   1085 		} else if(!ssl_printf(ssl, "\n"))
   1086 			return 0;
   1087 		if (zone_is_slave(zo)) {
   1088 			if(!ssl_printf(ssl, "	catalog-invalid: a catalog "
   1089 					"producer cannot be a secondary zone"))
   1090 				return 0;
   1091 		}
   1092 	}
   1093 	if(zone_is_catalog_member(zo)) {
   1094 		if(!ssl_printf(ssl, "	catalog-member-id: %s\n",
   1095 		   as_catalog_member_zone(zo)->member_id
   1096 		 ? dname_to_string(as_catalog_member_zone(zo)->member_id, NULL)
   1097 		 : "ERROR member-id is missing!"))
   1098 			return 0;
   1099 	}
   1100 	if(nz) {
   1101 		if(nz->is_waiting) {
   1102 			if(!ssl_printf(ssl, "	notify: \"waiting-for-fd\"\n"))
   1103 				return 0;
   1104 		} else if(nz->notify_send_enable || nz->notify_send6_enable) {
   1105 			int i;
   1106 			if(!ssl_printf(ssl, "	notify: \"send"))
   1107 				return 0;
   1108 			for(i=0; i<NOTIFY_CONCURRENT_MAX; i++) {
   1109 				if(!nz->pkts[i].dest) continue;
   1110 				if(!ssl_printf(ssl, " %s",
   1111 					nz->pkts[i].dest->ip_address_spec))
   1112 					return 0;
   1113 			}
   1114 			if(!ssl_printf(ssl, " with serial %u\"\n",
   1115 				(unsigned)ntohl(nz->current_soa->serial)))
   1116 				return 0;
   1117 		}
   1118 	}
   1119 	if(!xz) {
   1120 		if(!ssl_printf(ssl, "	state: primary\n"))
   1121 			return 0;
   1122 		return 1;
   1123 	}
   1124 	if(!ssl_printf(ssl, "	state: %s\n",
   1125 	     xz->state == xfrd_zone_expired                  ? "expired"
   1126 	   : xz->state != xfrd_zone_ok                       ? "refreshing"
   1127 	   : !xz->soa_nsd_acquired || !xz->soa_disk_acquired
   1128 	   || xz->soa_nsd.serial   ==  xz->soa_disk.serial   ? "ok"
   1129 	   : compare_serial( ntohl(xz->soa_nsd.serial)
   1130 	                   , ntohl(xz->soa_disk.serial)) < 0 ? "old-serial"
   1131 	                                                     : "future-serial"))
   1132 		return 0;
   1133 	if(!print_soa_status(ssl, "served-serial", &xz->soa_nsd,
   1134 		xz->soa_nsd_acquired))
   1135 		return 0;
   1136 	if(!print_soa_status(ssl, "commit-serial", &xz->soa_disk,
   1137 		xz->soa_disk_acquired))
   1138 		return 0;
   1139 	if(xz->round_num != -1) {
   1140 		if(!print_soa_status(ssl, "notified-serial", &xz->soa_notified,
   1141 			xz->soa_notified_acquired))
   1142 			return 0;
   1143 	} else if(xz->event_added) {
   1144 		if(!ssl_printf(ssl, "\twait: \"%lu sec between attempts\"\n",
   1145 			(unsigned long)xz->timeout.tv_sec))
   1146 			return 0;
   1147 	}
   1148 
   1149 	/* UDP */
   1150 	if(xz->udp_waiting) {
   1151 		if(!ssl_printf(ssl, "	transfer: \"waiting-for-UDP-fd\"\n"))
   1152 			return 0;
   1153 	} else if(xz->zone_handler.ev_fd != -1 && xz->tcp_conn == -1) {
   1154 		if(!ssl_printf(ssl, "	transfer: \"sent UDP to %s\"\n",
   1155 			xz->master->ip_address_spec))
   1156 			return 0;
   1157 	}
   1158 
   1159 	/* TCP */
   1160 	if(xz->tcp_waiting) {
   1161 		if(!ssl_printf(ssl, "	transfer: \"waiting-for-TCP-fd\"\n"))
   1162 			return 0;
   1163 	} else if(xz->tcp_conn != -1) {
   1164 		if(!ssl_printf(ssl, "	transfer: \"TCP connected to %s\"\n",
   1165 			xz->master->ip_address_spec))
   1166 			return 0;
   1167 	}
   1168 
   1169 	return 1;
   1170 }
   1171 
   1172 /** do the zonestatus command */
   1173 static void
   1174 do_zonestatus(RES* ssl, xfrd_state_type* xfrd, char* arg)
   1175 {
   1176 	struct zone_options* zo;
   1177 	if(!get_zone_arg(ssl, xfrd, arg, &zo))
   1178 		return;
   1179 	if(zo) (void)print_zonestatus(ssl, xfrd, zo);
   1180 	else {
   1181 		RBTREE_FOR(zo, struct zone_options*,
   1182 			xfrd->nsd->options->zone_options) {
   1183 			if(!print_zonestatus(ssl, xfrd, zo))
   1184 				return;
   1185 		}
   1186 	}
   1187 }
   1188 
   1189 /** do the verbosity command */
   1190 static void
   1191 do_verbosity(RES* ssl, char* str)
   1192 {
   1193 	int val = atoi(str);
   1194 	if(strcmp(str, "") == 0) {
   1195 		(void)ssl_printf(ssl, "verbosity %d\n", verbosity);
   1196 		return;
   1197 	}
   1198 	if(val == 0 && strcmp(str, "0") != 0) {
   1199 		(void)ssl_printf(ssl, "error in verbosity number syntax: %s\n", str);
   1200 		return;
   1201 	}
   1202 	verbosity = val;
   1203 	task_new_set_verbosity(xfrd->nsd->task[xfrd->nsd->mytask],
   1204 		xfrd->last_task, val);
   1205 	xfrd_set_reload_now(xfrd);
   1206 	send_ok(ssl);
   1207 }
   1208 
   1209 /** find second argument, modifies string */
   1210 static int
   1211 find_arg2(RES* ssl, char* arg, char** arg2)
   1212 {
   1213 	char* as = strrchr(arg, ' ');
   1214 	if(as) {
   1215 		as[0]=0;
   1216 		*arg2 = as+1;
   1217 		while(isspace((unsigned char)*as) && as > arg)
   1218 			as--;
   1219 		as[0]=0;
   1220 		return 1;
   1221 	}
   1222 	*arg2 = NULL;
   1223 	(void)ssl_printf(ssl, "error could not find next argument "
   1224 		"after %s\n", arg);
   1225 	return 0;
   1226 }
   1227 
   1228 /** find second and third arguments, modifies string,
   1229  * does not print error for missing arg3 so that if it does not find an
   1230  * arg3, the caller can use two arguments. */
   1231 static int
   1232 find_arg3(RES* ssl, char* arg, char** arg2, char** arg3)
   1233 {
   1234 	if(find_arg2(ssl, arg, arg2)) {
   1235 		char* as;
   1236 		*arg3 = *arg2;
   1237 		as = strrchr(arg, ' ');
   1238 		if(as) {
   1239 			as[0]=0;
   1240 			*arg2 = as+1;
   1241 			while(isspace((unsigned char)*as) && as > arg)
   1242 				as--;
   1243 			as[0]=0;
   1244 			return 1;
   1245 		}
   1246 	}
   1247 	*arg3 = NULL;
   1248 	return 0;
   1249 }
   1250 
   1251 /** do the status command */
   1252 static void
   1253 do_status(RES* ssl, xfrd_state_type* xfrd)
   1254 {
   1255 	if(!ssl_printf(ssl, "version: %s\n", PACKAGE_VERSION))
   1256 		return;
   1257 	if(!ssl_printf(ssl, "verbosity: %d\n", verbosity))
   1258 		return;
   1259 #ifdef RATELIMIT
   1260 	if(!ssl_printf(ssl, "ratelimit: %d\n",
   1261 		(int)xfrd->nsd->options->rrl_ratelimit))
   1262 		return;
   1263 #else
   1264 	(void)xfrd;
   1265 #endif
   1266 }
   1267 
   1268 /** do the stats command */
   1269 static void
   1270 do_stats(RES* ssl, xfrd_state_type* xfrd, int peek)
   1271 {
   1272 #ifdef BIND8_STATS
   1273 	process_stats(ssl, NULL, xfrd, peek);
   1274 #else
   1275 	(void)xfrd; (void)peek;
   1276 	(void)ssl_printf(ssl, "error no stats enabled at compile time\n");
   1277 #endif /* BIND8_STATS */
   1278 }
   1279 
   1280 /** see if we have more zonestatistics entries and it has to be incremented */
   1281 static void
   1282 zonestat_inc_ifneeded(xfrd_state_type* xfrd)
   1283 {
   1284 #ifdef USE_ZONE_STATS
   1285 	if(xfrd->nsd->options->zonestatnames->count != xfrd->zonestat_safe)
   1286 		task_new_zonestat_inc(xfrd->nsd->task[xfrd->nsd->mytask],
   1287 			xfrd->last_task,
   1288 			xfrd->nsd->options->zonestatnames->count);
   1289 #else
   1290 	(void)xfrd;
   1291 #endif /* USE_ZONE_STATS */
   1292 }
   1293 
   1294 /** perform the changezone command for one zone */
   1295 static int
   1296 perform_changezone(RES* ssl, xfrd_state_type* xfrd, char* arg)
   1297 {
   1298 	const dname_type* dname;
   1299 	struct zone_options* zopt;
   1300 	char* arg2 = NULL;
   1301 	if(!find_arg2(ssl, arg, &arg2))
   1302 		return 0;
   1303 
   1304 	/* if we add it to the xfrd now, then xfrd could download AXFR and
   1305 	 * store it and the NSD-reload would see it in the difffile before
   1306 	 * it sees the add-config task.
   1307 	 */
   1308 	/* thus: AXFRs and IXFRs must store the pattern name in the
   1309 	 * difffile, so that it can be added when the AXFR or IXFR is seen.
   1310 	 */
   1311 
   1312 	/* check that the pattern exists */
   1313 	if(!rbtree_search(xfrd->nsd->options->patterns, arg2)) {
   1314 		(void)ssl_printf(ssl, "error pattern %s does not exist\n",
   1315 			arg2);
   1316 		return 0;
   1317 	}
   1318 
   1319 	dname = dname_parse(xfrd->region, arg);
   1320 	if(!dname) {
   1321 		(void)ssl_printf(ssl, "error cannot parse zone name\n");
   1322 		return 0;
   1323 	}
   1324 
   1325 	/* see if zone is a duplicate */
   1326 	if( (zopt=zone_options_find(xfrd->nsd->options, dname)) ) {
   1327 		if(zopt->part_of_config) {
   1328 			(void)ssl_printf(ssl, "error zone defined in nsd.conf, "
   1329 			  "cannot delete it in this manner: remove it from "
   1330 			  "nsd.conf yourself and repattern\n");
   1331 			region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
   1332 			dname = NULL;
   1333 			return 0;
   1334 		}
   1335 		if(zone_is_catalog_consumer_member(zopt)) {
   1336 			(void)ssl_printf(ssl, "Error: Zone is a catalog "
   1337 			  "consumer member zone with id %s\nRepattern in the "
   1338 			  "catalog with a group property.\n", dname_to_string(
   1339 			  as_catalog_member_zone(zopt)->member_id, NULL));
   1340 			region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
   1341 			dname = NULL;
   1342 			return 0;
   1343 		}
   1344 		/* found the zone, now delete it */
   1345 		/* create deletion task */
   1346 		/* this deletion task is processed before the addition task,
   1347 		 * that is created below, in the same reload process, causing
   1348 		 * a seamless change from one to the other, with no downtime
   1349 		 * for the zone. */
   1350 		task_new_del_zone(xfrd->nsd->task[xfrd->nsd->mytask],
   1351 			xfrd->last_task, dname);
   1352 		xfrd_set_reload_now(xfrd);
   1353 		/* delete it in xfrd */
   1354 		if(zone_is_slave(zopt)) {
   1355 			xfrd_del_slave_zone(xfrd, dname);
   1356 		}
   1357 		xfrd_del_notify(xfrd, dname);
   1358 		/* delete it in xfrd's catalog consumers list */
   1359 		if(zone_is_catalog_consumer(zopt)) {
   1360 			xfrd_deinit_catalog_consumer_zone(xfrd, dname);
   1361 		}
   1362 		/* delete from config */
   1363 		zone_list_del(xfrd->nsd->options, zopt);
   1364 	} else {
   1365 		(void)ssl_printf(ssl, "zone %s did not exist, creating", arg);
   1366 	}
   1367 	region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
   1368 	dname = NULL;
   1369 
   1370 	/* add to zonelist and adds to config in memory */
   1371 	zopt = zone_list_add_or_cat(xfrd->nsd->options, arg, arg2,
   1372 			xfrd_add_catalog_producer_member);
   1373 	if(!zopt) {
   1374 		/* also dname parse error here */
   1375 		(void)ssl_printf(ssl, "error could not add zonelist entry\n");
   1376 		return 0;
   1377 	}
   1378 	/* make addzone task and schedule reload */
   1379 	task_new_add_zone(xfrd->nsd->task[xfrd->nsd->mytask],
   1380 		xfrd->last_task, arg, arg2,
   1381 		getzonestatid(xfrd->nsd->options, zopt));
   1382 	zonestat_inc_ifneeded(xfrd);
   1383 	xfrd_set_reload_now(xfrd);
   1384 	/* add to xfrd - catalog consumer zones */
   1385 	if (zone_is_catalog_consumer(zopt)) {
   1386 		xfrd_init_catalog_consumer_zone(xfrd, zopt);
   1387 	}
   1388 	/* add to xfrd - notify (for master and slaves) */
   1389 	init_notify_send(xfrd->notify_zones, xfrd->region, zopt);
   1390 	/* add to xfrd - slave */
   1391 	if(zone_is_slave(zopt)) {
   1392 		xfrd_init_slave_zone(xfrd, zopt);
   1393 	}
   1394 	return 1;
   1395 }
   1396 
   1397 /** perform the addzone command for one zone */
   1398 static int
   1399 perform_addzone(RES* ssl, xfrd_state_type* xfrd, char* arg)
   1400 {
   1401 	const dname_type* dname;
   1402 	struct zone_options* zopt;
   1403 	char* arg2 = NULL;
   1404 	if(!find_arg2(ssl, arg, &arg2))
   1405 		return 0;
   1406 
   1407 	/* if we add it to the xfrd now, then xfrd could download AXFR and
   1408 	 * store it and the NSD-reload would see it in the difffile before
   1409 	 * it sees the add-config task.
   1410 	 */
   1411 	/* thus: AXFRs and IXFRs must store the pattern name in the
   1412 	 * difffile, so that it can be added when the AXFR or IXFR is seen.
   1413 	 */
   1414 
   1415 	/* check that the pattern exists */
   1416 	if(!rbtree_search(xfrd->nsd->options->patterns, arg2)) {
   1417 		(void)ssl_printf(ssl, "error pattern %s does not exist\n",
   1418 			arg2);
   1419 		return 0;
   1420 	}
   1421 
   1422 	dname = dname_parse(xfrd->region, arg);
   1423 	if(!dname) {
   1424 		(void)ssl_printf(ssl, "error cannot parse zone name\n");
   1425 		return 0;
   1426 	}
   1427 
   1428 	/* see if zone is a duplicate */
   1429 	if( zone_options_find(xfrd->nsd->options, dname) ) {
   1430 		region_recycle(xfrd->region, (void*)dname,
   1431 			dname_total_size(dname));
   1432 		(void)ssl_printf(ssl, "zone %s already exists\n", arg);
   1433 		return 1;
   1434 	}
   1435 	region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
   1436 	dname = NULL;
   1437 
   1438 	/* add to zonelist and adds to config in memory */
   1439 	zopt = zone_list_add_or_cat(xfrd->nsd->options, arg, arg2,
   1440 			xfrd_add_catalog_producer_member);
   1441 	if(!zopt) {
   1442 		/* also dname parse error here */
   1443 		(void)ssl_printf(ssl, "error could not add zonelist entry\n");
   1444 		return 0;
   1445 	}
   1446 	/* make addzone task and schedule reload */
   1447 	task_new_add_zone(xfrd->nsd->task[xfrd->nsd->mytask],
   1448 		xfrd->last_task, arg, arg2,
   1449 		getzonestatid(xfrd->nsd->options, zopt));
   1450 	zonestat_inc_ifneeded(xfrd);
   1451 	xfrd_set_reload_now(xfrd);
   1452 	/* add to xfrd - catalog consumer zones */
   1453 	if (zone_is_catalog_consumer(zopt)) {
   1454 		xfrd_init_catalog_consumer_zone(xfrd, zopt);
   1455 	}
   1456 	/* add to xfrd - notify (for master and slaves) */
   1457 	init_notify_send(xfrd->notify_zones, xfrd->region, zopt);
   1458 	/* add to xfrd - slave */
   1459 	if(zone_is_slave(zopt)) {
   1460 		xfrd_init_slave_zone(xfrd, zopt);
   1461 	}
   1462 	return 1;
   1463 }
   1464 
   1465 /** perform the delzone command for one zone */
   1466 static int
   1467 perform_delzone(RES* ssl, xfrd_state_type* xfrd, char* arg)
   1468 {
   1469 	const dname_type* dname;
   1470 	struct zone_options* zopt;
   1471 	/* dont recycle dname when it becomes part of a xfrd_producer_member */
   1472 	int recycle_dname = 1;
   1473 
   1474 	dname = dname_parse(xfrd->region, arg);
   1475 	if(!dname) {
   1476 		(void)ssl_printf(ssl, "error cannot parse zone name\n");
   1477 		return 0;
   1478 	}
   1479 
   1480 	/* see if we have the zone in question */
   1481 	zopt = zone_options_find(xfrd->nsd->options, dname);
   1482 	if(!zopt) {
   1483 		region_recycle(xfrd->region, (void*)dname,
   1484 			dname_total_size(dname));
   1485 		/* nothing to do */
   1486 		(void)ssl_printf(ssl, "warning zone %s not present\n", arg);
   1487 		return 0;
   1488 	}
   1489 
   1490 	/* see if it can be deleted */
   1491 	if(zopt->part_of_config) {
   1492 		region_recycle(xfrd->region, (void*)dname,
   1493 			dname_total_size(dname));
   1494 		(void)ssl_printf(ssl, "error zone defined in nsd.conf, "
   1495 			"cannot delete it in this manner: remove it from "
   1496 			"nsd.conf yourself and repattern\n");
   1497 		return 0;
   1498 	}
   1499 	if(zone_is_catalog_consumer_member(zopt)
   1500 	&& as_catalog_member_zone(zopt)->member_id) {
   1501 		(void)ssl_printf(ssl, "Error: Zone is a catalog consumer "
   1502 		  "member zone with id %s\nRemove the member id from the "
   1503 		  "catalog to delete this zone.\n", dname_to_string(
   1504 		  as_catalog_member_zone(zopt)->member_id, NULL));
   1505 		region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
   1506 		dname = NULL;
   1507 		return 0;
   1508 
   1509 	}
   1510 	/* create deletion task */
   1511 	task_new_del_zone(xfrd->nsd->task[xfrd->nsd->mytask],
   1512 		xfrd->last_task, dname);
   1513 	xfrd_set_reload_now(xfrd);
   1514 	/* delete it in xfrd */
   1515 	if(zone_is_slave(zopt)) {
   1516 		xfrd_del_slave_zone(xfrd, dname);
   1517 	}
   1518 	xfrd_del_notify(xfrd, dname);
   1519 	/* delete it in xfrd's catalog consumers list */
   1520 	if(zone_is_catalog_consumer(zopt)) {
   1521 		xfrd_deinit_catalog_consumer_zone(xfrd, dname);
   1522 	} else {
   1523 		recycle_dname = !xfrd_del_catalog_producer_member(xfrd, dname);
   1524 	}
   1525 	/* delete from config */
   1526 	zone_list_del(xfrd->nsd->options, zopt);
   1527 
   1528 	if(recycle_dname)
   1529 		region_recycle(xfrd->region,
   1530 				(void*)dname, dname_total_size(dname));
   1531 	return 1;
   1532 }
   1533 
   1534 /** do the addzone command */
   1535 static void
   1536 do_addzone(RES* ssl, xfrd_state_type* xfrd, char* arg)
   1537 {
   1538 	if(!perform_addzone(ssl, xfrd, arg))
   1539 		return;
   1540 	send_ok(ssl);
   1541 }
   1542 
   1543 /** do the delzone command */
   1544 static void
   1545 do_delzone(RES* ssl, xfrd_state_type* xfrd, char* arg)
   1546 {
   1547 	if(!perform_delzone(ssl, xfrd, arg))
   1548 		return;
   1549 	send_ok(ssl);
   1550 }
   1551 
   1552 /** do the changezone command */
   1553 static void
   1554 do_changezone(RES* ssl, xfrd_state_type* xfrd, char* arg)
   1555 {
   1556 	if(!perform_changezone(ssl, xfrd, arg))
   1557 		return;
   1558 	send_ok(ssl);
   1559 }
   1560 
   1561 /** do the addzones command */
   1562 static void
   1563 do_addzones(RES* ssl, xfrd_state_type* xfrd)
   1564 {
   1565 	char buf[2048];
   1566 	int num = 0;
   1567 	while(ssl_read_line(ssl, buf, sizeof(buf))) {
   1568 		if(buf[0] == 0x04 && buf[1] == 0)
   1569 			break; /* end of transmission */
   1570 		if(!perform_addzone(ssl, xfrd, buf)) {
   1571 			if(!ssl_printf(ssl, "error for input line '%s'\n",
   1572 				buf))
   1573 				return;
   1574 		} else {
   1575 			if(!ssl_printf(ssl, "added: %s\n", buf))
   1576 				return;
   1577 			num++;
   1578 		}
   1579 	}
   1580 	(void)ssl_printf(ssl, "added %d zones\n", num);
   1581 }
   1582 
   1583 /** do the delzones command */
   1584 static void
   1585 do_delzones(RES* ssl, xfrd_state_type* xfrd)
   1586 {
   1587 	char buf[2048];
   1588 	int num = 0;
   1589 	while(ssl_read_line(ssl, buf, sizeof(buf))) {
   1590 		if(buf[0] == 0x04 && buf[1] == 0)
   1591 			break; /* end of transmission */
   1592 		if(!perform_delzone(ssl, xfrd, buf)) {
   1593 			if(!ssl_printf(ssl, "error for input line '%s'\n",
   1594 				buf))
   1595 				return;
   1596 		} else {
   1597 			if(!ssl_printf(ssl, "removed: %s\n", buf))
   1598 				return;
   1599 			num++;
   1600 		}
   1601 	}
   1602 	(void)ssl_printf(ssl, "deleted %d zones\n", num);
   1603 }
   1604 
   1605 
   1606 /** remove TSIG key from config and add task so that reload does too */
   1607 static void remove_key(xfrd_state_type* xfrd, const char* kname)
   1608 {
   1609 	/* add task before deletion because the name string could be deleted */
   1610 	task_new_del_key(xfrd->nsd->task[xfrd->nsd->mytask], xfrd->last_task,
   1611 		kname);
   1612 	key_options_remove(xfrd->nsd->options, kname);
   1613 	xfrd_set_reload_now(xfrd); /* this is executed when the current control
   1614 		command ends, thus the entire config changes are bunched up */
   1615 }
   1616 
   1617 /** add TSIG key to config and add task so that reload does too */
   1618 static void add_key(xfrd_state_type* xfrd, struct key_options* k)
   1619 {
   1620 	key_options_add_modify(xfrd->nsd->options, k);
   1621 	task_new_add_key(xfrd->nsd->task[xfrd->nsd->mytask], xfrd->last_task,
   1622 		k);
   1623 	xfrd_set_reload_now(xfrd);
   1624 }
   1625 
   1626 /** check if keys have changed */
   1627 static void repat_keys(xfrd_state_type* xfrd, struct nsd_options* newopt)
   1628 {
   1629 	struct nsd_options* oldopt = xfrd->nsd->options;
   1630 	struct key_options* k;
   1631 	/* find deleted keys */
   1632 	k = (struct key_options*)rbtree_first(oldopt->keys);
   1633 	while((rbnode_type*)k != RBTREE_NULL) {
   1634 		struct key_options* next = (struct key_options*)rbtree_next(
   1635 			(rbnode_type*)k);
   1636 		if(!key_options_find(newopt, k->name))
   1637 			remove_key(xfrd, k->name);
   1638 		k = next;
   1639 	}
   1640 	/* find added or changed keys */
   1641 	RBTREE_FOR(k, struct key_options*, newopt->keys) {
   1642 		struct key_options* origk = key_options_find(oldopt, k->name);
   1643 		if(!origk)
   1644 			add_key(xfrd, k);
   1645 		else if(!key_options_equal(k, origk))
   1646 			add_key(xfrd, k);
   1647 	}
   1648 }
   1649 
   1650 /** find zone given the implicit pattern */
   1651 static const dname_type*
   1652 parse_implicit_name(xfrd_state_type* xfrd,const char* pname)
   1653 {
   1654 	if(strncmp(pname, PATTERN_IMPLICIT_MARKER,
   1655 		strlen(PATTERN_IMPLICIT_MARKER)) != 0)
   1656 		return NULL;
   1657 	return dname_parse(xfrd->region, pname +
   1658 		strlen(PATTERN_IMPLICIT_MARKER));
   1659 }
   1660 
   1661 /** remove cfgzone and add task so that reload does too */
   1662 static void
   1663 remove_cfgzone(xfrd_state_type* xfrd, const char* pname)
   1664 {
   1665 	/* dname and find the zone for the implicit pattern */
   1666 	struct zone_options* zopt = NULL;
   1667 	const dname_type* dname = parse_implicit_name(xfrd, pname);
   1668 	if(!dname) {
   1669 		/* should have a parseable name, but it did not */
   1670 		return;
   1671 	}
   1672 
   1673 	/* find the zone entry for the implicit pattern */
   1674 	zopt = zone_options_find(xfrd->nsd->options, dname);
   1675 	if(!zopt) {
   1676 		/* this should not happen; implicit pattern has zone entry */
   1677 		region_recycle(xfrd->region, (void*)dname,
   1678 			dname_total_size(dname));
   1679 		return;
   1680 	}
   1681 
   1682 	/* create deletion task */
   1683 	task_new_del_zone(xfrd->nsd->task[xfrd->nsd->mytask],
   1684 		xfrd->last_task, dname);
   1685 	xfrd_set_reload_now(xfrd);
   1686 	/* delete it in xfrd */
   1687 	if(zone_is_slave(zopt)) {
   1688 		xfrd_del_slave_zone(xfrd, dname);
   1689 	}
   1690 	xfrd_del_notify(xfrd, dname);
   1691 	/* delete it in xfrd's catalog consumers list */
   1692 	if(zone_is_catalog_consumer(zopt)) {
   1693 		xfrd_deinit_catalog_consumer_zone(xfrd, dname);
   1694 	}
   1695 
   1696 	/* delete from zoneoptions */
   1697 	zone_options_delete(xfrd->nsd->options, zopt);
   1698 
   1699 	/* recycle parsed dname */
   1700 	region_recycle(xfrd->region, (void*)dname, dname_total_size(dname));
   1701 }
   1702 
   1703 /** add cfgzone and add task so that reload does too */
   1704 static void
   1705 add_cfgzone(xfrd_state_type* xfrd, const char* pname)
   1706 {
   1707 	/* add to our zonelist */
   1708 	struct zone_options* zopt = zone_options_create(
   1709 		xfrd->nsd->options->region);
   1710 	if(!zopt)
   1711 		return;
   1712 	zopt->part_of_config = 1;
   1713 	zopt->name = region_strdup(xfrd->nsd->options->region,
   1714 		pname + strlen(PATTERN_IMPLICIT_MARKER));
   1715 	zopt->pattern = pattern_options_find(xfrd->nsd->options, pname);
   1716 	if(!zopt->name || !zopt->pattern)
   1717 		return;
   1718 	if(!nsd_options_insert_zone(xfrd->nsd->options, zopt)) {
   1719 		log_msg(LOG_ERR, "bad domain name or duplicate zone '%s' "
   1720 			"pattern %s", zopt->name, pname);
   1721 	}
   1722 
   1723 	/* make addzone task and schedule reload */
   1724 	task_new_add_zone(xfrd->nsd->task[xfrd->nsd->mytask],
   1725 		xfrd->last_task, zopt->name, pname,
   1726 		getzonestatid(xfrd->nsd->options, zopt));
   1727 	/* zonestat_inc is done after the entire config file has been done */
   1728 	xfrd_set_reload_now(xfrd);
   1729 	/* add to xfrd - catalog consumer zones */
   1730 	if (zone_is_catalog_consumer(zopt)) {
   1731 		xfrd_init_catalog_consumer_zone(xfrd, zopt);
   1732 	}
   1733 	/* add to xfrd - notify (for master and slaves) */
   1734 	init_notify_send(xfrd->notify_zones, xfrd->region, zopt);
   1735 	/* add to xfrd - slave */
   1736 	if(zone_is_slave(zopt)) {
   1737 		xfrd_init_slave_zone(xfrd, zopt);
   1738 	}
   1739 }
   1740 
   1741 /** remove pattern and add task so that reload does too */
   1742 static void
   1743 remove_pat(xfrd_state_type* xfrd, const char* name)
   1744 {
   1745 	/* add task before deletion, because name-string could be deleted */
   1746 	task_new_del_pattern(xfrd->nsd->task[xfrd->nsd->mytask],
   1747 		xfrd->last_task, name);
   1748 	pattern_options_remove(xfrd->nsd->options, name);
   1749 	xfrd_set_reload_now(xfrd);
   1750 }
   1751 
   1752 /** add pattern and add task so that reload does too */
   1753 static void
   1754 add_pat(xfrd_state_type* xfrd, struct pattern_options* p)
   1755 {
   1756 	pattern_options_add_modify(xfrd->nsd->options, p);
   1757 	task_new_add_pattern(xfrd->nsd->task[xfrd->nsd->mytask],
   1758 		xfrd->last_task, p);
   1759 	xfrd_set_reload_now(xfrd);
   1760 }
   1761 
   1762 /** check if a zone's transfer configuration has actually changed */
   1763 static int
   1764 zone_transfer_config_changed(xfrd_zone_type* xz, struct pattern_options* oldp, struct pattern_options* newp)
   1765 {
   1766 	/* If pattern doesn't exist in new config, we must interrupt */
   1767 	if(!newp) {
   1768 		VERBOSITY(1, (LOG_INFO, "zone %s: pattern removed, interrupting transfer",
   1769 			xz->zone_options->name));
   1770 		return 1;
   1771 	}
   1772 
   1773 	/* Check if request_xfr ACL list has changed */
   1774 	/* This also tests for TSIG key name changes. */
   1775 	if(!acl_list_equal(oldp->request_xfr, newp->request_xfr)) {
   1776 		VERBOSITY(1, (LOG_INFO, "zone %s: request_xfr ACL changed, interrupting transfer",
   1777 			xz->zone_options->name));
   1778 		return 1;
   1779 	}
   1780 
   1781 	/* Check if other transfer-related settings have changed */
   1782 	if(oldp->size_limit_xfr != newp->size_limit_xfr) {
   1783 		VERBOSITY(1, (LOG_INFO, "zone %s: size_limit_xfr changed, interrupting transfer",
   1784 			xz->zone_options->name));
   1785 		return 1;
   1786 	}
   1787 
   1788 	if(oldp->allow_axfr_fallback != newp->allow_axfr_fallback) {
   1789 		VERBOSITY(1, (LOG_INFO, "zone %s: allow_axfr_fallback changed, interrupting transfer",
   1790 			xz->zone_options->name));
   1791 		return 1;
   1792 	}
   1793 
   1794 	if(oldp->max_refresh_time != newp->max_refresh_time) {
   1795 		VERBOSITY(1, (LOG_INFO, "zone %s: max_refresh_time changed, interrupting transfer",
   1796 			xz->zone_options->name));
   1797 		return 1;
   1798 	}
   1799 
   1800 	if(oldp->min_refresh_time != newp->min_refresh_time) {
   1801 		VERBOSITY(1, (LOG_INFO, "zone %s: min_refresh_time changed, interrupting transfer",
   1802 			xz->zone_options->name));
   1803 		return 1;
   1804 	}
   1805 
   1806 	if(oldp->max_retry_time != newp->max_retry_time) {
   1807 		VERBOSITY(1, (LOG_INFO, "zone %s: max_retry_time changed, interrupting transfer",
   1808 			xz->zone_options->name));
   1809 		return 1;
   1810 	}
   1811 
   1812 	if(oldp->min_retry_time != newp->min_retry_time) {
   1813 		VERBOSITY(1, (LOG_INFO, "zone %s: min_retry_time changed, interrupting transfer",
   1814 			xz->zone_options->name));
   1815 		return 1;
   1816 	}
   1817 
   1818 	if(oldp->min_expire_time != newp->min_expire_time) {
   1819 		VERBOSITY(1, (LOG_INFO, "zone %s: min_expire_time changed, interrupting transfer",
   1820 			xz->zone_options->name));
   1821 		return 1;
   1822 	}
   1823 
   1824 	/* No significant changes detected */
   1825 	/* Suppress logging when no changes detected to reduce log noise */
   1826 	return 0;
   1827 }
   1828 
   1829 /** check if a zone's notify configuration has actually changed */
   1830 static int
   1831 zone_notify_config_changed(struct notify_zone* nz, struct pattern_options* oldp, struct pattern_options* newp)
   1832 {
   1833 	/* If pattern doesn't exist in new config, we must interrupt */
   1834 	if(!newp) {
   1835 		VERBOSITY(1, (LOG_INFO, "notify zone %s: pattern removed, interrupting notify",
   1836 			nz->options->name));
   1837 		return 1;
   1838 	}
   1839 
   1840 	/* Check if notify ACL list has changed */
   1841 	/* This also tests for TSIG key name changes. */
   1842 	if(!acl_list_equal(oldp->notify, newp->notify)) {
   1843 		VERBOSITY(1, (LOG_INFO, "notify zone %s: notify ACL changed, interrupting notify",
   1844 			nz->options->name));
   1845 		return 1;
   1846 	}
   1847 
   1848 	/* Check if notify-related settings have changed */
   1849 	if(oldp->notify_retry != newp->notify_retry) {
   1850 		VERBOSITY(1, (LOG_INFO, "notify zone %s: notify_retry changed, interrupting notify",
   1851 			nz->options->name));
   1852 		return 1;
   1853 	}
   1854 
   1855 	/* No significant changes detected */
   1856 	/* Suppress logging when no changes detected to reduce log noise */
   1857 	return 0;
   1858 }
   1859 
   1860 static void
   1861 repat_interrupt_zones(xfrd_state_type* xfrd, struct nsd_options* newopt)
   1862 {
   1863 	/* if masterlist changed:
   1864 	 *   interrupt slave zone (UDP or TCP) transfers.
   1865 	 *   slave zones reset master to start of list.
   1866 	 */
   1867 	xfrd_zone_type* xz;
   1868 	struct notify_zone* nz;
   1869 	RBTREE_FOR(xz, xfrd_zone_type*, xfrd->zones) {
   1870 		struct pattern_options* oldp = xz->zone_options->pattern;
   1871 		struct pattern_options* newp = pattern_options_find(newopt,
   1872 			oldp->pname);
   1873 
   1874 		/* Only interrupt if the zone's transfer configuration has actually changed */
   1875 		if(zone_transfer_config_changed(xz, oldp, newp)) {
   1876 			/* interrupt transfer */
   1877 			if(xz->tcp_conn != -1) {
   1878 				xfrd_tcp_release(xfrd->tcp_set, xz);
   1879 				xfrd_set_refresh_now(xz);
   1880 			} else if(xz->zone_handler.ev_fd != -1) {
   1881 				xfrd_udp_release(xz);
   1882 				xfrd_set_refresh_now(xz);
   1883 			}
   1884 			xz->master = 0;
   1885 			xz->master_num = 0;
   1886 			xz->next_master = -1;
   1887 			xz->round_num = -1; /* fresh set of retries */
   1888 		}
   1889 	}
   1890 	/* if notify list changed:
   1891 	 *   interrupt notify that is busy.
   1892 	 *   reset notify to start of list.  (clear all other reset_notify)
   1893 	 */
   1894 	RBTREE_FOR(nz, struct notify_zone*, xfrd->notify_zones) {
   1895 		struct pattern_options* oldp = nz->options->pattern;
   1896 		struct pattern_options* newp = pattern_options_find(newopt,
   1897 			oldp->pname);
   1898 
   1899 		/* Only interrupt if the zone's notify configuration has actually changed */
   1900 		if(zone_notify_config_changed(nz, oldp, newp)) {
   1901 			/* interrupt notify */
   1902 			if(nz->notify_send_enable) {
   1903 				notify_disable(nz);
   1904 				/* set to restart the notify after the
   1905 				 * pattern has been changed. */
   1906 				nz->notify_restart = 2;
   1907 			} else {
   1908 				nz->notify_restart = 1;
   1909 			}
   1910 		} else {
   1911 			nz->notify_restart = 0;
   1912 		}
   1913 	}
   1914 }
   1915 
   1916 /** for notify, after the pattern changes, restart the affected notifies */
   1917 static void
   1918 repat_interrupt_notify_start(xfrd_state_type* xfrd)
   1919 {
   1920 	struct notify_zone* nz;
   1921 	RBTREE_FOR(nz, struct notify_zone*, xfrd->notify_zones) {
   1922 		if(nz->notify_restart) {
   1923 			if(nz->notify_current)
   1924 				nz->notify_current = nz->options->pattern->notify;
   1925 			if(nz->notify_restart == 2) {
   1926 				if(nz->notify_restart)
   1927 					xfrd_notify_start(nz, xfrd);
   1928 			}
   1929 		}
   1930 	}
   1931 }
   1932 
   1933 /** check if patterns have changed */
   1934 static void
   1935 repat_patterns(xfrd_state_type* xfrd, struct nsd_options* newopt)
   1936 {
   1937 	/* zones that use changed patterns must have:
   1938 	 * - their AXFR/IXFR interrupted: try again, acl may have changed.
   1939 	 *   if the old master/key still exists, OK, fix master-numptrs and
   1940 	 *   keep going.  Otherwise, stop xfer and reset TSIG.
   1941 	 * - send NOTIFY reset to start of NOTIFY list (and TSIG reset).
   1942 	 */
   1943 	struct nsd_options* oldopt = xfrd->nsd->options;
   1944 	struct pattern_options* p;
   1945 	int search_zones = 0;
   1946 
   1947 	repat_interrupt_zones(xfrd, newopt);
   1948 	/* find deleted patterns */
   1949 	p = (struct pattern_options*)rbtree_first(oldopt->patterns);
   1950 	while((rbnode_type*)p != RBTREE_NULL) {
   1951 		struct pattern_options* next = (struct pattern_options*)
   1952 			rbtree_next((rbnode_type*)p);
   1953 		if(!pattern_options_find(newopt, p->pname)) {
   1954 			if(p->implicit) {
   1955 				/* first remove its zone */
   1956 				VERBOSITY(1, (LOG_INFO, "zone removed from config: %s", p->pname + strlen(PATTERN_IMPLICIT_MARKER)));
   1957 				remove_cfgzone(xfrd, p->pname);
   1958 			}
   1959 			remove_pat(xfrd, p->pname);
   1960 		}
   1961 		p = next;
   1962 	}
   1963 	/* find added or changed patterns */
   1964 	RBTREE_FOR(p, struct pattern_options*, newopt->patterns) {
   1965 		struct pattern_options* origp = pattern_options_find(oldopt,
   1966 			p->pname);
   1967 		if(!origp) {
   1968 			/* no zones can use it, no zone_interrupt needed */
   1969 			add_pat(xfrd, p);
   1970 			if(p->implicit) {
   1971 				VERBOSITY(1, (LOG_INFO, "zone added to config: %s", p->pname + strlen(PATTERN_IMPLICIT_MARKER)));
   1972 				add_cfgzone(xfrd, p->pname);
   1973 			}
   1974 		} else if(!pattern_options_equal(p, origp)) {
   1975 			uint8_t newstate = 0;
   1976 			if (p->request_xfr && !origp->request_xfr) {
   1977 				newstate = REPAT_SLAVE;
   1978 			} else if (!p->request_xfr && origp->request_xfr) {
   1979 				newstate = REPAT_MASTER;
   1980 			}
   1981 			if (   p->catalog_role == CATALOG_ROLE_CONSUMER
   1982 			&& origp->catalog_role != CATALOG_ROLE_CONSUMER) {
   1983 				newstate |= REPAT_CATALOG_CONSUMER;
   1984 			} else if (p->catalog_role != CATALOG_ROLE_CONSUMER
   1985 			    && origp->catalog_role == CATALOG_ROLE_CONSUMER) {
   1986 				newstate |= REPAT_CATALOG_CONSUMER_DEINIT;
   1987 			}
   1988 			add_pat(xfrd, p);
   1989 			if (p->implicit && newstate) {
   1990 				const dname_type* dname =
   1991 					parse_implicit_name(xfrd, p->pname);
   1992 				if (dname) {
   1993 					if ((newstate & REPAT_SLAVE)) {
   1994 						struct zone_options* zopt =
   1995 							zone_options_find(
   1996 							oldopt, dname);
   1997 						if (zopt) {
   1998 							xfrd_init_slave_zone(
   1999 								xfrd, zopt);
   2000 						}
   2001 					} else if ((newstate & REPAT_MASTER)) {
   2002 						xfrd_del_slave_zone(xfrd,
   2003 							dname);
   2004 					}
   2005 					if ((newstate & REPAT_CATALOG_CONSUMER)) {
   2006 						struct zone_options* zopt =
   2007 							zone_options_find(
   2008 							oldopt, dname);
   2009 						if (zopt) {
   2010 							xfrd_init_catalog_consumer_zone(
   2011 								xfrd, zopt);
   2012 						}
   2013 					} else if ((newstate & REPAT_CATALOG_CONSUMER_DEINIT)) {
   2014 						xfrd_deinit_catalog_consumer_zone(
   2015 								xfrd, dname);
   2016 					}
   2017 					region_recycle(xfrd->region,
   2018 						(void*)dname,
   2019 						dname_total_size(dname));
   2020 				}
   2021 			} else if(!p->implicit && newstate) {
   2022 				/* search all zones with this pattern */
   2023 				search_zones = 1;
   2024 				origp->xfrd_flags = newstate;
   2025 			}
   2026 		}
   2027 	}
   2028 	if (search_zones) {
   2029 		struct zone_options* zone_opt;
   2030 		/* search in oldopt because 1) it contains zonelist zones,
   2031 		 * and 2) you need oldopt(existing) to call xfrd_init */
   2032 		RBTREE_FOR(zone_opt, struct zone_options*, oldopt->zone_options) {
   2033 			struct pattern_options* oldp = zone_opt->pattern;
   2034 			if (!oldp->implicit) {
   2035 				if ((oldp->xfrd_flags & REPAT_SLAVE)) {
   2036 					/* xfrd needs stable reference so get
   2037 					 * it from the oldopt(modified) tree */
   2038 					xfrd_init_slave_zone(xfrd, zone_opt);
   2039 				} else if ((oldp->xfrd_flags & REPAT_MASTER)) {
   2040 					xfrd_del_slave_zone(xfrd,
   2041 						(const dname_type*)
   2042 						zone_opt->node.key);
   2043 				}
   2044 				if ((oldp->xfrd_flags & REPAT_CATALOG_CONSUMER)) {
   2045 					xfrd_init_catalog_consumer_zone(xfrd,
   2046 							zone_opt);
   2047 				} else if ((oldp->xfrd_flags & REPAT_CATALOG_CONSUMER_DEINIT)) {
   2048 					xfrd_deinit_catalog_consumer_zone(xfrd,
   2049 						(const dname_type*)
   2050 						zone_opt->node.key);
   2051 				}
   2052 				oldp->xfrd_flags = 0;
   2053 			}
   2054 		}
   2055 	}
   2056 	repat_interrupt_notify_start(xfrd);
   2057 }
   2058 
   2059 /** true if options are different that can be set via repat. */
   2060 static int
   2061 repat_options_changed(xfrd_state_type* xfrd, struct nsd_options* newopt)
   2062 {
   2063 #ifdef RATELIMIT
   2064 	if(xfrd->nsd->options->rrl_ratelimit != newopt->rrl_ratelimit)
   2065 		return 1;
   2066 	if(xfrd->nsd->options->rrl_whitelist_ratelimit != newopt->rrl_whitelist_ratelimit)
   2067 		return 1;
   2068 	if(xfrd->nsd->options->rrl_slip != newopt->rrl_slip)
   2069 		return 1;
   2070 #else
   2071 	(void)xfrd; (void)newopt;
   2072 #endif
   2073 	return 0;
   2074 }
   2075 
   2076 static int opt_str_changed(const char* old, const char* new)
   2077 { return !old ? ( !new ? 0 : 1 ) : ( !new ? 1 : strcasecmp(old, new) ); }
   2078 
   2079 /** true if cookie options are different that can be set via repat. */
   2080 static int
   2081 repat_cookie_options_changed(struct nsd_options* old, struct nsd_options* new)
   2082 {
   2083 	return old->answer_cookie != new->answer_cookie
   2084 	    || opt_str_changed( old->cookie_secret
   2085 	                      , new->cookie_secret)
   2086 	    || opt_str_changed( old->cookie_staging_secret
   2087 	                      , new->cookie_staging_secret)
   2088 	    || old->cookie_secret_file_is_default !=
   2089 	       new->cookie_secret_file_is_default
   2090 	    || opt_str_changed( old->cookie_secret_file
   2091 	                      , new->cookie_secret_file);
   2092 }
   2093 
   2094 /** check if global options have changed */
   2095 static void
   2096 repat_options(xfrd_state_type* xfrd, struct nsd_options* newopt)
   2097 {
   2098 	struct nsd_options* oldopt = xfrd->nsd->options;
   2099 
   2100 	if(repat_options_changed(xfrd, newopt)) {
   2101 		/* update our options */
   2102 #ifdef RATELIMIT
   2103 		oldopt->rrl_ratelimit = newopt->rrl_ratelimit;
   2104 		oldopt->rrl_whitelist_ratelimit = newopt->rrl_whitelist_ratelimit;
   2105 		oldopt->rrl_slip = newopt->rrl_slip;
   2106 #endif
   2107 		task_new_opt_change(xfrd->nsd->task[xfrd->nsd->mytask],
   2108 			xfrd->last_task, newopt);
   2109 		xfrd_set_reload_now(xfrd);
   2110 	}
   2111 	if(repat_cookie_options_changed(oldopt, newopt)) {
   2112 		/* update our options */
   2113 		oldopt->answer_cookie = newopt->answer_cookie;
   2114 		region_str_replace(  oldopt->region
   2115 		                  , &oldopt->cookie_secret
   2116 		                  ,  newopt->cookie_secret);
   2117 		region_str_replace(  oldopt->region
   2118 		                  , &oldopt->cookie_staging_secret
   2119 		                  ,  newopt->cookie_staging_secret);
   2120 		oldopt->cookie_secret_file_is_default =
   2121 			newopt->cookie_secret_file_is_default;
   2122 		region_str_replace(  oldopt->region
   2123 		                  , &oldopt->cookie_secret_file
   2124 		                  ,  newopt->cookie_secret_file);
   2125 
   2126 		xfrd->nsd->cookie_count = 0;
   2127 		xfrd->nsd->cookie_secrets_source = COOKIE_SECRETS_NONE;
   2128 		reconfig_cookies(xfrd->nsd, newopt);
   2129 		task_new_cookies( xfrd->nsd->task[xfrd->nsd->mytask]
   2130 		                , xfrd->last_task
   2131 		                , xfrd->nsd->do_answer_cookie
   2132 		                , xfrd->nsd->cookie_count
   2133 		                , xfrd->nsd->cookie_secrets);
   2134 		xfrd_set_reload_now(xfrd);
   2135 	}
   2136 }
   2137 
   2138 /** print errors over ssl, gets pointer-to-pointer to ssl, so it can set
   2139  * the pointer to NULL on failure and stop printing */
   2140 static void
   2141 print_ssl_cfg_err(void* arg, const char* str)
   2142 {
   2143 	RES** ssl = (RES**)arg;
   2144 	if(!*ssl) return;
   2145 	if(!ssl_printf(*ssl, "%s", str))
   2146 		*ssl = NULL; /* failed, stop printing */
   2147 }
   2148 
   2149 /** do the repattern command: reread config file and apply keys, patterns */
   2150 static void
   2151 do_repattern(RES* ssl, xfrd_state_type* xfrd)
   2152 {
   2153 	region_type* region = region_create(xalloc, free);
   2154 	struct nsd_options* opt;
   2155 	const char* cfgfile = xfrd->nsd->options->configfile;
   2156 	int reload_needed_before = xfrd->need_to_send_reload;
   2157 
   2158 	/* check chroot and configfile, if possible to reread */
   2159 	if(xfrd->nsd->chrootdir) {
   2160 		size_t l = strlen(xfrd->nsd->chrootdir);
   2161 		while(l>0 && xfrd->nsd->chrootdir[l-1] == '/')
   2162 			--l;
   2163 		if(strncmp(xfrd->nsd->chrootdir, cfgfile, l) != 0) {
   2164 			(void)ssl_printf(ssl, "error %s is not relative to %s: "
   2165 				"chroot prevents reread of config\n",
   2166 				cfgfile, xfrd->nsd->chrootdir);
   2167 			region_destroy(region);
   2168 			return;
   2169 		}
   2170 		cfgfile += l;
   2171 	}
   2172 
   2173 	(void)ssl_printf(ssl, "reconfig start, read %s\n", cfgfile);
   2174 	opt = nsd_options_create(region);
   2175 	if(!parse_options_file(opt, cfgfile, &print_ssl_cfg_err, &ssl,
   2176 				xfrd->nsd->options)) {
   2177 		/* error already printed */
   2178 		region_destroy(region);
   2179 		return;
   2180 	}
   2181 	/* check for differences in TSIG keys and patterns, and apply,
   2182 	 * first the keys, so that pattern->keyptr can be set right. */
   2183 	repat_keys(xfrd, opt);
   2184 	repat_patterns(xfrd, opt);
   2185 	repat_options(xfrd, opt);
   2186 	zonestat_inc_ifneeded(xfrd);
   2187 
   2188 	/* Check if any changes were actually made by comparing reload state */
   2189 	if(xfrd->need_to_send_reload == reload_needed_before) {
   2190 		(void)ssl_printf(ssl, "reconfig completed: no changes detected\n");
   2191 	} else {
   2192 		(void)ssl_printf(ssl, "reconfig completed: changes applied\n");
   2193 	}
   2194 	send_ok(ssl);
   2195 	region_destroy(region);
   2196 }
   2197 
   2198 static void print_cfg_err(void *unused, const char *message)
   2199 {
   2200 	(void)unused;
   2201 	log_msg(LOG_ERR, "%s", message);
   2202 }
   2203 
   2204 /* mostly identical to do_repattern */
   2205 void xfrd_reload_config(xfrd_state_type *xfrd)
   2206 {
   2207 	const char *chrootdir = xfrd->nsd->chrootdir;
   2208 	const char *file = xfrd->nsd->options->configfile;
   2209 	region_type* region;
   2210 	struct nsd_options* options;
   2211 
   2212 	if (chrootdir && !file_inside_chroot(file, chrootdir))
   2213 	{
   2214 		log_msg(LOG_ERR, "%s is not relative to %s: %s",
   2215 			xfrd->nsd->options->configfile, xfrd->nsd->chrootdir,
   2216 			"chroot prevents reread of config");
   2217 		goto error_chroot;
   2218 	}
   2219 
   2220 	region = region_create(xalloc, free);
   2221 	options = nsd_options_create(region);
   2222 
   2223 	if (!parse_options_file(
   2224 		options, file, print_cfg_err, NULL, xfrd->nsd->options))
   2225 	{
   2226 		goto error_parse;
   2227 	}
   2228 
   2229 	repat_keys(xfrd, options);
   2230 	repat_patterns(xfrd, options); /* adds/deletes zones too */
   2231 	repat_options(xfrd, options);
   2232 	zonestat_inc_ifneeded(xfrd);
   2233 
   2234 error_parse:
   2235 	region_destroy(region);
   2236 error_chroot:
   2237 	return;
   2238 }
   2239 
   2240 /** do the serverpid command: printout pid of server process */
   2241 static void
   2242 do_serverpid(RES* ssl, xfrd_state_type* xfrd)
   2243 {
   2244 	(void)ssl_printf(ssl, "%u\n", (unsigned)xfrd->reload_pid);
   2245 }
   2246 
   2247 /** do the print_tsig command: printout tsig info */
   2248 static void
   2249 do_print_tsig(RES* ssl, xfrd_state_type* xfrd, char* arg)
   2250 {
   2251 	if(*arg == '\0') {
   2252 		struct key_options* key;
   2253 		RBTREE_FOR(key, struct key_options*, xfrd->nsd->options->keys) {
   2254 			if(!ssl_printf(ssl, "key: name: \"%s\" secret: \"%s\" algorithm: %s\n", key->name, key->secret, key->algorithm))
   2255 				return;
   2256 		}
   2257 		return;
   2258 	} else {
   2259 		struct key_options* key_opts = key_options_find(xfrd->nsd->options, arg);
   2260 		if(!key_opts) {
   2261 			(void)ssl_printf(ssl, "error: no such key with name: %s\n", arg);
   2262 			return;
   2263 		} else {
   2264 			(void)ssl_printf(ssl, "key: name: \"%s\" secret: \"%s\" algorithm: %s\n", arg, key_opts->secret, key_opts->algorithm);
   2265 		}
   2266 	}
   2267 }
   2268 
   2269 /** do the update_tsig command: change existing tsig to new secret */
   2270 static void
   2271 do_update_tsig(RES* ssl, xfrd_state_type* xfrd, char* arg)
   2272 {
   2273 	struct region* region = xfrd->nsd->options->region;
   2274 	char* arg2 = NULL;
   2275 	uint8_t data[65536]; /* 64K */
   2276 	struct key_options* key_opt;
   2277 
   2278 	if(*arg == '\0') {
   2279 		(void)ssl_printf(ssl, "error: missing argument (keyname)\n");
   2280 		return;
   2281 	}
   2282 	if(!find_arg2(ssl, arg, &arg2)) {
   2283 		(void)ssl_printf(ssl, "error: missing argument (secret)\n");
   2284 		return;
   2285 	}
   2286 	key_opt = key_options_find(xfrd->nsd->options, arg);
   2287 	if(!key_opt) {
   2288 		(void)ssl_printf(ssl, "error: no such key with name: %s\n", arg);
   2289 		memset(arg2, 0xdd, strlen(arg2));
   2290 		return;
   2291 	}
   2292 	if(b64_pton(arg2, data, sizeof(data)) == -1) {
   2293 		(void)ssl_printf(ssl, "error: the secret: %s is not in b64 format\n", arg2);
   2294 		memset(data, 0xdd, sizeof(data)); /* wipe secret */
   2295 		memset(arg2, 0xdd, strlen(arg2));
   2296 		return;
   2297 	}
   2298 	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);
   2299 	if(key_opt->secret) {
   2300 		/* wipe old secret */
   2301 		memset(key_opt->secret, 0xdd, strlen(key_opt->secret));
   2302 		region_recycle(region, key_opt->secret,
   2303 			strlen(key_opt->secret)+1);
   2304 	}
   2305 	key_opt->secret = region_strdup(region, arg2);
   2306 	log_msg(LOG_INFO, "the key: %s has new secret %s and algorithm: %s\n", arg, key_opt->secret, key_opt->algorithm);
   2307 	/* wipe secret from temp parse buffer */
   2308 	memset(arg2, 0xdd, strlen(arg2));
   2309 	memset(data, 0xdd, sizeof(data));
   2310 
   2311 	key_options_desetup(region, key_opt);
   2312 	key_options_setup(region, key_opt);
   2313 	task_new_add_key(xfrd->nsd->task[xfrd->nsd->mytask], xfrd->last_task,
   2314 		key_opt);
   2315 	xfrd_set_reload_now(xfrd);
   2316 
   2317 	send_ok(ssl);
   2318 }
   2319 
   2320 /** do the add tsig command, add new key with name, secret and algo given */
   2321 static void
   2322 do_add_tsig(RES* ssl, xfrd_state_type* xfrd, char* arg)
   2323 {
   2324 	char* arg2 = NULL;
   2325 	char* arg3 = NULL;
   2326 	uint8_t data[65536]; /* 64KB */
   2327 	uint8_t dname[MAXDOMAINLEN+1];
   2328 	char algo[256];
   2329 	region_type* region = xfrd->nsd->options->region;
   2330 	struct key_options* new_key_opt;
   2331 
   2332 	if(*arg == '\0') {
   2333 		(void)ssl_printf(ssl, "error: missing argument (keyname)\n");
   2334 		return;
   2335 	}
   2336 	if(!find_arg3(ssl, arg, &arg2, &arg3)) {
   2337 		strlcpy(algo, "hmac-sha256", sizeof(algo));
   2338 	} else {
   2339 		strlcpy(algo, arg3, sizeof(algo));
   2340 	}
   2341 	if(!arg2) {
   2342 		(void)ssl_printf(ssl, "error: missing argument (secret)\n");
   2343 		return;
   2344 	}
   2345 	if(key_options_find(xfrd->nsd->options, arg)) {
   2346 		(void)ssl_printf(ssl, "error: key %s already exists\n", arg);
   2347 		memset(arg2, 0xdd, strlen(arg2));
   2348 		return;
   2349 	}
   2350 	if(b64_pton(arg2, data, sizeof(data)) == -1) {
   2351 		(void)ssl_printf(ssl, "error: the secret: %s is not in b64 format\n", arg2);
   2352 		memset(data, 0xdd, sizeof(data)); /* wipe secret */
   2353 		memset(arg2, 0xdd, strlen(arg2));
   2354 		return;
   2355 	}
   2356 	memset(data, 0xdd, sizeof(data)); /* wipe secret from temp buffer */
   2357 	if(!dname_parse_wire(dname, arg)) {
   2358 		(void)ssl_printf(ssl, "error: could not parse key name: %s\n", arg);
   2359 		memset(arg2, 0xdd, strlen(arg2));
   2360 		return;
   2361 	}
   2362 	if(tsig_get_algorithm_by_name(algo) == NULL) {
   2363 		(void)ssl_printf(ssl, "error: unknown algorithm: %s\n", algo);
   2364 		memset(arg2, 0xdd, strlen(arg2));
   2365 		return;
   2366 	}
   2367 	log_msg(LOG_INFO, "adding key with name: %s and secret: %s with algo: %s\n", arg, arg2, algo);
   2368 	new_key_opt = key_options_create(region);
   2369 	new_key_opt->name = region_strdup(region, arg);
   2370 	new_key_opt->secret = region_strdup(region, arg2);
   2371 	new_key_opt->algorithm = region_strdup(region, algo);
   2372 	add_key(xfrd, new_key_opt);
   2373 
   2374 	/* wipe secret from temp buffer */
   2375 	memset(arg2, 0xdd, strlen(arg2));
   2376 	send_ok(ssl);
   2377 }
   2378 
   2379 /** set acl entries to use the given TSIG key */
   2380 static void
   2381 zopt_set_acl_to_tsig(struct acl_options* acl, struct region* region,
   2382 	const char* key_name, struct key_options* key_opt)
   2383 {
   2384 	while(acl) {
   2385 		if(acl->blocked) {
   2386 			acl = acl->next;
   2387 			continue;
   2388 		}
   2389 		acl->nokey = 0;
   2390 		if(acl->key_name)
   2391 			region_recycle(region, (void*)acl->key_name,
   2392 				strlen(acl->key_name)+1);
   2393 		acl->key_name = region_strdup(region, key_name);
   2394 		acl->key_options = key_opt;
   2395 		acl = acl->next;
   2396 	}
   2397 }
   2398 
   2399 /** do the assoc_tsig command: associate the zone to use the tsig name */
   2400 static void
   2401 do_assoc_tsig(RES* ssl, xfrd_state_type* xfrd, char* arg)
   2402 {
   2403 	region_type* region = xfrd->nsd->options->region;
   2404 	char* arg2 = NULL;
   2405 	struct zone_options* zone;
   2406 	struct key_options* key_opt;
   2407 
   2408 	if(*arg == '\0') {
   2409 		(void)ssl_printf(ssl, "error: missing argument (zonename)\n");
   2410 		return;
   2411 	}
   2412 	if(!find_arg2(ssl, arg, &arg2)) {
   2413 		(void)ssl_printf(ssl, "error: missing argument (keyname)\n");
   2414 		return;
   2415 	}
   2416 
   2417 	if(!get_zone_arg(ssl, xfrd, arg, &zone))
   2418 		return;
   2419 	if(!zone) {
   2420 		(void)ssl_printf(ssl, "error: missing argument (zone)\n");
   2421 		return;
   2422 	}
   2423 	key_opt = key_options_find(xfrd->nsd->options, arg2);
   2424 	if(!key_opt) {
   2425 		(void)ssl_printf(ssl, "error: key: %s does not exist\n", arg2);
   2426 		return;
   2427 	}
   2428 
   2429 	zopt_set_acl_to_tsig(zone->pattern->allow_notify, region, arg2,
   2430 		key_opt);
   2431 	zopt_set_acl_to_tsig(zone->pattern->notify, region, arg2, key_opt);
   2432 	zopt_set_acl_to_tsig(zone->pattern->request_xfr, region, arg2,
   2433 		key_opt);
   2434 	zopt_set_acl_to_tsig(zone->pattern->provide_xfr, region, arg2,
   2435 		key_opt);
   2436 	zopt_set_acl_to_tsig(zone->pattern->allow_query, region, arg2,
   2437 		key_opt);
   2438 
   2439 	task_new_add_pattern(xfrd->nsd->task[xfrd->nsd->mytask],
   2440 		xfrd->last_task, zone->pattern);
   2441 	xfrd_set_reload_now(xfrd);
   2442 
   2443 	send_ok(ssl);
   2444 }
   2445 
   2446 /** see if TSIG key is used in the acl */
   2447 static int
   2448 acl_contains_tsig_key(struct acl_options* acl, const char* name)
   2449 {
   2450 	while(acl) {
   2451 		if(acl->key_name && strcmp(acl->key_name, name) == 0)
   2452 			return 1;
   2453 		acl = acl->next;
   2454 	}
   2455 	return 0;
   2456 }
   2457 
   2458 /** do the del_tsig command, remove an (unused) tsig */
   2459 static void
   2460 do_del_tsig(RES* ssl, xfrd_state_type* xfrd, char* arg) {
   2461 	int used_key = 0;
   2462 	struct zone_options* zone;
   2463 	struct key_options* key_opt;
   2464 
   2465 	if(*arg == '\0') {
   2466 		(void)ssl_printf(ssl, "error: missing argument (keyname)\n");
   2467 		return;
   2468 	}
   2469 	key_opt = key_options_find(xfrd->nsd->options, arg);
   2470 	if(!key_opt) {
   2471 		(void)ssl_printf(ssl, "key %s does not exist, nothing to be deleted\n", arg);
   2472 		return;
   2473 	}
   2474 	RBTREE_FOR(zone, struct zone_options*, xfrd->nsd->options->zone_options)
   2475 	{
   2476 		if(acl_contains_tsig_key(zone->pattern->allow_notify, arg) ||
   2477 		   acl_contains_tsig_key(zone->pattern->notify, arg) ||
   2478 		   acl_contains_tsig_key(zone->pattern->request_xfr, arg) ||
   2479 		   acl_contains_tsig_key(zone->pattern->provide_xfr, arg) ||
   2480 		   acl_contains_tsig_key(zone->pattern->allow_query, arg)) {
   2481 			if(!ssl_printf(ssl, "zone %s uses key %s\n",
   2482 				zone->name, arg))
   2483 				return;
   2484 			used_key = 1;
   2485 			break;
   2486 		}
   2487 	}
   2488 
   2489 	if(used_key) {
   2490 		(void)ssl_printf(ssl, "error: key: %s is in use and cannot be deleted\n", arg);
   2491 		return;
   2492 	} else {
   2493 		remove_key(xfrd, arg);
   2494 		log_msg(LOG_INFO, "key: %s is successfully deleted\n", arg);
   2495 	}
   2496 
   2497 	send_ok(ssl);
   2498 }
   2499 
   2500 
   2501 static int
   2502 can_dump_cookie_secrets(RES* ssl, nsd_type* const nsd)
   2503 {
   2504 	if(!nsd->options->cookie_secret_file)
   2505 		(void)ssl_printf(ssl, "error: empty cookie-secret-file\n");
   2506 
   2507 	else if(nsd->cookie_secrets_source == COOKIE_SECRETS_FROM_CONFIG)
   2508 		(void)ssl_printf(ssl, "error: cookie secrets are already "
   2509 			"configured. Remove \"cookie-secret:\" and "
   2510 			"\"cookie-staging-secret:\" entries from configuration "
   2511 			"first (and reconfig) before managing cookies with "
   2512 			"nsd-control\n");
   2513 	else
   2514 		return 1;
   2515 	return 0;
   2516 
   2517 }
   2518 
   2519 /* returns `0` on failure */
   2520 static int
   2521 cookie_secret_file_dump_and_reload(RES* ssl, nsd_type* const nsd) {
   2522 	char secret_hex[NSD_COOKIE_SECRET_SIZE * 2 + 1];
   2523 	FILE* f;
   2524 	size_t i;
   2525 
   2526 	/* open write only and truncate */
   2527 	if(!nsd->options->cookie_secret_file) {
   2528 		(void)ssl_printf(ssl, "cookie-secret-file empty\n");
   2529 		return 0;
   2530 	}
   2531 	else if((f = fopen(nsd->options->cookie_secret_file, "w")) == NULL ) {
   2532 		(void)ssl_printf( ssl
   2533 		                , "unable to open cookie secret file %s: %s\n"
   2534 		                , nsd->options->cookie_secret_file
   2535 		                , strerror(errno));
   2536 		return 0;
   2537 	}
   2538 	for(i = 0; i < nsd->cookie_count; i++) {
   2539 		struct cookie_secret const* cs = &nsd->cookie_secrets[i];
   2540 		ssize_t const len = hex_ntop(cs->cookie_secret, NSD_COOKIE_SECRET_SIZE,
   2541 			secret_hex, sizeof(secret_hex));
   2542 		(void)len; /* silence unused variable warning with -DNDEBUG */
   2543 		assert( len == NSD_COOKIE_SECRET_SIZE * 2 );
   2544 		secret_hex[NSD_COOKIE_SECRET_SIZE * 2] = '\0';
   2545 		fprintf(f, "%s\n", secret_hex);
   2546 	}
   2547 	explicit_bzero(secret_hex, sizeof(secret_hex));
   2548 	fclose(f);
   2549 	nsd->cookie_secrets_source = COOKIE_SECRETS_FROM_FILE;
   2550 	region_str_replace(nsd->region, &nsd->cookie_secrets_filename
   2551 	                              , nsd->options->cookie_secret_file);
   2552 	task_new_cookies(xfrd->nsd->task[xfrd->nsd->mytask], xfrd->last_task,
   2553 		nsd->do_answer_cookie, nsd->cookie_count, nsd->cookie_secrets);
   2554 	xfrd_set_reload_now(xfrd);
   2555 	send_ok(ssl);
   2556 	return 1;
   2557 }
   2558 
   2559 static void
   2560 do_activate_cookie_secret(RES* ssl, xfrd_state_type* xrfd, char* arg) {
   2561 	nsd_type* nsd = xrfd->nsd;
   2562 	size_t backup_cookie_count;
   2563 	cookie_secrets_type backup_cookie_secrets;
   2564 	(void)arg;
   2565 
   2566 	if(!can_dump_cookie_secrets(ssl, xfrd->nsd))
   2567 		return;
   2568 
   2569 	if(nsd->cookie_count <= 1 ) {
   2570 		(void)ssl_printf(ssl, "error: no staging cookie secret to activate\n");
   2571 		return;
   2572 	}
   2573 	backup_cookie_count = nsd->cookie_count;
   2574 	memcpy( backup_cookie_secrets, nsd->cookie_secrets
   2575 	      , sizeof(cookie_secrets_type));
   2576 	activate_cookie_secret(nsd);
   2577 	if(!cookie_secret_file_dump_and_reload(ssl, nsd)) {
   2578 		memcpy( nsd->cookie_secrets, backup_cookie_secrets
   2579 		      , sizeof(cookie_secrets_type));
   2580 		nsd->cookie_count = backup_cookie_count;
   2581 	}
   2582 	explicit_bzero(backup_cookie_secrets, sizeof(cookie_secrets_type));
   2583 }
   2584 
   2585 static void
   2586 do_drop_cookie_secret(RES* ssl, xfrd_state_type* xrfd, char* arg) {
   2587 	nsd_type* nsd = xrfd->nsd;
   2588 	size_t backup_cookie_count;
   2589 	cookie_secrets_type backup_cookie_secrets;
   2590 	(void)arg;
   2591 
   2592 	if(!can_dump_cookie_secrets(ssl, xfrd->nsd))
   2593 		return;
   2594 
   2595 	if(nsd->cookie_count <= 1 ) {
   2596 		(void)ssl_printf(ssl, "error: can not drop the currently active cookie secret\n");
   2597 		return;
   2598 	}
   2599 	backup_cookie_count = nsd->cookie_count;
   2600 	memcpy( backup_cookie_secrets, nsd->cookie_secrets
   2601 	      , sizeof(cookie_secrets_type));
   2602 	drop_cookie_secret(nsd);
   2603 	if(!cookie_secret_file_dump_and_reload(ssl, nsd)) {
   2604 		memcpy( nsd->cookie_secrets, backup_cookie_secrets
   2605 		      , sizeof(cookie_secrets_type));
   2606 		nsd->cookie_count = backup_cookie_count;
   2607 	}
   2608 	explicit_bzero(backup_cookie_secrets, sizeof(cookie_secrets_type));
   2609 }
   2610 
   2611 static void
   2612 do_add_cookie_secret(RES* ssl, xfrd_state_type* xrfd, char* arg) {
   2613 	nsd_type* nsd = xrfd->nsd;
   2614 	uint8_t secret[NSD_COOKIE_SECRET_SIZE];
   2615 	size_t backup_cookie_count;
   2616 	cookie_secrets_type backup_cookie_secrets;
   2617 
   2618 	if(!can_dump_cookie_secrets(ssl, xfrd->nsd))
   2619 		return;
   2620 
   2621 	if(*arg == '\0') {
   2622 		(void)ssl_printf(ssl, "error: missing argument (cookie_secret)\n");
   2623 		return;
   2624 	}
   2625 	if(strlen(arg) != 32) {
   2626 		explicit_bzero(arg, strlen(arg));
   2627 		(void)ssl_printf(ssl, "invalid cookie secret: invalid argument length\n");
   2628 		(void)ssl_printf(ssl, "please provide a 128bit hex encoded secret\n");
   2629 		return;
   2630 	}
   2631 	if(hex_pton(arg, secret, NSD_COOKIE_SECRET_SIZE) != NSD_COOKIE_SECRET_SIZE ) {
   2632 		explicit_bzero(secret, NSD_COOKIE_SECRET_SIZE);
   2633 		explicit_bzero(arg, strlen(arg));
   2634 		(void)ssl_printf(ssl, "invalid cookie secret: parse error\n");
   2635 		(void)ssl_printf(ssl, "please provide a 128bit hex encoded secret\n");
   2636 		return;
   2637 	}
   2638 	explicit_bzero(arg, strlen(arg));
   2639 
   2640 	backup_cookie_count = nsd->cookie_count;
   2641 	memcpy( backup_cookie_secrets, nsd->cookie_secrets
   2642 	      , sizeof(cookie_secrets_type));
   2643 	if(nsd->cookie_secrets_source != COOKIE_SECRETS_FROM_FILE
   2644 	&& nsd->cookie_secrets_source != COOKIE_SECRETS_FROM_CONFIG) {
   2645 		nsd->cookie_count = 0;
   2646 	}
   2647 	add_cookie_secret(nsd, secret);
   2648 	explicit_bzero(secret, NSD_COOKIE_SECRET_SIZE);
   2649 	if(!cookie_secret_file_dump_and_reload(ssl, nsd)) {
   2650 		explicit_bzero(arg, strlen(arg));
   2651 		(void)ssl_printf(ssl, "error: writing to cookie secret file: \"%s\"\n"
   2652 		                , nsd->options->cookie_secret_file);
   2653 		memcpy( nsd->cookie_secrets, backup_cookie_secrets
   2654 		      , sizeof(cookie_secrets_type));
   2655 		nsd->cookie_count = backup_cookie_count;
   2656 	}
   2657 	explicit_bzero(backup_cookie_secrets, sizeof(cookie_secrets_type));
   2658 }
   2659 
   2660 static void
   2661 do_print_cookie_secrets(RES* ssl, xfrd_state_type* xrfd, char* arg) {
   2662 	nsd_type* nsd = xrfd->nsd;
   2663 	char secret_hex[NSD_COOKIE_SECRET_SIZE * 2 + 1];
   2664 	int i;
   2665 	(void)arg;
   2666 
   2667 	switch(nsd->cookie_secrets_source){
   2668 	case COOKIE_SECRETS_NONE:
   2669 		break;
   2670 	case COOKIE_SECRETS_GENERATED:
   2671 		if(!ssl_printf(ssl, "source : random generated\n"))
   2672 			return;
   2673 		break;
   2674 	case COOKIE_SECRETS_FROM_FILE:
   2675 		if(!ssl_printf( ssl, "source : \"%s\"\n"
   2676 		          , nsd->cookie_secrets_filename))
   2677 			return;
   2678 		break;
   2679 	case COOKIE_SECRETS_FROM_CONFIG:
   2680 		if(!ssl_printf(ssl, "source : configuration\n"))
   2681 			return;
   2682 		break;
   2683 	default:
   2684 		if(!ssl_printf(ssl, "source : unknown\n"))
   2685 			return;
   2686 		break;
   2687 	}
   2688 	for(i = 0; (size_t)i < nsd->cookie_count; i++) {
   2689 		struct cookie_secret const* cs = &nsd->cookie_secrets[i];
   2690 		ssize_t const len = hex_ntop(cs->cookie_secret, NSD_COOKIE_SECRET_SIZE,
   2691 		                             secret_hex, sizeof(secret_hex));
   2692 		(void)len; /* silence unused variable warning with -DNDEBUG */
   2693 		assert( len == NSD_COOKIE_SECRET_SIZE * 2 );
   2694 		secret_hex[NSD_COOKIE_SECRET_SIZE * 2] = '\0';
   2695 		if (i == 0)
   2696 			(void)ssl_printf(ssl, "active : %s\n",  secret_hex);
   2697 		else if (nsd->cookie_count == 2)
   2698 			(void)ssl_printf(ssl, "staging: %s\n",  secret_hex);
   2699 		else
   2700 			(void)ssl_printf(ssl, "staging[%d]: %s\n", i, secret_hex);
   2701 	}
   2702 	explicit_bzero(secret_hex, sizeof(secret_hex));
   2703 }
   2704 
   2705 /** check for name with end-of-string, space or tab after it */
   2706 static int
   2707 cmdcmp(char* p, const char* cmd, size_t len)
   2708 {
   2709 	return strncmp(p,cmd,len)==0 && (p[len]==0||p[len]==' '||p[len]=='\t');
   2710 }
   2711 
   2712 /** execute a remote control command */
   2713 static void
   2714 execute_cmd(struct daemon_remote* rc, RES* ssl, char* cmd)
   2715 {
   2716 	char* p = skipwhite(cmd);
   2717 	/* compare command */
   2718 	if(cmdcmp(p, "stop", 4)) {
   2719 		do_stop(ssl, rc->xfrd);
   2720 	} else if(cmdcmp(p, "reload", 6)) {
   2721 		do_reload(ssl, rc->xfrd, skipwhite(p+6));
   2722 	} else if(cmdcmp(p, "write", 5)) {
   2723 		do_write(ssl, rc->xfrd, skipwhite(p+5));
   2724 	} else if(cmdcmp(p, "status", 6)) {
   2725 		do_status(ssl, rc->xfrd);
   2726 	} else if(cmdcmp(p, "stats_noreset", 13)) {
   2727 		do_stats(ssl, rc->xfrd, 1);
   2728 	} else if(cmdcmp(p, "stats", 5)) {
   2729 		do_stats(ssl, rc->xfrd, 0);
   2730 	} else if(cmdcmp(p, "log_reopen", 10)) {
   2731 		do_log_reopen(ssl, rc->xfrd);
   2732 	} else if(cmdcmp(p, "addzone", 7)) {
   2733 		do_addzone(ssl, rc->xfrd, skipwhite(p+7));
   2734 	} else if(cmdcmp(p, "delzone", 7)) {
   2735 		do_delzone(ssl, rc->xfrd, skipwhite(p+7));
   2736 	} else if(cmdcmp(p, "changezone", 10)) {
   2737 		do_changezone(ssl, rc->xfrd, skipwhite(p+10));
   2738 	} else if(cmdcmp(p, "addzones", 8)) {
   2739 		do_addzones(ssl, rc->xfrd);
   2740 	} else if(cmdcmp(p, "delzones", 8)) {
   2741 		do_delzones(ssl, rc->xfrd);
   2742 	} else if(cmdcmp(p, "notify", 6)) {
   2743 		do_notify(ssl, rc->xfrd, skipwhite(p+6));
   2744 	} else if(cmdcmp(p, "transfer", 8)) {
   2745 		do_transfer(ssl, rc->xfrd, skipwhite(p+8));
   2746 	} else if(cmdcmp(p, "force_transfer", 14)) {
   2747 		do_force_transfer(ssl, rc->xfrd, skipwhite(p+14));
   2748 	} else if(cmdcmp(p, "zonestatus", 10)) {
   2749 		do_zonestatus(ssl, rc->xfrd, skipwhite(p+10));
   2750 	} else if(cmdcmp(p, "verbosity", 9)) {
   2751 		do_verbosity(ssl, skipwhite(p+9));
   2752 	} else if(cmdcmp(p, "repattern", 9)) {
   2753 		do_repattern(ssl, rc->xfrd);
   2754 	} else if(cmdcmp(p, "reconfig", 8)) {
   2755 		do_repattern(ssl, rc->xfrd);
   2756 	} else if(cmdcmp(p, "serverpid", 9)) {
   2757 		do_serverpid(ssl, rc->xfrd);
   2758 	} else if(cmdcmp(p, "print_tsig", 10)) {
   2759 		do_print_tsig(ssl, rc->xfrd, skipwhite(p+10));
   2760 	} else if(cmdcmp(p, "update_tsig", 11)) {
   2761 		do_update_tsig(ssl, rc->xfrd, skipwhite(p+11));
   2762 	} else if(cmdcmp(p, "add_tsig", 8)) {
   2763 		do_add_tsig(ssl, rc->xfrd, skipwhite(p+8));
   2764 	} else if(cmdcmp(p, "assoc_tsig", 10)) {
   2765 		do_assoc_tsig(ssl, rc->xfrd, skipwhite(p+10));
   2766 	} else if(cmdcmp(p, "del_tsig", 8)) {
   2767 		do_del_tsig(ssl, rc->xfrd, skipwhite(p+8));
   2768 	} else if(cmdcmp(p, "add_cookie_secret", 17)) {
   2769 		do_add_cookie_secret(ssl, rc->xfrd, skipwhite(p+17));
   2770 	} else if(cmdcmp(p, "drop_cookie_secret", 18)) {
   2771 		do_drop_cookie_secret(ssl, rc->xfrd, skipwhite(p+18));
   2772 	} else if(cmdcmp(p, "print_cookie_secrets", 20)) {
   2773 		do_print_cookie_secrets(ssl, rc->xfrd, skipwhite(p+20));
   2774 	} else if(cmdcmp(p, "activate_cookie_secret", 22)) {
   2775 		do_activate_cookie_secret(ssl, rc->xfrd, skipwhite(p+22));
   2776 	} else {
   2777 		(void)ssl_printf(ssl, "error unknown command '%s'\n", p);
   2778 	}
   2779 }
   2780 
   2781 /** handle remote control request */
   2782 static void
   2783 handle_req(struct daemon_remote* rc, struct rc_state* s, RES* res)
   2784 {
   2785 	int r;
   2786 	char pre[10];
   2787 	char magic[8];
   2788 	char buf[1024];
   2789 	if (fcntl(s->c.ev_fd, F_SETFL, 0) == -1) { /* set blocking */
   2790 		log_msg(LOG_ERR, "cannot fcntl rc: %s", strerror(errno));
   2791 	}
   2792 
   2793 	/* try to read magic UBCT[version]_space_ string */
   2794 #ifdef HAVE_SSL
   2795 	if(res->ssl) {
   2796 		ERR_clear_error();
   2797 		if((r=SSL_read(res->ssl, magic, (int)sizeof(magic)-1)) <= 0) {
   2798 			if(SSL_get_error(res->ssl, r) == SSL_ERROR_ZERO_RETURN)
   2799 				return;
   2800 			log_crypto_err("could not SSL_read");
   2801 			return;
   2802 		}
   2803 	} else {
   2804 #endif /* HAVE_SSL */
   2805 		while(1) {
   2806 			ssize_t rr = read(res->fd, magic, sizeof(magic)-1);
   2807 			if(rr <= 0) {
   2808 				if(rr == 0) return;
   2809 				if(errno == EINTR || errno == EAGAIN)
   2810 					continue;
   2811 				log_msg(LOG_ERR, "could not read: %s", strerror(errno));
   2812 				return;
   2813 			}
   2814 			r = (int)rr;
   2815 			break;
   2816 		}
   2817 #ifdef HAVE_SSL
   2818 	}
   2819 #endif /* HAVE_SSL */
   2820 	magic[7] = 0;
   2821 	if( r != 7 || strncmp(magic, "NSDCT", 5) != 0) {
   2822 		VERBOSITY(2, (LOG_INFO, "control connection has bad header"));
   2823 		/* probably wrong tool connected, ignore it completely */
   2824 		return;
   2825 	}
   2826 
   2827 	/* read the command line */
   2828 	if(!ssl_read_line(res, buf, sizeof(buf))) {
   2829 		return;
   2830 	}
   2831 	snprintf(pre, sizeof(pre), "NSDCT%d ", NSD_CONTROL_VERSION);
   2832 	if(strcmp(magic, pre) != 0) {
   2833 		VERBOSITY(2, (LOG_INFO, "control connection had bad "
   2834 			"version %s, cmd: %s", magic, buf));
   2835 		(void)ssl_printf(res, "error version mismatch\n");
   2836 		return;
   2837 	}
   2838 	/* always log control commands */
   2839 	VERBOSITY(0, (LOG_INFO, "control cmd: %s", buf));
   2840 
   2841 	/* figure out what to do */
   2842 	execute_cmd(rc, res, buf);
   2843 }
   2844 
   2845 #ifdef HAVE_SSL
   2846 /** handle SSL_do_handshake changes to the file descriptor to wait for later */
   2847 static void
   2848 remote_handshake_later(struct daemon_remote* rc, struct rc_state* s, int fd,
   2849 	int r, int r2)
   2850 {
   2851 	if(r2 == SSL_ERROR_WANT_READ) {
   2852 		if(s->shake_state == rc_hs_read) {
   2853 			/* try again later */
   2854 			return;
   2855 		}
   2856 		s->shake_state = rc_hs_read;
   2857 		if(s->event_added)
   2858 			event_del(&s->c);
   2859 		memset(&s->c, 0, sizeof(s->c));
   2860 		event_set(&s->c, fd, EV_PERSIST|EV_TIMEOUT|EV_READ,
   2861 			remote_control_callback, s);
   2862 		if(event_base_set(xfrd->event_base, &s->c) != 0)
   2863 			log_msg(LOG_ERR, "remote_accept: cannot set event_base");
   2864 		if(event_add(&s->c, &s->tval) != 0)
   2865 			log_msg(LOG_ERR, "remote_accept: cannot add event");
   2866 		s->event_added = 1;
   2867 		return;
   2868 	} else if(r2 == SSL_ERROR_WANT_WRITE) {
   2869 		if(s->shake_state == rc_hs_write) {
   2870 			/* try again later */
   2871 			return;
   2872 		}
   2873 		s->shake_state = rc_hs_write;
   2874 		if(s->event_added)
   2875 			event_del(&s->c);
   2876 		memset(&s->c, 0, sizeof(s->c));
   2877 		event_set(&s->c, fd, EV_PERSIST|EV_TIMEOUT|EV_WRITE,
   2878 			remote_control_callback, s);
   2879 		if(event_base_set(xfrd->event_base, &s->c) != 0)
   2880 			log_msg(LOG_ERR, "remote_accept: cannot set event_base");
   2881 		if(event_add(&s->c, &s->tval) != 0)
   2882 			log_msg(LOG_ERR, "remote_accept: cannot add event");
   2883 		s->event_added = 1;
   2884 		return;
   2885 	} else {
   2886 		if(r == 0)
   2887 			log_msg(LOG_ERR, "remote control connection closed prematurely");
   2888 		log_crypto_err("remote control failed ssl");
   2889 		clean_point(rc, s);
   2890 	}
   2891 }
   2892 #endif /* HAVE_SSL */
   2893 
   2894 static void
   2895 remote_control_callback(int fd, short event, void* arg)
   2896 {
   2897 	RES res;
   2898 	struct rc_state* s = (struct rc_state*)arg;
   2899 	struct daemon_remote* rc = s->rc;
   2900 	if( (event&EV_TIMEOUT) ) {
   2901 		log_msg(LOG_ERR, "remote control timed out");
   2902 		clean_point(rc, s);
   2903 		return;
   2904 	}
   2905 #ifdef HAVE_SSL
   2906 	if(s->ssl) {
   2907 		/* (continue to) setup the SSL connection */
   2908 		int r;
   2909 		ERR_clear_error();
   2910 		r = SSL_do_handshake(s->ssl);
   2911 		if(r != 1) {
   2912 			int r2 = SSL_get_error(s->ssl, r);
   2913 			remote_handshake_later(rc, s, fd, r, r2);
   2914 			return;
   2915 		}
   2916 		s->shake_state = rc_none;
   2917 	}
   2918 #endif /* HAVE_SSL */
   2919 
   2920 	/* once handshake has completed, check authentication */
   2921 	if (!rc->use_cert) {
   2922 		VERBOSITY(3, (LOG_INFO, "unauthenticated remote control connection"));
   2923 #ifdef HAVE_SSL
   2924 	} else if(SSL_get_verify_result(s->ssl) == X509_V_OK) {
   2925 #  ifdef HAVE_SSL_GET1_PEER_CERTIFICATE
   2926 		X509* x = SSL_get1_peer_certificate(s->ssl);
   2927 #  else
   2928 		X509* x = SSL_get_peer_certificate(s->ssl);
   2929 #  endif
   2930 		if(!x) {
   2931 			VERBOSITY(2, (LOG_INFO, "remote control connection "
   2932 				"provided no client certificate"));
   2933 			clean_point(rc, s);
   2934 			return;
   2935 		}
   2936 		VERBOSITY(3, (LOG_INFO, "remote control connection authenticated"));
   2937 		X509_free(x);
   2938 #endif /* HAVE_SSL */
   2939 	} else {
   2940 		VERBOSITY(2, (LOG_INFO, "remote control connection failed to "
   2941 			"authenticate with client certificate"));
   2942 		clean_point(rc, s);
   2943 		return;
   2944 	}
   2945 
   2946 	/* if OK start to actually handle the request */
   2947 #ifdef HAVE_SSL
   2948 	res.ssl = s->ssl;
   2949 #endif /* HAVE_SSL */
   2950 	res.fd = fd;
   2951 	handle_req(rc, s, &res);
   2952 
   2953 	VERBOSITY(3, (LOG_INFO, "remote control operation completed"));
   2954 	clean_point(rc, s);
   2955 }
   2956 
   2957 #ifdef BIND8_STATS
   2958 const char*
   2959 opcode2str(int o)
   2960 {
   2961 	switch(o) {
   2962 		case OPCODE_QUERY: return "QUERY";
   2963 		case OPCODE_IQUERY: return "IQUERY";
   2964 		case OPCODE_STATUS: return "STATUS";
   2965 		case OPCODE_NOTIFY: return "NOTIFY";
   2966 		case OPCODE_UPDATE: return "UPDATE";
   2967 		default: return "OTHER";
   2968 	}
   2969 }
   2970 
   2971 /** print long number */
   2972 static int
   2973 print_longnum(RES* ssl, char* desc, uint64_t x)
   2974 {
   2975 	if(x > (uint64_t)1024*1024*1024) {
   2976 		/* more than a Gb */
   2977 		size_t front = (size_t)(x / (uint64_t)1000000);
   2978 		size_t back = (size_t)(x % (uint64_t)1000000);
   2979 		return ssl_printf(ssl, "%s%lu%6.6lu\n", desc,
   2980 			(unsigned long)front, (unsigned long)back);
   2981 	} else {
   2982 		return ssl_printf(ssl, "%s%lu\n", desc, (unsigned long)x);
   2983 	}
   2984 }
   2985 
   2986 /* print one block of statistics.  n is name and d is delimiter */
   2987 static void
   2988 print_stat_block(RES* ssl, char* n, char* d, struct nsdst* st)
   2989 {
   2990 	const char* rcstr[] = {"NOERROR", "FORMERR", "SERVFAIL", "NXDOMAIN",
   2991 	    "NOTIMP", "REFUSED", "YXDOMAIN", "YXRRSET", "NXRRSET", "NOTAUTH",
   2992 	    "NOTZONE", "RCODE11", "RCODE12", "RCODE13", "RCODE14", "RCODE15",
   2993 	    "BADVERS"
   2994 	};
   2995 	size_t i;
   2996 	for(i=0; i<= 255; i++) {
   2997 		if(inhibit_zero && st->qtype[i] == 0 &&
   2998 			strncmp(rrtype_to_string(i), "TYPE", 4) == 0)
   2999 			continue;
   3000 		if(!ssl_printf(ssl, "%s%snum.type.%s=%lu\n", n, d,
   3001 			rrtype_to_string(i), (unsigned long)st->qtype[i]))
   3002 			return;
   3003 	}
   3004 
   3005 	/* opcode */
   3006 	for(i=0; i<6; i++) {
   3007 		if(inhibit_zero && st->opcode[i] == 0 && i != OPCODE_QUERY)
   3008 			continue;
   3009 		if(!ssl_printf(ssl, "%s%snum.opcode.%s=%lu\n", n, d,
   3010 			opcode2str(i), (unsigned long)st->opcode[i]))
   3011 			return;
   3012 	}
   3013 
   3014 	/* qclass */
   3015 	for(i=0; i<4; i++) {
   3016 		if(inhibit_zero && st->qclass[i] == 0 && i != CLASS_IN)
   3017 			continue;
   3018 		if(!ssl_printf(ssl, "%s%snum.class.%s=%lu\n", n, d,
   3019 			rrclass_to_string(i), (unsigned long)st->qclass[i]))
   3020 			return;
   3021 	}
   3022 
   3023 	/* rcode */
   3024 	for(i=0; i<17; i++) {
   3025 		if(inhibit_zero && st->rcode[i] == 0 &&
   3026 			i > RCODE_YXDOMAIN) /* NSD does not use larger */
   3027 			continue;
   3028 		if(!ssl_printf(ssl, "%s%snum.rcode.%s=%lu\n", n, d, rcstr[i],
   3029 			(unsigned long)st->rcode[i]))
   3030 			return;
   3031 	}
   3032 
   3033 	/* edns */
   3034 	if(!ssl_printf(ssl, "%s%snum.edns=%lu\n", n, d, (unsigned long)st->edns))
   3035 		return;
   3036 
   3037 	/* ednserr */
   3038 	if(!ssl_printf(ssl, "%s%snum.ednserr=%lu\n", n, d,
   3039 		(unsigned long)st->ednserr))
   3040 		return;
   3041 
   3042 	/* qudp */
   3043 	if(!ssl_printf(ssl, "%s%snum.udp=%lu\n", n, d, (unsigned long)st->qudp))
   3044 		return;
   3045 	/* qudp6 */
   3046 	if(!ssl_printf(ssl, "%s%snum.udp6=%lu\n", n, d, (unsigned long)st->qudp6))
   3047 		return;
   3048 	/* ctcp */
   3049 	if(!ssl_printf(ssl, "%s%snum.tcp=%lu\n", n, d, (unsigned long)st->ctcp))
   3050 		return;
   3051 	/* ctcp6 */
   3052 	if(!ssl_printf(ssl, "%s%snum.tcp6=%lu\n", n, d, (unsigned long)st->ctcp6))
   3053 		return;
   3054 	/* ctls */
   3055 	if(!ssl_printf(ssl, "%s%snum.tls=%lu\n", n, d, (unsigned long)st->ctls))
   3056 		return;
   3057 	/* ctls6 */
   3058 	if(!ssl_printf(ssl, "%s%snum.tls6=%lu\n", n, d, (unsigned long)st->ctls6))
   3059 		return;
   3060 
   3061 	/* nona */
   3062 	if(!ssl_printf(ssl, "%s%snum.answer_wo_aa=%lu\n", n, d,
   3063 		(unsigned long)st->nona))
   3064 		return;
   3065 
   3066 	/* rxerr */
   3067 	if(!ssl_printf(ssl, "%s%snum.rxerr=%lu\n", n, d, (unsigned long)st->rxerr))
   3068 		return;
   3069 
   3070 	/* txerr */
   3071 	if(!ssl_printf(ssl, "%s%snum.txerr=%lu\n", n, d, (unsigned long)st->txerr))
   3072 		return;
   3073 
   3074 	/* number of requested-axfr, number of times axfr served to clients */
   3075 	if(!ssl_printf(ssl, "%s%snum.raxfr=%lu\n", n, d, (unsigned long)st->raxfr))
   3076 		return;
   3077 
   3078 	/* number of requested-ixfr, number of times ixfr served to clients */
   3079 	if(!ssl_printf(ssl, "%s%snum.rixfr=%lu\n", n, d, (unsigned long)st->rixfr))
   3080 		return;
   3081 
   3082 	/* truncated */
   3083 	if(!ssl_printf(ssl, "%s%snum.truncated=%lu\n", n, d,
   3084 		(unsigned long)st->truncated))
   3085 		return;
   3086 
   3087 	/* dropped */
   3088 	if(!ssl_printf(ssl, "%s%snum.dropped=%lu\n", n, d,
   3089 		(unsigned long)st->dropped))
   3090 		return;
   3091 }
   3092 
   3093 #ifdef USE_ZONE_STATS
   3094 static void
   3095 resize_zonestat(xfrd_state_type* xfrd, size_t num)
   3096 {
   3097 	struct nsdst** a = xalloc_array_zero(num, sizeof(struct nsdst*));
   3098 	if(xfrd->zonestat_clear_num != 0)
   3099 		memcpy(a, xfrd->zonestat_clear, xfrd->zonestat_clear_num
   3100 			* sizeof(struct nsdst*));
   3101 	free(xfrd->zonestat_clear);
   3102 	xfrd->zonestat_clear = a;
   3103 	xfrd->zonestat_clear_num = num;
   3104 }
   3105 
   3106 void
   3107 zonestat_print(RES *ssl, struct evbuffer *evbuf, xfrd_state_type *xfrd,
   3108                int clear, struct nsdst **zonestats)
   3109 {
   3110 	struct zonestatname* n;
   3111 	struct nsdst stat0, stat1;
   3112 	RBTREE_FOR(n, struct zonestatname*, xfrd->nsd->options->zonestatnames){
   3113 		char* name = (char*)n->node.key;
   3114 		if(n->id >= xfrd->zonestat_safe)
   3115 			continue; /* newly allocated and reload has not yet
   3116 				done and replied with new size */
   3117 		if(name == NULL || name[0]==0)
   3118 			continue; /* empty name, do not output */
   3119 		/* the statistics are stored in two blocks, during reload
   3120 		 * the newly forked processes get the other block to use,
   3121 		 * these blocks are mmapped and are currently in use to
   3122 		 * add statistics to */
   3123 		memcpy(&stat0, &zonestats[0][n->id], sizeof(stat0));
   3124 		memcpy(&stat1, &zonestats[1][n->id], sizeof(stat1));
   3125 		stats_add(&stat0, &stat1);
   3126 
   3127 		/* save a copy of current (cumulative) stats in stat1 */
   3128 		memcpy(&stat1, &stat0, sizeof(stat1));
   3129 		/* subtract last total of stats that was 'cleared' */
   3130 		if(n->id < xfrd->zonestat_clear_num &&
   3131 			xfrd->zonestat_clear[n->id])
   3132 			stats_subtract(&stat0, xfrd->zonestat_clear[n->id]);
   3133 		if(clear) {
   3134 			/* extend storage array if needed */
   3135 			if(n->id >= xfrd->zonestat_clear_num) {
   3136 				if(n->id+1 < xfrd->nsd->options->zonestatnames->count)
   3137 					resize_zonestat(xfrd, xfrd->nsd->options->zonestatnames->count);
   3138 				else
   3139 					resize_zonestat(xfrd, n->id+1);
   3140 			}
   3141 			if(!xfrd->zonestat_clear[n->id])
   3142 				xfrd->zonestat_clear[n->id] = xalloc(
   3143 					sizeof(struct nsdst));
   3144 			/* store last total of stats */
   3145 			memcpy(xfrd->zonestat_clear[n->id], &stat1,
   3146 				sizeof(struct nsdst));
   3147 		}
   3148 
   3149 		/* stat0 contains the details that we want to print */
   3150 		if (ssl) {
   3151 			if(!ssl_printf(ssl, "%s%snum.queries=%lu\n", name, ".",
   3152 				(unsigned long)(stat0.qudp + stat0.qudp6 + stat0.ctcp +
   3153 					stat0.ctcp6 + stat0.ctls + stat0.ctls6)))
   3154 				return;
   3155 			print_stat_block(ssl, name, ".", &stat0);
   3156 		}
   3157 
   3158 #ifdef USE_METRICS
   3159 		if (evbuf) {
   3160 			metrics_zonestat_print_one(evbuf, name, &stat0);
   3161 		}
   3162 #else
   3163 		(void)evbuf;
   3164 #endif /* USE_METRICS */
   3165 	}
   3166 }
   3167 #endif /* USE_ZONE_STATS */
   3168 
   3169 static void
   3170 print_stats(RES* ssl, xfrd_state_type* xfrd, struct timeval* now, int clear,
   3171 	struct nsdst* st, struct nsdst** zonestats)
   3172 {
   3173 	size_t i;
   3174 	stc_type total = 0;
   3175 	struct timeval elapsed, uptime;
   3176 
   3177 	/* per CPU and total */
   3178 	for(i=0; i<xfrd->nsd->child_count; i++) {
   3179 		if(!ssl_printf(ssl, "server%d.queries=%lu\n", (int)i,
   3180 			(unsigned long)xfrd->nsd->children[i].query_count))
   3181 			return;
   3182 		total += xfrd->nsd->children[i].query_count;
   3183 	}
   3184 	if(!ssl_printf(ssl, "num.queries=%lu\n", (unsigned long)total))
   3185 		return;
   3186 
   3187 	/* time elapsed and uptime (in seconds) */
   3188 	timeval_subtract(&uptime, now, &xfrd->nsd->rc->boot_time);
   3189 	timeval_subtract(&elapsed, now, &xfrd->nsd->rc->stats_time);
   3190 	if(!ssl_printf(ssl, "time.boot=%lu.%6.6lu\n",
   3191 		(unsigned long)uptime.tv_sec, (unsigned long)uptime.tv_usec))
   3192 		return;
   3193 	if(!ssl_printf(ssl, "time.elapsed=%lu.%6.6lu\n",
   3194 		(unsigned long)elapsed.tv_sec, (unsigned long)elapsed.tv_usec))
   3195 		return;
   3196 
   3197 	/* mem info, database on disksize */
   3198 	if(!print_longnum(ssl, "size.db.disk=", st->db_disk))
   3199 		return;
   3200 	if(!print_longnum(ssl, "size.db.mem=", st->db_mem))
   3201 		return;
   3202 	if(!print_longnum(ssl, "size.xfrd.mem=", region_get_mem(xfrd->region)))
   3203 		return;
   3204 	if(!print_longnum(ssl, "size.config.disk=",
   3205 		xfrd->nsd->options->zonelist_off))
   3206 		return;
   3207 	if(!print_longnum(ssl, "size.config.mem=", region_get_mem(
   3208 		xfrd->nsd->options->region)))
   3209 		return;
   3210 	print_stat_block(ssl, "", "", st);
   3211 
   3212 	/* zone statistics */
   3213 	if(!ssl_printf(ssl, "zone.primary=%lu\n",
   3214 		(unsigned long)(xfrd->notify_zones->count - xfrd->zones->count)))
   3215 		return;
   3216 	if(!ssl_printf(ssl, "zone.secondary=%lu\n", (unsigned long)xfrd->zones->count))
   3217 		return;
   3218 	if(!ssl_printf(ssl, "zone.master=%lu\n",
   3219 		(unsigned long)(xfrd->notify_zones->count - xfrd->zones->count)))
   3220 		return;
   3221 	if(!ssl_printf(ssl, "zone.slave=%lu\n", (unsigned long)xfrd->zones->count))
   3222 		return;
   3223 #ifdef USE_ZONE_STATS
   3224 	zonestat_print(ssl, NULL, xfrd, clear, zonestats); /* per-zone statistics */
   3225 #else
   3226 	(void)clear; (void)zonestats;
   3227 #endif
   3228 }
   3229 
   3230 void
   3231 process_stats_alloc(struct xfrd_state* xfrd, struct nsdst** stats,
   3232 	struct nsdst** zonestats)
   3233 {
   3234 	*stats = xmallocarray(xfrd->nsd->child_count*2, sizeof(struct nsdst));
   3235 #ifdef USE_ZONE_STATS
   3236 	zonestats[0] = xmallocarray(xfrd->zonestat_safe, sizeof(struct nsdst));
   3237 	zonestats[1] = xmallocarray(xfrd->zonestat_safe, sizeof(struct nsdst));
   3238 #else
   3239 	(void)zonestats;
   3240 #endif
   3241 }
   3242 
   3243 void
   3244 process_stats_grab(struct xfrd_state* xfrd, struct timeval* stattime,
   3245 	struct nsdst* stats, struct nsdst** zonestats)
   3246 {
   3247 	if(gettimeofday(stattime, NULL) == -1)
   3248 		log_msg(LOG_ERR, "gettimeofday: %s", strerror(errno));
   3249 	memcpy(stats, xfrd->nsd->stat_map,
   3250 		xfrd->nsd->child_count*2*sizeof(struct nsdst));
   3251 #ifdef USE_ZONE_STATS
   3252 	memcpy(zonestats[0], xfrd->nsd->zonestat[0],
   3253 		xfrd->zonestat_safe*sizeof(struct nsdst));
   3254 	memcpy(zonestats[1], xfrd->nsd->zonestat[1],
   3255 		xfrd->zonestat_safe*sizeof(struct nsdst));
   3256 #else
   3257 	(void)zonestats;
   3258 #endif
   3259 }
   3260 
   3261 void
   3262 process_stats_add_old_new(struct xfrd_state* xfrd, struct nsdst* stats)
   3263 {
   3264 	size_t i;
   3265 	uint64_t dbd = stats[0].db_disk;
   3266 	uint64_t dbm = stats[0].db_mem;
   3267 	stc_type count1, count2;
   3268 
   3269 	/* Pick up the latest database memory use value. */
   3270 	count1 = stats[0].reloadcount;
   3271 	count2 = stats[xfrd->nsd->child_count+0].reloadcount;
   3272 	/* This comparison allows roll over, the check is count2 > count1. */
   3273 	if((count2 > count1 && count2-count1 < 0xffff) ||
   3274 	   (count2 < count1 && count1-count2 > 0xffff)) {
   3275 		dbd = stats[xfrd->nsd->child_count+0].db_disk;
   3276 		dbm = stats[xfrd->nsd->child_count+0].db_mem;
   3277 	}
   3278 
   3279 	/* The old and new server processes have separate stat blocks,
   3280 	 * and these are added up together. This results in the statistics
   3281 	 * values per server-child. The reload task briefly forks both
   3282 	 * old and new server processes. */
   3283 	for(i=0; i<xfrd->nsd->child_count; i++) {
   3284 		stats_add(&stats[i], &stats[xfrd->nsd->child_count+i]);
   3285 	}
   3286 	stats[0].db_disk = dbd;
   3287 	stats[0].db_mem = dbm;
   3288 }
   3289 
   3290 void
   3291 process_stats_manage_clear(struct xfrd_state* xfrd, struct nsdst* stats,
   3292 	int peek)
   3293 {
   3294 	struct nsdst st;
   3295 	size_t i;
   3296 	if(peek) {
   3297 		/* Subtract the earlier resetted values from the numbers,
   3298 		 * but do not reset the values that are retrieved now. */
   3299 		if(!xfrd->stat_clear)
   3300 			return; /* nothing to subtract */
   3301 		for(i=0; i<xfrd->nsd->child_count; i++) {
   3302 			/* subtract cumulative count that has been reset */
   3303 			stats_subtract(&stats[i], &xfrd->stat_clear[i]);
   3304 		}
   3305 		return;
   3306 	}
   3307 	if(!xfrd->stat_clear)
   3308 		xfrd->stat_clear = region_alloc_zero(xfrd->region,
   3309 			sizeof(struct nsdst)*xfrd->nsd->child_count);
   3310 	for(i=0; i<xfrd->nsd->child_count; i++) {
   3311 		/* store cumulative count copy */
   3312 		memcpy(&st, &stats[i], sizeof(st));
   3313 		/* subtract cumulative count that has been reset */
   3314 		stats_subtract(&stats[i], &xfrd->stat_clear[i]);
   3315 		/* store cumulative count in the cleared value array */
   3316 		memcpy(&xfrd->stat_clear[i], &st, sizeof(st));
   3317 	}
   3318 }
   3319 
   3320 void
   3321 process_stats_add_total(struct xfrd_state* xfrd, struct nsdst* total,
   3322 	struct nsdst* stats)
   3323 {
   3324 	size_t i;
   3325 	/* copy over the first one, with also the nonadded values. */
   3326 	memcpy(total, &stats[0], sizeof(*total));
   3327 	xfrd->nsd->children[0].query_count = stats[0].qudp + stats[0].qudp6
   3328 		+ stats[0].ctcp + stats[0].ctcp6 + stats[0].ctls
   3329 		+ stats[0].ctls6;
   3330 	for(i=1; i<xfrd->nsd->child_count; i++) {
   3331 		stats_add(total, &stats[i]);
   3332 		xfrd->nsd->children[i].query_count = stats[i].qudp
   3333 			+ stats[i].qudp6 + stats[i].ctcp + stats[i].ctcp6
   3334 			+ stats[i].ctls + stats[i].ctls6;
   3335 	}
   3336 }
   3337 
   3338 void
   3339 process_stats(RES* ssl, struct evbuffer *evbuf, struct xfrd_state* xfrd, int peek)
   3340 {
   3341 	struct timeval stattime;
   3342 	struct nsdst* stats, *zonestats[2], total;
   3343 
   3344 	/* it only really makes sense for one to be used at a time and would
   3345 	 * otherwise cause issues if peek is zero */
   3346 	assert((ssl && !evbuf) || (!ssl && evbuf));
   3347 
   3348 	process_stats_alloc(xfrd, &stats, zonestats);
   3349 	process_stats_grab(xfrd, &stattime, stats, zonestats);
   3350 	process_stats_add_old_new(xfrd, stats);
   3351 	process_stats_manage_clear(xfrd, stats, peek);
   3352 	process_stats_add_total(xfrd, &total, stats);
   3353 	if (ssl) {
   3354 		print_stats(ssl, xfrd, &stattime, !peek, &total, zonestats);
   3355 	}
   3356 #ifdef USE_METRICS
   3357 	if (evbuf) {
   3358 		if (xfrd->nsd->options->control_enable) {
   3359 			/* only pass in rc->stats_time if remote-conrol is enabled,
   3360 			 * otherwise stats_time is uninitialized */
   3361 			metrics_print_stats(evbuf, xfrd, &stattime, !peek, &total, zonestats,
   3362 			                    &xfrd->nsd->rc->stats_time);
   3363 		} else {
   3364 			metrics_print_stats(evbuf, xfrd, &stattime, !peek, &total, zonestats,
   3365 			                    NULL);
   3366 		}
   3367 	}
   3368 #else
   3369 	(void)evbuf;
   3370 #endif /* USE_METRICS */
   3371 	if(!peek) {
   3372 		xfrd->nsd->rc->stats_time = stattime;
   3373 	}
   3374 
   3375 	free(stats);
   3376 #ifdef USE_ZONE_STATS
   3377 	free(zonestats[0]);
   3378 	free(zonestats[1]);
   3379 #endif
   3380 
   3381 	VERBOSITY(3, (LOG_INFO, "remote control stats printed"));
   3382 }
   3383 #endif /* BIND8_STATS */
   3384 
   3385 int
   3386 create_local_accept_sock(const char *path, int* noproto)
   3387 {
   3388 #ifdef HAVE_SYS_UN_H
   3389 	int s;
   3390 	struct sockaddr_un usock;
   3391 
   3392 	VERBOSITY(3, (LOG_INFO, "creating unix socket %s", path));
   3393 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
   3394 	/* this member exists on BSDs, not Linux */
   3395 	usock.sun_len = (unsigned)sizeof(usock);
   3396 #endif
   3397 	usock.sun_family = AF_LOCAL;
   3398 	/* length is 92-108, 104 on FreeBSD */
   3399 	(void)strlcpy(usock.sun_path, path, sizeof(usock.sun_path));
   3400 
   3401 	if ((s = socket(AF_LOCAL, SOCK_STREAM, 0)) == -1) {
   3402 		log_msg(LOG_ERR, "Cannot create local socket %s (%s)",
   3403 			path, strerror(errno));
   3404 		return -1;
   3405 	}
   3406 
   3407 	if (unlink(path) && errno != ENOENT) {
   3408 		/* The socket already exists and cannot be removed */
   3409 		log_msg(LOG_ERR, "Cannot remove old local socket %s (%s)",
   3410 			path, strerror(errno));
   3411 		goto err;
   3412 	}
   3413 
   3414 	if (bind(s, (struct sockaddr *)&usock,
   3415 		(socklen_t)sizeof(struct sockaddr_un)) == -1) {
   3416 		log_msg(LOG_ERR, "Cannot bind local socket %s (%s)",
   3417 			path, strerror(errno));
   3418 		goto err;
   3419 	}
   3420 
   3421 	if (fcntl(s, F_SETFL, O_NONBLOCK) == -1) {
   3422 		log_msg(LOG_ERR, "Cannot set non-blocking mode");
   3423 		goto err;
   3424 	}
   3425 
   3426 	if (listen(s, nsd.options->tcp_listen_queue) == -1) {
   3427 		log_msg(LOG_ERR, "can't listen: %s", strerror(errno));
   3428 		goto err;
   3429 	}
   3430 
   3431 	(void)noproto; /*unused*/
   3432 	return s;
   3433 
   3434 err:
   3435 	close(s);
   3436 	return -1;
   3437 
   3438 #else
   3439 	(void)path;
   3440 	log_msg(LOG_ERR, "Local sockets are not supported");
   3441 	*noproto = 1;
   3442 	return -1;
   3443 #endif
   3444 }
   3445