xref: /freebsd/contrib/unbound/daemon/remote.c (revision 4731124cace5e7a0224e29784617d2856e5c59ab)
1 /*
2  * daemon/remote.c - remote control for the unbound 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  * unbound-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_OPENSSL_ERR_H
47 #include <openssl/err.h>
48 #endif
49 #ifdef HAVE_OPENSSL_DH_H
50 #include <openssl/dh.h>
51 #endif
52 #ifdef HAVE_OPENSSL_BN_H
53 #include <openssl/bn.h>
54 #endif
55 
56 #include <ctype.h>
57 #include "daemon/remote.h"
58 #include "daemon/worker.h"
59 #include "daemon/daemon.h"
60 #include "daemon/stats.h"
61 #include "daemon/cachedump.h"
62 #include "util/log.h"
63 #include "util/config_file.h"
64 #include "util/net_help.h"
65 #include "util/module.h"
66 #include "services/listen_dnsport.h"
67 #include "services/cache/rrset.h"
68 #include "services/cache/infra.h"
69 #include "services/mesh.h"
70 #include "services/localzone.h"
71 #include "services/authzone.h"
72 #include "services/rpz.h"
73 #include "util/storage/slabhash.h"
74 #include "util/fptr_wlist.h"
75 #include "util/data/dname.h"
76 #include "validator/validator.h"
77 #include "validator/val_kcache.h"
78 #include "validator/val_kentry.h"
79 #include "validator/val_anchor.h"
80 #include "iterator/iterator.h"
81 #include "iterator/iter_fwd.h"
82 #include "iterator/iter_hints.h"
83 #include "iterator/iter_delegpt.h"
84 #include "services/outbound_list.h"
85 #include "services/outside_network.h"
86 #include "sldns/str2wire.h"
87 #include "sldns/parseutil.h"
88 #include "sldns/wire2str.h"
89 #include "sldns/sbuffer.h"
90 
91 #ifdef HAVE_SYS_TYPES_H
92 #  include <sys/types.h>
93 #endif
94 #ifdef HAVE_SYS_STAT_H
95 #include <sys/stat.h>
96 #endif
97 #ifdef HAVE_NETDB_H
98 #include <netdb.h>
99 #endif
100 
101 /* just for portability */
102 #ifdef SQ
103 #undef SQ
104 #endif
105 
106 /** what to put on statistics lines between var and value, ": " or "=" */
107 #define SQ "="
108 /** if true, inhibits a lot of =0 lines from the stats output */
109 static const int inhibit_zero = 1;
110 
111 /** subtract timers and the values do not overflow or become negative */
112 static void
113 timeval_subtract(struct timeval* d, const struct timeval* end,
114 	const struct timeval* start)
115 {
116 #ifndef S_SPLINT_S
117 	time_t end_usec = end->tv_usec;
118 	d->tv_sec = end->tv_sec - start->tv_sec;
119 	if(end_usec < start->tv_usec) {
120 		end_usec += 1000000;
121 		d->tv_sec--;
122 	}
123 	d->tv_usec = end_usec - start->tv_usec;
124 #endif
125 }
126 
127 /** divide sum of timers to get average */
128 static void
129 timeval_divide(struct timeval* avg, const struct timeval* sum, long long d)
130 {
131 #ifndef S_SPLINT_S
132 	size_t leftover;
133 	if(d <= 0) {
134 		avg->tv_sec = 0;
135 		avg->tv_usec = 0;
136 		return;
137 	}
138 	avg->tv_sec = sum->tv_sec / d;
139 	avg->tv_usec = sum->tv_usec / d;
140 	/* handle fraction from seconds divide */
141 	leftover = sum->tv_sec - avg->tv_sec*d;
142 	if(leftover <= 0)
143 		leftover = 0;
144 	avg->tv_usec += (((long long)leftover)*((long long)1000000))/d;
145 	if(avg->tv_sec < 0)
146 		avg->tv_sec = 0;
147 	if(avg->tv_usec < 0)
148 		avg->tv_usec = 0;
149 #endif
150 }
151 
152 static int
153 remote_setup_ctx(struct daemon_remote* rc, struct config_file* cfg)
154 {
155 	char* s_cert;
156 	char* s_key;
157 	rc->ctx = SSL_CTX_new(SSLv23_server_method());
158 	if(!rc->ctx) {
159 		log_crypto_err("could not SSL_CTX_new");
160 		return 0;
161 	}
162 	if(!listen_sslctx_setup(rc->ctx)) {
163 		return 0;
164 	}
165 
166 	s_cert = fname_after_chroot(cfg->server_cert_file, cfg, 1);
167 	s_key = fname_after_chroot(cfg->server_key_file, cfg, 1);
168 	if(!s_cert || !s_key) {
169 		log_err("out of memory in remote control fname");
170 		goto setup_error;
171 	}
172 	verbose(VERB_ALGO, "setup SSL certificates");
173 	if (!SSL_CTX_use_certificate_chain_file(rc->ctx,s_cert)) {
174 		log_err("Error for server-cert-file: %s", s_cert);
175 		log_crypto_err("Error in SSL_CTX use_certificate_chain_file");
176 		goto setup_error;
177 	}
178 	if(!SSL_CTX_use_PrivateKey_file(rc->ctx,s_key,SSL_FILETYPE_PEM)) {
179 		log_err("Error for server-key-file: %s", s_key);
180 		log_crypto_err("Error in SSL_CTX use_PrivateKey_file");
181 		goto setup_error;
182 	}
183 	if(!SSL_CTX_check_private_key(rc->ctx)) {
184 		log_err("Error for server-key-file: %s", s_key);
185 		log_crypto_err("Error in SSL_CTX check_private_key");
186 		goto setup_error;
187 	}
188 	listen_sslctx_setup_2(rc->ctx);
189 	if(!SSL_CTX_load_verify_locations(rc->ctx, s_cert, NULL)) {
190 		log_crypto_err("Error setting up SSL_CTX verify locations");
191 	setup_error:
192 		free(s_cert);
193 		free(s_key);
194 		return 0;
195 	}
196 	SSL_CTX_set_client_CA_list(rc->ctx, SSL_load_client_CA_file(s_cert));
197 	SSL_CTX_set_verify(rc->ctx, SSL_VERIFY_PEER, NULL);
198 	free(s_cert);
199 	free(s_key);
200 	return 1;
201 }
202 
203 struct daemon_remote*
204 daemon_remote_create(struct config_file* cfg)
205 {
206 	struct daemon_remote* rc = (struct daemon_remote*)calloc(1,
207 		sizeof(*rc));
208 	if(!rc) {
209 		log_err("out of memory in daemon_remote_create");
210 		return NULL;
211 	}
212 	rc->max_active = 10;
213 
214 	if(!cfg->remote_control_enable) {
215 		rc->ctx = NULL;
216 		return rc;
217 	}
218 	if(options_remote_is_address(cfg) && cfg->control_use_cert) {
219 		if(!remote_setup_ctx(rc, cfg)) {
220 			daemon_remote_delete(rc);
221 			return NULL;
222 		}
223 		rc->use_cert = 1;
224 	} else {
225 		struct config_strlist* p;
226 		rc->ctx = NULL;
227 		rc->use_cert = 0;
228 		if(!options_remote_is_address(cfg))
229 		  for(p = cfg->control_ifs.first; p; p = p->next) {
230 			if(p->str && p->str[0] != '/')
231 				log_warn("control-interface %s is not using TLS, but plain transfer, because first control-interface in config file is a local socket (starts with a /).", p->str);
232 		}
233 	}
234 	return rc;
235 }
236 
237 void daemon_remote_clear(struct daemon_remote* rc)
238 {
239 	struct rc_state* p, *np;
240 	if(!rc) return;
241 	/* but do not close the ports */
242 	listen_list_delete(rc->accept_list);
243 	rc->accept_list = NULL;
244 	/* do close these sockets */
245 	p = rc->busy_list;
246 	while(p) {
247 		np = p->next;
248 		if(p->ssl)
249 			SSL_free(p->ssl);
250 		comm_point_delete(p->c);
251 		free(p);
252 		p = np;
253 	}
254 	rc->busy_list = NULL;
255 	rc->active = 0;
256 	rc->worker = NULL;
257 }
258 
259 void daemon_remote_delete(struct daemon_remote* rc)
260 {
261 	if(!rc) return;
262 	daemon_remote_clear(rc);
263 	if(rc->ctx) {
264 		SSL_CTX_free(rc->ctx);
265 	}
266 	free(rc);
267 }
268 
269 /**
270  * Add and open a new control port
271  * @param ip: ip str
272  * @param nr: port nr
273  * @param list: list head
274  * @param noproto_is_err: if lack of protocol support is an error.
275  * @param cfg: config with username for chown of unix-sockets.
276  * @return false on failure.
277  */
278 static int
279 add_open(const char* ip, int nr, struct listen_port** list, int noproto_is_err,
280 	struct config_file* cfg)
281 {
282 	struct addrinfo hints;
283 	struct addrinfo* res;
284 	struct listen_port* n;
285 	int noproto = 0;
286 	int fd, r;
287 	char port[15];
288 	snprintf(port, sizeof(port), "%d", nr);
289 	port[sizeof(port)-1]=0;
290 	memset(&hints, 0, sizeof(hints));
291 	log_assert(ip);
292 
293 	if(ip[0] == '/') {
294 		/* This looks like a local socket */
295 		fd = create_local_accept_sock(ip, &noproto, cfg->use_systemd);
296 		/*
297 		 * Change socket ownership and permissions so users other
298 		 * than root can access it provided they are in the same
299 		 * group as the user we run as.
300 		 */
301 		if(fd != -1) {
302 #ifdef HAVE_CHOWN
303 			if (cfg->username && cfg->username[0] &&
304 				cfg_uid != (uid_t)-1) {
305 				if(chown(ip, cfg_uid, cfg_gid) == -1)
306 					verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
307 					  (unsigned)cfg_uid, (unsigned)cfg_gid,
308 					  ip, strerror(errno));
309 			}
310 			chmod(ip, (mode_t)(S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP));
311 #else
312 			(void)cfg;
313 #endif
314 		}
315 	} else {
316 		hints.ai_socktype = SOCK_STREAM;
317 		hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
318 		if((r = getaddrinfo(ip, port, &hints, &res)) != 0 || !res) {
319 #ifdef USE_WINSOCK
320 			if(!noproto_is_err && r == EAI_NONAME) {
321 				/* tried to lookup the address as name */
322 				return 1; /* return success, but do nothing */
323 			}
324 #endif /* USE_WINSOCK */
325 			log_err("control interface %s:%s getaddrinfo: %s %s",
326 				ip?ip:"default", port, gai_strerror(r),
327 #ifdef EAI_SYSTEM
328 				r==EAI_SYSTEM?(char*)strerror(errno):""
329 #else
330 				""
331 #endif
332 			);
333 			return 0;
334 		}
335 
336 		/* open fd */
337 		fd = create_tcp_accept_sock(res, 1, &noproto, 0,
338 			cfg->ip_transparent, 0, 0, cfg->ip_freebind,
339 			cfg->use_systemd, cfg->ip_dscp);
340 		freeaddrinfo(res);
341 	}
342 
343 	if(fd == -1 && noproto) {
344 		if(!noproto_is_err)
345 			return 1; /* return success, but do nothing */
346 		log_err("cannot open control interface %s %d : "
347 			"protocol not supported", ip, nr);
348 		return 0;
349 	}
350 	if(fd == -1) {
351 		log_err("cannot open control interface %s %d", ip, nr);
352 		return 0;
353 	}
354 
355 	/* alloc */
356 	n = (struct listen_port*)calloc(1, sizeof(*n));
357 	if(!n) {
358 		sock_close(fd);
359 		log_err("out of memory");
360 		return 0;
361 	}
362 	n->next = *list;
363 	*list = n;
364 	n->fd = fd;
365 	return 1;
366 }
367 
368 struct listen_port* daemon_remote_open_ports(struct config_file* cfg)
369 {
370 	struct listen_port* l = NULL;
371 	log_assert(cfg->remote_control_enable && cfg->control_port);
372 	if(cfg->control_ifs.first) {
373 		char** rcif = NULL;
374 		int i, num_rcif = 0;
375 		if(!resolve_interface_names(NULL, 0, cfg->control_ifs.first,
376 			&rcif, &num_rcif)) {
377 			return NULL;
378 		}
379 		for(i=0; i<num_rcif; i++) {
380 			if(!add_open(rcif[i], cfg->control_port, &l, 1, cfg)) {
381 				listening_ports_free(l);
382 				config_del_strarray(rcif, num_rcif);
383 				return NULL;
384 			}
385 		}
386 		config_del_strarray(rcif, num_rcif);
387 	} else {
388 		/* defaults */
389 		if(cfg->do_ip6 &&
390 			!add_open("::1", cfg->control_port, &l, 0, cfg)) {
391 			listening_ports_free(l);
392 			return NULL;
393 		}
394 		if(cfg->do_ip4 &&
395 			!add_open("127.0.0.1", cfg->control_port, &l, 1, cfg)) {
396 			listening_ports_free(l);
397 			return NULL;
398 		}
399 	}
400 	return l;
401 }
402 
403 /** open accept commpoint */
404 static int
405 accept_open(struct daemon_remote* rc, int fd)
406 {
407 	struct listen_list* n = (struct listen_list*)malloc(sizeof(*n));
408 	if(!n) {
409 		log_err("out of memory");
410 		return 0;
411 	}
412 	n->next = rc->accept_list;
413 	rc->accept_list = n;
414 	/* open commpt */
415 	n->com = comm_point_create_raw(rc->worker->base, fd, 0,
416 		&remote_accept_callback, rc);
417 	if(!n->com)
418 		return 0;
419 	/* keep this port open, its fd is kept in the rc portlist */
420 	n->com->do_not_close = 1;
421 	return 1;
422 }
423 
424 int daemon_remote_open_accept(struct daemon_remote* rc,
425 	struct listen_port* ports, struct worker* worker)
426 {
427 	struct listen_port* p;
428 	rc->worker = worker;
429 	for(p = ports; p; p = p->next) {
430 		if(!accept_open(rc, p->fd)) {
431 			log_err("could not create accept comm point");
432 			return 0;
433 		}
434 	}
435 	return 1;
436 }
437 
438 void daemon_remote_stop_accept(struct daemon_remote* rc)
439 {
440 	struct listen_list* p;
441 	for(p=rc->accept_list; p; p=p->next) {
442 		comm_point_stop_listening(p->com);
443 	}
444 }
445 
446 void daemon_remote_start_accept(struct daemon_remote* rc)
447 {
448 	struct listen_list* p;
449 	for(p=rc->accept_list; p; p=p->next) {
450 		comm_point_start_listening(p->com, -1, -1);
451 	}
452 }
453 
454 int remote_accept_callback(struct comm_point* c, void* arg, int err,
455 	struct comm_reply* ATTR_UNUSED(rep))
456 {
457 	struct daemon_remote* rc = (struct daemon_remote*)arg;
458 	struct sockaddr_storage addr;
459 	socklen_t addrlen;
460 	int newfd;
461 	struct rc_state* n;
462 	if(err != NETEVENT_NOERROR) {
463 		log_err("error %d on remote_accept_callback", err);
464 		return 0;
465 	}
466 	/* perform the accept */
467 	newfd = comm_point_perform_accept(c, &addr, &addrlen);
468 	if(newfd == -1)
469 		return 0;
470 	/* create new commpoint unless we are servicing already */
471 	if(rc->active >= rc->max_active) {
472 		log_warn("drop incoming remote control: too many connections");
473 	close_exit:
474 		sock_close(newfd);
475 		return 0;
476 	}
477 
478 	/* setup commpoint to service the remote control command */
479 	n = (struct rc_state*)calloc(1, sizeof(*n));
480 	if(!n) {
481 		log_err("out of memory");
482 		goto close_exit;
483 	}
484 	n->fd = newfd;
485 	/* start in reading state */
486 	n->c = comm_point_create_raw(rc->worker->base, newfd, 0,
487 		&remote_control_callback, n);
488 	if(!n->c) {
489 		log_err("out of memory");
490 		free(n);
491 		goto close_exit;
492 	}
493 	log_addr(VERB_QUERY, "new control connection from", &addr, addrlen);
494 	n->c->do_not_close = 0;
495 	comm_point_stop_listening(n->c);
496 	comm_point_start_listening(n->c, -1, REMOTE_CONTROL_TCP_TIMEOUT);
497 	memcpy(&n->c->repinfo.addr, &addr, addrlen);
498 	n->c->repinfo.addrlen = addrlen;
499 	if(rc->use_cert) {
500 		n->shake_state = rc_hs_read;
501 		n->ssl = SSL_new(rc->ctx);
502 		if(!n->ssl) {
503 			log_crypto_err("could not SSL_new");
504 			comm_point_delete(n->c);
505 			free(n);
506 			goto close_exit;
507 		}
508 		SSL_set_accept_state(n->ssl);
509 		(void)SSL_set_mode(n->ssl, (long)SSL_MODE_AUTO_RETRY);
510 		if(!SSL_set_fd(n->ssl, newfd)) {
511 			log_crypto_err("could not SSL_set_fd");
512 			SSL_free(n->ssl);
513 			comm_point_delete(n->c);
514 			free(n);
515 			goto close_exit;
516 		}
517 	} else {
518 		n->ssl = NULL;
519 	}
520 
521 	n->rc = rc;
522 	n->next = rc->busy_list;
523 	rc->busy_list = n;
524 	rc->active ++;
525 
526 	/* perform the first nonblocking read already, for windows,
527 	 * so it can return wouldblock. could be faster too. */
528 	(void)remote_control_callback(n->c, n, NETEVENT_NOERROR, NULL);
529 	return 0;
530 }
531 
532 /** delete from list */
533 static void
534 state_list_remove_elem(struct rc_state** list, struct comm_point* c)
535 {
536 	while(*list) {
537 		if( (*list)->c == c) {
538 			*list = (*list)->next;
539 			return;
540 		}
541 		list = &(*list)->next;
542 	}
543 }
544 
545 /** decrease active count and remove commpoint from busy list */
546 static void
547 clean_point(struct daemon_remote* rc, struct rc_state* s)
548 {
549 	state_list_remove_elem(&rc->busy_list, s->c);
550 	rc->active --;
551 	if(s->ssl) {
552 		SSL_shutdown(s->ssl);
553 		SSL_free(s->ssl);
554 	}
555 	comm_point_delete(s->c);
556 	free(s);
557 }
558 
559 int
560 ssl_print_text(RES* res, const char* text)
561 {
562 	int r;
563 	if(!res)
564 		return 0;
565 	if(res->ssl) {
566 		ERR_clear_error();
567 		if((r=SSL_write(res->ssl, text, (int)strlen(text))) <= 0) {
568 			if(SSL_get_error(res->ssl, r) == SSL_ERROR_ZERO_RETURN) {
569 				verbose(VERB_QUERY, "warning, in SSL_write, peer "
570 					"closed connection");
571 				return 0;
572 			}
573 			log_crypto_err("could not SSL_write");
574 			return 0;
575 		}
576 	} else {
577 		size_t at = 0;
578 		while(at < strlen(text)) {
579 			ssize_t r = send(res->fd, text+at, strlen(text)-at, 0);
580 			if(r == -1) {
581 				if(errno == EAGAIN || errno == EINTR)
582 					continue;
583 				log_err("could not send: %s",
584 					sock_strerror(errno));
585 				return 0;
586 			}
587 			at += r;
588 		}
589 	}
590 	return 1;
591 }
592 
593 /** print text over the ssl connection */
594 static int
595 ssl_print_vmsg(RES* ssl, const char* format, va_list args)
596 {
597 	char msg[1024];
598 	vsnprintf(msg, sizeof(msg), format, args);
599 	return ssl_print_text(ssl, msg);
600 }
601 
602 /** printf style printing to the ssl connection */
603 int ssl_printf(RES* ssl, const char* format, ...)
604 {
605 	va_list args;
606 	int ret;
607 	va_start(args, format);
608 	ret = ssl_print_vmsg(ssl, format, args);
609 	va_end(args);
610 	return ret;
611 }
612 
613 int
614 ssl_read_line(RES* res, char* buf, size_t max)
615 {
616 	int r;
617 	size_t len = 0;
618 	if(!res)
619 		return 0;
620 	while(len < max) {
621 		if(res->ssl) {
622 			ERR_clear_error();
623 			if((r=SSL_read(res->ssl, buf+len, 1)) <= 0) {
624 				if(SSL_get_error(res->ssl, r) == SSL_ERROR_ZERO_RETURN) {
625 					buf[len] = 0;
626 					return 1;
627 				}
628 				log_crypto_err("could not SSL_read");
629 				return 0;
630 			}
631 		} else {
632 			while(1) {
633 				ssize_t rr = recv(res->fd, buf+len, 1, 0);
634 				if(rr <= 0) {
635 					if(rr == 0) {
636 						buf[len] = 0;
637 						return 1;
638 					}
639 					if(errno == EINTR || errno == EAGAIN)
640 						continue;
641 					log_err("could not recv: %s",
642 						sock_strerror(errno));
643 					return 0;
644 				}
645 				break;
646 			}
647 		}
648 		if(buf[len] == '\n') {
649 			/* return string without \n */
650 			buf[len] = 0;
651 			return 1;
652 		}
653 		len++;
654 	}
655 	buf[max-1] = 0;
656 	log_err("control line too long (%d): %s", (int)max, buf);
657 	return 0;
658 }
659 
660 /** skip whitespace, return new pointer into string */
661 static char*
662 skipwhite(char* str)
663 {
664 	/* EOS \0 is not a space */
665 	while( isspace((unsigned char)*str) )
666 		str++;
667 	return str;
668 }
669 
670 /** send the OK to the control client */
671 static void send_ok(RES* ssl)
672 {
673 	(void)ssl_printf(ssl, "ok\n");
674 }
675 
676 /** do the stop command */
677 static void
678 do_stop(RES* ssl, struct worker* worker)
679 {
680 	worker->need_to_exit = 1;
681 	comm_base_exit(worker->base);
682 	send_ok(ssl);
683 }
684 
685 /** do the reload command */
686 static void
687 do_reload(RES* ssl, struct worker* worker)
688 {
689 	worker->need_to_exit = 0;
690 	comm_base_exit(worker->base);
691 	send_ok(ssl);
692 }
693 
694 /** do the verbosity command */
695 static void
696 do_verbosity(RES* ssl, char* str)
697 {
698 	int val = atoi(str);
699 	if(val == 0 && strcmp(str, "0") != 0) {
700 		ssl_printf(ssl, "error in verbosity number syntax: %s\n", str);
701 		return;
702 	}
703 	verbosity = val;
704 	send_ok(ssl);
705 }
706 
707 /** print stats from statinfo */
708 static int
709 print_stats(RES* ssl, const char* nm, struct ub_stats_info* s)
710 {
711 	struct timeval sumwait, avg;
712 	if(!ssl_printf(ssl, "%s.num.queries"SQ"%lu\n", nm,
713 		(unsigned long)s->svr.num_queries)) return 0;
714 	if(!ssl_printf(ssl, "%s.num.queries_ip_ratelimited"SQ"%lu\n", nm,
715 		(unsigned long)s->svr.num_queries_ip_ratelimited)) return 0;
716 	if(!ssl_printf(ssl, "%s.num.cachehits"SQ"%lu\n", nm,
717 		(unsigned long)(s->svr.num_queries
718 			- s->svr.num_queries_missed_cache))) return 0;
719 	if(!ssl_printf(ssl, "%s.num.cachemiss"SQ"%lu\n", nm,
720 		(unsigned long)s->svr.num_queries_missed_cache)) return 0;
721 	if(!ssl_printf(ssl, "%s.num.prefetch"SQ"%lu\n", nm,
722 		(unsigned long)s->svr.num_queries_prefetch)) return 0;
723 	if(!ssl_printf(ssl, "%s.num.expired"SQ"%lu\n", nm,
724 		(unsigned long)s->svr.ans_expired)) return 0;
725 	if(!ssl_printf(ssl, "%s.num.recursivereplies"SQ"%lu\n", nm,
726 		(unsigned long)s->mesh_replies_sent)) return 0;
727 #ifdef USE_DNSCRYPT
728 	if(!ssl_printf(ssl, "%s.num.dnscrypt.crypted"SQ"%lu\n", nm,
729 		(unsigned long)s->svr.num_query_dnscrypt_crypted)) return 0;
730 	if(!ssl_printf(ssl, "%s.num.dnscrypt.cert"SQ"%lu\n", nm,
731 		(unsigned long)s->svr.num_query_dnscrypt_cert)) return 0;
732 	if(!ssl_printf(ssl, "%s.num.dnscrypt.cleartext"SQ"%lu\n", nm,
733 		(unsigned long)s->svr.num_query_dnscrypt_cleartext)) return 0;
734 	if(!ssl_printf(ssl, "%s.num.dnscrypt.malformed"SQ"%lu\n", nm,
735 		(unsigned long)s->svr.num_query_dnscrypt_crypted_malformed)) return 0;
736 #endif
737 	if(!ssl_printf(ssl, "%s.requestlist.avg"SQ"%g\n", nm,
738 		(s->svr.num_queries_missed_cache+s->svr.num_queries_prefetch)?
739 			(double)s->svr.sum_query_list_size/
740 			(double)(s->svr.num_queries_missed_cache+
741 			s->svr.num_queries_prefetch) : 0.0)) return 0;
742 	if(!ssl_printf(ssl, "%s.requestlist.max"SQ"%lu\n", nm,
743 		(unsigned long)s->svr.max_query_list_size)) return 0;
744 	if(!ssl_printf(ssl, "%s.requestlist.overwritten"SQ"%lu\n", nm,
745 		(unsigned long)s->mesh_jostled)) return 0;
746 	if(!ssl_printf(ssl, "%s.requestlist.exceeded"SQ"%lu\n", nm,
747 		(unsigned long)s->mesh_dropped)) return 0;
748 	if(!ssl_printf(ssl, "%s.requestlist.current.all"SQ"%lu\n", nm,
749 		(unsigned long)s->mesh_num_states)) return 0;
750 	if(!ssl_printf(ssl, "%s.requestlist.current.user"SQ"%lu\n", nm,
751 		(unsigned long)s->mesh_num_reply_states)) return 0;
752 #ifndef S_SPLINT_S
753 	sumwait.tv_sec = s->mesh_replies_sum_wait_sec;
754 	sumwait.tv_usec = s->mesh_replies_sum_wait_usec;
755 #endif
756 	timeval_divide(&avg, &sumwait, s->mesh_replies_sent);
757 	if(!ssl_printf(ssl, "%s.recursion.time.avg"SQ ARG_LL "d.%6.6d\n", nm,
758 		(long long)avg.tv_sec, (int)avg.tv_usec)) return 0;
759 	if(!ssl_printf(ssl, "%s.recursion.time.median"SQ"%g\n", nm,
760 		s->mesh_time_median)) return 0;
761 	if(!ssl_printf(ssl, "%s.tcpusage"SQ"%lu\n", nm,
762 		(unsigned long)s->svr.tcp_accept_usage)) return 0;
763 	return 1;
764 }
765 
766 /** print stats for one thread */
767 static int
768 print_thread_stats(RES* ssl, int i, struct ub_stats_info* s)
769 {
770 	char nm[32];
771 	snprintf(nm, sizeof(nm), "thread%d", i);
772 	nm[sizeof(nm)-1]=0;
773 	return print_stats(ssl, nm, s);
774 }
775 
776 /** print long number */
777 static int
778 print_longnum(RES* ssl, const char* desc, size_t x)
779 {
780 	if(x > 1024*1024*1024) {
781 		/* more than a Gb */
782 		size_t front = x / (size_t)1000000;
783 		size_t back = x % (size_t)1000000;
784 		return ssl_printf(ssl, "%s%u%6.6u\n", desc,
785 			(unsigned)front, (unsigned)back);
786 	} else {
787 		return ssl_printf(ssl, "%s%lu\n", desc, (unsigned long)x);
788 	}
789 }
790 
791 /** print mem stats */
792 static int
793 print_mem(RES* ssl, struct worker* worker, struct daemon* daemon,
794 	struct ub_stats_info* s)
795 {
796 	size_t msg, rrset, val, iter, respip;
797 #ifdef CLIENT_SUBNET
798 	size_t subnet = 0;
799 #endif /* CLIENT_SUBNET */
800 #ifdef USE_IPSECMOD
801 	size_t ipsecmod = 0;
802 #endif /* USE_IPSECMOD */
803 #ifdef USE_DNSCRYPT
804 	size_t dnscrypt_shared_secret = 0;
805 	size_t dnscrypt_nonce = 0;
806 #endif /* USE_DNSCRYPT */
807 #ifdef WITH_DYNLIBMODULE
808     size_t dynlib = 0;
809 #endif /* WITH_DYNLIBMODULE */
810 	msg = slabhash_get_mem(daemon->env->msg_cache);
811 	rrset = slabhash_get_mem(&daemon->env->rrset_cache->table);
812 	val = mod_get_mem(&worker->env, "validator");
813 	iter = mod_get_mem(&worker->env, "iterator");
814 	respip = mod_get_mem(&worker->env, "respip");
815 #ifdef CLIENT_SUBNET
816 	subnet = mod_get_mem(&worker->env, "subnetcache");
817 #endif /* CLIENT_SUBNET */
818 #ifdef USE_IPSECMOD
819 	ipsecmod = mod_get_mem(&worker->env, "ipsecmod");
820 #endif /* USE_IPSECMOD */
821 #ifdef USE_DNSCRYPT
822 	if(daemon->dnscenv) {
823 		dnscrypt_shared_secret = slabhash_get_mem(
824 			daemon->dnscenv->shared_secrets_cache);
825 		dnscrypt_nonce = slabhash_get_mem(daemon->dnscenv->nonces_cache);
826 	}
827 #endif /* USE_DNSCRYPT */
828 #ifdef WITH_DYNLIBMODULE
829     dynlib = mod_get_mem(&worker->env, "dynlib");
830 #endif /* WITH_DYNLIBMODULE */
831 
832 	if(!print_longnum(ssl, "mem.cache.rrset"SQ, rrset))
833 		return 0;
834 	if(!print_longnum(ssl, "mem.cache.message"SQ, msg))
835 		return 0;
836 	if(!print_longnum(ssl, "mem.mod.iterator"SQ, iter))
837 		return 0;
838 	if(!print_longnum(ssl, "mem.mod.validator"SQ, val))
839 		return 0;
840 	if(!print_longnum(ssl, "mem.mod.respip"SQ, respip))
841 		return 0;
842 #ifdef CLIENT_SUBNET
843 	if(!print_longnum(ssl, "mem.mod.subnet"SQ, subnet))
844 		return 0;
845 #endif /* CLIENT_SUBNET */
846 #ifdef USE_IPSECMOD
847 	if(!print_longnum(ssl, "mem.mod.ipsecmod"SQ, ipsecmod))
848 		return 0;
849 #endif /* USE_IPSECMOD */
850 #ifdef USE_DNSCRYPT
851 	if(!print_longnum(ssl, "mem.cache.dnscrypt_shared_secret"SQ,
852 			dnscrypt_shared_secret))
853 		return 0;
854 	if(!print_longnum(ssl, "mem.cache.dnscrypt_nonce"SQ,
855 			dnscrypt_nonce))
856 		return 0;
857 #endif /* USE_DNSCRYPT */
858 #ifdef WITH_DYNLIBMODULE
859 	if(!print_longnum(ssl, "mem.mod.dynlibmod"SQ, dynlib))
860 		return 0;
861 #endif /* WITH_DYNLIBMODULE */
862 	if(!print_longnum(ssl, "mem.streamwait"SQ,
863 		(size_t)s->svr.mem_stream_wait))
864 		return 0;
865 	if(!print_longnum(ssl, "mem.http.query_buffer"SQ,
866 		(size_t)s->svr.mem_http2_query_buffer))
867 		return 0;
868 	if(!print_longnum(ssl, "mem.http.response_buffer"SQ,
869 		(size_t)s->svr.mem_http2_response_buffer))
870 		return 0;
871 	return 1;
872 }
873 
874 /** print uptime stats */
875 static int
876 print_uptime(RES* ssl, struct worker* worker, int reset)
877 {
878 	struct timeval now = *worker->env.now_tv;
879 	struct timeval up, dt;
880 	timeval_subtract(&up, &now, &worker->daemon->time_boot);
881 	timeval_subtract(&dt, &now, &worker->daemon->time_last_stat);
882 	if(reset)
883 		worker->daemon->time_last_stat = now;
884 	if(!ssl_printf(ssl, "time.now"SQ ARG_LL "d.%6.6d\n",
885 		(long long)now.tv_sec, (unsigned)now.tv_usec)) return 0;
886 	if(!ssl_printf(ssl, "time.up"SQ ARG_LL "d.%6.6d\n",
887 		(long long)up.tv_sec, (unsigned)up.tv_usec)) return 0;
888 	if(!ssl_printf(ssl, "time.elapsed"SQ ARG_LL "d.%6.6d\n",
889 		(long long)dt.tv_sec, (unsigned)dt.tv_usec)) return 0;
890 	return 1;
891 }
892 
893 /** print extended histogram */
894 static int
895 print_hist(RES* ssl, struct ub_stats_info* s)
896 {
897 	struct timehist* hist;
898 	size_t i;
899 	hist = timehist_setup();
900 	if(!hist) {
901 		log_err("out of memory");
902 		return 0;
903 	}
904 	timehist_import(hist, s->svr.hist, NUM_BUCKETS_HIST);
905 	for(i=0; i<hist->num; i++) {
906 		if(!ssl_printf(ssl,
907 			"histogram.%6.6d.%6.6d.to.%6.6d.%6.6d=%lu\n",
908 			(int)hist->buckets[i].lower.tv_sec,
909 			(int)hist->buckets[i].lower.tv_usec,
910 			(int)hist->buckets[i].upper.tv_sec,
911 			(int)hist->buckets[i].upper.tv_usec,
912 			(unsigned long)hist->buckets[i].count)) {
913 			timehist_delete(hist);
914 			return 0;
915 		}
916 	}
917 	timehist_delete(hist);
918 	return 1;
919 }
920 
921 /** print extended stats */
922 static int
923 print_ext(RES* ssl, struct ub_stats_info* s)
924 {
925 	int i;
926 	char nm[32];
927 	const sldns_rr_descriptor* desc;
928 	const sldns_lookup_table* lt;
929 	/* TYPE */
930 	for(i=0; i<UB_STATS_QTYPE_NUM; i++) {
931 		if(inhibit_zero && s->svr.qtype[i] == 0)
932 			continue;
933 		desc = sldns_rr_descript((uint16_t)i);
934 		if(desc && desc->_name) {
935 			snprintf(nm, sizeof(nm), "%s", desc->_name);
936 		} else if (i == LDNS_RR_TYPE_IXFR) {
937 			snprintf(nm, sizeof(nm), "IXFR");
938 		} else if (i == LDNS_RR_TYPE_AXFR) {
939 			snprintf(nm, sizeof(nm), "AXFR");
940 		} else if (i == LDNS_RR_TYPE_MAILA) {
941 			snprintf(nm, sizeof(nm), "MAILA");
942 		} else if (i == LDNS_RR_TYPE_MAILB) {
943 			snprintf(nm, sizeof(nm), "MAILB");
944 		} else if (i == LDNS_RR_TYPE_ANY) {
945 			snprintf(nm, sizeof(nm), "ANY");
946 		} else {
947 			snprintf(nm, sizeof(nm), "TYPE%d", i);
948 		}
949 		if(!ssl_printf(ssl, "num.query.type.%s"SQ"%lu\n",
950 			nm, (unsigned long)s->svr.qtype[i])) return 0;
951 	}
952 	if(!inhibit_zero || s->svr.qtype_big) {
953 		if(!ssl_printf(ssl, "num.query.type.other"SQ"%lu\n",
954 			(unsigned long)s->svr.qtype_big)) return 0;
955 	}
956 	/* CLASS */
957 	for(i=0; i<UB_STATS_QCLASS_NUM; i++) {
958 		if(inhibit_zero && s->svr.qclass[i] == 0)
959 			continue;
960 		lt = sldns_lookup_by_id(sldns_rr_classes, i);
961 		if(lt && lt->name) {
962 			snprintf(nm, sizeof(nm), "%s", lt->name);
963 		} else {
964 			snprintf(nm, sizeof(nm), "CLASS%d", i);
965 		}
966 		if(!ssl_printf(ssl, "num.query.class.%s"SQ"%lu\n",
967 			nm, (unsigned long)s->svr.qclass[i])) return 0;
968 	}
969 	if(!inhibit_zero || s->svr.qclass_big) {
970 		if(!ssl_printf(ssl, "num.query.class.other"SQ"%lu\n",
971 			(unsigned long)s->svr.qclass_big)) return 0;
972 	}
973 	/* OPCODE */
974 	for(i=0; i<UB_STATS_OPCODE_NUM; i++) {
975 		if(inhibit_zero && s->svr.qopcode[i] == 0)
976 			continue;
977 		lt = sldns_lookup_by_id(sldns_opcodes, i);
978 		if(lt && lt->name) {
979 			snprintf(nm, sizeof(nm), "%s", lt->name);
980 		} else {
981 			snprintf(nm, sizeof(nm), "OPCODE%d", i);
982 		}
983 		if(!ssl_printf(ssl, "num.query.opcode.%s"SQ"%lu\n",
984 			nm, (unsigned long)s->svr.qopcode[i])) return 0;
985 	}
986 	/* transport */
987 	if(!ssl_printf(ssl, "num.query.tcp"SQ"%lu\n",
988 		(unsigned long)s->svr.qtcp)) return 0;
989 	if(!ssl_printf(ssl, "num.query.tcpout"SQ"%lu\n",
990 		(unsigned long)s->svr.qtcp_outgoing)) return 0;
991 	if(!ssl_printf(ssl, "num.query.tls"SQ"%lu\n",
992 		(unsigned long)s->svr.qtls)) return 0;
993 	if(!ssl_printf(ssl, "num.query.tls.resume"SQ"%lu\n",
994 		(unsigned long)s->svr.qtls_resume)) return 0;
995 	if(!ssl_printf(ssl, "num.query.ipv6"SQ"%lu\n",
996 		(unsigned long)s->svr.qipv6)) return 0;
997 	if(!ssl_printf(ssl, "num.query.https"SQ"%lu\n",
998 		(unsigned long)s->svr.qhttps)) return 0;
999 	/* flags */
1000 	if(!ssl_printf(ssl, "num.query.flags.QR"SQ"%lu\n",
1001 		(unsigned long)s->svr.qbit_QR)) return 0;
1002 	if(!ssl_printf(ssl, "num.query.flags.AA"SQ"%lu\n",
1003 		(unsigned long)s->svr.qbit_AA)) return 0;
1004 	if(!ssl_printf(ssl, "num.query.flags.TC"SQ"%lu\n",
1005 		(unsigned long)s->svr.qbit_TC)) return 0;
1006 	if(!ssl_printf(ssl, "num.query.flags.RD"SQ"%lu\n",
1007 		(unsigned long)s->svr.qbit_RD)) return 0;
1008 	if(!ssl_printf(ssl, "num.query.flags.RA"SQ"%lu\n",
1009 		(unsigned long)s->svr.qbit_RA)) return 0;
1010 	if(!ssl_printf(ssl, "num.query.flags.Z"SQ"%lu\n",
1011 		(unsigned long)s->svr.qbit_Z)) return 0;
1012 	if(!ssl_printf(ssl, "num.query.flags.AD"SQ"%lu\n",
1013 		(unsigned long)s->svr.qbit_AD)) return 0;
1014 	if(!ssl_printf(ssl, "num.query.flags.CD"SQ"%lu\n",
1015 		(unsigned long)s->svr.qbit_CD)) return 0;
1016 	if(!ssl_printf(ssl, "num.query.edns.present"SQ"%lu\n",
1017 		(unsigned long)s->svr.qEDNS)) return 0;
1018 	if(!ssl_printf(ssl, "num.query.edns.DO"SQ"%lu\n",
1019 		(unsigned long)s->svr.qEDNS_DO)) return 0;
1020 
1021 	/* RCODE */
1022 	for(i=0; i<UB_STATS_RCODE_NUM; i++) {
1023 		/* Always include RCODEs 0-5 */
1024 		if(inhibit_zero && i > LDNS_RCODE_REFUSED && s->svr.ans_rcode[i] == 0)
1025 			continue;
1026 		lt = sldns_lookup_by_id(sldns_rcodes, i);
1027 		if(lt && lt->name) {
1028 			snprintf(nm, sizeof(nm), "%s", lt->name);
1029 		} else {
1030 			snprintf(nm, sizeof(nm), "RCODE%d", i);
1031 		}
1032 		if(!ssl_printf(ssl, "num.answer.rcode.%s"SQ"%lu\n",
1033 			nm, (unsigned long)s->svr.ans_rcode[i])) return 0;
1034 	}
1035 	if(!inhibit_zero || s->svr.ans_rcode_nodata) {
1036 		if(!ssl_printf(ssl, "num.answer.rcode.nodata"SQ"%lu\n",
1037 			(unsigned long)s->svr.ans_rcode_nodata)) return 0;
1038 	}
1039 	/* iteration */
1040 	if(!ssl_printf(ssl, "num.query.ratelimited"SQ"%lu\n",
1041 		(unsigned long)s->svr.queries_ratelimited)) return 0;
1042 	/* validation */
1043 	if(!ssl_printf(ssl, "num.answer.secure"SQ"%lu\n",
1044 		(unsigned long)s->svr.ans_secure)) return 0;
1045 	if(!ssl_printf(ssl, "num.answer.bogus"SQ"%lu\n",
1046 		(unsigned long)s->svr.ans_bogus)) return 0;
1047 	if(!ssl_printf(ssl, "num.rrset.bogus"SQ"%lu\n",
1048 		(unsigned long)s->svr.rrset_bogus)) return 0;
1049 	if(!ssl_printf(ssl, "num.query.aggressive.NOERROR"SQ"%lu\n",
1050 		(unsigned long)s->svr.num_neg_cache_noerror)) return 0;
1051 	if(!ssl_printf(ssl, "num.query.aggressive.NXDOMAIN"SQ"%lu\n",
1052 		(unsigned long)s->svr.num_neg_cache_nxdomain)) return 0;
1053 	/* threat detection */
1054 	if(!ssl_printf(ssl, "unwanted.queries"SQ"%lu\n",
1055 		(unsigned long)s->svr.unwanted_queries)) return 0;
1056 	if(!ssl_printf(ssl, "unwanted.replies"SQ"%lu\n",
1057 		(unsigned long)s->svr.unwanted_replies)) return 0;
1058 	/* cache counts */
1059 	if(!ssl_printf(ssl, "msg.cache.count"SQ"%u\n",
1060 		(unsigned)s->svr.msg_cache_count)) return 0;
1061 	if(!ssl_printf(ssl, "rrset.cache.count"SQ"%u\n",
1062 		(unsigned)s->svr.rrset_cache_count)) return 0;
1063 	if(!ssl_printf(ssl, "infra.cache.count"SQ"%u\n",
1064 		(unsigned)s->svr.infra_cache_count)) return 0;
1065 	if(!ssl_printf(ssl, "key.cache.count"SQ"%u\n",
1066 		(unsigned)s->svr.key_cache_count)) return 0;
1067 	/* applied RPZ actions */
1068 	for(i=0; i<UB_STATS_RPZ_ACTION_NUM; i++) {
1069 		if(i == RPZ_NO_OVERRIDE_ACTION)
1070 			continue;
1071 		if(inhibit_zero && s->svr.rpz_action[i] == 0)
1072 			continue;
1073 		if(!ssl_printf(ssl, "num.rpz.action.%s"SQ"%lu\n",
1074 			rpz_action_to_string(i),
1075 			(unsigned long)s->svr.rpz_action[i])) return 0;
1076 	}
1077 #ifdef USE_DNSCRYPT
1078 	if(!ssl_printf(ssl, "dnscrypt_shared_secret.cache.count"SQ"%u\n",
1079 		(unsigned)s->svr.shared_secret_cache_count)) return 0;
1080 	if(!ssl_printf(ssl, "dnscrypt_nonce.cache.count"SQ"%u\n",
1081 		(unsigned)s->svr.nonce_cache_count)) return 0;
1082 	if(!ssl_printf(ssl, "num.query.dnscrypt.shared_secret.cachemiss"SQ"%lu\n",
1083 		(unsigned long)s->svr.num_query_dnscrypt_secret_missed_cache)) return 0;
1084 	if(!ssl_printf(ssl, "num.query.dnscrypt.replay"SQ"%lu\n",
1085 		(unsigned long)s->svr.num_query_dnscrypt_replay)) return 0;
1086 #endif /* USE_DNSCRYPT */
1087 	if(!ssl_printf(ssl, "num.query.authzone.up"SQ"%lu\n",
1088 		(unsigned long)s->svr.num_query_authzone_up)) return 0;
1089 	if(!ssl_printf(ssl, "num.query.authzone.down"SQ"%lu\n",
1090 		(unsigned long)s->svr.num_query_authzone_down)) return 0;
1091 #ifdef CLIENT_SUBNET
1092 	if(!ssl_printf(ssl, "num.query.subnet"SQ"%lu\n",
1093 		(unsigned long)s->svr.num_query_subnet)) return 0;
1094 	if(!ssl_printf(ssl, "num.query.subnet_cache"SQ"%lu\n",
1095 		(unsigned long)s->svr.num_query_subnet_cache)) return 0;
1096 #endif /* CLIENT_SUBNET */
1097 	return 1;
1098 }
1099 
1100 /** do the stats command */
1101 static void
1102 do_stats(RES* ssl, struct worker* worker, int reset)
1103 {
1104 	struct daemon* daemon = worker->daemon;
1105 	struct ub_stats_info total;
1106 	struct ub_stats_info s;
1107 	int i;
1108 	memset(&total, 0, sizeof(total));
1109 	log_assert(daemon->num > 0);
1110 	/* gather all thread statistics in one place */
1111 	for(i=0; i<daemon->num; i++) {
1112 		server_stats_obtain(worker, daemon->workers[i], &s, reset);
1113 		if(!print_thread_stats(ssl, i, &s))
1114 			return;
1115 		if(i == 0)
1116 			total = s;
1117 		else	server_stats_add(&total, &s);
1118 	}
1119 	/* print the thread statistics */
1120 	total.mesh_time_median /= (double)daemon->num;
1121 	if(!print_stats(ssl, "total", &total))
1122 		return;
1123 	if(!print_uptime(ssl, worker, reset))
1124 		return;
1125 	if(daemon->cfg->stat_extended) {
1126 		if(!print_mem(ssl, worker, daemon, &total))
1127 			return;
1128 		if(!print_hist(ssl, &total))
1129 			return;
1130 		if(!print_ext(ssl, &total))
1131 			return;
1132 	}
1133 }
1134 
1135 /** parse commandline argument domain name */
1136 static int
1137 parse_arg_name(RES* ssl, char* str, uint8_t** res, size_t* len, int* labs)
1138 {
1139 	uint8_t nm[LDNS_MAX_DOMAINLEN+1];
1140 	size_t nmlen = sizeof(nm);
1141 	int status;
1142 	*res = NULL;
1143 	*len = 0;
1144 	*labs = 0;
1145 	if(str[0] == '\0') {
1146 		ssl_printf(ssl, "error: this option requires a domain name\n");
1147 		return 0;
1148 	}
1149 	status = sldns_str2wire_dname_buf(str, nm, &nmlen);
1150 	if(status != 0) {
1151 		ssl_printf(ssl, "error cannot parse name %s at %d: %s\n", str,
1152 			LDNS_WIREPARSE_OFFSET(status),
1153 			sldns_get_errorstr_parse(status));
1154 		return 0;
1155 	}
1156 	*res = memdup(nm, nmlen);
1157 	if(!*res) {
1158 		ssl_printf(ssl, "error out of memory\n");
1159 		return 0;
1160 	}
1161 	*labs = dname_count_size_labels(*res, len);
1162 	return 1;
1163 }
1164 
1165 /** find second argument, modifies string */
1166 static int
1167 find_arg2(RES* ssl, char* arg, char** arg2)
1168 {
1169 	char* as = strchr(arg, ' ');
1170 	char* at = strchr(arg, '\t');
1171 	if(as && at) {
1172 		if(at < as)
1173 			as = at;
1174 		as[0]=0;
1175 		*arg2 = skipwhite(as+1);
1176 	} else if(as) {
1177 		as[0]=0;
1178 		*arg2 = skipwhite(as+1);
1179 	} else if(at) {
1180 		at[0]=0;
1181 		*arg2 = skipwhite(at+1);
1182 	} else {
1183 		ssl_printf(ssl, "error could not find next argument "
1184 			"after %s\n", arg);
1185 		return 0;
1186 	}
1187 	return 1;
1188 }
1189 
1190 /** Add a new zone */
1191 static int
1192 perform_zone_add(RES* ssl, struct local_zones* zones, char* arg)
1193 {
1194 	uint8_t* nm;
1195 	int nmlabs;
1196 	size_t nmlen;
1197 	char* arg2;
1198 	enum localzone_type t;
1199 	struct local_zone* z;
1200 	if(!find_arg2(ssl, arg, &arg2))
1201 		return 0;
1202 	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1203 		return 0;
1204 	if(!local_zone_str2type(arg2, &t)) {
1205 		ssl_printf(ssl, "error not a zone type. %s\n", arg2);
1206 		free(nm);
1207 		return 0;
1208 	}
1209 	lock_rw_wrlock(&zones->lock);
1210 	if((z=local_zones_find(zones, nm, nmlen,
1211 		nmlabs, LDNS_RR_CLASS_IN))) {
1212 		/* already present in tree */
1213 		lock_rw_wrlock(&z->lock);
1214 		z->type = t; /* update type anyway */
1215 		lock_rw_unlock(&z->lock);
1216 		free(nm);
1217 		lock_rw_unlock(&zones->lock);
1218 		return 1;
1219 	}
1220 	if(!local_zones_add_zone(zones, nm, nmlen,
1221 		nmlabs, LDNS_RR_CLASS_IN, t)) {
1222 		lock_rw_unlock(&zones->lock);
1223 		ssl_printf(ssl, "error out of memory\n");
1224 		return 0;
1225 	}
1226 	lock_rw_unlock(&zones->lock);
1227 	return 1;
1228 }
1229 
1230 /** Do the local_zone command */
1231 static void
1232 do_zone_add(RES* ssl, struct local_zones* zones, char* arg)
1233 {
1234 	if(!perform_zone_add(ssl, zones, arg))
1235 		return;
1236 	send_ok(ssl);
1237 }
1238 
1239 /** Do the local_zones command */
1240 static void
1241 do_zones_add(RES* ssl, struct local_zones* zones)
1242 {
1243 	char buf[2048];
1244 	int num = 0;
1245 	while(ssl_read_line(ssl, buf, sizeof(buf))) {
1246 		if(buf[0] == 0x04 && buf[1] == 0)
1247 			break; /* end of transmission */
1248 		if(!perform_zone_add(ssl, zones, buf)) {
1249 			if(!ssl_printf(ssl, "error for input line: %s\n", buf))
1250 				return;
1251 		}
1252 		else
1253 			num++;
1254 	}
1255 	(void)ssl_printf(ssl, "added %d zones\n", num);
1256 }
1257 
1258 /** Remove a zone */
1259 static int
1260 perform_zone_remove(RES* ssl, struct local_zones* zones, char* arg)
1261 {
1262 	uint8_t* nm;
1263 	int nmlabs;
1264 	size_t nmlen;
1265 	struct local_zone* z;
1266 	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1267 		return 0;
1268 	lock_rw_wrlock(&zones->lock);
1269 	if((z=local_zones_find(zones, nm, nmlen,
1270 		nmlabs, LDNS_RR_CLASS_IN))) {
1271 		/* present in tree */
1272 		local_zones_del_zone(zones, z);
1273 	}
1274 	lock_rw_unlock(&zones->lock);
1275 	free(nm);
1276 	return 1;
1277 }
1278 
1279 /** Do the local_zone_remove command */
1280 static void
1281 do_zone_remove(RES* ssl, struct local_zones* zones, char* arg)
1282 {
1283 	if(!perform_zone_remove(ssl, zones, arg))
1284 		return;
1285 	send_ok(ssl);
1286 }
1287 
1288 /** Do the local_zones_remove command */
1289 static void
1290 do_zones_remove(RES* ssl, struct local_zones* zones)
1291 {
1292 	char buf[2048];
1293 	int num = 0;
1294 	while(ssl_read_line(ssl, buf, sizeof(buf))) {
1295 		if(buf[0] == 0x04 && buf[1] == 0)
1296 			break; /* end of transmission */
1297 		if(!perform_zone_remove(ssl, zones, buf)) {
1298 			if(!ssl_printf(ssl, "error for input line: %s\n", buf))
1299 				return;
1300 		}
1301 		else
1302 			num++;
1303 	}
1304 	(void)ssl_printf(ssl, "removed %d zones\n", num);
1305 }
1306 
1307 /** check syntax of newly added RR */
1308 static int
1309 check_RR_syntax(RES* ssl, char* str, int line)
1310 {
1311 	uint8_t rr[LDNS_RR_BUF_SIZE];
1312 	size_t len = sizeof(rr), dname_len = 0;
1313 	int s = sldns_str2wire_rr_buf(str, rr, &len, &dname_len, 3600,
1314 		NULL, 0, NULL, 0);
1315 	if(s != 0) {
1316 		char linestr[32];
1317 		if(line == 0)
1318 			linestr[0]=0;
1319 		else 	snprintf(linestr, sizeof(linestr), "line %d ", line);
1320 		if(!ssl_printf(ssl, "error parsing local-data at %sposition %d '%s': %s\n",
1321 			linestr, LDNS_WIREPARSE_OFFSET(s), str,
1322 			sldns_get_errorstr_parse(s)))
1323 			return 0;
1324 		return 0;
1325 	}
1326 	return 1;
1327 }
1328 
1329 /** Add new RR data */
1330 static int
1331 perform_data_add(RES* ssl, struct local_zones* zones, char* arg, int line)
1332 {
1333 	if(!check_RR_syntax(ssl, arg, line)) {
1334 		return 0;
1335 	}
1336 	if(!local_zones_add_RR(zones, arg)) {
1337 		ssl_printf(ssl,"error in syntax or out of memory, %s\n", arg);
1338 		return 0;
1339 	}
1340 	return 1;
1341 }
1342 
1343 /** Do the local_data command */
1344 static void
1345 do_data_add(RES* ssl, struct local_zones* zones, char* arg)
1346 {
1347 	if(!perform_data_add(ssl, zones, arg, 0))
1348 		return;
1349 	send_ok(ssl);
1350 }
1351 
1352 /** Do the local_datas command */
1353 static void
1354 do_datas_add(RES* ssl, struct local_zones* zones)
1355 {
1356 	char buf[2048];
1357 	int num = 0, line = 0;
1358 	while(ssl_read_line(ssl, buf, sizeof(buf))) {
1359 		if(buf[0] == 0x04 && buf[1] == 0)
1360 			break; /* end of transmission */
1361 		line++;
1362 		if(perform_data_add(ssl, zones, buf, line))
1363 			num++;
1364 	}
1365 	(void)ssl_printf(ssl, "added %d datas\n", num);
1366 }
1367 
1368 /** Remove RR data */
1369 static int
1370 perform_data_remove(RES* ssl, struct local_zones* zones, char* arg)
1371 {
1372 	uint8_t* nm;
1373 	int nmlabs;
1374 	size_t nmlen;
1375 	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1376 		return 0;
1377 	local_zones_del_data(zones, nm,
1378 		nmlen, nmlabs, LDNS_RR_CLASS_IN);
1379 	free(nm);
1380 	return 1;
1381 }
1382 
1383 /** Do the local_data_remove command */
1384 static void
1385 do_data_remove(RES* ssl, struct local_zones* zones, char* arg)
1386 {
1387 	if(!perform_data_remove(ssl, zones, arg))
1388 		return;
1389 	send_ok(ssl);
1390 }
1391 
1392 /** Do the local_datas_remove command */
1393 static void
1394 do_datas_remove(RES* ssl, struct local_zones* zones)
1395 {
1396 	char buf[2048];
1397 	int num = 0;
1398 	while(ssl_read_line(ssl, buf, sizeof(buf))) {
1399 		if(buf[0] == 0x04 && buf[1] == 0)
1400 			break; /* end of transmission */
1401 		if(!perform_data_remove(ssl, zones, buf)) {
1402 			if(!ssl_printf(ssl, "error for input line: %s\n", buf))
1403 				return;
1404 		}
1405 		else
1406 			num++;
1407 	}
1408 	(void)ssl_printf(ssl, "removed %d datas\n", num);
1409 }
1410 
1411 /** Add a new zone to view */
1412 static void
1413 do_view_zone_add(RES* ssl, struct worker* worker, char* arg)
1414 {
1415 	char* arg2;
1416 	struct view* v;
1417 	if(!find_arg2(ssl, arg, &arg2))
1418 		return;
1419 	v = views_find_view(worker->daemon->views,
1420 		arg, 1 /* get write lock*/);
1421 	if(!v) {
1422 		ssl_printf(ssl,"no view with name: %s\n", arg);
1423 		return;
1424 	}
1425 	if(!v->local_zones) {
1426 		if(!(v->local_zones = local_zones_create())){
1427 			lock_rw_unlock(&v->lock);
1428 			ssl_printf(ssl,"error out of memory\n");
1429 			return;
1430 		}
1431 		if(!v->isfirst) {
1432 			/* Global local-zone is not used for this view,
1433 			 * therefore add defaults to this view-specic
1434 			 * local-zone. */
1435 			struct config_file lz_cfg;
1436 			memset(&lz_cfg, 0, sizeof(lz_cfg));
1437 			local_zone_enter_defaults(v->local_zones, &lz_cfg);
1438 		}
1439 	}
1440 	do_zone_add(ssl, v->local_zones, arg2);
1441 	lock_rw_unlock(&v->lock);
1442 }
1443 
1444 /** Remove a zone from view */
1445 static void
1446 do_view_zone_remove(RES* ssl, struct worker* worker, char* arg)
1447 {
1448 	char* arg2;
1449 	struct view* v;
1450 	if(!find_arg2(ssl, arg, &arg2))
1451 		return;
1452 	v = views_find_view(worker->daemon->views,
1453 		arg, 1 /* get write lock*/);
1454 	if(!v) {
1455 		ssl_printf(ssl,"no view with name: %s\n", arg);
1456 		return;
1457 	}
1458 	if(!v->local_zones) {
1459 		lock_rw_unlock(&v->lock);
1460 		send_ok(ssl);
1461 		return;
1462 	}
1463 	do_zone_remove(ssl, v->local_zones, arg2);
1464 	lock_rw_unlock(&v->lock);
1465 }
1466 
1467 /** Add new RR data to view */
1468 static void
1469 do_view_data_add(RES* ssl, struct worker* worker, char* arg)
1470 {
1471 	char* arg2;
1472 	struct view* v;
1473 	if(!find_arg2(ssl, arg, &arg2))
1474 		return;
1475 	v = views_find_view(worker->daemon->views,
1476 		arg, 1 /* get write lock*/);
1477 	if(!v) {
1478 		ssl_printf(ssl,"no view with name: %s\n", arg);
1479 		return;
1480 	}
1481 	if(!v->local_zones) {
1482 		if(!(v->local_zones = local_zones_create())){
1483 			lock_rw_unlock(&v->lock);
1484 			ssl_printf(ssl,"error out of memory\n");
1485 			return;
1486 		}
1487 	}
1488 	do_data_add(ssl, v->local_zones, arg2);
1489 	lock_rw_unlock(&v->lock);
1490 }
1491 
1492 /** Add new RR data from stdin to view */
1493 static void
1494 do_view_datas_add(RES* ssl, struct worker* worker, char* arg)
1495 {
1496 	struct view* v;
1497 	v = views_find_view(worker->daemon->views,
1498 		arg, 1 /* get write lock*/);
1499 	if(!v) {
1500 		ssl_printf(ssl,"no view with name: %s\n", arg);
1501 		return;
1502 	}
1503 	if(!v->local_zones) {
1504 		if(!(v->local_zones = local_zones_create())){
1505 			lock_rw_unlock(&v->lock);
1506 			ssl_printf(ssl,"error out of memory\n");
1507 			return;
1508 		}
1509 	}
1510 	do_datas_add(ssl, v->local_zones);
1511 	lock_rw_unlock(&v->lock);
1512 }
1513 
1514 /** Remove RR data from view */
1515 static void
1516 do_view_data_remove(RES* ssl, struct worker* worker, char* arg)
1517 {
1518 	char* arg2;
1519 	struct view* v;
1520 	if(!find_arg2(ssl, arg, &arg2))
1521 		return;
1522 	v = views_find_view(worker->daemon->views,
1523 		arg, 1 /* get write lock*/);
1524 	if(!v) {
1525 		ssl_printf(ssl,"no view with name: %s\n", arg);
1526 		return;
1527 	}
1528 	if(!v->local_zones) {
1529 		lock_rw_unlock(&v->lock);
1530 		send_ok(ssl);
1531 		return;
1532 	}
1533 	do_data_remove(ssl, v->local_zones, arg2);
1534 	lock_rw_unlock(&v->lock);
1535 }
1536 
1537 /** Remove RR data from stdin from view */
1538 static void
1539 do_view_datas_remove(RES* ssl, struct worker* worker, char* arg)
1540 {
1541 	struct view* v;
1542 	v = views_find_view(worker->daemon->views,
1543 		arg, 1 /* get write lock*/);
1544 	if(!v) {
1545 		ssl_printf(ssl,"no view with name: %s\n", arg);
1546 		return;
1547 	}
1548 	if(!v->local_zones){
1549 		lock_rw_unlock(&v->lock);
1550 		ssl_printf(ssl, "removed 0 datas\n");
1551 		return;
1552 	}
1553 
1554 	do_datas_remove(ssl, v->local_zones);
1555 	lock_rw_unlock(&v->lock);
1556 }
1557 
1558 /** cache lookup of nameservers */
1559 static void
1560 do_lookup(RES* ssl, struct worker* worker, char* arg)
1561 {
1562 	uint8_t* nm;
1563 	int nmlabs;
1564 	size_t nmlen;
1565 	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1566 		return;
1567 	(void)print_deleg_lookup(ssl, worker, nm, nmlen, nmlabs);
1568 	free(nm);
1569 }
1570 
1571 /** flush something from rrset and msg caches */
1572 static void
1573 do_cache_remove(struct worker* worker, uint8_t* nm, size_t nmlen,
1574 	uint16_t t, uint16_t c)
1575 {
1576 	hashvalue_type h;
1577 	struct query_info k;
1578 	rrset_cache_remove(worker->env.rrset_cache, nm, nmlen, t, c, 0);
1579 	if(t == LDNS_RR_TYPE_SOA)
1580 		rrset_cache_remove(worker->env.rrset_cache, nm, nmlen, t, c,
1581 			PACKED_RRSET_SOA_NEG);
1582 	k.qname = nm;
1583 	k.qname_len = nmlen;
1584 	k.qtype = t;
1585 	k.qclass = c;
1586 	k.local_alias = NULL;
1587 	h = query_info_hash(&k, 0);
1588 	slabhash_remove(worker->env.msg_cache, h, &k);
1589 	if(t == LDNS_RR_TYPE_AAAA) {
1590 		/* for AAAA also flush dns64 bit_cd packet */
1591 		h = query_info_hash(&k, BIT_CD);
1592 		slabhash_remove(worker->env.msg_cache, h, &k);
1593 	}
1594 }
1595 
1596 /** flush a type */
1597 static void
1598 do_flush_type(RES* ssl, struct worker* worker, char* arg)
1599 {
1600 	uint8_t* nm;
1601 	int nmlabs;
1602 	size_t nmlen;
1603 	char* arg2;
1604 	uint16_t t;
1605 	if(!find_arg2(ssl, arg, &arg2))
1606 		return;
1607 	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1608 		return;
1609 	t = sldns_get_rr_type_by_name(arg2);
1610 	do_cache_remove(worker, nm, nmlen, t, LDNS_RR_CLASS_IN);
1611 
1612 	free(nm);
1613 	send_ok(ssl);
1614 }
1615 
1616 /** flush statistics */
1617 static void
1618 do_flush_stats(RES* ssl, struct worker* worker)
1619 {
1620 	worker_stats_clear(worker);
1621 	send_ok(ssl);
1622 }
1623 
1624 /**
1625  * Local info for deletion functions
1626  */
1627 struct del_info {
1628 	/** worker */
1629 	struct worker* worker;
1630 	/** name to delete */
1631 	uint8_t* name;
1632 	/** length */
1633 	size_t len;
1634 	/** labels */
1635 	int labs;
1636 	/** time to invalidate to */
1637 	time_t expired;
1638 	/** number of rrsets removed */
1639 	size_t num_rrsets;
1640 	/** number of msgs removed */
1641 	size_t num_msgs;
1642 	/** number of key entries removed */
1643 	size_t num_keys;
1644 	/** length of addr */
1645 	socklen_t addrlen;
1646 	/** socket address for host deletion */
1647 	struct sockaddr_storage addr;
1648 };
1649 
1650 /** callback to delete hosts in infra cache */
1651 static void
1652 infra_del_host(struct lruhash_entry* e, void* arg)
1653 {
1654 	/* entry is locked */
1655 	struct del_info* inf = (struct del_info*)arg;
1656 	struct infra_key* k = (struct infra_key*)e->key;
1657 	if(sockaddr_cmp(&inf->addr, inf->addrlen, &k->addr, k->addrlen) == 0) {
1658 		struct infra_data* d = (struct infra_data*)e->data;
1659 		d->probedelay = 0;
1660 		d->timeout_A = 0;
1661 		d->timeout_AAAA = 0;
1662 		d->timeout_other = 0;
1663 		rtt_init(&d->rtt);
1664 		if(d->ttl > inf->expired) {
1665 			d->ttl = inf->expired;
1666 			inf->num_keys++;
1667 		}
1668 	}
1669 }
1670 
1671 /** flush infra cache */
1672 static void
1673 do_flush_infra(RES* ssl, struct worker* worker, char* arg)
1674 {
1675 	struct sockaddr_storage addr;
1676 	socklen_t len;
1677 	struct del_info inf;
1678 	if(strcmp(arg, "all") == 0) {
1679 		slabhash_clear(worker->env.infra_cache->hosts);
1680 		send_ok(ssl);
1681 		return;
1682 	}
1683 	if(!ipstrtoaddr(arg, UNBOUND_DNS_PORT, &addr, &len)) {
1684 		(void)ssl_printf(ssl, "error parsing ip addr: '%s'\n", arg);
1685 		return;
1686 	}
1687 	/* delete all entries from cache */
1688 	/* what we do is to set them all expired */
1689 	inf.worker = worker;
1690 	inf.name = 0;
1691 	inf.len = 0;
1692 	inf.labs = 0;
1693 	inf.expired = *worker->env.now;
1694 	inf.expired -= 3; /* handle 3 seconds skew between threads */
1695 	inf.num_rrsets = 0;
1696 	inf.num_msgs = 0;
1697 	inf.num_keys = 0;
1698 	inf.addrlen = len;
1699 	memmove(&inf.addr, &addr, len);
1700 	slabhash_traverse(worker->env.infra_cache->hosts, 1, &infra_del_host,
1701 		&inf);
1702 	send_ok(ssl);
1703 }
1704 
1705 /** flush requestlist */
1706 static void
1707 do_flush_requestlist(RES* ssl, struct worker* worker)
1708 {
1709 	mesh_delete_all(worker->env.mesh);
1710 	send_ok(ssl);
1711 }
1712 
1713 /** callback to delete rrsets in a zone */
1714 static void
1715 zone_del_rrset(struct lruhash_entry* e, void* arg)
1716 {
1717 	/* entry is locked */
1718 	struct del_info* inf = (struct del_info*)arg;
1719 	struct ub_packed_rrset_key* k = (struct ub_packed_rrset_key*)e->key;
1720 	if(dname_subdomain_c(k->rk.dname, inf->name)) {
1721 		struct packed_rrset_data* d =
1722 			(struct packed_rrset_data*)e->data;
1723 		if(d->ttl > inf->expired) {
1724 			d->ttl = inf->expired;
1725 			inf->num_rrsets++;
1726 		}
1727 	}
1728 }
1729 
1730 /** callback to delete messages in a zone */
1731 static void
1732 zone_del_msg(struct lruhash_entry* e, void* arg)
1733 {
1734 	/* entry is locked */
1735 	struct del_info* inf = (struct del_info*)arg;
1736 	struct msgreply_entry* k = (struct msgreply_entry*)e->key;
1737 	if(dname_subdomain_c(k->key.qname, inf->name)) {
1738 		struct reply_info* d = (struct reply_info*)e->data;
1739 		if(d->ttl > inf->expired) {
1740 			d->ttl = inf->expired;
1741 			d->prefetch_ttl = inf->expired;
1742 			d->serve_expired_ttl = inf->expired;
1743 			inf->num_msgs++;
1744 		}
1745 	}
1746 }
1747 
1748 /** callback to delete keys in zone */
1749 static void
1750 zone_del_kcache(struct lruhash_entry* e, void* arg)
1751 {
1752 	/* entry is locked */
1753 	struct del_info* inf = (struct del_info*)arg;
1754 	struct key_entry_key* k = (struct key_entry_key*)e->key;
1755 	if(dname_subdomain_c(k->name, inf->name)) {
1756 		struct key_entry_data* d = (struct key_entry_data*)e->data;
1757 		if(d->ttl > inf->expired) {
1758 			d->ttl = inf->expired;
1759 			inf->num_keys++;
1760 		}
1761 	}
1762 }
1763 
1764 /** remove all rrsets and keys from zone from cache */
1765 static void
1766 do_flush_zone(RES* ssl, struct worker* worker, char* arg)
1767 {
1768 	uint8_t* nm;
1769 	int nmlabs;
1770 	size_t nmlen;
1771 	struct del_info inf;
1772 	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1773 		return;
1774 	/* delete all RRs and key entries from zone */
1775 	/* what we do is to set them all expired */
1776 	inf.worker = worker;
1777 	inf.name = nm;
1778 	inf.len = nmlen;
1779 	inf.labs = nmlabs;
1780 	inf.expired = *worker->env.now;
1781 	inf.expired -= 3; /* handle 3 seconds skew between threads */
1782 	inf.num_rrsets = 0;
1783 	inf.num_msgs = 0;
1784 	inf.num_keys = 0;
1785 	slabhash_traverse(&worker->env.rrset_cache->table, 1,
1786 		&zone_del_rrset, &inf);
1787 
1788 	slabhash_traverse(worker->env.msg_cache, 1, &zone_del_msg, &inf);
1789 
1790 	/* and validator cache */
1791 	if(worker->env.key_cache) {
1792 		slabhash_traverse(worker->env.key_cache->slab, 1,
1793 			&zone_del_kcache, &inf);
1794 	}
1795 
1796 	free(nm);
1797 
1798 	(void)ssl_printf(ssl, "ok removed %lu rrsets, %lu messages "
1799 		"and %lu key entries\n", (unsigned long)inf.num_rrsets,
1800 		(unsigned long)inf.num_msgs, (unsigned long)inf.num_keys);
1801 }
1802 
1803 /** callback to delete bogus rrsets */
1804 static void
1805 bogus_del_rrset(struct lruhash_entry* e, void* arg)
1806 {
1807 	/* entry is locked */
1808 	struct del_info* inf = (struct del_info*)arg;
1809 	struct packed_rrset_data* d = (struct packed_rrset_data*)e->data;
1810 	if(d->security == sec_status_bogus) {
1811 		d->ttl = inf->expired;
1812 		inf->num_rrsets++;
1813 	}
1814 }
1815 
1816 /** callback to delete bogus messages */
1817 static void
1818 bogus_del_msg(struct lruhash_entry* e, void* arg)
1819 {
1820 	/* entry is locked */
1821 	struct del_info* inf = (struct del_info*)arg;
1822 	struct reply_info* d = (struct reply_info*)e->data;
1823 	if(d->security == sec_status_bogus) {
1824 		d->ttl = inf->expired;
1825 		inf->num_msgs++;
1826 	}
1827 }
1828 
1829 /** callback to delete bogus keys */
1830 static void
1831 bogus_del_kcache(struct lruhash_entry* e, void* arg)
1832 {
1833 	/* entry is locked */
1834 	struct del_info* inf = (struct del_info*)arg;
1835 	struct key_entry_data* d = (struct key_entry_data*)e->data;
1836 	if(d->isbad) {
1837 		d->ttl = inf->expired;
1838 		inf->num_keys++;
1839 	}
1840 }
1841 
1842 /** remove all bogus rrsets, msgs and keys from cache */
1843 static void
1844 do_flush_bogus(RES* ssl, struct worker* worker)
1845 {
1846 	struct del_info inf;
1847 	/* what we do is to set them all expired */
1848 	inf.worker = worker;
1849 	inf.expired = *worker->env.now;
1850 	inf.expired -= 3; /* handle 3 seconds skew between threads */
1851 	inf.num_rrsets = 0;
1852 	inf.num_msgs = 0;
1853 	inf.num_keys = 0;
1854 	slabhash_traverse(&worker->env.rrset_cache->table, 1,
1855 		&bogus_del_rrset, &inf);
1856 
1857 	slabhash_traverse(worker->env.msg_cache, 1, &bogus_del_msg, &inf);
1858 
1859 	/* and validator cache */
1860 	if(worker->env.key_cache) {
1861 		slabhash_traverse(worker->env.key_cache->slab, 1,
1862 			&bogus_del_kcache, &inf);
1863 	}
1864 
1865 	(void)ssl_printf(ssl, "ok removed %lu rrsets, %lu messages "
1866 		"and %lu key entries\n", (unsigned long)inf.num_rrsets,
1867 		(unsigned long)inf.num_msgs, (unsigned long)inf.num_keys);
1868 }
1869 
1870 /** callback to delete negative and servfail rrsets */
1871 static void
1872 negative_del_rrset(struct lruhash_entry* e, void* arg)
1873 {
1874 	/* entry is locked */
1875 	struct del_info* inf = (struct del_info*)arg;
1876 	struct ub_packed_rrset_key* k = (struct ub_packed_rrset_key*)e->key;
1877 	struct packed_rrset_data* d = (struct packed_rrset_data*)e->data;
1878 	/* delete the parentside negative cache rrsets,
1879 	 * these are nameserver rrsets that failed lookup, rdata empty */
1880 	if((k->rk.flags & PACKED_RRSET_PARENT_SIDE) && d->count == 1 &&
1881 		d->rrsig_count == 0 && d->rr_len[0] == 0) {
1882 		d->ttl = inf->expired;
1883 		inf->num_rrsets++;
1884 	}
1885 }
1886 
1887 /** callback to delete negative and servfail messages */
1888 static void
1889 negative_del_msg(struct lruhash_entry* e, void* arg)
1890 {
1891 	/* entry is locked */
1892 	struct del_info* inf = (struct del_info*)arg;
1893 	struct reply_info* d = (struct reply_info*)e->data;
1894 	/* rcode not NOERROR: NXDOMAIN, SERVFAIL, ..: an nxdomain or error
1895 	 * or NOERROR rcode with ANCOUNT==0: a NODATA answer */
1896 	if(FLAGS_GET_RCODE(d->flags) != 0 || d->an_numrrsets == 0) {
1897 		d->ttl = inf->expired;
1898 		inf->num_msgs++;
1899 	}
1900 }
1901 
1902 /** callback to delete negative key entries */
1903 static void
1904 negative_del_kcache(struct lruhash_entry* e, void* arg)
1905 {
1906 	/* entry is locked */
1907 	struct del_info* inf = (struct del_info*)arg;
1908 	struct key_entry_data* d = (struct key_entry_data*)e->data;
1909 	/* could be bad because of lookup failure on the DS, DNSKEY, which
1910 	 * was nxdomain or servfail, and thus a result of negative lookups */
1911 	if(d->isbad) {
1912 		d->ttl = inf->expired;
1913 		inf->num_keys++;
1914 	}
1915 }
1916 
1917 /** remove all negative(NODATA,NXDOMAIN), and servfail messages from cache */
1918 static void
1919 do_flush_negative(RES* ssl, struct worker* worker)
1920 {
1921 	struct del_info inf;
1922 	/* what we do is to set them all expired */
1923 	inf.worker = worker;
1924 	inf.expired = *worker->env.now;
1925 	inf.expired -= 3; /* handle 3 seconds skew between threads */
1926 	inf.num_rrsets = 0;
1927 	inf.num_msgs = 0;
1928 	inf.num_keys = 0;
1929 	slabhash_traverse(&worker->env.rrset_cache->table, 1,
1930 		&negative_del_rrset, &inf);
1931 
1932 	slabhash_traverse(worker->env.msg_cache, 1, &negative_del_msg, &inf);
1933 
1934 	/* and validator cache */
1935 	if(worker->env.key_cache) {
1936 		slabhash_traverse(worker->env.key_cache->slab, 1,
1937 			&negative_del_kcache, &inf);
1938 	}
1939 
1940 	(void)ssl_printf(ssl, "ok removed %lu rrsets, %lu messages "
1941 		"and %lu key entries\n", (unsigned long)inf.num_rrsets,
1942 		(unsigned long)inf.num_msgs, (unsigned long)inf.num_keys);
1943 }
1944 
1945 /** remove name rrset from cache */
1946 static void
1947 do_flush_name(RES* ssl, struct worker* w, char* arg)
1948 {
1949 	uint8_t* nm;
1950 	int nmlabs;
1951 	size_t nmlen;
1952 	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1953 		return;
1954 	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_A, LDNS_RR_CLASS_IN);
1955 	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_AAAA, LDNS_RR_CLASS_IN);
1956 	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_NS, LDNS_RR_CLASS_IN);
1957 	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SOA, LDNS_RR_CLASS_IN);
1958 	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_CNAME, LDNS_RR_CLASS_IN);
1959 	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_DNAME, LDNS_RR_CLASS_IN);
1960 	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_MX, LDNS_RR_CLASS_IN);
1961 	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_PTR, LDNS_RR_CLASS_IN);
1962 	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SRV, LDNS_RR_CLASS_IN);
1963 	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_NAPTR, LDNS_RR_CLASS_IN);
1964 
1965 	free(nm);
1966 	send_ok(ssl);
1967 }
1968 
1969 /** printout a delegation point info */
1970 static int
1971 ssl_print_name_dp(RES* ssl, const char* str, uint8_t* nm, uint16_t dclass,
1972 	struct delegpt* dp)
1973 {
1974 	char buf[257];
1975 	struct delegpt_ns* ns;
1976 	struct delegpt_addr* a;
1977 	int f = 0;
1978 	if(str) { /* print header for forward, stub */
1979 		char* c = sldns_wire2str_class(dclass);
1980 		dname_str(nm, buf);
1981 		if(!ssl_printf(ssl, "%s %s %s ", buf, (c?c:"CLASS??"), str)) {
1982 			free(c);
1983 			return 0;
1984 		}
1985 		free(c);
1986 	}
1987 	for(ns = dp->nslist; ns; ns = ns->next) {
1988 		dname_str(ns->name, buf);
1989 		if(!ssl_printf(ssl, "%s%s", (f?" ":""), buf))
1990 			return 0;
1991 		f = 1;
1992 	}
1993 	for(a = dp->target_list; a; a = a->next_target) {
1994 		addr_to_str(&a->addr, a->addrlen, buf, sizeof(buf));
1995 		if(!ssl_printf(ssl, "%s%s", (f?" ":""), buf))
1996 			return 0;
1997 		f = 1;
1998 	}
1999 	return ssl_printf(ssl, "\n");
2000 }
2001 
2002 
2003 /** print root forwards */
2004 static int
2005 print_root_fwds(RES* ssl, struct iter_forwards* fwds, uint8_t* root)
2006 {
2007 	struct delegpt* dp;
2008 	dp = forwards_lookup(fwds, root, LDNS_RR_CLASS_IN);
2009 	if(!dp)
2010 		return ssl_printf(ssl, "off (using root hints)\n");
2011 	/* if dp is returned it must be the root */
2012 	log_assert(query_dname_compare(dp->name, root)==0);
2013 	return ssl_print_name_dp(ssl, NULL, root, LDNS_RR_CLASS_IN, dp);
2014 }
2015 
2016 /** parse args into delegpt */
2017 static struct delegpt*
2018 parse_delegpt(RES* ssl, char* args, uint8_t* nm, int allow_names)
2019 {
2020 	/* parse args and add in */
2021 	char* p = args;
2022 	char* todo;
2023 	struct delegpt* dp = delegpt_create_mlc(nm);
2024 	struct sockaddr_storage addr;
2025 	socklen_t addrlen;
2026 	char* auth_name;
2027 	if(!dp) {
2028 		(void)ssl_printf(ssl, "error out of memory\n");
2029 		return NULL;
2030 	}
2031 	while(p) {
2032 		todo = p;
2033 		p = strchr(p, ' '); /* find next spot, if any */
2034 		if(p) {
2035 			*p++ = 0;	/* end this spot */
2036 			p = skipwhite(p); /* position at next spot */
2037 		}
2038 		/* parse address */
2039 		if(!authextstrtoaddr(todo, &addr, &addrlen, &auth_name)) {
2040 			if(allow_names) {
2041 				uint8_t* n = NULL;
2042 				size_t ln;
2043 				int lb;
2044 				if(!parse_arg_name(ssl, todo, &n, &ln, &lb)) {
2045 					(void)ssl_printf(ssl, "error cannot "
2046 						"parse IP address or name "
2047 						"'%s'\n", todo);
2048 					delegpt_free_mlc(dp);
2049 					return NULL;
2050 				}
2051 				if(!delegpt_add_ns_mlc(dp, n, 0)) {
2052 					(void)ssl_printf(ssl, "error out of memory\n");
2053 					free(n);
2054 					delegpt_free_mlc(dp);
2055 					return NULL;
2056 				}
2057 				free(n);
2058 
2059 			} else {
2060 				(void)ssl_printf(ssl, "error cannot parse"
2061 					" IP address '%s'\n", todo);
2062 				delegpt_free_mlc(dp);
2063 				return NULL;
2064 			}
2065 		} else {
2066 #if ! defined(HAVE_SSL_SET1_HOST) && ! defined(HAVE_X509_VERIFY_PARAM_SET1_HOST)
2067 			if(auth_name)
2068 			  log_err("no name verification functionality in "
2069 				"ssl library, ignored name for %s", todo);
2070 #endif
2071 			/* add address */
2072 			if(!delegpt_add_addr_mlc(dp, &addr, addrlen, 0, 0,
2073 				auth_name)) {
2074 				(void)ssl_printf(ssl, "error out of memory\n");
2075 				delegpt_free_mlc(dp);
2076 				return NULL;
2077 			}
2078 		}
2079 	}
2080 	dp->has_parent_side_NS = 1;
2081 	return dp;
2082 }
2083 
2084 /** do the status command */
2085 static void
2086 do_forward(RES* ssl, struct worker* worker, char* args)
2087 {
2088 	struct iter_forwards* fwd = worker->env.fwds;
2089 	uint8_t* root = (uint8_t*)"\000";
2090 	if(!fwd) {
2091 		(void)ssl_printf(ssl, "error: structure not allocated\n");
2092 		return;
2093 	}
2094 	if(args == NULL || args[0] == 0) {
2095 		(void)print_root_fwds(ssl, fwd, root);
2096 		return;
2097 	}
2098 	/* set root forwards for this thread. since we are in remote control
2099 	 * the actual mesh is not running, so we can freely edit it. */
2100 	/* delete all the existing queries first */
2101 	mesh_delete_all(worker->env.mesh);
2102 	if(strcmp(args, "off") == 0) {
2103 		forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, root);
2104 	} else {
2105 		struct delegpt* dp;
2106 		if(!(dp = parse_delegpt(ssl, args, root, 0)))
2107 			return;
2108 		if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp)) {
2109 			(void)ssl_printf(ssl, "error out of memory\n");
2110 			return;
2111 		}
2112 	}
2113 	send_ok(ssl);
2114 }
2115 
2116 static int
2117 parse_fs_args(RES* ssl, char* args, uint8_t** nm, struct delegpt** dp,
2118 	int* insecure, int* prime)
2119 {
2120 	char* zonename;
2121 	char* rest;
2122 	size_t nmlen;
2123 	int nmlabs;
2124 	/* parse all -x args */
2125 	while(args[0] == '+') {
2126 		if(!find_arg2(ssl, args, &rest))
2127 			return 0;
2128 		while(*(++args) != 0) {
2129 			if(*args == 'i' && insecure)
2130 				*insecure = 1;
2131 			else if(*args == 'p' && prime)
2132 				*prime = 1;
2133 			else {
2134 				(void)ssl_printf(ssl, "error: unknown option %s\n", args);
2135 				return 0;
2136 			}
2137 		}
2138 		args = rest;
2139 	}
2140 	/* parse name */
2141 	if(dp) {
2142 		if(!find_arg2(ssl, args, &rest))
2143 			return 0;
2144 		zonename = args;
2145 		args = rest;
2146 	} else	zonename = args;
2147 	if(!parse_arg_name(ssl, zonename, nm, &nmlen, &nmlabs))
2148 		return 0;
2149 
2150 	/* parse dp */
2151 	if(dp) {
2152 		if(!(*dp = parse_delegpt(ssl, args, *nm, 1))) {
2153 			free(*nm);
2154 			return 0;
2155 		}
2156 	}
2157 	return 1;
2158 }
2159 
2160 /** do the forward_add command */
2161 static void
2162 do_forward_add(RES* ssl, struct worker* worker, char* args)
2163 {
2164 	struct iter_forwards* fwd = worker->env.fwds;
2165 	int insecure = 0;
2166 	uint8_t* nm = NULL;
2167 	struct delegpt* dp = NULL;
2168 	if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, NULL))
2169 		return;
2170 	if(insecure && worker->env.anchors) {
2171 		if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2172 			nm)) {
2173 			(void)ssl_printf(ssl, "error out of memory\n");
2174 			delegpt_free_mlc(dp);
2175 			free(nm);
2176 			return;
2177 		}
2178 	}
2179 	if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp)) {
2180 		(void)ssl_printf(ssl, "error out of memory\n");
2181 		free(nm);
2182 		return;
2183 	}
2184 	free(nm);
2185 	send_ok(ssl);
2186 }
2187 
2188 /** do the forward_remove command */
2189 static void
2190 do_forward_remove(RES* ssl, struct worker* worker, char* args)
2191 {
2192 	struct iter_forwards* fwd = worker->env.fwds;
2193 	int insecure = 0;
2194 	uint8_t* nm = NULL;
2195 	if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL))
2196 		return;
2197 	if(insecure && worker->env.anchors)
2198 		anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2199 			nm);
2200 	forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, nm);
2201 	free(nm);
2202 	send_ok(ssl);
2203 }
2204 
2205 /** do the stub_add command */
2206 static void
2207 do_stub_add(RES* ssl, struct worker* worker, char* args)
2208 {
2209 	struct iter_forwards* fwd = worker->env.fwds;
2210 	int insecure = 0, prime = 0;
2211 	uint8_t* nm = NULL;
2212 	struct delegpt* dp = NULL;
2213 	if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, &prime))
2214 		return;
2215 	if(insecure && worker->env.anchors) {
2216 		if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2217 			nm)) {
2218 			(void)ssl_printf(ssl, "error out of memory\n");
2219 			delegpt_free_mlc(dp);
2220 			free(nm);
2221 			return;
2222 		}
2223 	}
2224 	if(!forwards_add_stub_hole(fwd, LDNS_RR_CLASS_IN, nm)) {
2225 		if(insecure && worker->env.anchors)
2226 			anchors_delete_insecure(worker->env.anchors,
2227 				LDNS_RR_CLASS_IN, nm);
2228 		(void)ssl_printf(ssl, "error out of memory\n");
2229 		delegpt_free_mlc(dp);
2230 		free(nm);
2231 		return;
2232 	}
2233 	if(!hints_add_stub(worker->env.hints, LDNS_RR_CLASS_IN, dp, !prime)) {
2234 		(void)ssl_printf(ssl, "error out of memory\n");
2235 		forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm);
2236 		if(insecure && worker->env.anchors)
2237 			anchors_delete_insecure(worker->env.anchors,
2238 				LDNS_RR_CLASS_IN, nm);
2239 		free(nm);
2240 		return;
2241 	}
2242 	free(nm);
2243 	send_ok(ssl);
2244 }
2245 
2246 /** do the stub_remove command */
2247 static void
2248 do_stub_remove(RES* ssl, struct worker* worker, char* args)
2249 {
2250 	struct iter_forwards* fwd = worker->env.fwds;
2251 	int insecure = 0;
2252 	uint8_t* nm = NULL;
2253 	if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL))
2254 		return;
2255 	if(insecure && worker->env.anchors)
2256 		anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2257 			nm);
2258 	forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm);
2259 	hints_delete_stub(worker->env.hints, LDNS_RR_CLASS_IN, nm);
2260 	free(nm);
2261 	send_ok(ssl);
2262 }
2263 
2264 /** do the insecure_add command */
2265 static void
2266 do_insecure_add(RES* ssl, struct worker* worker, char* arg)
2267 {
2268 	size_t nmlen;
2269 	int nmlabs;
2270 	uint8_t* nm = NULL;
2271 	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
2272 		return;
2273 	if(worker->env.anchors) {
2274 		if(!anchors_add_insecure(worker->env.anchors,
2275 			LDNS_RR_CLASS_IN, nm)) {
2276 			(void)ssl_printf(ssl, "error out of memory\n");
2277 			free(nm);
2278 			return;
2279 		}
2280 	}
2281 	free(nm);
2282 	send_ok(ssl);
2283 }
2284 
2285 /** do the insecure_remove command */
2286 static void
2287 do_insecure_remove(RES* ssl, struct worker* worker, char* arg)
2288 {
2289 	size_t nmlen;
2290 	int nmlabs;
2291 	uint8_t* nm = NULL;
2292 	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
2293 		return;
2294 	if(worker->env.anchors)
2295 		anchors_delete_insecure(worker->env.anchors,
2296 			LDNS_RR_CLASS_IN, nm);
2297 	free(nm);
2298 	send_ok(ssl);
2299 }
2300 
2301 static void
2302 do_insecure_list(RES* ssl, struct worker* worker)
2303 {
2304 	char buf[257];
2305 	struct trust_anchor* a;
2306 	if(worker->env.anchors) {
2307 		RBTREE_FOR(a, struct trust_anchor*, worker->env.anchors->tree) {
2308 			if(a->numDS == 0 && a->numDNSKEY == 0) {
2309 				dname_str(a->name, buf);
2310 				ssl_printf(ssl, "%s\n", buf);
2311 			}
2312 		}
2313 	}
2314 }
2315 
2316 /** do the status command */
2317 static void
2318 do_status(RES* ssl, struct worker* worker)
2319 {
2320 	int i;
2321 	time_t uptime;
2322 	if(!ssl_printf(ssl, "version: %s\n", PACKAGE_VERSION))
2323 		return;
2324 	if(!ssl_printf(ssl, "verbosity: %d\n", verbosity))
2325 		return;
2326 	if(!ssl_printf(ssl, "threads: %d\n", worker->daemon->num))
2327 		return;
2328 	if(!ssl_printf(ssl, "modules: %d [", worker->daemon->mods.num))
2329 		return;
2330 	for(i=0; i<worker->daemon->mods.num; i++) {
2331 		if(!ssl_printf(ssl, " %s", worker->daemon->mods.mod[i]->name))
2332 			return;
2333 	}
2334 	if(!ssl_printf(ssl, " ]\n"))
2335 		return;
2336 	uptime = (time_t)time(NULL) - (time_t)worker->daemon->time_boot.tv_sec;
2337 	if(!ssl_printf(ssl, "uptime: " ARG_LL "d seconds\n", (long long)uptime))
2338 		return;
2339 	if(!ssl_printf(ssl, "options:%s%s%s%s\n" ,
2340 		(worker->daemon->reuseport?" reuseport":""),
2341 		(worker->daemon->rc->accept_list?" control":""),
2342 		(worker->daemon->rc->accept_list && worker->daemon->rc->use_cert?"(ssl)":""),
2343 		(worker->daemon->rc->accept_list && worker->daemon->cfg->control_ifs.first && worker->daemon->cfg->control_ifs.first->str && worker->daemon->cfg->control_ifs.first->str[0] == '/'?"(namedpipe)":"")
2344 		))
2345 		return;
2346 	if(!ssl_printf(ssl, "unbound (pid %d) is running...\n",
2347 		(int)getpid()))
2348 		return;
2349 }
2350 
2351 /** get age for the mesh state */
2352 static void
2353 get_mesh_age(struct mesh_state* m, char* buf, size_t len,
2354 	struct module_env* env)
2355 {
2356 	if(m->reply_list) {
2357 		struct timeval d;
2358 		struct mesh_reply* r = m->reply_list;
2359 		/* last reply is the oldest */
2360 		while(r && r->next)
2361 			r = r->next;
2362 		timeval_subtract(&d, env->now_tv, &r->start_time);
2363 		snprintf(buf, len, ARG_LL "d.%6.6d",
2364 			(long long)d.tv_sec, (int)d.tv_usec);
2365 	} else {
2366 		snprintf(buf, len, "-");
2367 	}
2368 }
2369 
2370 /** get status of a mesh state */
2371 static void
2372 get_mesh_status(struct mesh_area* mesh, struct mesh_state* m,
2373 	char* buf, size_t len)
2374 {
2375 	enum module_ext_state s = m->s.ext_state[m->s.curmod];
2376 	const char *modname = mesh->mods.mod[m->s.curmod]->name;
2377 	size_t l;
2378 	if(strcmp(modname, "iterator") == 0 && s == module_wait_reply &&
2379 		m->s.minfo[m->s.curmod]) {
2380 		/* break into iterator to find out who its waiting for */
2381 		struct iter_qstate* qstate = (struct iter_qstate*)
2382 			m->s.minfo[m->s.curmod];
2383 		struct outbound_list* ol = &qstate->outlist;
2384 		struct outbound_entry* e;
2385 		snprintf(buf, len, "%s wait for", modname);
2386 		l = strlen(buf);
2387 		buf += l; len -= l;
2388 		if(ol->first == NULL)
2389 			snprintf(buf, len, " (empty_list)");
2390 		for(e = ol->first; e; e = e->next) {
2391 			snprintf(buf, len, " ");
2392 			l = strlen(buf);
2393 			buf += l; len -= l;
2394 			addr_to_str(&e->qsent->addr, e->qsent->addrlen,
2395 				buf, len);
2396 			l = strlen(buf);
2397 			buf += l; len -= l;
2398 		}
2399 	} else if(s == module_wait_subquery) {
2400 		/* look in subs from mesh state to see what */
2401 		char nm[257];
2402 		struct mesh_state_ref* sub;
2403 		snprintf(buf, len, "%s wants", modname);
2404 		l = strlen(buf);
2405 		buf += l; len -= l;
2406 		if(m->sub_set.count == 0)
2407 			snprintf(buf, len, " (empty_list)");
2408 		RBTREE_FOR(sub, struct mesh_state_ref*, &m->sub_set) {
2409 			char* t = sldns_wire2str_type(sub->s->s.qinfo.qtype);
2410 			char* c = sldns_wire2str_class(sub->s->s.qinfo.qclass);
2411 			dname_str(sub->s->s.qinfo.qname, nm);
2412 			snprintf(buf, len, " %s %s %s", (t?t:"TYPE??"),
2413 				(c?c:"CLASS??"), nm);
2414 			l = strlen(buf);
2415 			buf += l; len -= l;
2416 			free(t);
2417 			free(c);
2418 		}
2419 	} else {
2420 		snprintf(buf, len, "%s is %s", modname, strextstate(s));
2421 	}
2422 }
2423 
2424 /** do the dump_requestlist command */
2425 static void
2426 do_dump_requestlist(RES* ssl, struct worker* worker)
2427 {
2428 	struct mesh_area* mesh;
2429 	struct mesh_state* m;
2430 	int num = 0;
2431 	char buf[257];
2432 	char timebuf[32];
2433 	char statbuf[10240];
2434 	if(!ssl_printf(ssl, "thread #%d\n", worker->thread_num))
2435 		return;
2436 	if(!ssl_printf(ssl, "#   type cl name    seconds    module status\n"))
2437 		return;
2438 	/* show worker mesh contents */
2439 	mesh = worker->env.mesh;
2440 	if(!mesh) return;
2441 	RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
2442 		char* t = sldns_wire2str_type(m->s.qinfo.qtype);
2443 		char* c = sldns_wire2str_class(m->s.qinfo.qclass);
2444 		dname_str(m->s.qinfo.qname, buf);
2445 		get_mesh_age(m, timebuf, sizeof(timebuf), &worker->env);
2446 		get_mesh_status(mesh, m, statbuf, sizeof(statbuf));
2447 		if(!ssl_printf(ssl, "%3d %4s %2s %s %s %s\n",
2448 			num, (t?t:"TYPE??"), (c?c:"CLASS??"), buf, timebuf,
2449 			statbuf)) {
2450 			free(t);
2451 			free(c);
2452 			return;
2453 		}
2454 		num++;
2455 		free(t);
2456 		free(c);
2457 	}
2458 }
2459 
2460 /** structure for argument data for dump infra host */
2461 struct infra_arg {
2462 	/** the infra cache */
2463 	struct infra_cache* infra;
2464 	/** the SSL connection */
2465 	RES* ssl;
2466 	/** the time now */
2467 	time_t now;
2468 	/** ssl failure? stop writing and skip the rest.  If the tcp
2469 	 * connection is broken, and writes fail, we then stop writing. */
2470 	int ssl_failed;
2471 };
2472 
2473 /** callback for every host element in the infra cache */
2474 static void
2475 dump_infra_host(struct lruhash_entry* e, void* arg)
2476 {
2477 	struct infra_arg* a = (struct infra_arg*)arg;
2478 	struct infra_key* k = (struct infra_key*)e->key;
2479 	struct infra_data* d = (struct infra_data*)e->data;
2480 	char ip_str[1024];
2481 	char name[257];
2482 	int port;
2483 	if(a->ssl_failed)
2484 		return;
2485 	addr_to_str(&k->addr, k->addrlen, ip_str, sizeof(ip_str));
2486 	dname_str(k->zonename, name);
2487 	port = (int)ntohs(((struct sockaddr_in*)&k->addr)->sin_port);
2488 	if(port != UNBOUND_DNS_PORT) {
2489 		snprintf(ip_str+strlen(ip_str), sizeof(ip_str)-strlen(ip_str),
2490 			"@%d", port);
2491 	}
2492 	/* skip expired stuff (only backed off) */
2493 	if(d->ttl < a->now) {
2494 		if(d->rtt.rto >= USEFUL_SERVER_TOP_TIMEOUT) {
2495 			if(!ssl_printf(a->ssl, "%s %s expired rto %d\n", ip_str,
2496 				name, d->rtt.rto))  {
2497 				a->ssl_failed = 1;
2498 				return;
2499 			}
2500 		}
2501 		return;
2502 	}
2503 	if(!ssl_printf(a->ssl, "%s %s ttl %lu ping %d var %d rtt %d rto %d "
2504 		"tA %d tAAAA %d tother %d "
2505 		"ednsknown %d edns %d delay %d lame dnssec %d rec %d A %d "
2506 		"other %d\n", ip_str, name, (unsigned long)(d->ttl - a->now),
2507 		d->rtt.srtt, d->rtt.rttvar, rtt_notimeout(&d->rtt), d->rtt.rto,
2508 		d->timeout_A, d->timeout_AAAA, d->timeout_other,
2509 		(int)d->edns_lame_known, (int)d->edns_version,
2510 		(int)(a->now<d->probedelay?(d->probedelay - a->now):0),
2511 		(int)d->isdnsseclame, (int)d->rec_lame, (int)d->lame_type_A,
2512 		(int)d->lame_other)) {
2513 		a->ssl_failed = 1;
2514 		return;
2515 	}
2516 }
2517 
2518 /** do the dump_infra command */
2519 static void
2520 do_dump_infra(RES* ssl, struct worker* worker)
2521 {
2522 	struct infra_arg arg;
2523 	arg.infra = worker->env.infra_cache;
2524 	arg.ssl = ssl;
2525 	arg.now = *worker->env.now;
2526 	arg.ssl_failed = 0;
2527 	slabhash_traverse(arg.infra->hosts, 0, &dump_infra_host, (void*)&arg);
2528 }
2529 
2530 /** do the log_reopen command */
2531 static void
2532 do_log_reopen(RES* ssl, struct worker* worker)
2533 {
2534 	struct config_file* cfg = worker->env.cfg;
2535 	send_ok(ssl);
2536 	log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
2537 }
2538 
2539 /** do the auth_zone_reload command */
2540 static void
2541 do_auth_zone_reload(RES* ssl, struct worker* worker, char* arg)
2542 {
2543 	size_t nmlen;
2544 	int nmlabs;
2545 	uint8_t* nm = NULL;
2546 	struct auth_zones* az = worker->env.auth_zones;
2547 	struct auth_zone* z = NULL;
2548 	struct auth_xfer* xfr = NULL;
2549 	char* reason = NULL;
2550 	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
2551 		return;
2552 	if(az) {
2553 		lock_rw_rdlock(&az->lock);
2554 		z = auth_zone_find(az, nm, nmlen, LDNS_RR_CLASS_IN);
2555 		if(z) {
2556 			lock_rw_wrlock(&z->lock);
2557 		}
2558 		xfr = auth_xfer_find(az, nm, nmlen, LDNS_RR_CLASS_IN);
2559 		if(xfr) {
2560 			lock_basic_lock(&xfr->lock);
2561 		}
2562 		lock_rw_unlock(&az->lock);
2563 	}
2564 	free(nm);
2565 	if(!z) {
2566 		if(xfr) {
2567 			lock_basic_unlock(&xfr->lock);
2568 		}
2569 		(void)ssl_printf(ssl, "error no auth-zone %s\n", arg);
2570 		return;
2571 	}
2572 	if(!auth_zone_read_zonefile(z, worker->env.cfg)) {
2573 		lock_rw_unlock(&z->lock);
2574 		if(xfr) {
2575 			lock_basic_unlock(&xfr->lock);
2576 		}
2577 		(void)ssl_printf(ssl, "error failed to read %s\n", arg);
2578 		return;
2579 	}
2580 
2581 	z->zone_expired = 0;
2582 	if(xfr) {
2583 		xfr->zone_expired = 0;
2584 		if(!xfr_find_soa(z, xfr)) {
2585 			if(z->data.count == 0) {
2586 				lock_rw_unlock(&z->lock);
2587 				lock_basic_unlock(&xfr->lock);
2588 				(void)ssl_printf(ssl, "zone %s has no contents\n", arg);
2589 				return;
2590 			}
2591 			lock_rw_unlock(&z->lock);
2592 			lock_basic_unlock(&xfr->lock);
2593 			(void)ssl_printf(ssl, "error: no SOA in zone after read %s\n", arg);
2594 			return;
2595 		}
2596 		if(xfr->have_zone)
2597 			xfr->lease_time = *worker->env.now;
2598 		lock_basic_unlock(&xfr->lock);
2599 	}
2600 
2601 	auth_zone_verify_zonemd(z, &worker->env, &worker->env.mesh->mods,
2602 		&reason, 0, 0);
2603 	if(reason && z->zone_expired) {
2604 		lock_rw_unlock(&z->lock);
2605 		(void)ssl_printf(ssl, "error zonemd for %s failed: %s\n",
2606 			arg, reason);
2607 		free(reason);
2608 		return;
2609 	} else if(reason && strcmp(reason, "ZONEMD verification successful")
2610 		==0) {
2611 		(void)ssl_printf(ssl, "%s: %s\n", arg, reason);
2612 	}
2613 	lock_rw_unlock(&z->lock);
2614 	free(reason);
2615 	send_ok(ssl);
2616 }
2617 
2618 /** do the auth_zone_transfer command */
2619 static void
2620 do_auth_zone_transfer(RES* ssl, struct worker* worker, char* arg)
2621 {
2622 	size_t nmlen;
2623 	int nmlabs;
2624 	uint8_t* nm = NULL;
2625 	struct auth_zones* az = worker->env.auth_zones;
2626 	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
2627 		return;
2628 	if(!az || !auth_zones_startprobesequence(az, &worker->env, nm, nmlen,
2629 		LDNS_RR_CLASS_IN)) {
2630 		(void)ssl_printf(ssl, "error zone xfr task not found %s\n", arg);
2631 		free(nm);
2632 		return;
2633 	}
2634 	free(nm);
2635 	send_ok(ssl);
2636 }
2637 
2638 /** do the set_option command */
2639 static void
2640 do_set_option(RES* ssl, struct worker* worker, char* arg)
2641 {
2642 	char* arg2;
2643 	if(!find_arg2(ssl, arg, &arg2))
2644 		return;
2645 	if(!config_set_option(worker->env.cfg, arg, arg2)) {
2646 		(void)ssl_printf(ssl, "error setting option\n");
2647 		return;
2648 	}
2649 	/* effectuate some arguments */
2650 	if(strcmp(arg, "val-override-date:") == 0) {
2651 		int m = modstack_find(&worker->env.mesh->mods, "validator");
2652 		struct val_env* val_env = NULL;
2653 		if(m != -1) val_env = (struct val_env*)worker->env.modinfo[m];
2654 		if(val_env)
2655 			val_env->date_override = worker->env.cfg->val_date_override;
2656 	}
2657 	send_ok(ssl);
2658 }
2659 
2660 /* routine to printout option values over SSL */
2661 void remote_get_opt_ssl(char* line, void* arg)
2662 {
2663 	RES* ssl = (RES*)arg;
2664 	(void)ssl_printf(ssl, "%s\n", line);
2665 }
2666 
2667 /** do the get_option command */
2668 static void
2669 do_get_option(RES* ssl, struct worker* worker, char* arg)
2670 {
2671 	int r;
2672 	r = config_get_option(worker->env.cfg, arg, remote_get_opt_ssl, ssl);
2673 	if(!r) {
2674 		(void)ssl_printf(ssl, "error unknown option\n");
2675 		return;
2676 	}
2677 }
2678 
2679 /** do the list_forwards command */
2680 static void
2681 do_list_forwards(RES* ssl, struct worker* worker)
2682 {
2683 	/* since its a per-worker structure no locks needed */
2684 	struct iter_forwards* fwds = worker->env.fwds;
2685 	struct iter_forward_zone* z;
2686 	struct trust_anchor* a;
2687 	int insecure;
2688 	RBTREE_FOR(z, struct iter_forward_zone*, fwds->tree) {
2689 		if(!z->dp) continue; /* skip empty marker for stub */
2690 
2691 		/* see if it is insecure */
2692 		insecure = 0;
2693 		if(worker->env.anchors &&
2694 			(a=anchor_find(worker->env.anchors, z->name,
2695 			z->namelabs, z->namelen,  z->dclass))) {
2696 			if(!a->keylist && !a->numDS && !a->numDNSKEY)
2697 				insecure = 1;
2698 			lock_basic_unlock(&a->lock);
2699 		}
2700 
2701 		if(!ssl_print_name_dp(ssl, (insecure?"forward +i":"forward"),
2702 			z->name, z->dclass, z->dp))
2703 			return;
2704 	}
2705 }
2706 
2707 /** do the list_stubs command */
2708 static void
2709 do_list_stubs(RES* ssl, struct worker* worker)
2710 {
2711 	struct iter_hints_stub* z;
2712 	struct trust_anchor* a;
2713 	int insecure;
2714 	char str[32];
2715 	RBTREE_FOR(z, struct iter_hints_stub*, &worker->env.hints->tree) {
2716 
2717 		/* see if it is insecure */
2718 		insecure = 0;
2719 		if(worker->env.anchors &&
2720 			(a=anchor_find(worker->env.anchors, z->node.name,
2721 			z->node.labs, z->node.len,  z->node.dclass))) {
2722 			if(!a->keylist && !a->numDS && !a->numDNSKEY)
2723 				insecure = 1;
2724 			lock_basic_unlock(&a->lock);
2725 		}
2726 
2727 		snprintf(str, sizeof(str), "stub %sprime%s",
2728 			(z->noprime?"no":""), (insecure?" +i":""));
2729 		if(!ssl_print_name_dp(ssl, str, z->node.name,
2730 			z->node.dclass, z->dp))
2731 			return;
2732 	}
2733 }
2734 
2735 /** do the list_auth_zones command */
2736 static void
2737 do_list_auth_zones(RES* ssl, struct auth_zones* az)
2738 {
2739 	struct auth_zone* z;
2740 	char buf[257], buf2[256];
2741 	lock_rw_rdlock(&az->lock);
2742 	RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
2743 		lock_rw_rdlock(&z->lock);
2744 		dname_str(z->name, buf);
2745 		if(z->zone_expired)
2746 			snprintf(buf2, sizeof(buf2), "expired");
2747 		else {
2748 			uint32_t serial = 0;
2749 			if(auth_zone_get_serial(z, &serial))
2750 				snprintf(buf2, sizeof(buf2), "serial %u",
2751 					(unsigned)serial);
2752 			else	snprintf(buf2, sizeof(buf2), "no serial");
2753 		}
2754 		if(!ssl_printf(ssl, "%s\t%s\n", buf, buf2)) {
2755 			/* failure to print */
2756 			lock_rw_unlock(&z->lock);
2757 			lock_rw_unlock(&az->lock);
2758 			return;
2759 		}
2760 		lock_rw_unlock(&z->lock);
2761 	}
2762 	lock_rw_unlock(&az->lock);
2763 }
2764 
2765 /** do the list_local_zones command */
2766 static void
2767 do_list_local_zones(RES* ssl, struct local_zones* zones)
2768 {
2769 	struct local_zone* z;
2770 	char buf[257];
2771 	lock_rw_rdlock(&zones->lock);
2772 	RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
2773 		lock_rw_rdlock(&z->lock);
2774 		dname_str(z->name, buf);
2775 		if(!ssl_printf(ssl, "%s %s\n", buf,
2776 			local_zone_type2str(z->type))) {
2777 			/* failure to print */
2778 			lock_rw_unlock(&z->lock);
2779 			lock_rw_unlock(&zones->lock);
2780 			return;
2781 		}
2782 		lock_rw_unlock(&z->lock);
2783 	}
2784 	lock_rw_unlock(&zones->lock);
2785 }
2786 
2787 /** do the list_local_data command */
2788 static void
2789 do_list_local_data(RES* ssl, struct worker* worker, struct local_zones* zones)
2790 {
2791 	struct local_zone* z;
2792 	struct local_data* d;
2793 	struct local_rrset* p;
2794 	char* s = (char*)sldns_buffer_begin(worker->env.scratch_buffer);
2795 	size_t slen = sldns_buffer_capacity(worker->env.scratch_buffer);
2796 	lock_rw_rdlock(&zones->lock);
2797 	RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
2798 		lock_rw_rdlock(&z->lock);
2799 		RBTREE_FOR(d, struct local_data*, &z->data) {
2800 			for(p = d->rrsets; p; p = p->next) {
2801 				struct packed_rrset_data* d =
2802 					(struct packed_rrset_data*)p->rrset->entry.data;
2803 				size_t i;
2804 				for(i=0; i<d->count + d->rrsig_count; i++) {
2805 					if(!packed_rr_to_string(p->rrset, i,
2806 						0, s, slen)) {
2807 						if(!ssl_printf(ssl, "BADRR\n")) {
2808 							lock_rw_unlock(&z->lock);
2809 							lock_rw_unlock(&zones->lock);
2810 							return;
2811 						}
2812 					}
2813 				        if(!ssl_printf(ssl, "%s\n", s)) {
2814 						lock_rw_unlock(&z->lock);
2815 						lock_rw_unlock(&zones->lock);
2816 						return;
2817 					}
2818 				}
2819 			}
2820 		}
2821 		lock_rw_unlock(&z->lock);
2822 	}
2823 	lock_rw_unlock(&zones->lock);
2824 }
2825 
2826 /** do the view_list_local_zones command */
2827 static void
2828 do_view_list_local_zones(RES* ssl, struct worker* worker, char* arg)
2829 {
2830 	struct view* v = views_find_view(worker->daemon->views,
2831 		arg, 0 /* get read lock*/);
2832 	if(!v) {
2833 		ssl_printf(ssl,"no view with name: %s\n", arg);
2834 		return;
2835 	}
2836 	if(v->local_zones) {
2837 		do_list_local_zones(ssl, v->local_zones);
2838 	}
2839 	lock_rw_unlock(&v->lock);
2840 }
2841 
2842 /** do the view_list_local_data command */
2843 static void
2844 do_view_list_local_data(RES* ssl, struct worker* worker, char* arg)
2845 {
2846 	struct view* v = views_find_view(worker->daemon->views,
2847 		arg, 0 /* get read lock*/);
2848 	if(!v) {
2849 		ssl_printf(ssl,"no view with name: %s\n", arg);
2850 		return;
2851 	}
2852 	if(v->local_zones) {
2853 		do_list_local_data(ssl, worker, v->local_zones);
2854 	}
2855 	lock_rw_unlock(&v->lock);
2856 }
2857 
2858 /** struct for user arg ratelimit list */
2859 struct ratelimit_list_arg {
2860 	/** the infra cache */
2861 	struct infra_cache* infra;
2862 	/** the SSL to print to */
2863 	RES* ssl;
2864 	/** all or only ratelimited */
2865 	int all;
2866 	/** current time */
2867 	time_t now;
2868 };
2869 
2870 #define ip_ratelimit_list_arg ratelimit_list_arg
2871 
2872 /** list items in the ratelimit table */
2873 static void
2874 rate_list(struct lruhash_entry* e, void* arg)
2875 {
2876 	struct ratelimit_list_arg* a = (struct ratelimit_list_arg*)arg;
2877 	struct rate_key* k = (struct rate_key*)e->key;
2878 	struct rate_data* d = (struct rate_data*)e->data;
2879 	char buf[257];
2880 	int lim = infra_find_ratelimit(a->infra, k->name, k->namelen);
2881 	int max = infra_rate_max(d, a->now);
2882 	if(a->all == 0) {
2883 		if(max < lim)
2884 			return;
2885 	}
2886 	dname_str(k->name, buf);
2887 	ssl_printf(a->ssl, "%s %d limit %d\n", buf, max, lim);
2888 }
2889 
2890 /** list items in the ip_ratelimit table */
2891 static void
2892 ip_rate_list(struct lruhash_entry* e, void* arg)
2893 {
2894 	char ip[128];
2895 	struct ip_ratelimit_list_arg* a = (struct ip_ratelimit_list_arg*)arg;
2896 	struct ip_rate_key* k = (struct ip_rate_key*)e->key;
2897 	struct ip_rate_data* d = (struct ip_rate_data*)e->data;
2898 	int lim = infra_ip_ratelimit;
2899 	int max = infra_rate_max(d, a->now);
2900 	if(a->all == 0) {
2901 		if(max < lim)
2902 			return;
2903 	}
2904 	addr_to_str(&k->addr, k->addrlen, ip, sizeof(ip));
2905 	ssl_printf(a->ssl, "%s %d limit %d\n", ip, max, lim);
2906 }
2907 
2908 /** do the ratelimit_list command */
2909 static void
2910 do_ratelimit_list(RES* ssl, struct worker* worker, char* arg)
2911 {
2912 	struct ratelimit_list_arg a;
2913 	a.all = 0;
2914 	a.infra = worker->env.infra_cache;
2915 	a.now = *worker->env.now;
2916 	a.ssl = ssl;
2917 	arg = skipwhite(arg);
2918 	if(strcmp(arg, "+a") == 0)
2919 		a.all = 1;
2920 	if(a.infra->domain_rates==NULL ||
2921 		(a.all == 0 && infra_dp_ratelimit == 0))
2922 		return;
2923 	slabhash_traverse(a.infra->domain_rates, 0, rate_list, &a);
2924 }
2925 
2926 /** do the ip_ratelimit_list command */
2927 static void
2928 do_ip_ratelimit_list(RES* ssl, struct worker* worker, char* arg)
2929 {
2930 	struct ip_ratelimit_list_arg a;
2931 	a.all = 0;
2932 	a.infra = worker->env.infra_cache;
2933 	a.now = *worker->env.now;
2934 	a.ssl = ssl;
2935 	arg = skipwhite(arg);
2936 	if(strcmp(arg, "+a") == 0)
2937 		a.all = 1;
2938 	if(a.infra->client_ip_rates==NULL ||
2939 		(a.all == 0 && infra_ip_ratelimit == 0))
2940 		return;
2941 	slabhash_traverse(a.infra->client_ip_rates, 0, ip_rate_list, &a);
2942 }
2943 
2944 /** do the rpz_enable/disable command */
2945 static void
2946 do_rpz_enable_disable(RES* ssl, struct worker* worker, char* arg, int enable) {
2947     size_t nmlen;
2948     int nmlabs;
2949     uint8_t *nm = NULL;
2950     struct auth_zones *az = worker->env.auth_zones;
2951     struct auth_zone *z = NULL;
2952     if (!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
2953         return;
2954     if (az) {
2955         lock_rw_rdlock(&az->lock);
2956         z = auth_zone_find(az, nm, nmlen, LDNS_RR_CLASS_IN);
2957         if (z) {
2958             lock_rw_wrlock(&z->lock);
2959         }
2960         lock_rw_unlock(&az->lock);
2961     }
2962     free(nm);
2963     if (!z) {
2964         (void) ssl_printf(ssl, "error no auth-zone %s\n", arg);
2965         return;
2966     }
2967     if (!z->rpz) {
2968         (void) ssl_printf(ssl, "error auth-zone %s not RPZ\n", arg);
2969         lock_rw_unlock(&z->lock);
2970         return;
2971     }
2972     if (enable) {
2973         rpz_enable(z->rpz);
2974     } else {
2975         rpz_disable(z->rpz);
2976     }
2977     lock_rw_unlock(&z->lock);
2978     send_ok(ssl);
2979 }
2980 
2981 /** do the rpz_enable command */
2982 static void
2983 do_rpz_enable(RES* ssl, struct worker* worker, char* arg)
2984 {
2985     do_rpz_enable_disable(ssl, worker, arg, 1);
2986 }
2987 
2988 /** do the rpz_disable command */
2989 static void
2990 do_rpz_disable(RES* ssl, struct worker* worker, char* arg)
2991 {
2992     do_rpz_enable_disable(ssl, worker, arg, 0);
2993 }
2994 
2995 /** tell other processes to execute the command */
2996 static void
2997 distribute_cmd(struct daemon_remote* rc, RES* ssl, char* cmd)
2998 {
2999 	int i;
3000 	if(!cmd || !ssl)
3001 		return;
3002 	/* skip i=0 which is me */
3003 	for(i=1; i<rc->worker->daemon->num; i++) {
3004 		worker_send_cmd(rc->worker->daemon->workers[i],
3005 			worker_cmd_remote);
3006 		if(!tube_write_msg(rc->worker->daemon->workers[i]->cmd,
3007 			(uint8_t*)cmd, strlen(cmd)+1, 0)) {
3008 			ssl_printf(ssl, "error could not distribute cmd\n");
3009 			return;
3010 		}
3011 	}
3012 }
3013 
3014 /** check for name with end-of-string, space or tab after it */
3015 static int
3016 cmdcmp(char* p, const char* cmd, size_t len)
3017 {
3018 	return strncmp(p,cmd,len)==0 && (p[len]==0||p[len]==' '||p[len]=='\t');
3019 }
3020 
3021 /** execute a remote control command */
3022 static void
3023 execute_cmd(struct daemon_remote* rc, RES* ssl, char* cmd,
3024 	struct worker* worker)
3025 {
3026 	char* p = skipwhite(cmd);
3027 	/* compare command */
3028 	if(cmdcmp(p, "stop", 4)) {
3029 		do_stop(ssl, worker);
3030 		return;
3031 	} else if(cmdcmp(p, "reload", 6)) {
3032 		do_reload(ssl, worker);
3033 		return;
3034 	} else if(cmdcmp(p, "stats_noreset", 13)) {
3035 		do_stats(ssl, worker, 0);
3036 		return;
3037 	} else if(cmdcmp(p, "stats", 5)) {
3038 		do_stats(ssl, worker, 1);
3039 		return;
3040 	} else if(cmdcmp(p, "status", 6)) {
3041 		do_status(ssl, worker);
3042 		return;
3043 	} else if(cmdcmp(p, "dump_cache", 10)) {
3044 		(void)dump_cache(ssl, worker);
3045 		return;
3046 	} else if(cmdcmp(p, "load_cache", 10)) {
3047 		if(load_cache(ssl, worker)) send_ok(ssl);
3048 		return;
3049 	} else if(cmdcmp(p, "list_forwards", 13)) {
3050 		do_list_forwards(ssl, worker);
3051 		return;
3052 	} else if(cmdcmp(p, "list_stubs", 10)) {
3053 		do_list_stubs(ssl, worker);
3054 		return;
3055 	} else if(cmdcmp(p, "list_insecure", 13)) {
3056 		do_insecure_list(ssl, worker);
3057 		return;
3058 	} else if(cmdcmp(p, "list_local_zones", 16)) {
3059 		do_list_local_zones(ssl, worker->daemon->local_zones);
3060 		return;
3061 	} else if(cmdcmp(p, "list_local_data", 15)) {
3062 		do_list_local_data(ssl, worker, worker->daemon->local_zones);
3063 		return;
3064 	} else if(cmdcmp(p, "view_list_local_zones", 21)) {
3065 		do_view_list_local_zones(ssl, worker, skipwhite(p+21));
3066 		return;
3067 	} else if(cmdcmp(p, "view_list_local_data", 20)) {
3068 		do_view_list_local_data(ssl, worker, skipwhite(p+20));
3069 		return;
3070 	} else if(cmdcmp(p, "ratelimit_list", 14)) {
3071 		do_ratelimit_list(ssl, worker, p+14);
3072 		return;
3073 	} else if(cmdcmp(p, "ip_ratelimit_list", 17)) {
3074 		do_ip_ratelimit_list(ssl, worker, p+17);
3075 		return;
3076 	} else if(cmdcmp(p, "list_auth_zones", 15)) {
3077 		do_list_auth_zones(ssl, worker->env.auth_zones);
3078 		return;
3079 	} else if(cmdcmp(p, "auth_zone_reload", 16)) {
3080 		do_auth_zone_reload(ssl, worker, skipwhite(p+16));
3081 		return;
3082 	} else if(cmdcmp(p, "auth_zone_transfer", 18)) {
3083 		do_auth_zone_transfer(ssl, worker, skipwhite(p+18));
3084 		return;
3085 	} else if(cmdcmp(p, "stub_add", 8)) {
3086 		/* must always distribute this cmd */
3087 		if(rc) distribute_cmd(rc, ssl, cmd);
3088 		do_stub_add(ssl, worker, skipwhite(p+8));
3089 		return;
3090 	} else if(cmdcmp(p, "stub_remove", 11)) {
3091 		/* must always distribute this cmd */
3092 		if(rc) distribute_cmd(rc, ssl, cmd);
3093 		do_stub_remove(ssl, worker, skipwhite(p+11));
3094 		return;
3095 	} else if(cmdcmp(p, "forward_add", 11)) {
3096 		/* must always distribute this cmd */
3097 		if(rc) distribute_cmd(rc, ssl, cmd);
3098 		do_forward_add(ssl, worker, skipwhite(p+11));
3099 		return;
3100 	} else if(cmdcmp(p, "forward_remove", 14)) {
3101 		/* must always distribute this cmd */
3102 		if(rc) distribute_cmd(rc, ssl, cmd);
3103 		do_forward_remove(ssl, worker, skipwhite(p+14));
3104 		return;
3105 	} else if(cmdcmp(p, "insecure_add", 12)) {
3106 		/* must always distribute this cmd */
3107 		if(rc) distribute_cmd(rc, ssl, cmd);
3108 		do_insecure_add(ssl, worker, skipwhite(p+12));
3109 		return;
3110 	} else if(cmdcmp(p, "insecure_remove", 15)) {
3111 		/* must always distribute this cmd */
3112 		if(rc) distribute_cmd(rc, ssl, cmd);
3113 		do_insecure_remove(ssl, worker, skipwhite(p+15));
3114 		return;
3115 	} else if(cmdcmp(p, "forward", 7)) {
3116 		/* must always distribute this cmd */
3117 		if(rc) distribute_cmd(rc, ssl, cmd);
3118 		do_forward(ssl, worker, skipwhite(p+7));
3119 		return;
3120 	} else if(cmdcmp(p, "flush_stats", 11)) {
3121 		/* must always distribute this cmd */
3122 		if(rc) distribute_cmd(rc, ssl, cmd);
3123 		do_flush_stats(ssl, worker);
3124 		return;
3125 	} else if(cmdcmp(p, "flush_requestlist", 17)) {
3126 		/* must always distribute this cmd */
3127 		if(rc) distribute_cmd(rc, ssl, cmd);
3128 		do_flush_requestlist(ssl, worker);
3129 		return;
3130 	} else if(cmdcmp(p, "lookup", 6)) {
3131 		do_lookup(ssl, worker, skipwhite(p+6));
3132 		return;
3133 	}
3134 
3135 #ifdef THREADS_DISABLED
3136 	/* other processes must execute the command as well */
3137 	/* commands that should not be distributed, returned above. */
3138 	if(rc) { /* only if this thread is the master (rc) thread */
3139 		/* done before the code below, which may split the string */
3140 		distribute_cmd(rc, ssl, cmd);
3141 	}
3142 #endif
3143 	if(cmdcmp(p, "verbosity", 9)) {
3144 		do_verbosity(ssl, skipwhite(p+9));
3145 	} else if(cmdcmp(p, "local_zone_remove", 17)) {
3146 		do_zone_remove(ssl, worker->daemon->local_zones, skipwhite(p+17));
3147 	} else if(cmdcmp(p, "local_zones_remove", 18)) {
3148 		do_zones_remove(ssl, worker->daemon->local_zones);
3149 	} else if(cmdcmp(p, "local_zone", 10)) {
3150 		do_zone_add(ssl, worker->daemon->local_zones, skipwhite(p+10));
3151 	} else if(cmdcmp(p, "local_zones", 11)) {
3152 		do_zones_add(ssl, worker->daemon->local_zones);
3153 	} else if(cmdcmp(p, "local_data_remove", 17)) {
3154 		do_data_remove(ssl, worker->daemon->local_zones, skipwhite(p+17));
3155 	} else if(cmdcmp(p, "local_datas_remove", 18)) {
3156 		do_datas_remove(ssl, worker->daemon->local_zones);
3157 	} else if(cmdcmp(p, "local_data", 10)) {
3158 		do_data_add(ssl, worker->daemon->local_zones, skipwhite(p+10));
3159 	} else if(cmdcmp(p, "local_datas", 11)) {
3160 		do_datas_add(ssl, worker->daemon->local_zones);
3161 	} else if(cmdcmp(p, "view_local_zone_remove", 22)) {
3162 		do_view_zone_remove(ssl, worker, skipwhite(p+22));
3163 	} else if(cmdcmp(p, "view_local_zone", 15)) {
3164 		do_view_zone_add(ssl, worker, skipwhite(p+15));
3165 	} else if(cmdcmp(p, "view_local_data_remove", 22)) {
3166 		do_view_data_remove(ssl, worker, skipwhite(p+22));
3167 	} else if(cmdcmp(p, "view_local_datas_remove", 23)){
3168 		do_view_datas_remove(ssl, worker, skipwhite(p+23));
3169 	} else if(cmdcmp(p, "view_local_data", 15)) {
3170 		do_view_data_add(ssl, worker, skipwhite(p+15));
3171 	} else if(cmdcmp(p, "view_local_datas", 16)) {
3172 		do_view_datas_add(ssl, worker, skipwhite(p+16));
3173 	} else if(cmdcmp(p, "flush_zone", 10)) {
3174 		do_flush_zone(ssl, worker, skipwhite(p+10));
3175 	} else if(cmdcmp(p, "flush_type", 10)) {
3176 		do_flush_type(ssl, worker, skipwhite(p+10));
3177 	} else if(cmdcmp(p, "flush_infra", 11)) {
3178 		do_flush_infra(ssl, worker, skipwhite(p+11));
3179 	} else if(cmdcmp(p, "flush", 5)) {
3180 		do_flush_name(ssl, worker, skipwhite(p+5));
3181 	} else if(cmdcmp(p, "dump_requestlist", 16)) {
3182 		do_dump_requestlist(ssl, worker);
3183 	} else if(cmdcmp(p, "dump_infra", 10)) {
3184 		do_dump_infra(ssl, worker);
3185 	} else if(cmdcmp(p, "log_reopen", 10)) {
3186 		do_log_reopen(ssl, worker);
3187 	} else if(cmdcmp(p, "set_option", 10)) {
3188 		do_set_option(ssl, worker, skipwhite(p+10));
3189 	} else if(cmdcmp(p, "get_option", 10)) {
3190 		do_get_option(ssl, worker, skipwhite(p+10));
3191 	} else if(cmdcmp(p, "flush_bogus", 11)) {
3192 		do_flush_bogus(ssl, worker);
3193 	} else if(cmdcmp(p, "flush_negative", 14)) {
3194 		do_flush_negative(ssl, worker);
3195     } else if(cmdcmp(p, "rpz_enable", 10)) {
3196         do_rpz_enable(ssl, worker, skipwhite(p+10));
3197     } else if(cmdcmp(p, "rpz_disable", 11)) {
3198         do_rpz_disable(ssl, worker, skipwhite(p+11));
3199 	} else {
3200 		(void)ssl_printf(ssl, "error unknown command '%s'\n", p);
3201 	}
3202 }
3203 
3204 void
3205 daemon_remote_exec(struct worker* worker)
3206 {
3207 	/* read the cmd string */
3208 	uint8_t* msg = NULL;
3209 	uint32_t len = 0;
3210 	if(!tube_read_msg(worker->cmd, &msg, &len, 0)) {
3211 		log_err("daemon_remote_exec: tube_read_msg failed");
3212 		return;
3213 	}
3214 	verbose(VERB_ALGO, "remote exec distributed: %s", (char*)msg);
3215 	execute_cmd(NULL, NULL, (char*)msg, worker);
3216 	free(msg);
3217 }
3218 
3219 /** handle remote control request */
3220 static void
3221 handle_req(struct daemon_remote* rc, struct rc_state* s, RES* res)
3222 {
3223 	int r;
3224 	char pre[10];
3225 	char magic[7];
3226 	char buf[1024];
3227 #ifdef USE_WINSOCK
3228 	/* makes it possible to set the socket blocking again. */
3229 	/* basically removes it from winsock_event ... */
3230 	WSAEventSelect(s->c->fd, NULL, 0);
3231 #endif
3232 	fd_set_block(s->c->fd);
3233 
3234 	/* try to read magic UBCT[version]_space_ string */
3235 	if(res->ssl) {
3236 		ERR_clear_error();
3237 		if((r=SSL_read(res->ssl, magic, (int)sizeof(magic)-1)) <= 0) {
3238 			if(SSL_get_error(res->ssl, r) == SSL_ERROR_ZERO_RETURN)
3239 				return;
3240 			log_crypto_err("could not SSL_read");
3241 			return;
3242 		}
3243 	} else {
3244 		while(1) {
3245 			ssize_t rr = recv(res->fd, magic, sizeof(magic)-1, 0);
3246 			if(rr <= 0) {
3247 				if(rr == 0) return;
3248 				if(errno == EINTR || errno == EAGAIN)
3249 					continue;
3250 				log_err("could not recv: %s", sock_strerror(errno));
3251 				return;
3252 			}
3253 			r = (int)rr;
3254 			break;
3255 		}
3256 	}
3257 	magic[6] = 0;
3258 	if( r != 6 || strncmp(magic, "UBCT", 4) != 0) {
3259 		verbose(VERB_QUERY, "control connection has bad magic string");
3260 		/* probably wrong tool connected, ignore it completely */
3261 		return;
3262 	}
3263 
3264 	/* read the command line */
3265 	if(!ssl_read_line(res, buf, sizeof(buf))) {
3266 		return;
3267 	}
3268 	snprintf(pre, sizeof(pre), "UBCT%d ", UNBOUND_CONTROL_VERSION);
3269 	if(strcmp(magic, pre) != 0) {
3270 		verbose(VERB_QUERY, "control connection had bad "
3271 			"version %s, cmd: %s", magic, buf);
3272 		ssl_printf(res, "error version mismatch\n");
3273 		return;
3274 	}
3275 	verbose(VERB_DETAIL, "control cmd: %s", buf);
3276 
3277 	/* figure out what to do */
3278 	execute_cmd(rc, res, buf, rc->worker);
3279 }
3280 
3281 /** handle SSL_do_handshake changes to the file descriptor to wait for later */
3282 static int
3283 remote_handshake_later(struct daemon_remote* rc, struct rc_state* s,
3284 	struct comm_point* c, int r, int r2)
3285 {
3286 	if(r2 == SSL_ERROR_WANT_READ) {
3287 		if(s->shake_state == rc_hs_read) {
3288 			/* try again later */
3289 			return 0;
3290 		}
3291 		s->shake_state = rc_hs_read;
3292 		comm_point_listen_for_rw(c, 1, 0);
3293 		return 0;
3294 	} else if(r2 == SSL_ERROR_WANT_WRITE) {
3295 		if(s->shake_state == rc_hs_write) {
3296 			/* try again later */
3297 			return 0;
3298 		}
3299 		s->shake_state = rc_hs_write;
3300 		comm_point_listen_for_rw(c, 0, 1);
3301 		return 0;
3302 	} else {
3303 		if(r == 0)
3304 			log_err("remote control connection closed prematurely");
3305 		log_addr(VERB_OPS, "failed connection from",
3306 			&s->c->repinfo.addr, s->c->repinfo.addrlen);
3307 		log_crypto_err("remote control failed ssl");
3308 		clean_point(rc, s);
3309 	}
3310 	return 0;
3311 }
3312 
3313 int remote_control_callback(struct comm_point* c, void* arg, int err,
3314 	struct comm_reply* ATTR_UNUSED(rep))
3315 {
3316 	RES res;
3317 	struct rc_state* s = (struct rc_state*)arg;
3318 	struct daemon_remote* rc = s->rc;
3319 	int r;
3320 	if(err != NETEVENT_NOERROR) {
3321 		if(err==NETEVENT_TIMEOUT)
3322 			log_err("remote control timed out");
3323 		clean_point(rc, s);
3324 		return 0;
3325 	}
3326 	if(s->ssl) {
3327 		/* (continue to) setup the SSL connection */
3328 		ERR_clear_error();
3329 		r = SSL_do_handshake(s->ssl);
3330 		if(r != 1) {
3331 			int r2 = SSL_get_error(s->ssl, r);
3332 			return remote_handshake_later(rc, s, c, r, r2);
3333 		}
3334 		s->shake_state = rc_none;
3335 	}
3336 
3337 	/* once handshake has completed, check authentication */
3338 	if (!rc->use_cert) {
3339 		verbose(VERB_ALGO, "unauthenticated remote control connection");
3340 	} else if(SSL_get_verify_result(s->ssl) == X509_V_OK) {
3341 #ifdef HAVE_SSL_GET1_PEER_CERTIFICATE
3342 		X509* x = SSL_get1_peer_certificate(s->ssl);
3343 #else
3344 		X509* x = SSL_get_peer_certificate(s->ssl);
3345 #endif
3346 		if(!x) {
3347 			verbose(VERB_DETAIL, "remote control connection "
3348 				"provided no client certificate");
3349 			clean_point(rc, s);
3350 			return 0;
3351 		}
3352 		verbose(VERB_ALGO, "remote control connection authenticated");
3353 		X509_free(x);
3354 	} else {
3355 		verbose(VERB_DETAIL, "remote control connection failed to "
3356 			"authenticate with client certificate");
3357 		clean_point(rc, s);
3358 		return 0;
3359 	}
3360 
3361 	/* if OK start to actually handle the request */
3362 	res.ssl = s->ssl;
3363 	res.fd = c->fd;
3364 	handle_req(rc, s, &res);
3365 
3366 	verbose(VERB_ALGO, "remote control operation completed");
3367 	clean_point(rc, s);
3368 	return 0;
3369 }
3370