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