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