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