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