xref: /freebsd/contrib/unbound/daemon/remote.c (revision 924226fba12cc9a228c73b956e1b7fa24c60b055)
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 			chmod(ip, (mode_t)(S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP));
304 			if (cfg->username && cfg->username[0] &&
305 				cfg_uid != (uid_t)-1) {
306 				if(chown(ip, cfg_uid, cfg_gid) == -1)
307 					verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
308 					  (unsigned)cfg_uid, (unsigned)cfg_gid,
309 					  ip, strerror(errno));
310 			}
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)
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 			uint8_t* dname= NULL;
2041 			int port;
2042 			dname = authextstrtodname(todo, &port, &auth_name);
2043 			if(!dname) {
2044 				(void)ssl_printf(ssl, "error cannot parse"
2045 					" '%s'\n", todo);
2046 				delegpt_free_mlc(dp);
2047 				return NULL;
2048 			}
2049 #if ! defined(HAVE_SSL_SET1_HOST) && ! defined(HAVE_X509_VERIFY_PARAM_SET1_HOST)
2050 			if(auth_name)
2051 				log_err("no name verification functionality in "
2052 				"ssl library, ignored name for %s", todo);
2053 #endif
2054 			if(!delegpt_add_ns_mlc(dp, dname, 0, auth_name, port)) {
2055 				(void)ssl_printf(ssl, "error out of memory\n");
2056 				free(dname);
2057 				delegpt_free_mlc(dp);
2058 				return NULL;
2059 			}
2060 		} else {
2061 #if ! defined(HAVE_SSL_SET1_HOST) && ! defined(HAVE_X509_VERIFY_PARAM_SET1_HOST)
2062 			if(auth_name)
2063 				log_err("no name verification functionality in "
2064 				"ssl library, ignored name for %s", todo);
2065 #endif
2066 			/* add address */
2067 			if(!delegpt_add_addr_mlc(dp, &addr, addrlen, 0, 0,
2068 				auth_name, -1)) {
2069 				(void)ssl_printf(ssl, "error out of memory\n");
2070 				delegpt_free_mlc(dp);
2071 				return NULL;
2072 			}
2073 		}
2074 	}
2075 	dp->has_parent_side_NS = 1;
2076 	return dp;
2077 }
2078 
2079 /** do the status command */
2080 static void
2081 do_forward(RES* ssl, struct worker* worker, char* args)
2082 {
2083 	struct iter_forwards* fwd = worker->env.fwds;
2084 	uint8_t* root = (uint8_t*)"\000";
2085 	if(!fwd) {
2086 		(void)ssl_printf(ssl, "error: structure not allocated\n");
2087 		return;
2088 	}
2089 	if(args == NULL || args[0] == 0) {
2090 		(void)print_root_fwds(ssl, fwd, root);
2091 		return;
2092 	}
2093 	/* set root forwards for this thread. since we are in remote control
2094 	 * the actual mesh is not running, so we can freely edit it. */
2095 	/* delete all the existing queries first */
2096 	mesh_delete_all(worker->env.mesh);
2097 	if(strcmp(args, "off") == 0) {
2098 		forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, root);
2099 	} else {
2100 		struct delegpt* dp;
2101 		if(!(dp = parse_delegpt(ssl, args, root)))
2102 			return;
2103 		if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp)) {
2104 			(void)ssl_printf(ssl, "error out of memory\n");
2105 			return;
2106 		}
2107 	}
2108 	send_ok(ssl);
2109 }
2110 
2111 static int
2112 parse_fs_args(RES* ssl, char* args, uint8_t** nm, struct delegpt** dp,
2113 	int* insecure, int* prime)
2114 {
2115 	char* zonename;
2116 	char* rest;
2117 	size_t nmlen;
2118 	int nmlabs;
2119 	/* parse all -x args */
2120 	while(args[0] == '+') {
2121 		if(!find_arg2(ssl, args, &rest))
2122 			return 0;
2123 		while(*(++args) != 0) {
2124 			if(*args == 'i' && insecure)
2125 				*insecure = 1;
2126 			else if(*args == 'p' && prime)
2127 				*prime = 1;
2128 			else {
2129 				(void)ssl_printf(ssl, "error: unknown option %s\n", args);
2130 				return 0;
2131 			}
2132 		}
2133 		args = rest;
2134 	}
2135 	/* parse name */
2136 	if(dp) {
2137 		if(!find_arg2(ssl, args, &rest))
2138 			return 0;
2139 		zonename = args;
2140 		args = rest;
2141 	} else	zonename = args;
2142 	if(!parse_arg_name(ssl, zonename, nm, &nmlen, &nmlabs))
2143 		return 0;
2144 
2145 	/* parse dp */
2146 	if(dp) {
2147 		if(!(*dp = parse_delegpt(ssl, args, *nm))) {
2148 			free(*nm);
2149 			return 0;
2150 		}
2151 	}
2152 	return 1;
2153 }
2154 
2155 /** do the forward_add command */
2156 static void
2157 do_forward_add(RES* ssl, struct worker* worker, char* args)
2158 {
2159 	struct iter_forwards* fwd = worker->env.fwds;
2160 	int insecure = 0;
2161 	uint8_t* nm = NULL;
2162 	struct delegpt* dp = NULL;
2163 	if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, NULL))
2164 		return;
2165 	if(insecure && worker->env.anchors) {
2166 		if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2167 			nm)) {
2168 			(void)ssl_printf(ssl, "error out of memory\n");
2169 			delegpt_free_mlc(dp);
2170 			free(nm);
2171 			return;
2172 		}
2173 	}
2174 	if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp)) {
2175 		(void)ssl_printf(ssl, "error out of memory\n");
2176 		free(nm);
2177 		return;
2178 	}
2179 	free(nm);
2180 	send_ok(ssl);
2181 }
2182 
2183 /** do the forward_remove command */
2184 static void
2185 do_forward_remove(RES* ssl, struct worker* worker, char* args)
2186 {
2187 	struct iter_forwards* fwd = worker->env.fwds;
2188 	int insecure = 0;
2189 	uint8_t* nm = NULL;
2190 	if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL))
2191 		return;
2192 	if(insecure && worker->env.anchors)
2193 		anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2194 			nm);
2195 	forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, nm);
2196 	free(nm);
2197 	send_ok(ssl);
2198 }
2199 
2200 /** do the stub_add command */
2201 static void
2202 do_stub_add(RES* ssl, struct worker* worker, char* args)
2203 {
2204 	struct iter_forwards* fwd = worker->env.fwds;
2205 	int insecure = 0, prime = 0;
2206 	uint8_t* nm = NULL;
2207 	struct delegpt* dp = NULL;
2208 	if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, &prime))
2209 		return;
2210 	if(insecure && worker->env.anchors) {
2211 		if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2212 			nm)) {
2213 			(void)ssl_printf(ssl, "error out of memory\n");
2214 			delegpt_free_mlc(dp);
2215 			free(nm);
2216 			return;
2217 		}
2218 	}
2219 	if(!forwards_add_stub_hole(fwd, LDNS_RR_CLASS_IN, nm)) {
2220 		if(insecure && worker->env.anchors)
2221 			anchors_delete_insecure(worker->env.anchors,
2222 				LDNS_RR_CLASS_IN, nm);
2223 		(void)ssl_printf(ssl, "error out of memory\n");
2224 		delegpt_free_mlc(dp);
2225 		free(nm);
2226 		return;
2227 	}
2228 	if(!hints_add_stub(worker->env.hints, LDNS_RR_CLASS_IN, dp, !prime)) {
2229 		(void)ssl_printf(ssl, "error out of memory\n");
2230 		forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm);
2231 		if(insecure && worker->env.anchors)
2232 			anchors_delete_insecure(worker->env.anchors,
2233 				LDNS_RR_CLASS_IN, nm);
2234 		free(nm);
2235 		return;
2236 	}
2237 	free(nm);
2238 	send_ok(ssl);
2239 }
2240 
2241 /** do the stub_remove command */
2242 static void
2243 do_stub_remove(RES* ssl, struct worker* worker, char* args)
2244 {
2245 	struct iter_forwards* fwd = worker->env.fwds;
2246 	int insecure = 0;
2247 	uint8_t* nm = NULL;
2248 	if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL))
2249 		return;
2250 	if(insecure && worker->env.anchors)
2251 		anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2252 			nm);
2253 	forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm);
2254 	hints_delete_stub(worker->env.hints, LDNS_RR_CLASS_IN, nm);
2255 	free(nm);
2256 	send_ok(ssl);
2257 }
2258 
2259 /** do the insecure_add command */
2260 static void
2261 do_insecure_add(RES* ssl, struct worker* worker, char* arg)
2262 {
2263 	size_t nmlen;
2264 	int nmlabs;
2265 	uint8_t* nm = NULL;
2266 	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
2267 		return;
2268 	if(worker->env.anchors) {
2269 		if(!anchors_add_insecure(worker->env.anchors,
2270 			LDNS_RR_CLASS_IN, nm)) {
2271 			(void)ssl_printf(ssl, "error out of memory\n");
2272 			free(nm);
2273 			return;
2274 		}
2275 	}
2276 	free(nm);
2277 	send_ok(ssl);
2278 }
2279 
2280 /** do the insecure_remove command */
2281 static void
2282 do_insecure_remove(RES* ssl, struct worker* worker, char* arg)
2283 {
2284 	size_t nmlen;
2285 	int nmlabs;
2286 	uint8_t* nm = NULL;
2287 	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
2288 		return;
2289 	if(worker->env.anchors)
2290 		anchors_delete_insecure(worker->env.anchors,
2291 			LDNS_RR_CLASS_IN, nm);
2292 	free(nm);
2293 	send_ok(ssl);
2294 }
2295 
2296 static void
2297 do_insecure_list(RES* ssl, struct worker* worker)
2298 {
2299 	char buf[257];
2300 	struct trust_anchor* a;
2301 	if(worker->env.anchors) {
2302 		RBTREE_FOR(a, struct trust_anchor*, worker->env.anchors->tree) {
2303 			if(a->numDS == 0 && a->numDNSKEY == 0) {
2304 				dname_str(a->name, buf);
2305 				ssl_printf(ssl, "%s\n", buf);
2306 			}
2307 		}
2308 	}
2309 }
2310 
2311 /** do the status command */
2312 static void
2313 do_status(RES* ssl, struct worker* worker)
2314 {
2315 	int i;
2316 	time_t uptime;
2317 	if(!ssl_printf(ssl, "version: %s\n", PACKAGE_VERSION))
2318 		return;
2319 	if(!ssl_printf(ssl, "verbosity: %d\n", verbosity))
2320 		return;
2321 	if(!ssl_printf(ssl, "threads: %d\n", worker->daemon->num))
2322 		return;
2323 	if(!ssl_printf(ssl, "modules: %d [", worker->daemon->mods.num))
2324 		return;
2325 	for(i=0; i<worker->daemon->mods.num; i++) {
2326 		if(!ssl_printf(ssl, " %s", worker->daemon->mods.mod[i]->name))
2327 			return;
2328 	}
2329 	if(!ssl_printf(ssl, " ]\n"))
2330 		return;
2331 	uptime = (time_t)time(NULL) - (time_t)worker->daemon->time_boot.tv_sec;
2332 	if(!ssl_printf(ssl, "uptime: " ARG_LL "d seconds\n", (long long)uptime))
2333 		return;
2334 	if(!ssl_printf(ssl, "options:%s%s%s%s\n" ,
2335 		(worker->daemon->reuseport?" reuseport":""),
2336 		(worker->daemon->rc->accept_list?" control":""),
2337 		(worker->daemon->rc->accept_list && worker->daemon->rc->use_cert?"(ssl)":""),
2338 		(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)":"")
2339 		))
2340 		return;
2341 	if(!ssl_printf(ssl, "unbound (pid %d) is running...\n",
2342 		(int)getpid()))
2343 		return;
2344 }
2345 
2346 /** get age for the mesh state */
2347 static void
2348 get_mesh_age(struct mesh_state* m, char* buf, size_t len,
2349 	struct module_env* env)
2350 {
2351 	if(m->reply_list) {
2352 		struct timeval d;
2353 		struct mesh_reply* r = m->reply_list;
2354 		/* last reply is the oldest */
2355 		while(r && r->next)
2356 			r = r->next;
2357 		timeval_subtract(&d, env->now_tv, &r->start_time);
2358 		snprintf(buf, len, ARG_LL "d.%6.6d",
2359 			(long long)d.tv_sec, (int)d.tv_usec);
2360 	} else {
2361 		snprintf(buf, len, "-");
2362 	}
2363 }
2364 
2365 /** get status of a mesh state */
2366 static void
2367 get_mesh_status(struct mesh_area* mesh, struct mesh_state* m,
2368 	char* buf, size_t len)
2369 {
2370 	enum module_ext_state s = m->s.ext_state[m->s.curmod];
2371 	const char *modname = mesh->mods.mod[m->s.curmod]->name;
2372 	size_t l;
2373 	if(strcmp(modname, "iterator") == 0 && s == module_wait_reply &&
2374 		m->s.minfo[m->s.curmod]) {
2375 		/* break into iterator to find out who its waiting for */
2376 		struct iter_qstate* qstate = (struct iter_qstate*)
2377 			m->s.minfo[m->s.curmod];
2378 		struct outbound_list* ol = &qstate->outlist;
2379 		struct outbound_entry* e;
2380 		snprintf(buf, len, "%s wait for", modname);
2381 		l = strlen(buf);
2382 		buf += l; len -= l;
2383 		if(ol->first == NULL)
2384 			snprintf(buf, len, " (empty_list)");
2385 		for(e = ol->first; e; e = e->next) {
2386 			snprintf(buf, len, " ");
2387 			l = strlen(buf);
2388 			buf += l; len -= l;
2389 			addr_to_str(&e->qsent->addr, e->qsent->addrlen,
2390 				buf, len);
2391 			l = strlen(buf);
2392 			buf += l; len -= l;
2393 		}
2394 	} else if(s == module_wait_subquery) {
2395 		/* look in subs from mesh state to see what */
2396 		char nm[257];
2397 		struct mesh_state_ref* sub;
2398 		snprintf(buf, len, "%s wants", modname);
2399 		l = strlen(buf);
2400 		buf += l; len -= l;
2401 		if(m->sub_set.count == 0)
2402 			snprintf(buf, len, " (empty_list)");
2403 		RBTREE_FOR(sub, struct mesh_state_ref*, &m->sub_set) {
2404 			char* t = sldns_wire2str_type(sub->s->s.qinfo.qtype);
2405 			char* c = sldns_wire2str_class(sub->s->s.qinfo.qclass);
2406 			dname_str(sub->s->s.qinfo.qname, nm);
2407 			snprintf(buf, len, " %s %s %s", (t?t:"TYPE??"),
2408 				(c?c:"CLASS??"), nm);
2409 			l = strlen(buf);
2410 			buf += l; len -= l;
2411 			free(t);
2412 			free(c);
2413 		}
2414 	} else {
2415 		snprintf(buf, len, "%s is %s", modname, strextstate(s));
2416 	}
2417 }
2418 
2419 /** do the dump_requestlist command */
2420 static void
2421 do_dump_requestlist(RES* ssl, struct worker* worker)
2422 {
2423 	struct mesh_area* mesh;
2424 	struct mesh_state* m;
2425 	int num = 0;
2426 	char buf[257];
2427 	char timebuf[32];
2428 	char statbuf[10240];
2429 	if(!ssl_printf(ssl, "thread #%d\n", worker->thread_num))
2430 		return;
2431 	if(!ssl_printf(ssl, "#   type cl name    seconds    module status\n"))
2432 		return;
2433 	/* show worker mesh contents */
2434 	mesh = worker->env.mesh;
2435 	if(!mesh) return;
2436 	RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
2437 		char* t = sldns_wire2str_type(m->s.qinfo.qtype);
2438 		char* c = sldns_wire2str_class(m->s.qinfo.qclass);
2439 		dname_str(m->s.qinfo.qname, buf);
2440 		get_mesh_age(m, timebuf, sizeof(timebuf), &worker->env);
2441 		get_mesh_status(mesh, m, statbuf, sizeof(statbuf));
2442 		if(!ssl_printf(ssl, "%3d %4s %2s %s %s %s\n",
2443 			num, (t?t:"TYPE??"), (c?c:"CLASS??"), buf, timebuf,
2444 			statbuf)) {
2445 			free(t);
2446 			free(c);
2447 			return;
2448 		}
2449 		num++;
2450 		free(t);
2451 		free(c);
2452 	}
2453 }
2454 
2455 /** structure for argument data for dump infra host */
2456 struct infra_arg {
2457 	/** the infra cache */
2458 	struct infra_cache* infra;
2459 	/** the SSL connection */
2460 	RES* ssl;
2461 	/** the time now */
2462 	time_t now;
2463 	/** ssl failure? stop writing and skip the rest.  If the tcp
2464 	 * connection is broken, and writes fail, we then stop writing. */
2465 	int ssl_failed;
2466 };
2467 
2468 /** callback for every host element in the infra cache */
2469 static void
2470 dump_infra_host(struct lruhash_entry* e, void* arg)
2471 {
2472 	struct infra_arg* a = (struct infra_arg*)arg;
2473 	struct infra_key* k = (struct infra_key*)e->key;
2474 	struct infra_data* d = (struct infra_data*)e->data;
2475 	char ip_str[1024];
2476 	char name[257];
2477 	int port;
2478 	if(a->ssl_failed)
2479 		return;
2480 	addr_to_str(&k->addr, k->addrlen, ip_str, sizeof(ip_str));
2481 	dname_str(k->zonename, name);
2482 	port = (int)ntohs(((struct sockaddr_in*)&k->addr)->sin_port);
2483 	if(port != UNBOUND_DNS_PORT) {
2484 		snprintf(ip_str+strlen(ip_str), sizeof(ip_str)-strlen(ip_str),
2485 			"@%d", port);
2486 	}
2487 	/* skip expired stuff (only backed off) */
2488 	if(d->ttl < a->now) {
2489 		if(d->rtt.rto >= USEFUL_SERVER_TOP_TIMEOUT) {
2490 			if(!ssl_printf(a->ssl, "%s %s expired rto %d\n", ip_str,
2491 				name, d->rtt.rto))  {
2492 				a->ssl_failed = 1;
2493 				return;
2494 			}
2495 		}
2496 		return;
2497 	}
2498 	if(!ssl_printf(a->ssl, "%s %s ttl %lu ping %d var %d rtt %d rto %d "
2499 		"tA %d tAAAA %d tother %d "
2500 		"ednsknown %d edns %d delay %d lame dnssec %d rec %d A %d "
2501 		"other %d\n", ip_str, name, (unsigned long)(d->ttl - a->now),
2502 		d->rtt.srtt, d->rtt.rttvar, rtt_notimeout(&d->rtt), d->rtt.rto,
2503 		d->timeout_A, d->timeout_AAAA, d->timeout_other,
2504 		(int)d->edns_lame_known, (int)d->edns_version,
2505 		(int)(a->now<d->probedelay?(d->probedelay - a->now):0),
2506 		(int)d->isdnsseclame, (int)d->rec_lame, (int)d->lame_type_A,
2507 		(int)d->lame_other)) {
2508 		a->ssl_failed = 1;
2509 		return;
2510 	}
2511 }
2512 
2513 /** do the dump_infra command */
2514 static void
2515 do_dump_infra(RES* ssl, struct worker* worker)
2516 {
2517 	struct infra_arg arg;
2518 	arg.infra = worker->env.infra_cache;
2519 	arg.ssl = ssl;
2520 	arg.now = *worker->env.now;
2521 	arg.ssl_failed = 0;
2522 	slabhash_traverse(arg.infra->hosts, 0, &dump_infra_host, (void*)&arg);
2523 }
2524 
2525 /** do the log_reopen command */
2526 static void
2527 do_log_reopen(RES* ssl, struct worker* worker)
2528 {
2529 	struct config_file* cfg = worker->env.cfg;
2530 	send_ok(ssl);
2531 	log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
2532 }
2533 
2534 /** do the auth_zone_reload command */
2535 static void
2536 do_auth_zone_reload(RES* ssl, struct worker* worker, char* arg)
2537 {
2538 	size_t nmlen;
2539 	int nmlabs;
2540 	uint8_t* nm = NULL;
2541 	struct auth_zones* az = worker->env.auth_zones;
2542 	struct auth_zone* z = NULL;
2543 	struct auth_xfer* xfr = NULL;
2544 	char* reason = NULL;
2545 	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
2546 		return;
2547 	if(az) {
2548 		lock_rw_rdlock(&az->lock);
2549 		z = auth_zone_find(az, nm, nmlen, LDNS_RR_CLASS_IN);
2550 		if(z) {
2551 			lock_rw_wrlock(&z->lock);
2552 		}
2553 		xfr = auth_xfer_find(az, nm, nmlen, LDNS_RR_CLASS_IN);
2554 		if(xfr) {
2555 			lock_basic_lock(&xfr->lock);
2556 		}
2557 		lock_rw_unlock(&az->lock);
2558 	}
2559 	free(nm);
2560 	if(!z) {
2561 		if(xfr) {
2562 			lock_basic_unlock(&xfr->lock);
2563 		}
2564 		(void)ssl_printf(ssl, "error no auth-zone %s\n", arg);
2565 		return;
2566 	}
2567 	if(!auth_zone_read_zonefile(z, worker->env.cfg)) {
2568 		lock_rw_unlock(&z->lock);
2569 		if(xfr) {
2570 			lock_basic_unlock(&xfr->lock);
2571 		}
2572 		(void)ssl_printf(ssl, "error failed to read %s\n", arg);
2573 		return;
2574 	}
2575 
2576 	z->zone_expired = 0;
2577 	if(xfr) {
2578 		xfr->zone_expired = 0;
2579 		if(!xfr_find_soa(z, xfr)) {
2580 			if(z->data.count == 0) {
2581 				lock_rw_unlock(&z->lock);
2582 				lock_basic_unlock(&xfr->lock);
2583 				(void)ssl_printf(ssl, "zone %s has no contents\n", arg);
2584 				return;
2585 			}
2586 			lock_rw_unlock(&z->lock);
2587 			lock_basic_unlock(&xfr->lock);
2588 			(void)ssl_printf(ssl, "error: no SOA in zone after read %s\n", arg);
2589 			return;
2590 		}
2591 		if(xfr->have_zone)
2592 			xfr->lease_time = *worker->env.now;
2593 		lock_basic_unlock(&xfr->lock);
2594 	}
2595 
2596 	auth_zone_verify_zonemd(z, &worker->env, &worker->env.mesh->mods,
2597 		&reason, 0, 0);
2598 	if(reason && z->zone_expired) {
2599 		lock_rw_unlock(&z->lock);
2600 		(void)ssl_printf(ssl, "error zonemd for %s failed: %s\n",
2601 			arg, reason);
2602 		free(reason);
2603 		return;
2604 	} else if(reason && strcmp(reason, "ZONEMD verification successful")
2605 		==0) {
2606 		(void)ssl_printf(ssl, "%s: %s\n", arg, reason);
2607 	}
2608 	lock_rw_unlock(&z->lock);
2609 	free(reason);
2610 	send_ok(ssl);
2611 }
2612 
2613 /** do the auth_zone_transfer command */
2614 static void
2615 do_auth_zone_transfer(RES* ssl, struct worker* worker, char* arg)
2616 {
2617 	size_t nmlen;
2618 	int nmlabs;
2619 	uint8_t* nm = NULL;
2620 	struct auth_zones* az = worker->env.auth_zones;
2621 	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
2622 		return;
2623 	if(!az || !auth_zones_startprobesequence(az, &worker->env, nm, nmlen,
2624 		LDNS_RR_CLASS_IN)) {
2625 		(void)ssl_printf(ssl, "error zone xfr task not found %s\n", arg);
2626 		free(nm);
2627 		return;
2628 	}
2629 	free(nm);
2630 	send_ok(ssl);
2631 }
2632 
2633 /** do the set_option command */
2634 static void
2635 do_set_option(RES* ssl, struct worker* worker, char* arg)
2636 {
2637 	char* arg2;
2638 	if(!find_arg2(ssl, arg, &arg2))
2639 		return;
2640 	if(!config_set_option(worker->env.cfg, arg, arg2)) {
2641 		(void)ssl_printf(ssl, "error setting option\n");
2642 		return;
2643 	}
2644 	/* effectuate some arguments */
2645 	if(strcmp(arg, "val-override-date:") == 0) {
2646 		int m = modstack_find(&worker->env.mesh->mods, "validator");
2647 		struct val_env* val_env = NULL;
2648 		if(m != -1) val_env = (struct val_env*)worker->env.modinfo[m];
2649 		if(val_env)
2650 			val_env->date_override = worker->env.cfg->val_date_override;
2651 	}
2652 	send_ok(ssl);
2653 }
2654 
2655 /* routine to printout option values over SSL */
2656 void remote_get_opt_ssl(char* line, void* arg)
2657 {
2658 	RES* ssl = (RES*)arg;
2659 	(void)ssl_printf(ssl, "%s\n", line);
2660 }
2661 
2662 /** do the get_option command */
2663 static void
2664 do_get_option(RES* ssl, struct worker* worker, char* arg)
2665 {
2666 	int r;
2667 	r = config_get_option(worker->env.cfg, arg, remote_get_opt_ssl, ssl);
2668 	if(!r) {
2669 		(void)ssl_printf(ssl, "error unknown option\n");
2670 		return;
2671 	}
2672 }
2673 
2674 /** do the list_forwards command */
2675 static void
2676 do_list_forwards(RES* ssl, struct worker* worker)
2677 {
2678 	/* since its a per-worker structure no locks needed */
2679 	struct iter_forwards* fwds = worker->env.fwds;
2680 	struct iter_forward_zone* z;
2681 	struct trust_anchor* a;
2682 	int insecure;
2683 	RBTREE_FOR(z, struct iter_forward_zone*, fwds->tree) {
2684 		if(!z->dp) continue; /* skip empty marker for stub */
2685 
2686 		/* see if it is insecure */
2687 		insecure = 0;
2688 		if(worker->env.anchors &&
2689 			(a=anchor_find(worker->env.anchors, z->name,
2690 			z->namelabs, z->namelen,  z->dclass))) {
2691 			if(!a->keylist && !a->numDS && !a->numDNSKEY)
2692 				insecure = 1;
2693 			lock_basic_unlock(&a->lock);
2694 		}
2695 
2696 		if(!ssl_print_name_dp(ssl, (insecure?"forward +i":"forward"),
2697 			z->name, z->dclass, z->dp))
2698 			return;
2699 	}
2700 }
2701 
2702 /** do the list_stubs command */
2703 static void
2704 do_list_stubs(RES* ssl, struct worker* worker)
2705 {
2706 	struct iter_hints_stub* z;
2707 	struct trust_anchor* a;
2708 	int insecure;
2709 	char str[32];
2710 	RBTREE_FOR(z, struct iter_hints_stub*, &worker->env.hints->tree) {
2711 
2712 		/* see if it is insecure */
2713 		insecure = 0;
2714 		if(worker->env.anchors &&
2715 			(a=anchor_find(worker->env.anchors, z->node.name,
2716 			z->node.labs, z->node.len,  z->node.dclass))) {
2717 			if(!a->keylist && !a->numDS && !a->numDNSKEY)
2718 				insecure = 1;
2719 			lock_basic_unlock(&a->lock);
2720 		}
2721 
2722 		snprintf(str, sizeof(str), "stub %sprime%s",
2723 			(z->noprime?"no":""), (insecure?" +i":""));
2724 		if(!ssl_print_name_dp(ssl, str, z->node.name,
2725 			z->node.dclass, z->dp))
2726 			return;
2727 	}
2728 }
2729 
2730 /** do the list_auth_zones command */
2731 static void
2732 do_list_auth_zones(RES* ssl, struct auth_zones* az)
2733 {
2734 	struct auth_zone* z;
2735 	char buf[257], buf2[256];
2736 	lock_rw_rdlock(&az->lock);
2737 	RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
2738 		lock_rw_rdlock(&z->lock);
2739 		dname_str(z->name, buf);
2740 		if(z->zone_expired)
2741 			snprintf(buf2, sizeof(buf2), "expired");
2742 		else {
2743 			uint32_t serial = 0;
2744 			if(auth_zone_get_serial(z, &serial))
2745 				snprintf(buf2, sizeof(buf2), "serial %u",
2746 					(unsigned)serial);
2747 			else	snprintf(buf2, sizeof(buf2), "no serial");
2748 		}
2749 		if(!ssl_printf(ssl, "%s\t%s\n", buf, buf2)) {
2750 			/* failure to print */
2751 			lock_rw_unlock(&z->lock);
2752 			lock_rw_unlock(&az->lock);
2753 			return;
2754 		}
2755 		lock_rw_unlock(&z->lock);
2756 	}
2757 	lock_rw_unlock(&az->lock);
2758 }
2759 
2760 /** do the list_local_zones command */
2761 static void
2762 do_list_local_zones(RES* ssl, struct local_zones* zones)
2763 {
2764 	struct local_zone* z;
2765 	char buf[257];
2766 	lock_rw_rdlock(&zones->lock);
2767 	RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
2768 		lock_rw_rdlock(&z->lock);
2769 		dname_str(z->name, buf);
2770 		if(!ssl_printf(ssl, "%s %s\n", buf,
2771 			local_zone_type2str(z->type))) {
2772 			/* failure to print */
2773 			lock_rw_unlock(&z->lock);
2774 			lock_rw_unlock(&zones->lock);
2775 			return;
2776 		}
2777 		lock_rw_unlock(&z->lock);
2778 	}
2779 	lock_rw_unlock(&zones->lock);
2780 }
2781 
2782 /** do the list_local_data command */
2783 static void
2784 do_list_local_data(RES* ssl, struct worker* worker, struct local_zones* zones)
2785 {
2786 	struct local_zone* z;
2787 	struct local_data* d;
2788 	struct local_rrset* p;
2789 	char* s = (char*)sldns_buffer_begin(worker->env.scratch_buffer);
2790 	size_t slen = sldns_buffer_capacity(worker->env.scratch_buffer);
2791 	lock_rw_rdlock(&zones->lock);
2792 	RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
2793 		lock_rw_rdlock(&z->lock);
2794 		RBTREE_FOR(d, struct local_data*, &z->data) {
2795 			for(p = d->rrsets; p; p = p->next) {
2796 				struct packed_rrset_data* d =
2797 					(struct packed_rrset_data*)p->rrset->entry.data;
2798 				size_t i;
2799 				for(i=0; i<d->count + d->rrsig_count; i++) {
2800 					if(!packed_rr_to_string(p->rrset, i,
2801 						0, s, slen)) {
2802 						if(!ssl_printf(ssl, "BADRR\n")) {
2803 							lock_rw_unlock(&z->lock);
2804 							lock_rw_unlock(&zones->lock);
2805 							return;
2806 						}
2807 					}
2808 				        if(!ssl_printf(ssl, "%s\n", s)) {
2809 						lock_rw_unlock(&z->lock);
2810 						lock_rw_unlock(&zones->lock);
2811 						return;
2812 					}
2813 				}
2814 			}
2815 		}
2816 		lock_rw_unlock(&z->lock);
2817 	}
2818 	lock_rw_unlock(&zones->lock);
2819 }
2820 
2821 /** do the view_list_local_zones command */
2822 static void
2823 do_view_list_local_zones(RES* ssl, struct worker* worker, char* arg)
2824 {
2825 	struct view* v = views_find_view(worker->daemon->views,
2826 		arg, 0 /* get read lock*/);
2827 	if(!v) {
2828 		ssl_printf(ssl,"no view with name: %s\n", arg);
2829 		return;
2830 	}
2831 	if(v->local_zones) {
2832 		do_list_local_zones(ssl, v->local_zones);
2833 	}
2834 	lock_rw_unlock(&v->lock);
2835 }
2836 
2837 /** do the view_list_local_data command */
2838 static void
2839 do_view_list_local_data(RES* ssl, struct worker* worker, char* arg)
2840 {
2841 	struct view* v = views_find_view(worker->daemon->views,
2842 		arg, 0 /* get read lock*/);
2843 	if(!v) {
2844 		ssl_printf(ssl,"no view with name: %s\n", arg);
2845 		return;
2846 	}
2847 	if(v->local_zones) {
2848 		do_list_local_data(ssl, worker, v->local_zones);
2849 	}
2850 	lock_rw_unlock(&v->lock);
2851 }
2852 
2853 /** struct for user arg ratelimit list */
2854 struct ratelimit_list_arg {
2855 	/** the infra cache */
2856 	struct infra_cache* infra;
2857 	/** the SSL to print to */
2858 	RES* ssl;
2859 	/** all or only ratelimited */
2860 	int all;
2861 	/** current time */
2862 	time_t now;
2863 	/** if backoff is enabled */
2864 	int backoff;
2865 };
2866 
2867 #define ip_ratelimit_list_arg ratelimit_list_arg
2868 
2869 /** list items in the ratelimit table */
2870 static void
2871 rate_list(struct lruhash_entry* e, void* arg)
2872 {
2873 	struct ratelimit_list_arg* a = (struct ratelimit_list_arg*)arg;
2874 	struct rate_key* k = (struct rate_key*)e->key;
2875 	struct rate_data* d = (struct rate_data*)e->data;
2876 	char buf[257];
2877 	int lim = infra_find_ratelimit(a->infra, k->name, k->namelen);
2878 	int max = infra_rate_max(d, a->now, a->backoff);
2879 	if(a->all == 0) {
2880 		if(max < lim)
2881 			return;
2882 	}
2883 	dname_str(k->name, buf);
2884 	ssl_printf(a->ssl, "%s %d limit %d\n", buf, max, lim);
2885 }
2886 
2887 /** list items in the ip_ratelimit table */
2888 static void
2889 ip_rate_list(struct lruhash_entry* e, void* arg)
2890 {
2891 	char ip[128];
2892 	struct ip_ratelimit_list_arg* a = (struct ip_ratelimit_list_arg*)arg;
2893 	struct ip_rate_key* k = (struct ip_rate_key*)e->key;
2894 	struct ip_rate_data* d = (struct ip_rate_data*)e->data;
2895 	int lim = infra_ip_ratelimit;
2896 	int max = infra_rate_max(d, a->now, a->backoff);
2897 	if(a->all == 0) {
2898 		if(max < lim)
2899 			return;
2900 	}
2901 	addr_to_str(&k->addr, k->addrlen, ip, sizeof(ip));
2902 	ssl_printf(a->ssl, "%s %d limit %d\n", ip, max, lim);
2903 }
2904 
2905 /** do the ratelimit_list command */
2906 static void
2907 do_ratelimit_list(RES* ssl, struct worker* worker, char* arg)
2908 {
2909 	struct ratelimit_list_arg a;
2910 	a.all = 0;
2911 	a.infra = worker->env.infra_cache;
2912 	a.now = *worker->env.now;
2913 	a.ssl = ssl;
2914 	a.backoff = worker->env.cfg->ratelimit_backoff;
2915 	arg = skipwhite(arg);
2916 	if(strcmp(arg, "+a") == 0)
2917 		a.all = 1;
2918 	if(a.infra->domain_rates==NULL ||
2919 		(a.all == 0 && infra_dp_ratelimit == 0))
2920 		return;
2921 	slabhash_traverse(a.infra->domain_rates, 0, rate_list, &a);
2922 }
2923 
2924 /** do the ip_ratelimit_list command */
2925 static void
2926 do_ip_ratelimit_list(RES* ssl, struct worker* worker, char* arg)
2927 {
2928 	struct ip_ratelimit_list_arg a;
2929 	a.all = 0;
2930 	a.infra = worker->env.infra_cache;
2931 	a.now = *worker->env.now;
2932 	a.ssl = ssl;
2933 	a.backoff = worker->env.cfg->ip_ratelimit_backoff;
2934 	arg = skipwhite(arg);
2935 	if(strcmp(arg, "+a") == 0)
2936 		a.all = 1;
2937 	if(a.infra->client_ip_rates==NULL ||
2938 		(a.all == 0 && infra_ip_ratelimit == 0))
2939 		return;
2940 	slabhash_traverse(a.infra->client_ip_rates, 0, ip_rate_list, &a);
2941 }
2942 
2943 /** do the rpz_enable/disable command */
2944 static void
2945 do_rpz_enable_disable(RES* ssl, struct worker* worker, char* arg, int enable) {
2946     size_t nmlen;
2947     int nmlabs;
2948     uint8_t *nm = NULL;
2949     struct auth_zones *az = worker->env.auth_zones;
2950     struct auth_zone *z = NULL;
2951     if (!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
2952         return;
2953     if (az) {
2954         lock_rw_rdlock(&az->lock);
2955         z = auth_zone_find(az, nm, nmlen, LDNS_RR_CLASS_IN);
2956         if (z) {
2957             lock_rw_wrlock(&z->lock);
2958         }
2959         lock_rw_unlock(&az->lock);
2960     }
2961     free(nm);
2962     if (!z) {
2963         (void) ssl_printf(ssl, "error no auth-zone %s\n", arg);
2964         return;
2965     }
2966     if (!z->rpz) {
2967         (void) ssl_printf(ssl, "error auth-zone %s not RPZ\n", arg);
2968         lock_rw_unlock(&z->lock);
2969         return;
2970     }
2971     if (enable) {
2972         rpz_enable(z->rpz);
2973     } else {
2974         rpz_disable(z->rpz);
2975     }
2976     lock_rw_unlock(&z->lock);
2977     send_ok(ssl);
2978 }
2979 
2980 /** do the rpz_enable command */
2981 static void
2982 do_rpz_enable(RES* ssl, struct worker* worker, char* arg)
2983 {
2984     do_rpz_enable_disable(ssl, worker, arg, 1);
2985 }
2986 
2987 /** do the rpz_disable command */
2988 static void
2989 do_rpz_disable(RES* ssl, struct worker* worker, char* arg)
2990 {
2991     do_rpz_enable_disable(ssl, worker, arg, 0);
2992 }
2993 
2994 /** tell other processes to execute the command */
2995 static void
2996 distribute_cmd(struct daemon_remote* rc, RES* ssl, char* cmd)
2997 {
2998 	int i;
2999 	if(!cmd || !ssl)
3000 		return;
3001 	/* skip i=0 which is me */
3002 	for(i=1; i<rc->worker->daemon->num; i++) {
3003 		worker_send_cmd(rc->worker->daemon->workers[i],
3004 			worker_cmd_remote);
3005 		if(!tube_write_msg(rc->worker->daemon->workers[i]->cmd,
3006 			(uint8_t*)cmd, strlen(cmd)+1, 0)) {
3007 			ssl_printf(ssl, "error could not distribute cmd\n");
3008 			return;
3009 		}
3010 	}
3011 }
3012 
3013 /** check for name with end-of-string, space or tab after it */
3014 static int
3015 cmdcmp(char* p, const char* cmd, size_t len)
3016 {
3017 	return strncmp(p,cmd,len)==0 && (p[len]==0||p[len]==' '||p[len]=='\t');
3018 }
3019 
3020 /** execute a remote control command */
3021 static void
3022 execute_cmd(struct daemon_remote* rc, RES* ssl, char* cmd,
3023 	struct worker* worker)
3024 {
3025 	char* p = skipwhite(cmd);
3026 	/* compare command */
3027 	if(cmdcmp(p, "stop", 4)) {
3028 		do_stop(ssl, worker);
3029 		return;
3030 	} else if(cmdcmp(p, "reload", 6)) {
3031 		do_reload(ssl, worker);
3032 		return;
3033 	} else if(cmdcmp(p, "stats_noreset", 13)) {
3034 		do_stats(ssl, worker, 0);
3035 		return;
3036 	} else if(cmdcmp(p, "stats", 5)) {
3037 		do_stats(ssl, worker, 1);
3038 		return;
3039 	} else if(cmdcmp(p, "status", 6)) {
3040 		do_status(ssl, worker);
3041 		return;
3042 	} else if(cmdcmp(p, "dump_cache", 10)) {
3043 		(void)dump_cache(ssl, worker);
3044 		return;
3045 	} else if(cmdcmp(p, "load_cache", 10)) {
3046 		if(load_cache(ssl, worker)) send_ok(ssl);
3047 		return;
3048 	} else if(cmdcmp(p, "list_forwards", 13)) {
3049 		do_list_forwards(ssl, worker);
3050 		return;
3051 	} else if(cmdcmp(p, "list_stubs", 10)) {
3052 		do_list_stubs(ssl, worker);
3053 		return;
3054 	} else if(cmdcmp(p, "list_insecure", 13)) {
3055 		do_insecure_list(ssl, worker);
3056 		return;
3057 	} else if(cmdcmp(p, "list_local_zones", 16)) {
3058 		do_list_local_zones(ssl, worker->daemon->local_zones);
3059 		return;
3060 	} else if(cmdcmp(p, "list_local_data", 15)) {
3061 		do_list_local_data(ssl, worker, worker->daemon->local_zones);
3062 		return;
3063 	} else if(cmdcmp(p, "view_list_local_zones", 21)) {
3064 		do_view_list_local_zones(ssl, worker, skipwhite(p+21));
3065 		return;
3066 	} else if(cmdcmp(p, "view_list_local_data", 20)) {
3067 		do_view_list_local_data(ssl, worker, skipwhite(p+20));
3068 		return;
3069 	} else if(cmdcmp(p, "ratelimit_list", 14)) {
3070 		do_ratelimit_list(ssl, worker, p+14);
3071 		return;
3072 	} else if(cmdcmp(p, "ip_ratelimit_list", 17)) {
3073 		do_ip_ratelimit_list(ssl, worker, p+17);
3074 		return;
3075 	} else if(cmdcmp(p, "list_auth_zones", 15)) {
3076 		do_list_auth_zones(ssl, worker->env.auth_zones);
3077 		return;
3078 	} else if(cmdcmp(p, "auth_zone_reload", 16)) {
3079 		do_auth_zone_reload(ssl, worker, skipwhite(p+16));
3080 		return;
3081 	} else if(cmdcmp(p, "auth_zone_transfer", 18)) {
3082 		do_auth_zone_transfer(ssl, worker, skipwhite(p+18));
3083 		return;
3084 	} else if(cmdcmp(p, "stub_add", 8)) {
3085 		/* must always distribute this cmd */
3086 		if(rc) distribute_cmd(rc, ssl, cmd);
3087 		do_stub_add(ssl, worker, skipwhite(p+8));
3088 		return;
3089 	} else if(cmdcmp(p, "stub_remove", 11)) {
3090 		/* must always distribute this cmd */
3091 		if(rc) distribute_cmd(rc, ssl, cmd);
3092 		do_stub_remove(ssl, worker, skipwhite(p+11));
3093 		return;
3094 	} else if(cmdcmp(p, "forward_add", 11)) {
3095 		/* must always distribute this cmd */
3096 		if(rc) distribute_cmd(rc, ssl, cmd);
3097 		do_forward_add(ssl, worker, skipwhite(p+11));
3098 		return;
3099 	} else if(cmdcmp(p, "forward_remove", 14)) {
3100 		/* must always distribute this cmd */
3101 		if(rc) distribute_cmd(rc, ssl, cmd);
3102 		do_forward_remove(ssl, worker, skipwhite(p+14));
3103 		return;
3104 	} else if(cmdcmp(p, "insecure_add", 12)) {
3105 		/* must always distribute this cmd */
3106 		if(rc) distribute_cmd(rc, ssl, cmd);
3107 		do_insecure_add(ssl, worker, skipwhite(p+12));
3108 		return;
3109 	} else if(cmdcmp(p, "insecure_remove", 15)) {
3110 		/* must always distribute this cmd */
3111 		if(rc) distribute_cmd(rc, ssl, cmd);
3112 		do_insecure_remove(ssl, worker, skipwhite(p+15));
3113 		return;
3114 	} else if(cmdcmp(p, "forward", 7)) {
3115 		/* must always distribute this cmd */
3116 		if(rc) distribute_cmd(rc, ssl, cmd);
3117 		do_forward(ssl, worker, skipwhite(p+7));
3118 		return;
3119 	} else if(cmdcmp(p, "flush_stats", 11)) {
3120 		/* must always distribute this cmd */
3121 		if(rc) distribute_cmd(rc, ssl, cmd);
3122 		do_flush_stats(ssl, worker);
3123 		return;
3124 	} else if(cmdcmp(p, "flush_requestlist", 17)) {
3125 		/* must always distribute this cmd */
3126 		if(rc) distribute_cmd(rc, ssl, cmd);
3127 		do_flush_requestlist(ssl, worker);
3128 		return;
3129 	} else if(cmdcmp(p, "lookup", 6)) {
3130 		do_lookup(ssl, worker, skipwhite(p+6));
3131 		return;
3132 	}
3133 
3134 #ifdef THREADS_DISABLED
3135 	/* other processes must execute the command as well */
3136 	/* commands that should not be distributed, returned above. */
3137 	if(rc) { /* only if this thread is the master (rc) thread */
3138 		/* done before the code below, which may split the string */
3139 		distribute_cmd(rc, ssl, cmd);
3140 	}
3141 #endif
3142 	if(cmdcmp(p, "verbosity", 9)) {
3143 		do_verbosity(ssl, skipwhite(p+9));
3144 	} else if(cmdcmp(p, "local_zone_remove", 17)) {
3145 		do_zone_remove(ssl, worker->daemon->local_zones, skipwhite(p+17));
3146 	} else if(cmdcmp(p, "local_zones_remove", 18)) {
3147 		do_zones_remove(ssl, worker->daemon->local_zones);
3148 	} else if(cmdcmp(p, "local_zone", 10)) {
3149 		do_zone_add(ssl, worker->daemon->local_zones, skipwhite(p+10));
3150 	} else if(cmdcmp(p, "local_zones", 11)) {
3151 		do_zones_add(ssl, worker->daemon->local_zones);
3152 	} else if(cmdcmp(p, "local_data_remove", 17)) {
3153 		do_data_remove(ssl, worker->daemon->local_zones, skipwhite(p+17));
3154 	} else if(cmdcmp(p, "local_datas_remove", 18)) {
3155 		do_datas_remove(ssl, worker->daemon->local_zones);
3156 	} else if(cmdcmp(p, "local_data", 10)) {
3157 		do_data_add(ssl, worker->daemon->local_zones, skipwhite(p+10));
3158 	} else if(cmdcmp(p, "local_datas", 11)) {
3159 		do_datas_add(ssl, worker->daemon->local_zones);
3160 	} else if(cmdcmp(p, "view_local_zone_remove", 22)) {
3161 		do_view_zone_remove(ssl, worker, skipwhite(p+22));
3162 	} else if(cmdcmp(p, "view_local_zone", 15)) {
3163 		do_view_zone_add(ssl, worker, skipwhite(p+15));
3164 	} else if(cmdcmp(p, "view_local_data_remove", 22)) {
3165 		do_view_data_remove(ssl, worker, skipwhite(p+22));
3166 	} else if(cmdcmp(p, "view_local_datas_remove", 23)){
3167 		do_view_datas_remove(ssl, worker, skipwhite(p+23));
3168 	} else if(cmdcmp(p, "view_local_data", 15)) {
3169 		do_view_data_add(ssl, worker, skipwhite(p+15));
3170 	} else if(cmdcmp(p, "view_local_datas", 16)) {
3171 		do_view_datas_add(ssl, worker, skipwhite(p+16));
3172 	} else if(cmdcmp(p, "flush_zone", 10)) {
3173 		do_flush_zone(ssl, worker, skipwhite(p+10));
3174 	} else if(cmdcmp(p, "flush_type", 10)) {
3175 		do_flush_type(ssl, worker, skipwhite(p+10));
3176 	} else if(cmdcmp(p, "flush_infra", 11)) {
3177 		do_flush_infra(ssl, worker, skipwhite(p+11));
3178 	} else if(cmdcmp(p, "flush", 5)) {
3179 		do_flush_name(ssl, worker, skipwhite(p+5));
3180 	} else if(cmdcmp(p, "dump_requestlist", 16)) {
3181 		do_dump_requestlist(ssl, worker);
3182 	} else if(cmdcmp(p, "dump_infra", 10)) {
3183 		do_dump_infra(ssl, worker);
3184 	} else if(cmdcmp(p, "log_reopen", 10)) {
3185 		do_log_reopen(ssl, worker);
3186 	} else if(cmdcmp(p, "set_option", 10)) {
3187 		do_set_option(ssl, worker, skipwhite(p+10));
3188 	} else if(cmdcmp(p, "get_option", 10)) {
3189 		do_get_option(ssl, worker, skipwhite(p+10));
3190 	} else if(cmdcmp(p, "flush_bogus", 11)) {
3191 		do_flush_bogus(ssl, worker);
3192 	} else if(cmdcmp(p, "flush_negative", 14)) {
3193 		do_flush_negative(ssl, worker);
3194     } else if(cmdcmp(p, "rpz_enable", 10)) {
3195         do_rpz_enable(ssl, worker, skipwhite(p+10));
3196     } else if(cmdcmp(p, "rpz_disable", 11)) {
3197         do_rpz_disable(ssl, worker, skipwhite(p+11));
3198 	} else {
3199 		(void)ssl_printf(ssl, "error unknown command '%s'\n", p);
3200 	}
3201 }
3202 
3203 void
3204 daemon_remote_exec(struct worker* worker)
3205 {
3206 	/* read the cmd string */
3207 	uint8_t* msg = NULL;
3208 	uint32_t len = 0;
3209 	if(!tube_read_msg(worker->cmd, &msg, &len, 0)) {
3210 		log_err("daemon_remote_exec: tube_read_msg failed");
3211 		return;
3212 	}
3213 	verbose(VERB_ALGO, "remote exec distributed: %s", (char*)msg);
3214 	execute_cmd(NULL, NULL, (char*)msg, worker);
3215 	free(msg);
3216 }
3217 
3218 /** handle remote control request */
3219 static void
3220 handle_req(struct daemon_remote* rc, struct rc_state* s, RES* res)
3221 {
3222 	int r;
3223 	char pre[10];
3224 	char magic[7];
3225 	char buf[1024];
3226 #ifdef USE_WINSOCK
3227 	/* makes it possible to set the socket blocking again. */
3228 	/* basically removes it from winsock_event ... */
3229 	WSAEventSelect(s->c->fd, NULL, 0);
3230 #endif
3231 	fd_set_block(s->c->fd);
3232 
3233 	/* try to read magic UBCT[version]_space_ string */
3234 	if(res->ssl) {
3235 		ERR_clear_error();
3236 		if((r=SSL_read(res->ssl, magic, (int)sizeof(magic)-1)) <= 0) {
3237 			if(SSL_get_error(res->ssl, r) == SSL_ERROR_ZERO_RETURN)
3238 				return;
3239 			log_crypto_err("could not SSL_read");
3240 			return;
3241 		}
3242 	} else {
3243 		while(1) {
3244 			ssize_t rr = recv(res->fd, magic, sizeof(magic)-1, 0);
3245 			if(rr <= 0) {
3246 				if(rr == 0) return;
3247 				if(errno == EINTR || errno == EAGAIN)
3248 					continue;
3249 				log_err("could not recv: %s", sock_strerror(errno));
3250 				return;
3251 			}
3252 			r = (int)rr;
3253 			break;
3254 		}
3255 	}
3256 	magic[6] = 0;
3257 	if( r != 6 || strncmp(magic, "UBCT", 4) != 0) {
3258 		verbose(VERB_QUERY, "control connection has bad magic string");
3259 		/* probably wrong tool connected, ignore it completely */
3260 		return;
3261 	}
3262 
3263 	/* read the command line */
3264 	if(!ssl_read_line(res, buf, sizeof(buf))) {
3265 		return;
3266 	}
3267 	snprintf(pre, sizeof(pre), "UBCT%d ", UNBOUND_CONTROL_VERSION);
3268 	if(strcmp(magic, pre) != 0) {
3269 		verbose(VERB_QUERY, "control connection had bad "
3270 			"version %s, cmd: %s", magic, buf);
3271 		ssl_printf(res, "error version mismatch\n");
3272 		return;
3273 	}
3274 	verbose(VERB_DETAIL, "control cmd: %s", buf);
3275 
3276 	/* figure out what to do */
3277 	execute_cmd(rc, res, buf, rc->worker);
3278 }
3279 
3280 /** handle SSL_do_handshake changes to the file descriptor to wait for later */
3281 static int
3282 remote_handshake_later(struct daemon_remote* rc, struct rc_state* s,
3283 	struct comm_point* c, int r, int r2)
3284 {
3285 	if(r2 == SSL_ERROR_WANT_READ) {
3286 		if(s->shake_state == rc_hs_read) {
3287 			/* try again later */
3288 			return 0;
3289 		}
3290 		s->shake_state = rc_hs_read;
3291 		comm_point_listen_for_rw(c, 1, 0);
3292 		return 0;
3293 	} else if(r2 == SSL_ERROR_WANT_WRITE) {
3294 		if(s->shake_state == rc_hs_write) {
3295 			/* try again later */
3296 			return 0;
3297 		}
3298 		s->shake_state = rc_hs_write;
3299 		comm_point_listen_for_rw(c, 0, 1);
3300 		return 0;
3301 	} else {
3302 		if(r == 0)
3303 			log_err("remote control connection closed prematurely");
3304 		log_addr(VERB_OPS, "failed connection from",
3305 			&s->c->repinfo.addr, s->c->repinfo.addrlen);
3306 		log_crypto_err("remote control failed ssl");
3307 		clean_point(rc, s);
3308 	}
3309 	return 0;
3310 }
3311 
3312 int remote_control_callback(struct comm_point* c, void* arg, int err,
3313 	struct comm_reply* ATTR_UNUSED(rep))
3314 {
3315 	RES res;
3316 	struct rc_state* s = (struct rc_state*)arg;
3317 	struct daemon_remote* rc = s->rc;
3318 	int r;
3319 	if(err != NETEVENT_NOERROR) {
3320 		if(err==NETEVENT_TIMEOUT)
3321 			log_err("remote control timed out");
3322 		clean_point(rc, s);
3323 		return 0;
3324 	}
3325 	if(s->ssl) {
3326 		/* (continue to) setup the SSL connection */
3327 		ERR_clear_error();
3328 		r = SSL_do_handshake(s->ssl);
3329 		if(r != 1) {
3330 			int r2 = SSL_get_error(s->ssl, r);
3331 			return remote_handshake_later(rc, s, c, r, r2);
3332 		}
3333 		s->shake_state = rc_none;
3334 	}
3335 
3336 	/* once handshake has completed, check authentication */
3337 	if (!rc->use_cert) {
3338 		verbose(VERB_ALGO, "unauthenticated remote control connection");
3339 	} else if(SSL_get_verify_result(s->ssl) == X509_V_OK) {
3340 #ifdef HAVE_SSL_GET1_PEER_CERTIFICATE
3341 		X509* x = SSL_get1_peer_certificate(s->ssl);
3342 #else
3343 		X509* x = SSL_get_peer_certificate(s->ssl);
3344 #endif
3345 		if(!x) {
3346 			verbose(VERB_DETAIL, "remote control connection "
3347 				"provided no client certificate");
3348 			clean_point(rc, s);
3349 			return 0;
3350 		}
3351 		verbose(VERB_ALGO, "remote control connection authenticated");
3352 		X509_free(x);
3353 	} else {
3354 		verbose(VERB_DETAIL, "remote control connection failed to "
3355 			"authenticate with client certificate");
3356 		clean_point(rc, s);
3357 		return 0;
3358 	}
3359 
3360 	/* if OK start to actually handle the request */
3361 	res.ssl = s->ssl;
3362 	res.fd = c->fd;
3363 	handle_req(rc, s, &res);
3364 
3365 	verbose(VERB_ALGO, "remote control operation completed");
3366 	clean_point(rc, s);
3367 	return 0;
3368 }
3369