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