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