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