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