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