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