remote.c revision 238106
1243791Sdim/*
2243791Sdim * daemon/remote.c - remote control for the unbound daemon.
3243791Sdim *
4243791Sdim * Copyright (c) 2008, NLnet Labs. All rights reserved.
5243791Sdim *
6243791Sdim * This software is open source.
7243791Sdim *
8243791Sdim * Redistribution and use in source and binary forms, with or without
9243791Sdim * modification, are permitted provided that the following conditions
10243791Sdim * are met:
11243791Sdim *
12243791Sdim * Redistributions of source code must retain the above copyright notice,
13243791Sdim * this list of conditions and the following disclaimer.
14243791Sdim *
15243791Sdim * Redistributions in binary form must reproduce the above copyright notice,
16243791Sdim * this list of conditions and the following disclaimer in the documentation
17243791Sdim * and/or other materials provided with the distribution.
18243791Sdim *
19249423Sdim * Neither the name of the NLNET LABS nor the names of its contributors may
20243791Sdim * be used to endorse or promote products derived from this software without
21243791Sdim * specific prior written permission.
22243791Sdim *
23243791Sdim * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24243791Sdim * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
25243791Sdim * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26243791Sdim * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
27243791Sdim * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28249423Sdim * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29243791Sdim * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30243791Sdim * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31243791Sdim * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32243791Sdim * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33243791Sdim * POSSIBILITY OF SUCH DAMAGE.
34243791Sdim */
35243791Sdim
36243791Sdim/**
37243791Sdim * \file
38243791Sdim *
39243791Sdim * This file contains the remote control functionality for the daemon.
40243791Sdim * The remote control can be performed using either the commandline
41243791Sdim * unbound-control tool, or a SSLv3/TLS capable web browser.
42243791Sdim * The channel is secured using SSLv3 or TLSv1, and certificates.
43243791Sdim * Both the server and the client(control tool) have their own keys.
44243791Sdim */
45243791Sdim#include "config.h"
46243791Sdim#ifdef HAVE_OPENSSL_ERR_H
47243791Sdim#include <openssl/err.h>
48243791Sdim#endif
49243791Sdim#include <ctype.h>
50243791Sdim#include <ldns/ldns.h>
51243791Sdim#include "daemon/remote.h"
52243791Sdim#include "daemon/worker.h"
53249423Sdim#include "daemon/daemon.h"
54243791Sdim#include "daemon/stats.h"
55243791Sdim#include "daemon/cachedump.h"
56243791Sdim#include "util/log.h"
57243791Sdim#include "util/config_file.h"
58243791Sdim#include "util/net_help.h"
59243791Sdim#include "util/module.h"
60243791Sdim#include "services/listen_dnsport.h"
61243791Sdim#include "services/cache/rrset.h"
62243791Sdim#include "services/cache/infra.h"
63243791Sdim#include "services/mesh.h"
64243791Sdim#include "services/localzone.h"
65243791Sdim#include "util/storage/slabhash.h"
66243791Sdim#include "util/fptr_wlist.h"
67243791Sdim#include "util/data/dname.h"
68243791Sdim#include "validator/validator.h"
69243791Sdim#include "validator/val_kcache.h"
70243791Sdim#include "validator/val_kentry.h"
71243791Sdim#include "validator/val_anchor.h"
72243791Sdim#include "iterator/iterator.h"
73243791Sdim#include "iterator/iter_fwd.h"
74243791Sdim#include "iterator/iter_hints.h"
75243791Sdim#include "iterator/iter_delegpt.h"
76243791Sdim#include "services/outbound_list.h"
77243791Sdim#include "services/outside_network.h"
78243791Sdim
79243791Sdim#ifdef HAVE_SYS_TYPES_H
80243791Sdim#  include <sys/types.h>
81243791Sdim#endif
82249423Sdim#ifdef HAVE_NETDB_H
83249423Sdim#include <netdb.h>
84249423Sdim#endif
85249423Sdim
86249423Sdim/* just for portability */
87243791Sdim#ifdef SQ
88243791Sdim#undef SQ
89243791Sdim#endif
90243791Sdim
91243791Sdim/** what to put on statistics lines between var and value, ": " or "=" */
92243791Sdim#define SQ "="
93243791Sdim/** if true, inhibits a lot of =0 lines from the stats output */
94243791Sdimstatic const int inhibit_zero = 1;
95243791Sdim
96243791Sdim/** subtract timers and the values do not overflow or become negative */
97243791Sdimstatic void
98243791Sdimtimeval_subtract(struct timeval* d, const struct timeval* end,
99243791Sdim	const struct timeval* start)
100243791Sdim{
101243791Sdim#ifndef S_SPLINT_S
102243791Sdim	time_t end_usec = end->tv_usec;
103243791Sdim	d->tv_sec = end->tv_sec - start->tv_sec;
104243791Sdim	if(end_usec < start->tv_usec) {
105243791Sdim		end_usec += 1000000;
106243791Sdim		d->tv_sec--;
107243791Sdim	}
108243791Sdim	d->tv_usec = end_usec - start->tv_usec;
109243791Sdim#endif
110243791Sdim}
111243791Sdim
112243791Sdim/** divide sum of timers to get average */
113243791Sdimstatic void
114243791Sdimtimeval_divide(struct timeval* avg, const struct timeval* sum, size_t d)
115243791Sdim{
116243791Sdim#ifndef S_SPLINT_S
117243791Sdim	size_t leftover;
118243791Sdim	if(d == 0) {
119243791Sdim		avg->tv_sec = 0;
120243791Sdim		avg->tv_usec = 0;
121243791Sdim		return;
122243791Sdim	}
123243791Sdim	avg->tv_sec = sum->tv_sec / d;
124243791Sdim	avg->tv_usec = sum->tv_usec / d;
125243791Sdim	/* handle fraction from seconds divide */
126243791Sdim	leftover = sum->tv_sec - avg->tv_sec*d;
127243791Sdim	avg->tv_usec += (leftover*1000000)/d;
128243791Sdim#endif
129243791Sdim}
130243791Sdim
131243791Sdimstruct daemon_remote*
132243791Sdimdaemon_remote_create(struct config_file* cfg)
133243791Sdim{
134243791Sdim	char* s_cert;
135243791Sdim	char* s_key;
136243791Sdim	struct daemon_remote* rc = (struct daemon_remote*)calloc(1,
137243791Sdim		sizeof(*rc));
138243791Sdim	if(!rc) {
139243791Sdim		log_err("out of memory in daemon_remote_create");
140243791Sdim		return NULL;
141243791Sdim	}
142243791Sdim	rc->max_active = 10;
143243791Sdim
144243791Sdim	if(!cfg->remote_control_enable) {
145243791Sdim		rc->ctx = NULL;
146243791Sdim		return rc;
147243791Sdim	}
148243791Sdim	rc->ctx = SSL_CTX_new(SSLv23_server_method());
149243791Sdim	if(!rc->ctx) {
150243791Sdim		log_crypto_err("could not SSL_CTX_new");
151243791Sdim		free(rc);
152243791Sdim		return NULL;
153243791Sdim	}
154243791Sdim	/* no SSLv2 because has defects */
155243791Sdim	if(!(SSL_CTX_set_options(rc->ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)){
156243791Sdim		log_crypto_err("could not set SSL_OP_NO_SSLv2");
157243791Sdim		daemon_remote_delete(rc);
158243791Sdim		return NULL;
159243791Sdim	}
160243791Sdim	s_cert = fname_after_chroot(cfg->server_cert_file, cfg, 1);
161243791Sdim	s_key = fname_after_chroot(cfg->server_key_file, cfg, 1);
162243791Sdim	if(!s_cert || !s_key) {
163243791Sdim		log_err("out of memory in remote control fname");
164243791Sdim		goto setup_error;
165243791Sdim	}
166243791Sdim	verbose(VERB_ALGO, "setup SSL certificates");
167243791Sdim	if (!SSL_CTX_use_certificate_file(rc->ctx,s_cert,SSL_FILETYPE_PEM)) {
168243791Sdim		log_err("Error for server-cert-file: %s", s_cert);
169243791Sdim		log_crypto_err("Error in SSL_CTX use_certificate_file");
170243791Sdim		goto setup_error;
171243791Sdim	}
172243791Sdim	if(!SSL_CTX_use_PrivateKey_file(rc->ctx,s_key,SSL_FILETYPE_PEM)) {
173243791Sdim		log_err("Error for server-key-file: %s", s_key);
174243791Sdim		log_crypto_err("Error in SSL_CTX use_PrivateKey_file");
175243791Sdim		goto setup_error;
176243791Sdim	}
177243791Sdim	if(!SSL_CTX_check_private_key(rc->ctx)) {
178243791Sdim		log_err("Error for server-key-file: %s", s_key);
179243791Sdim		log_crypto_err("Error in SSL_CTX check_private_key");
180243791Sdim		goto setup_error;
181243791Sdim	}
182243791Sdim	if(!SSL_CTX_load_verify_locations(rc->ctx, s_cert, NULL)) {
183243791Sdim		log_crypto_err("Error setting up SSL_CTX verify locations");
184243791Sdim	setup_error:
185243791Sdim		free(s_cert);
186243791Sdim		free(s_key);
187243791Sdim		daemon_remote_delete(rc);
188243791Sdim		return NULL;
189243791Sdim	}
190243791Sdim	SSL_CTX_set_client_CA_list(rc->ctx, SSL_load_client_CA_file(s_cert));
191243791Sdim	SSL_CTX_set_verify(rc->ctx, SSL_VERIFY_PEER, NULL);
192243791Sdim	free(s_cert);
193243791Sdim	free(s_key);
194243791Sdim
195243791Sdim	return rc;
196243791Sdim}
197243791Sdim
198243791Sdimvoid daemon_remote_clear(struct daemon_remote* rc)
199243791Sdim{
200243791Sdim	struct rc_state* p, *np;
201243791Sdim	if(!rc) return;
202243791Sdim	/* but do not close the ports */
203243791Sdim	listen_list_delete(rc->accept_list);
204243791Sdim	rc->accept_list = NULL;
205243791Sdim	/* do close these sockets */
206243791Sdim	p = rc->busy_list;
207243791Sdim	while(p) {
208243791Sdim		np = p->next;
209243791Sdim		if(p->ssl)
210243791Sdim			SSL_free(p->ssl);
211243791Sdim		comm_point_delete(p->c);
212243791Sdim		free(p);
213243791Sdim		p = np;
214243791Sdim	}
215243791Sdim	rc->busy_list = NULL;
216243791Sdim	rc->active = 0;
217243791Sdim	rc->worker = NULL;
218243791Sdim}
219243791Sdim
220243791Sdimvoid daemon_remote_delete(struct daemon_remote* rc)
221243791Sdim{
222243791Sdim	if(!rc) return;
223243791Sdim	daemon_remote_clear(rc);
224243791Sdim	if(rc->ctx) {
225243791Sdim		SSL_CTX_free(rc->ctx);
226243791Sdim	}
227243791Sdim	free(rc);
228243791Sdim}
229243791Sdim
230249423Sdim/**
231243791Sdim * Add and open a new control port
232243791Sdim * @param ip: ip str
233243791Sdim * @param nr: port nr
234243791Sdim * @param list: list head
235243791Sdim * @param noproto_is_err: if lack of protocol support is an error.
236243791Sdim * @return false on failure.
237243791Sdim */
238243791Sdimstatic int
239243791Sdimadd_open(const char* ip, int nr, struct listen_port** list, int noproto_is_err)
240243791Sdim{
241243791Sdim	struct addrinfo hints;
242243791Sdim	struct addrinfo* res;
243243791Sdim	struct listen_port* n;
244243791Sdim	int noproto;
245243791Sdim	int fd, r;
246243791Sdim	char port[15];
247243791Sdim	snprintf(port, sizeof(port), "%d", nr);
248243791Sdim	port[sizeof(port)-1]=0;
249243791Sdim	memset(&hints, 0, sizeof(hints));
250243791Sdim	hints.ai_socktype = SOCK_STREAM;
251243791Sdim	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
252243791Sdim	if((r = getaddrinfo(ip, port, &hints, &res)) != 0 || !res) {
253243791Sdim#ifdef USE_WINSOCK
254249423Sdim		if(!noproto_is_err && r == EAI_NONAME) {
255243791Sdim			/* tried to lookup the address as name */
256243791Sdim			return 1; /* return success, but do nothing */
257249423Sdim		}
258249423Sdim#endif /* USE_WINSOCK */
259249423Sdim                log_err("control interface %s:%s getaddrinfo: %s %s",
260249423Sdim			ip?ip:"default", port, gai_strerror(r),
261249423Sdim#ifdef EAI_SYSTEM
262249423Sdim			r==EAI_SYSTEM?(char*)strerror(errno):""
263249423Sdim#else
264249423Sdim			""
265243791Sdim#endif
266243791Sdim			);
267243791Sdim		return 0;
268249423Sdim	}
269249423Sdim
270249423Sdim	/* open fd */
271249423Sdim	fd = create_tcp_accept_sock(res, 1, &noproto);
272249423Sdim	freeaddrinfo(res);
273243791Sdim	if(fd == -1 && noproto) {
274243791Sdim		if(!noproto_is_err)
275249423Sdim			return 1; /* return success, but do nothing */
276243791Sdim		log_err("cannot open control interface %s %d : "
277243791Sdim			"protocol not supported", ip, nr);
278243791Sdim		return 0;
279243791Sdim	}
280243791Sdim	if(fd == -1) {
281243791Sdim		log_err("cannot open control interface %s %d", ip, nr);
282243791Sdim		return 0;
283243791Sdim	}
284243791Sdim
285243791Sdim	/* alloc */
286243791Sdim	n = (struct listen_port*)calloc(1, sizeof(*n));
287243791Sdim	if(!n) {
288243791Sdim#ifndef USE_WINSOCK
289243791Sdim		close(fd);
290#else
291		closesocket(fd);
292#endif
293		log_err("out of memory");
294		return 0;
295	}
296	n->next = *list;
297	*list = n;
298	n->fd = fd;
299	return 1;
300}
301
302struct listen_port* daemon_remote_open_ports(struct config_file* cfg)
303{
304	struct listen_port* l = NULL;
305	log_assert(cfg->remote_control_enable && cfg->control_port);
306	if(cfg->control_ifs) {
307		struct config_strlist* p;
308		for(p = cfg->control_ifs; p; p = p->next) {
309			if(!add_open(p->str, cfg->control_port, &l, 1)) {
310				listening_ports_free(l);
311				return NULL;
312			}
313		}
314	} else {
315		/* defaults */
316		if(cfg->do_ip6 &&
317			!add_open("::1", cfg->control_port, &l, 0)) {
318			listening_ports_free(l);
319			return NULL;
320		}
321		if(cfg->do_ip4 &&
322			!add_open("127.0.0.1", cfg->control_port, &l, 1)) {
323			listening_ports_free(l);
324			return NULL;
325		}
326	}
327	return l;
328}
329
330/** open accept commpoint */
331static int
332accept_open(struct daemon_remote* rc, int fd)
333{
334	struct listen_list* n = (struct listen_list*)malloc(sizeof(*n));
335	if(!n) {
336		log_err("out of memory");
337		return 0;
338	}
339	n->next = rc->accept_list;
340	rc->accept_list = n;
341	/* open commpt */
342	n->com = comm_point_create_raw(rc->worker->base, fd, 0,
343		&remote_accept_callback, rc);
344	if(!n->com)
345		return 0;
346	/* keep this port open, its fd is kept in the rc portlist */
347	n->com->do_not_close = 1;
348	return 1;
349}
350
351int daemon_remote_open_accept(struct daemon_remote* rc,
352	struct listen_port* ports, struct worker* worker)
353{
354	struct listen_port* p;
355	rc->worker = worker;
356	for(p = ports; p; p = p->next) {
357		if(!accept_open(rc, p->fd)) {
358			log_err("could not create accept comm point");
359			return 0;
360		}
361	}
362	return 1;
363}
364
365void daemon_remote_stop_accept(struct daemon_remote* rc)
366{
367	struct listen_list* p;
368	for(p=rc->accept_list; p; p=p->next) {
369		comm_point_stop_listening(p->com);
370	}
371}
372
373void daemon_remote_start_accept(struct daemon_remote* rc)
374{
375	struct listen_list* p;
376	for(p=rc->accept_list; p; p=p->next) {
377		comm_point_start_listening(p->com, -1, -1);
378	}
379}
380
381int remote_accept_callback(struct comm_point* c, void* arg, int err,
382	struct comm_reply* ATTR_UNUSED(rep))
383{
384	struct daemon_remote* rc = (struct daemon_remote*)arg;
385	struct sockaddr_storage addr;
386	socklen_t addrlen;
387	int newfd;
388	struct rc_state* n;
389	if(err != NETEVENT_NOERROR) {
390		log_err("error %d on remote_accept_callback", err);
391		return 0;
392	}
393	/* perform the accept */
394	newfd = comm_point_perform_accept(c, &addr, &addrlen);
395	if(newfd == -1)
396		return 0;
397	/* create new commpoint unless we are servicing already */
398	if(rc->active >= rc->max_active) {
399		log_warn("drop incoming remote control: too many connections");
400	close_exit:
401#ifndef USE_WINSOCK
402		close(newfd);
403#else
404		closesocket(newfd);
405#endif
406		return 0;
407	}
408
409	/* setup commpoint to service the remote control command */
410	n = (struct rc_state*)calloc(1, sizeof(*n));
411	if(!n) {
412		log_err("out of memory");
413		goto close_exit;
414	}
415	/* start in reading state */
416	n->c = comm_point_create_raw(rc->worker->base, newfd, 0,
417		&remote_control_callback, n);
418	if(!n->c) {
419		log_err("out of memory");
420		free(n);
421		goto close_exit;
422	}
423	log_addr(VERB_QUERY, "new control connection from", &addr, addrlen);
424	n->c->do_not_close = 0;
425	comm_point_stop_listening(n->c);
426	comm_point_start_listening(n->c, -1, REMOTE_CONTROL_TCP_TIMEOUT);
427	memcpy(&n->c->repinfo.addr, &addr, addrlen);
428	n->c->repinfo.addrlen = addrlen;
429	n->shake_state = rc_hs_read;
430	n->ssl = SSL_new(rc->ctx);
431	if(!n->ssl) {
432		log_crypto_err("could not SSL_new");
433		comm_point_delete(n->c);
434		free(n);
435		goto close_exit;
436	}
437	SSL_set_accept_state(n->ssl);
438        (void)SSL_set_mode(n->ssl, SSL_MODE_AUTO_RETRY);
439	if(!SSL_set_fd(n->ssl, newfd)) {
440		log_crypto_err("could not SSL_set_fd");
441		SSL_free(n->ssl);
442		comm_point_delete(n->c);
443		free(n);
444		goto close_exit;
445	}
446
447	n->rc = rc;
448	n->next = rc->busy_list;
449	rc->busy_list = n;
450	rc->active ++;
451
452	/* perform the first nonblocking read already, for windows,
453	 * so it can return wouldblock. could be faster too. */
454	(void)remote_control_callback(n->c, n, NETEVENT_NOERROR, NULL);
455	return 0;
456}
457
458/** delete from list */
459static void
460state_list_remove_elem(struct rc_state** list, struct comm_point* c)
461{
462	while(*list) {
463		if( (*list)->c == c) {
464			*list = (*list)->next;
465			return;
466		}
467		list = &(*list)->next;
468	}
469}
470
471/** decrease active count and remove commpoint from busy list */
472static void
473clean_point(struct daemon_remote* rc, struct rc_state* s)
474{
475	state_list_remove_elem(&rc->busy_list, s->c);
476	rc->active --;
477	if(s->ssl) {
478		SSL_shutdown(s->ssl);
479		SSL_free(s->ssl);
480	}
481	comm_point_delete(s->c);
482	free(s);
483}
484
485int
486ssl_print_text(SSL* ssl, const char* text)
487{
488	int r;
489	if(!ssl)
490		return 0;
491	ERR_clear_error();
492	if((r=SSL_write(ssl, text, (int)strlen(text))) <= 0) {
493		if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
494			verbose(VERB_QUERY, "warning, in SSL_write, peer "
495				"closed connection");
496			return 0;
497		}
498		log_crypto_err("could not SSL_write");
499		return 0;
500	}
501	return 1;
502}
503
504/** print text over the ssl connection */
505static int
506ssl_print_vmsg(SSL* ssl, const char* format, va_list args)
507{
508	char msg[1024];
509	vsnprintf(msg, sizeof(msg), format, args);
510	return ssl_print_text(ssl, msg);
511}
512
513/** printf style printing to the ssl connection */
514int ssl_printf(SSL* ssl, const char* format, ...)
515{
516	va_list args;
517	int ret;
518	va_start(args, format);
519	ret = ssl_print_vmsg(ssl, format, args);
520	va_end(args);
521	return ret;
522}
523
524int
525ssl_read_line(SSL* ssl, char* buf, size_t max)
526{
527	int r;
528	size_t len = 0;
529	if(!ssl)
530		return 0;
531	while(len < max) {
532		ERR_clear_error();
533		if((r=SSL_read(ssl, buf+len, 1)) <= 0) {
534			if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
535				buf[len] = 0;
536				return 1;
537			}
538			log_crypto_err("could not SSL_read");
539			return 0;
540		}
541		if(buf[len] == '\n') {
542			/* return string without \n */
543			buf[len] = 0;
544			return 1;
545		}
546		len++;
547	}
548	buf[max-1] = 0;
549	log_err("control line too long (%d): %s", (int)max, buf);
550	return 0;
551}
552
553/** skip whitespace, return new pointer into string */
554static char*
555skipwhite(char* str)
556{
557	/* EOS \0 is not a space */
558	while( isspace(*str) )
559		str++;
560	return str;
561}
562
563/** send the OK to the control client */
564static void send_ok(SSL* ssl)
565{
566	(void)ssl_printf(ssl, "ok\n");
567}
568
569/** do the stop command */
570static void
571do_stop(SSL* ssl, struct daemon_remote* rc)
572{
573	rc->worker->need_to_exit = 1;
574	comm_base_exit(rc->worker->base);
575	send_ok(ssl);
576}
577
578/** do the reload command */
579static void
580do_reload(SSL* ssl, struct daemon_remote* rc)
581{
582	rc->worker->need_to_exit = 0;
583	comm_base_exit(rc->worker->base);
584	send_ok(ssl);
585}
586
587/** do the verbosity command */
588static void
589do_verbosity(SSL* ssl, char* str)
590{
591	int val = atoi(str);
592	if(val == 0 && strcmp(str, "0") != 0) {
593		ssl_printf(ssl, "error in verbosity number syntax: %s\n", str);
594		return;
595	}
596	verbosity = val;
597	send_ok(ssl);
598}
599
600/** print stats from statinfo */
601static int
602print_stats(SSL* ssl, const char* nm, struct stats_info* s)
603{
604	struct timeval avg;
605	if(!ssl_printf(ssl, "%s.num.queries"SQ"%u\n", nm,
606		(unsigned)s->svr.num_queries)) return 0;
607	if(!ssl_printf(ssl, "%s.num.cachehits"SQ"%u\n", nm,
608		(unsigned)(s->svr.num_queries
609			- s->svr.num_queries_missed_cache))) return 0;
610	if(!ssl_printf(ssl, "%s.num.cachemiss"SQ"%u\n", nm,
611		(unsigned)s->svr.num_queries_missed_cache)) return 0;
612	if(!ssl_printf(ssl, "%s.num.prefetch"SQ"%u\n", nm,
613		(unsigned)s->svr.num_queries_prefetch)) return 0;
614	if(!ssl_printf(ssl, "%s.num.recursivereplies"SQ"%u\n", nm,
615		(unsigned)s->mesh_replies_sent)) return 0;
616	if(!ssl_printf(ssl, "%s.requestlist.avg"SQ"%g\n", nm,
617		(s->svr.num_queries_missed_cache+s->svr.num_queries_prefetch)?
618			(double)s->svr.sum_query_list_size/
619			(s->svr.num_queries_missed_cache+
620			s->svr.num_queries_prefetch) : 0.0)) return 0;
621	if(!ssl_printf(ssl, "%s.requestlist.max"SQ"%u\n", nm,
622		(unsigned)s->svr.max_query_list_size)) return 0;
623	if(!ssl_printf(ssl, "%s.requestlist.overwritten"SQ"%u\n", nm,
624		(unsigned)s->mesh_jostled)) return 0;
625	if(!ssl_printf(ssl, "%s.requestlist.exceeded"SQ"%u\n", nm,
626		(unsigned)s->mesh_dropped)) return 0;
627	if(!ssl_printf(ssl, "%s.requestlist.current.all"SQ"%u\n", nm,
628		(unsigned)s->mesh_num_states)) return 0;
629	if(!ssl_printf(ssl, "%s.requestlist.current.user"SQ"%u\n", nm,
630		(unsigned)s->mesh_num_reply_states)) return 0;
631	timeval_divide(&avg, &s->mesh_replies_sum_wait, s->mesh_replies_sent);
632	if(!ssl_printf(ssl, "%s.recursion.time.avg"SQ"%d.%6.6d\n", nm,
633		(int)avg.tv_sec, (int)avg.tv_usec)) return 0;
634	if(!ssl_printf(ssl, "%s.recursion.time.median"SQ"%g\n", nm,
635		s->mesh_time_median)) return 0;
636	return 1;
637}
638
639/** print stats for one thread */
640static int
641print_thread_stats(SSL* ssl, int i, struct stats_info* s)
642{
643	char nm[16];
644	snprintf(nm, sizeof(nm), "thread%d", i);
645	nm[sizeof(nm)-1]=0;
646	return print_stats(ssl, nm, s);
647}
648
649/** print long number */
650static int
651print_longnum(SSL* ssl, char* desc, size_t x)
652{
653	if(x > 1024*1024*1024) {
654		/* more than a Gb */
655		size_t front = x / (size_t)1000000;
656		size_t back = x % (size_t)1000000;
657		return ssl_printf(ssl, "%s%u%6.6u\n", desc,
658			(unsigned)front, (unsigned)back);
659	} else {
660		return ssl_printf(ssl, "%s%u\n", desc, (unsigned)x);
661	}
662}
663
664/** print mem stats */
665static int
666print_mem(SSL* ssl, struct worker* worker, struct daemon* daemon)
667{
668	int m;
669	size_t msg, rrset, val, iter;
670#ifdef HAVE_SBRK
671	extern void* unbound_start_brk;
672	void* cur = sbrk(0);
673	if(!print_longnum(ssl, "mem.total.sbrk"SQ,
674		(size_t)((char*)cur - (char*)unbound_start_brk))) return 0;
675#endif /* HAVE_SBRK */
676	msg = slabhash_get_mem(daemon->env->msg_cache);
677	rrset = slabhash_get_mem(&daemon->env->rrset_cache->table);
678	val=0;
679	iter=0;
680	m = modstack_find(&worker->env.mesh->mods, "validator");
681	if(m != -1) {
682		fptr_ok(fptr_whitelist_mod_get_mem(worker->env.mesh->
683			mods.mod[m]->get_mem));
684		val = (*worker->env.mesh->mods.mod[m]->get_mem)
685			(&worker->env, m);
686	}
687	m = modstack_find(&worker->env.mesh->mods, "iterator");
688	if(m != -1) {
689		fptr_ok(fptr_whitelist_mod_get_mem(worker->env.mesh->
690			mods.mod[m]->get_mem));
691		iter = (*worker->env.mesh->mods.mod[m]->get_mem)
692			(&worker->env, m);
693	}
694
695	if(!print_longnum(ssl, "mem.cache.rrset"SQ, rrset))
696		return 0;
697	if(!print_longnum(ssl, "mem.cache.message"SQ, msg))
698		return 0;
699	if(!print_longnum(ssl, "mem.mod.iterator"SQ, iter))
700		return 0;
701	if(!print_longnum(ssl, "mem.mod.validator"SQ, val))
702		return 0;
703	return 1;
704}
705
706/** print uptime stats */
707static int
708print_uptime(SSL* ssl, struct worker* worker, int reset)
709{
710	struct timeval now = *worker->env.now_tv;
711	struct timeval up, dt;
712	timeval_subtract(&up, &now, &worker->daemon->time_boot);
713	timeval_subtract(&dt, &now, &worker->daemon->time_last_stat);
714	if(reset)
715		worker->daemon->time_last_stat = now;
716	if(!ssl_printf(ssl, "time.now"SQ"%d.%6.6d\n",
717		(unsigned)now.tv_sec, (unsigned)now.tv_usec)) return 0;
718	if(!ssl_printf(ssl, "time.up"SQ"%d.%6.6d\n",
719		(unsigned)up.tv_sec, (unsigned)up.tv_usec)) return 0;
720	if(!ssl_printf(ssl, "time.elapsed"SQ"%d.%6.6d\n",
721		(unsigned)dt.tv_sec, (unsigned)dt.tv_usec)) return 0;
722	return 1;
723}
724
725/** print extended histogram */
726static int
727print_hist(SSL* ssl, struct stats_info* s)
728{
729	struct timehist* hist;
730	size_t i;
731	hist = timehist_setup();
732	if(!hist) {
733		log_err("out of memory");
734		return 0;
735	}
736	timehist_import(hist, s->svr.hist, NUM_BUCKETS_HIST);
737	for(i=0; i<hist->num; i++) {
738		if(!ssl_printf(ssl,
739			"histogram.%6.6d.%6.6d.to.%6.6d.%6.6d=%u\n",
740			(int)hist->buckets[i].lower.tv_sec,
741			(int)hist->buckets[i].lower.tv_usec,
742			(int)hist->buckets[i].upper.tv_sec,
743			(int)hist->buckets[i].upper.tv_usec,
744			(unsigned)hist->buckets[i].count)) {
745			timehist_delete(hist);
746			return 0;
747		}
748	}
749	timehist_delete(hist);
750	return 1;
751}
752
753/** print extended stats */
754static int
755print_ext(SSL* ssl, struct stats_info* s)
756{
757	int i;
758	char nm[16];
759	const ldns_rr_descriptor* desc;
760	const ldns_lookup_table* lt;
761	/* TYPE */
762	for(i=0; i<STATS_QTYPE_NUM; i++) {
763		if(inhibit_zero && s->svr.qtype[i] == 0)
764			continue;
765		desc = ldns_rr_descript((uint16_t)i);
766		if(desc && desc->_name) {
767			snprintf(nm, sizeof(nm), "%s", desc->_name);
768		} else if (i == LDNS_RR_TYPE_IXFR) {
769			snprintf(nm, sizeof(nm), "IXFR");
770		} else if (i == LDNS_RR_TYPE_AXFR) {
771			snprintf(nm, sizeof(nm), "AXFR");
772		} else if (i == LDNS_RR_TYPE_MAILA) {
773			snprintf(nm, sizeof(nm), "MAILA");
774		} else if (i == LDNS_RR_TYPE_MAILB) {
775			snprintf(nm, sizeof(nm), "MAILB");
776		} else if (i == LDNS_RR_TYPE_ANY) {
777			snprintf(nm, sizeof(nm), "ANY");
778		} else {
779			snprintf(nm, sizeof(nm), "TYPE%d", i);
780		}
781		if(!ssl_printf(ssl, "num.query.type.%s"SQ"%u\n",
782			nm, (unsigned)s->svr.qtype[i])) return 0;
783	}
784	if(!inhibit_zero || s->svr.qtype_big) {
785		if(!ssl_printf(ssl, "num.query.type.other"SQ"%u\n",
786			(unsigned)s->svr.qtype_big)) return 0;
787	}
788	/* CLASS */
789	for(i=0; i<STATS_QCLASS_NUM; i++) {
790		if(inhibit_zero && s->svr.qclass[i] == 0)
791			continue;
792		lt = ldns_lookup_by_id(ldns_rr_classes, i);
793		if(lt && lt->name) {
794			snprintf(nm, sizeof(nm), "%s", lt->name);
795		} else {
796			snprintf(nm, sizeof(nm), "CLASS%d", i);
797		}
798		if(!ssl_printf(ssl, "num.query.class.%s"SQ"%u\n",
799			nm, (unsigned)s->svr.qclass[i])) return 0;
800	}
801	if(!inhibit_zero || s->svr.qclass_big) {
802		if(!ssl_printf(ssl, "num.query.class.other"SQ"%u\n",
803			(unsigned)s->svr.qclass_big)) return 0;
804	}
805	/* OPCODE */
806	for(i=0; i<STATS_OPCODE_NUM; i++) {
807		if(inhibit_zero && s->svr.qopcode[i] == 0)
808			continue;
809		lt = ldns_lookup_by_id(ldns_opcodes, i);
810		if(lt && lt->name) {
811			snprintf(nm, sizeof(nm), "%s", lt->name);
812		} else {
813			snprintf(nm, sizeof(nm), "OPCODE%d", i);
814		}
815		if(!ssl_printf(ssl, "num.query.opcode.%s"SQ"%u\n",
816			nm, (unsigned)s->svr.qopcode[i])) return 0;
817	}
818	/* transport */
819	if(!ssl_printf(ssl, "num.query.tcp"SQ"%u\n",
820		(unsigned)s->svr.qtcp)) return 0;
821	if(!ssl_printf(ssl, "num.query.ipv6"SQ"%u\n",
822		(unsigned)s->svr.qipv6)) return 0;
823	/* flags */
824	if(!ssl_printf(ssl, "num.query.flags.QR"SQ"%u\n",
825		(unsigned)s->svr.qbit_QR)) return 0;
826	if(!ssl_printf(ssl, "num.query.flags.AA"SQ"%u\n",
827		(unsigned)s->svr.qbit_AA)) return 0;
828	if(!ssl_printf(ssl, "num.query.flags.TC"SQ"%u\n",
829		(unsigned)s->svr.qbit_TC)) return 0;
830	if(!ssl_printf(ssl, "num.query.flags.RD"SQ"%u\n",
831		(unsigned)s->svr.qbit_RD)) return 0;
832	if(!ssl_printf(ssl, "num.query.flags.RA"SQ"%u\n",
833		(unsigned)s->svr.qbit_RA)) return 0;
834	if(!ssl_printf(ssl, "num.query.flags.Z"SQ"%u\n",
835		(unsigned)s->svr.qbit_Z)) return 0;
836	if(!ssl_printf(ssl, "num.query.flags.AD"SQ"%u\n",
837		(unsigned)s->svr.qbit_AD)) return 0;
838	if(!ssl_printf(ssl, "num.query.flags.CD"SQ"%u\n",
839		(unsigned)s->svr.qbit_CD)) return 0;
840	if(!ssl_printf(ssl, "num.query.edns.present"SQ"%u\n",
841		(unsigned)s->svr.qEDNS)) return 0;
842	if(!ssl_printf(ssl, "num.query.edns.DO"SQ"%u\n",
843		(unsigned)s->svr.qEDNS_DO)) return 0;
844
845	/* RCODE */
846	for(i=0; i<STATS_RCODE_NUM; i++) {
847		if(inhibit_zero && s->svr.ans_rcode[i] == 0)
848			continue;
849		lt = ldns_lookup_by_id(ldns_rcodes, i);
850		if(lt && lt->name) {
851			snprintf(nm, sizeof(nm), "%s", lt->name);
852		} else {
853			snprintf(nm, sizeof(nm), "RCODE%d", i);
854		}
855		if(!ssl_printf(ssl, "num.answer.rcode.%s"SQ"%u\n",
856			nm, (unsigned)s->svr.ans_rcode[i])) return 0;
857	}
858	if(!inhibit_zero || s->svr.ans_rcode_nodata) {
859		if(!ssl_printf(ssl, "num.answer.rcode.nodata"SQ"%u\n",
860			(unsigned)s->svr.ans_rcode_nodata)) return 0;
861	}
862	/* validation */
863	if(!ssl_printf(ssl, "num.answer.secure"SQ"%u\n",
864		(unsigned)s->svr.ans_secure)) return 0;
865	if(!ssl_printf(ssl, "num.answer.bogus"SQ"%u\n",
866		(unsigned)s->svr.ans_bogus)) return 0;
867	if(!ssl_printf(ssl, "num.rrset.bogus"SQ"%u\n",
868		(unsigned)s->svr.rrset_bogus)) return 0;
869	/* threat detection */
870	if(!ssl_printf(ssl, "unwanted.queries"SQ"%u\n",
871		(unsigned)s->svr.unwanted_queries)) return 0;
872	if(!ssl_printf(ssl, "unwanted.replies"SQ"%u\n",
873		(unsigned)s->svr.unwanted_replies)) return 0;
874	return 1;
875}
876
877/** do the stats command */
878static void
879do_stats(SSL* ssl, struct daemon_remote* rc, int reset)
880{
881	struct daemon* daemon = rc->worker->daemon;
882	struct stats_info total;
883	struct stats_info s;
884	int i;
885	log_assert(daemon->num > 0);
886	/* gather all thread statistics in one place */
887	for(i=0; i<daemon->num; i++) {
888		server_stats_obtain(rc->worker, daemon->workers[i], &s, reset);
889		if(!print_thread_stats(ssl, i, &s))
890			return;
891		if(i == 0)
892			total = s;
893		else	server_stats_add(&total, &s);
894	}
895	/* print the thread statistics */
896	total.mesh_time_median /= (double)daemon->num;
897	if(!print_stats(ssl, "total", &total))
898		return;
899	if(!print_uptime(ssl, rc->worker, reset))
900		return;
901	if(daemon->cfg->stat_extended) {
902		if(!print_mem(ssl, rc->worker, daemon))
903			return;
904		if(!print_hist(ssl, &total))
905			return;
906		if(!print_ext(ssl, &total))
907			return;
908	}
909}
910
911/** parse commandline argument domain name */
912static int
913parse_arg_name(SSL* ssl, char* str, uint8_t** res, size_t* len, int* labs)
914{
915	ldns_rdf* rdf;
916	*res = NULL;
917	*len = 0;
918	*labs = 0;
919	rdf = ldns_dname_new_frm_str(str);
920	if(!rdf) {
921		ssl_printf(ssl, "error cannot parse name %s\n", str);
922		return 0;
923	}
924	*res = memdup(ldns_rdf_data(rdf), ldns_rdf_size(rdf));
925	ldns_rdf_deep_free(rdf);
926	if(!*res) {
927		ssl_printf(ssl, "error out of memory\n");
928		return 0;
929	}
930	*labs = dname_count_size_labels(*res, len);
931	return 1;
932}
933
934/** find second argument, modifies string */
935static int
936find_arg2(SSL* ssl, char* arg, char** arg2)
937{
938	char* as = strchr(arg, ' ');
939	char* at = strchr(arg, '\t');
940	if(as && at) {
941		if(at < as)
942			as = at;
943		as[0]=0;
944		*arg2 = skipwhite(as+1);
945	} else if(as) {
946		as[0]=0;
947		*arg2 = skipwhite(as+1);
948	} else if(at) {
949		at[0]=0;
950		*arg2 = skipwhite(at+1);
951	} else {
952		ssl_printf(ssl, "error could not find next argument "
953			"after %s\n", arg);
954		return 0;
955	}
956	return 1;
957}
958
959/** Add a new zone */
960static void
961do_zone_add(SSL* ssl, struct worker* worker, char* arg)
962{
963	uint8_t* nm;
964	int nmlabs;
965	size_t nmlen;
966	char* arg2;
967	enum localzone_type t;
968	struct local_zone* z;
969	if(!find_arg2(ssl, arg, &arg2))
970		return;
971	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
972		return;
973	if(!local_zone_str2type(arg2, &t)) {
974		ssl_printf(ssl, "error not a zone type. %s\n", arg2);
975		free(nm);
976		return;
977	}
978	lock_quick_lock(&worker->daemon->local_zones->lock);
979	if((z=local_zones_find(worker->daemon->local_zones, nm, nmlen,
980		nmlabs, LDNS_RR_CLASS_IN))) {
981		/* already present in tree */
982		lock_rw_wrlock(&z->lock);
983		z->type = t; /* update type anyway */
984		lock_rw_unlock(&z->lock);
985		free(nm);
986		lock_quick_unlock(&worker->daemon->local_zones->lock);
987		send_ok(ssl);
988		return;
989	}
990	if(!local_zones_add_zone(worker->daemon->local_zones, nm, nmlen,
991		nmlabs, LDNS_RR_CLASS_IN, t)) {
992		lock_quick_unlock(&worker->daemon->local_zones->lock);
993		ssl_printf(ssl, "error out of memory\n");
994		return;
995	}
996	lock_quick_unlock(&worker->daemon->local_zones->lock);
997	send_ok(ssl);
998}
999
1000/** Remove a zone */
1001static void
1002do_zone_remove(SSL* ssl, struct worker* worker, char* arg)
1003{
1004	uint8_t* nm;
1005	int nmlabs;
1006	size_t nmlen;
1007	struct local_zone* z;
1008	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1009		return;
1010	lock_quick_lock(&worker->daemon->local_zones->lock);
1011	if((z=local_zones_find(worker->daemon->local_zones, nm, nmlen,
1012		nmlabs, LDNS_RR_CLASS_IN))) {
1013		/* present in tree */
1014		local_zones_del_zone(worker->daemon->local_zones, z);
1015	}
1016	lock_quick_unlock(&worker->daemon->local_zones->lock);
1017	free(nm);
1018	send_ok(ssl);
1019}
1020
1021/** Add new RR data */
1022static void
1023do_data_add(SSL* ssl, struct worker* worker, char* arg)
1024{
1025	if(!local_zones_add_RR(worker->daemon->local_zones, arg,
1026		worker->env.scratch_buffer)) {
1027		ssl_printf(ssl,"error in syntax or out of memory, %s\n", arg);
1028		return;
1029	}
1030	send_ok(ssl);
1031}
1032
1033/** Remove RR data */
1034static void
1035do_data_remove(SSL* ssl, struct worker* worker, char* arg)
1036{
1037	uint8_t* nm;
1038	int nmlabs;
1039	size_t nmlen;
1040	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1041		return;
1042	local_zones_del_data(worker->daemon->local_zones, nm,
1043		nmlen, nmlabs, LDNS_RR_CLASS_IN);
1044	free(nm);
1045	send_ok(ssl);
1046}
1047
1048/** cache lookup of nameservers */
1049static void
1050do_lookup(SSL* ssl, struct worker* worker, char* arg)
1051{
1052	uint8_t* nm;
1053	int nmlabs;
1054	size_t nmlen;
1055	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1056		return;
1057	(void)print_deleg_lookup(ssl, worker, nm, nmlen, nmlabs);
1058	free(nm);
1059}
1060
1061/** flush something from rrset and msg caches */
1062static void
1063do_cache_remove(struct worker* worker, uint8_t* nm, size_t nmlen,
1064	uint16_t t, uint16_t c)
1065{
1066	hashvalue_t h;
1067	struct query_info k;
1068	rrset_cache_remove(worker->env.rrset_cache, nm, nmlen, t, c, 0);
1069	if(t == LDNS_RR_TYPE_SOA)
1070		rrset_cache_remove(worker->env.rrset_cache, nm, nmlen, t, c,
1071			PACKED_RRSET_SOA_NEG);
1072	k.qname = nm;
1073	k.qname_len = nmlen;
1074	k.qtype = t;
1075	k.qclass = c;
1076	h = query_info_hash(&k);
1077	slabhash_remove(worker->env.msg_cache, h, &k);
1078}
1079
1080/** flush a type */
1081static void
1082do_flush_type(SSL* ssl, struct worker* worker, char* arg)
1083{
1084	uint8_t* nm;
1085	int nmlabs;
1086	size_t nmlen;
1087	char* arg2;
1088	uint16_t t;
1089	if(!find_arg2(ssl, arg, &arg2))
1090		return;
1091	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1092		return;
1093	t = ldns_get_rr_type_by_name(arg2);
1094	do_cache_remove(worker, nm, nmlen, t, LDNS_RR_CLASS_IN);
1095
1096	free(nm);
1097	send_ok(ssl);
1098}
1099
1100/** flush statistics */
1101static void
1102do_flush_stats(SSL* ssl, struct worker* worker)
1103{
1104	worker_stats_clear(worker);
1105	send_ok(ssl);
1106}
1107
1108/**
1109 * Local info for deletion functions
1110 */
1111struct del_info {
1112	/** worker */
1113	struct worker* worker;
1114	/** name to delete */
1115	uint8_t* name;
1116	/** length */
1117	size_t len;
1118	/** labels */
1119	int labs;
1120	/** now */
1121	uint32_t now;
1122	/** time to invalidate to */
1123	uint32_t expired;
1124	/** number of rrsets removed */
1125	size_t num_rrsets;
1126	/** number of msgs removed */
1127	size_t num_msgs;
1128	/** number of key entries removed */
1129	size_t num_keys;
1130	/** length of addr */
1131	socklen_t addrlen;
1132	/** socket address for host deletion */
1133	struct sockaddr_storage addr;
1134};
1135
1136/** callback to delete hosts in infra cache */
1137static void
1138infra_del_host(struct lruhash_entry* e, void* arg)
1139{
1140	/* entry is locked */
1141	struct del_info* inf = (struct del_info*)arg;
1142	struct infra_key* k = (struct infra_key*)e->key;
1143	if(sockaddr_cmp(&inf->addr, inf->addrlen, &k->addr, k->addrlen) == 0) {
1144		struct infra_data* d = (struct infra_data*)e->data;
1145		d->probedelay = 0;
1146		d->timeout_A = 0;
1147		d->timeout_AAAA = 0;
1148		d->timeout_other = 0;
1149		rtt_init(&d->rtt);
1150		if(d->ttl >= inf->now) {
1151			d->ttl = inf->expired;
1152			inf->num_keys++;
1153		}
1154	}
1155}
1156
1157/** flush infra cache */
1158static void
1159do_flush_infra(SSL* ssl, struct worker* worker, char* arg)
1160{
1161	struct sockaddr_storage addr;
1162	socklen_t len;
1163	struct del_info inf;
1164	if(strcmp(arg, "all") == 0) {
1165		slabhash_clear(worker->env.infra_cache->hosts);
1166		send_ok(ssl);
1167		return;
1168	}
1169	if(!ipstrtoaddr(arg, UNBOUND_DNS_PORT, &addr, &len)) {
1170		(void)ssl_printf(ssl, "error parsing ip addr: '%s'\n", arg);
1171		return;
1172	}
1173	/* delete all entries from cache */
1174	/* what we do is to set them all expired */
1175	inf.worker = worker;
1176	inf.name = 0;
1177	inf.len = 0;
1178	inf.labs = 0;
1179	inf.now = *worker->env.now;
1180	inf.expired = *worker->env.now;
1181	inf.expired -= 3; /* handle 3 seconds skew between threads */
1182	inf.num_rrsets = 0;
1183	inf.num_msgs = 0;
1184	inf.num_keys = 0;
1185	inf.addrlen = len;
1186	memmove(&inf.addr, &addr, len);
1187	slabhash_traverse(worker->env.infra_cache->hosts, 1, &infra_del_host,
1188		&inf);
1189	send_ok(ssl);
1190}
1191
1192/** flush requestlist */
1193static void
1194do_flush_requestlist(SSL* ssl, struct worker* worker)
1195{
1196	mesh_delete_all(worker->env.mesh);
1197	send_ok(ssl);
1198}
1199
1200/** callback to delete rrsets in a zone */
1201static void
1202zone_del_rrset(struct lruhash_entry* e, void* arg)
1203{
1204	/* entry is locked */
1205	struct del_info* inf = (struct del_info*)arg;
1206	struct ub_packed_rrset_key* k = (struct ub_packed_rrset_key*)e->key;
1207	if(dname_subdomain_c(k->rk.dname, inf->name)) {
1208		struct packed_rrset_data* d =
1209			(struct packed_rrset_data*)e->data;
1210		if(d->ttl >= inf->now) {
1211			d->ttl = inf->expired;
1212			inf->num_rrsets++;
1213		}
1214	}
1215}
1216
1217/** callback to delete messages in a zone */
1218static void
1219zone_del_msg(struct lruhash_entry* e, void* arg)
1220{
1221	/* entry is locked */
1222	struct del_info* inf = (struct del_info*)arg;
1223	struct msgreply_entry* k = (struct msgreply_entry*)e->key;
1224	if(dname_subdomain_c(k->key.qname, inf->name)) {
1225		struct reply_info* d = (struct reply_info*)e->data;
1226		if(d->ttl >= inf->now) {
1227			d->ttl = inf->expired;
1228			inf->num_msgs++;
1229		}
1230	}
1231}
1232
1233/** callback to delete keys in zone */
1234static void
1235zone_del_kcache(struct lruhash_entry* e, void* arg)
1236{
1237	/* entry is locked */
1238	struct del_info* inf = (struct del_info*)arg;
1239	struct key_entry_key* k = (struct key_entry_key*)e->key;
1240	if(dname_subdomain_c(k->name, inf->name)) {
1241		struct key_entry_data* d = (struct key_entry_data*)e->data;
1242		if(d->ttl >= inf->now) {
1243			d->ttl = inf->expired;
1244			inf->num_keys++;
1245		}
1246	}
1247}
1248
1249/** remove all rrsets and keys from zone from cache */
1250static void
1251do_flush_zone(SSL* ssl, struct worker* worker, char* arg)
1252{
1253	uint8_t* nm;
1254	int nmlabs;
1255	size_t nmlen;
1256	struct del_info inf;
1257	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1258		return;
1259	/* delete all RRs and key entries from zone */
1260	/* what we do is to set them all expired */
1261	inf.worker = worker;
1262	inf.name = nm;
1263	inf.len = nmlen;
1264	inf.labs = nmlabs;
1265	inf.now = *worker->env.now;
1266	inf.expired = *worker->env.now;
1267	inf.expired -= 3; /* handle 3 seconds skew between threads */
1268	inf.num_rrsets = 0;
1269	inf.num_msgs = 0;
1270	inf.num_keys = 0;
1271	slabhash_traverse(&worker->env.rrset_cache->table, 1,
1272		&zone_del_rrset, &inf);
1273
1274	slabhash_traverse(worker->env.msg_cache, 1, &zone_del_msg, &inf);
1275
1276	/* and validator cache */
1277	if(worker->env.key_cache) {
1278		slabhash_traverse(worker->env.key_cache->slab, 1,
1279			&zone_del_kcache, &inf);
1280	}
1281
1282	free(nm);
1283
1284	(void)ssl_printf(ssl, "ok removed %u rrsets, %u messages "
1285		"and %u key entries\n", (unsigned)inf.num_rrsets,
1286		(unsigned)inf.num_msgs, (unsigned)inf.num_keys);
1287}
1288
1289/** remove name rrset from cache */
1290static void
1291do_flush_name(SSL* ssl, struct worker* w, char* arg)
1292{
1293	uint8_t* nm;
1294	int nmlabs;
1295	size_t nmlen;
1296	if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1297		return;
1298	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_A, LDNS_RR_CLASS_IN);
1299	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_AAAA, LDNS_RR_CLASS_IN);
1300	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_NS, LDNS_RR_CLASS_IN);
1301	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SOA, LDNS_RR_CLASS_IN);
1302	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_CNAME, LDNS_RR_CLASS_IN);
1303	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_DNAME, LDNS_RR_CLASS_IN);
1304	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_MX, LDNS_RR_CLASS_IN);
1305	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_PTR, LDNS_RR_CLASS_IN);
1306	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SRV, LDNS_RR_CLASS_IN);
1307	do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_NAPTR, LDNS_RR_CLASS_IN);
1308
1309	free(nm);
1310	send_ok(ssl);
1311}
1312
1313/** printout a delegation point info */
1314static int
1315ssl_print_name_dp(SSL* ssl, char* str, uint8_t* nm, uint16_t dclass,
1316	struct delegpt* dp)
1317{
1318	char buf[257];
1319	struct delegpt_ns* ns;
1320	struct delegpt_addr* a;
1321	int f = 0;
1322	if(str) { /* print header for forward, stub */
1323		char* c = ldns_rr_class2str(dclass);
1324		dname_str(nm, buf);
1325		if(!ssl_printf(ssl, "%s %s %s: ", buf, c, str)) {
1326			free(c);
1327			return 0;
1328		}
1329		free(c);
1330	}
1331	for(ns = dp->nslist; ns; ns = ns->next) {
1332		dname_str(ns->name, buf);
1333		if(!ssl_printf(ssl, "%s%s", (f?" ":""), buf))
1334			return 0;
1335		f = 1;
1336	}
1337	for(a = dp->target_list; a; a = a->next_target) {
1338		addr_to_str(&a->addr, a->addrlen, buf, sizeof(buf));
1339		if(!ssl_printf(ssl, "%s%s", (f?" ":""), buf))
1340			return 0;
1341		f = 1;
1342	}
1343	return ssl_printf(ssl, "\n");
1344}
1345
1346
1347/** print root forwards */
1348static int
1349print_root_fwds(SSL* ssl, struct iter_forwards* fwds, uint8_t* root)
1350{
1351	struct delegpt* dp;
1352	dp = forwards_lookup(fwds, root, LDNS_RR_CLASS_IN);
1353	if(!dp)
1354		return ssl_printf(ssl, "off (using root hints)\n");
1355	/* if dp is returned it must be the root */
1356	log_assert(query_dname_compare(dp->name, root)==0);
1357	return ssl_print_name_dp(ssl, NULL, root, LDNS_RR_CLASS_IN, dp);
1358}
1359
1360/** parse args into delegpt */
1361static struct delegpt*
1362parse_delegpt(SSL* ssl, char* args, uint8_t* nm, int allow_names)
1363{
1364	/* parse args and add in */
1365	char* p = args;
1366	char* todo;
1367	struct delegpt* dp = delegpt_create_mlc(nm);
1368	struct sockaddr_storage addr;
1369	socklen_t addrlen;
1370	if(!dp) {
1371		(void)ssl_printf(ssl, "error out of memory\n");
1372		return NULL;
1373	}
1374	while(p) {
1375		todo = p;
1376		p = strchr(p, ' '); /* find next spot, if any */
1377		if(p) {
1378			*p++ = 0;	/* end this spot */
1379			p = skipwhite(p); /* position at next spot */
1380		}
1381		/* parse address */
1382		if(!extstrtoaddr(todo, &addr, &addrlen)) {
1383			if(allow_names) {
1384				uint8_t* n = NULL;
1385				size_t ln;
1386				int lb;
1387				if(!parse_arg_name(ssl, todo, &n, &ln, &lb)) {
1388					(void)ssl_printf(ssl, "error cannot "
1389						"parse IP address or name "
1390						"'%s'\n", todo);
1391					delegpt_free_mlc(dp);
1392					return NULL;
1393				}
1394				if(!delegpt_add_ns_mlc(dp, n, 0)) {
1395					(void)ssl_printf(ssl, "error out of memory\n");
1396					delegpt_free_mlc(dp);
1397					return NULL;
1398				}
1399				free(n);
1400
1401			} else {
1402				(void)ssl_printf(ssl, "error cannot parse"
1403					" IP address '%s'\n", todo);
1404				delegpt_free_mlc(dp);
1405				return NULL;
1406			}
1407		} else {
1408			/* add address */
1409			if(!delegpt_add_addr_mlc(dp, &addr, addrlen, 0, 0)) {
1410				(void)ssl_printf(ssl, "error out of memory\n");
1411				delegpt_free_mlc(dp);
1412				return NULL;
1413			}
1414		}
1415	}
1416	return dp;
1417}
1418
1419/** do the status command */
1420static void
1421do_forward(SSL* ssl, struct worker* worker, char* args)
1422{
1423	struct iter_forwards* fwd = worker->env.fwds;
1424	uint8_t* root = (uint8_t*)"\000";
1425	if(!fwd) {
1426		(void)ssl_printf(ssl, "error: structure not allocated\n");
1427		return;
1428	}
1429	if(args == NULL || args[0] == 0) {
1430		(void)print_root_fwds(ssl, fwd, root);
1431		return;
1432	}
1433	/* set root forwards for this thread. since we are in remote control
1434	 * the actual mesh is not running, so we can freely edit it. */
1435	/* delete all the existing queries first */
1436	mesh_delete_all(worker->env.mesh);
1437	if(strcmp(args, "off") == 0) {
1438		forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, root);
1439	} else {
1440		struct delegpt* dp;
1441		if(!(dp = parse_delegpt(ssl, args, root, 0)))
1442			return;
1443		if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp)) {
1444			(void)ssl_printf(ssl, "error out of memory\n");
1445			delegpt_free_mlc(dp);
1446			return;
1447		}
1448	}
1449	send_ok(ssl);
1450}
1451
1452static int
1453parse_fs_args(SSL* ssl, char* args, uint8_t** nm, struct delegpt** dp,
1454	int* insecure, int* prime)
1455{
1456	char* zonename;
1457	char* rest;
1458	size_t nmlen;
1459	int nmlabs;
1460	/* parse all -x args */
1461	while(args[0] == '+') {
1462		if(!find_arg2(ssl, args, &rest))
1463			return 0;
1464		while(*(++args) != 0) {
1465			if(*args == 'i' && insecure)
1466				*insecure = 1;
1467			else if(*args == 'p' && prime)
1468				*prime = 1;
1469			else {
1470				(void)ssl_printf(ssl, "error: unknown option %s\n", args);
1471				return 0;
1472			}
1473		}
1474		args = rest;
1475	}
1476	/* parse name */
1477	if(dp) {
1478		if(!find_arg2(ssl, args, &rest))
1479			return 0;
1480		zonename = args;
1481		args = rest;
1482	} else	zonename = args;
1483	if(!parse_arg_name(ssl, zonename, nm, &nmlen, &nmlabs))
1484		return 0;
1485
1486	/* parse dp */
1487	if(dp) {
1488		if(!(*dp = parse_delegpt(ssl, args, *nm, 1))) {
1489			free(*nm);
1490			return 0;
1491		}
1492	}
1493	return 1;
1494}
1495
1496/** do the forward_add command */
1497static void
1498do_forward_add(SSL* ssl, struct worker* worker, char* args)
1499{
1500	struct iter_forwards* fwd = worker->env.fwds;
1501	int insecure = 0;
1502	uint8_t* nm = NULL;
1503	struct delegpt* dp = NULL;
1504	if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, NULL))
1505		return;
1506	if(insecure) {
1507		if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
1508			nm)) {
1509			(void)ssl_printf(ssl, "error out of memory\n");
1510			delegpt_free_mlc(dp);
1511			free(nm);
1512			return;
1513		}
1514	}
1515	if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp)) {
1516		(void)ssl_printf(ssl, "error out of memory\n");
1517		delegpt_free_mlc(dp);
1518		free(nm);
1519		return;
1520	}
1521	free(nm);
1522	send_ok(ssl);
1523}
1524
1525/** do the forward_remove command */
1526static void
1527do_forward_remove(SSL* ssl, struct worker* worker, char* args)
1528{
1529	struct iter_forwards* fwd = worker->env.fwds;
1530	int insecure = 0;
1531	uint8_t* nm = NULL;
1532	if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL))
1533		return;
1534	if(insecure)
1535		anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
1536			nm);
1537	forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, nm);
1538	free(nm);
1539	send_ok(ssl);
1540}
1541
1542/** do the stub_add command */
1543static void
1544do_stub_add(SSL* ssl, struct worker* worker, char* args)
1545{
1546	struct iter_forwards* fwd = worker->env.fwds;
1547	int insecure = 0, prime = 0;
1548	uint8_t* nm = NULL;
1549	struct delegpt* dp = NULL;
1550	if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, &prime))
1551		return;
1552	if(insecure) {
1553		if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
1554			nm)) {
1555			(void)ssl_printf(ssl, "error out of memory\n");
1556			delegpt_free_mlc(dp);
1557			free(nm);
1558			return;
1559		}
1560	}
1561	if(!forwards_add_stub_hole(fwd, LDNS_RR_CLASS_IN, nm)) {
1562		if(insecure) anchors_delete_insecure(worker->env.anchors,
1563			LDNS_RR_CLASS_IN, nm);
1564		(void)ssl_printf(ssl, "error out of memory\n");
1565		delegpt_free_mlc(dp);
1566		free(nm);
1567		return;
1568	}
1569	if(!hints_add_stub(worker->env.hints, LDNS_RR_CLASS_IN, dp, !prime)) {
1570		(void)ssl_printf(ssl, "error out of memory\n");
1571		forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm);
1572		if(insecure) anchors_delete_insecure(worker->env.anchors,
1573			LDNS_RR_CLASS_IN, nm);
1574		delegpt_free_mlc(dp);
1575		free(nm);
1576		return;
1577	}
1578	free(nm);
1579	send_ok(ssl);
1580}
1581
1582/** do the stub_remove command */
1583static void
1584do_stub_remove(SSL* ssl, struct worker* worker, char* args)
1585{
1586	struct iter_forwards* fwd = worker->env.fwds;
1587	int insecure = 0;
1588	uint8_t* nm = NULL;
1589	if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL))
1590		return;
1591	if(insecure)
1592		anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
1593			nm);
1594	forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm);
1595	hints_delete_stub(worker->env.hints, LDNS_RR_CLASS_IN, nm);
1596	free(nm);
1597	send_ok(ssl);
1598}
1599
1600/** do the status command */
1601static void
1602do_status(SSL* ssl, struct worker* worker)
1603{
1604	int i;
1605	time_t uptime;
1606	if(!ssl_printf(ssl, "version: %s\n", PACKAGE_VERSION))
1607		return;
1608	if(!ssl_printf(ssl, "verbosity: %d\n", verbosity))
1609		return;
1610	if(!ssl_printf(ssl, "threads: %d\n", worker->daemon->num))
1611		return;
1612	if(!ssl_printf(ssl, "modules: %d [", worker->daemon->mods.num))
1613		return;
1614	for(i=0; i<worker->daemon->mods.num; i++) {
1615		if(!ssl_printf(ssl, " %s", worker->daemon->mods.mod[i]->name))
1616			return;
1617	}
1618	if(!ssl_printf(ssl, " ]\n"))
1619		return;
1620	uptime = (time_t)time(NULL) - (time_t)worker->daemon->time_boot.tv_sec;
1621	if(!ssl_printf(ssl, "uptime: %u seconds\n", (unsigned)uptime))
1622		return;
1623	if(!ssl_printf(ssl, "unbound (pid %d) is running...\n",
1624		(int)getpid()))
1625		return;
1626}
1627
1628/** get age for the mesh state */
1629static void
1630get_mesh_age(struct mesh_state* m, char* buf, size_t len,
1631	struct module_env* env)
1632{
1633	if(m->reply_list) {
1634		struct timeval d;
1635		struct mesh_reply* r = m->reply_list;
1636		/* last reply is the oldest */
1637		while(r && r->next)
1638			r = r->next;
1639		timeval_subtract(&d, env->now_tv, &r->start_time);
1640		snprintf(buf, len, "%d.%6.6d", (int)d.tv_sec, (int)d.tv_usec);
1641	} else {
1642		snprintf(buf, len, "-");
1643	}
1644}
1645
1646/** get status of a mesh state */
1647static void
1648get_mesh_status(struct mesh_area* mesh, struct mesh_state* m,
1649	char* buf, size_t len)
1650{
1651	enum module_ext_state s = m->s.ext_state[m->s.curmod];
1652	const char *modname = mesh->mods.mod[m->s.curmod]->name;
1653	size_t l;
1654	if(strcmp(modname, "iterator") == 0 && s == module_wait_reply &&
1655		m->s.minfo[m->s.curmod]) {
1656		/* break into iterator to find out who its waiting for */
1657		struct iter_qstate* qstate = (struct iter_qstate*)
1658			m->s.minfo[m->s.curmod];
1659		struct outbound_list* ol = &qstate->outlist;
1660		struct outbound_entry* e;
1661		snprintf(buf, len, "%s wait for", modname);
1662		l = strlen(buf);
1663		buf += l; len -= l;
1664		if(ol->first == NULL)
1665			snprintf(buf, len, " (empty_list)");
1666		for(e = ol->first; e; e = e->next) {
1667			snprintf(buf, len, " ");
1668			l = strlen(buf);
1669			buf += l; len -= l;
1670			addr_to_str(&e->qsent->addr, e->qsent->addrlen,
1671				buf, len);
1672			l = strlen(buf);
1673			buf += l; len -= l;
1674		}
1675	} else if(s == module_wait_subquery) {
1676		/* look in subs from mesh state to see what */
1677		char nm[257];
1678		struct mesh_state_ref* sub;
1679		snprintf(buf, len, "%s wants", modname);
1680		l = strlen(buf);
1681		buf += l; len -= l;
1682		if(m->sub_set.count == 0)
1683			snprintf(buf, len, " (empty_list)");
1684		RBTREE_FOR(sub, struct mesh_state_ref*, &m->sub_set) {
1685			char* t = ldns_rr_type2str(sub->s->s.qinfo.qtype);
1686			char* c = ldns_rr_class2str(sub->s->s.qinfo.qclass);
1687			dname_str(sub->s->s.qinfo.qname, nm);
1688			snprintf(buf, len, " %s %s %s", t, c, nm);
1689			l = strlen(buf);
1690			buf += l; len -= l;
1691			free(t);
1692			free(c);
1693		}
1694	} else {
1695		snprintf(buf, len, "%s is %s", modname, strextstate(s));
1696	}
1697}
1698
1699/** do the dump_requestlist command */
1700static void
1701do_dump_requestlist(SSL* ssl, struct worker* worker)
1702{
1703	struct mesh_area* mesh;
1704	struct mesh_state* m;
1705	int num = 0;
1706	char buf[257];
1707	char timebuf[32];
1708	char statbuf[10240];
1709	if(!ssl_printf(ssl, "thread #%d\n", worker->thread_num))
1710		return;
1711	if(!ssl_printf(ssl, "#   type cl name    seconds    module status\n"))
1712		return;
1713	/* show worker mesh contents */
1714	mesh = worker->env.mesh;
1715	if(!mesh) return;
1716	RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
1717		char* t = ldns_rr_type2str(m->s.qinfo.qtype);
1718		char* c = ldns_rr_class2str(m->s.qinfo.qclass);
1719		dname_str(m->s.qinfo.qname, buf);
1720		get_mesh_age(m, timebuf, sizeof(timebuf), &worker->env);
1721		get_mesh_status(mesh, m, statbuf, sizeof(statbuf));
1722		if(!ssl_printf(ssl, "%3d %4s %2s %s %s %s\n",
1723			num, t, c, buf, timebuf, statbuf)) {
1724			free(t);
1725			free(c);
1726			return;
1727		}
1728		num++;
1729		free(t);
1730		free(c);
1731	}
1732}
1733
1734/** structure for argument data for dump infra host */
1735struct infra_arg {
1736	/** the infra cache */
1737	struct infra_cache* infra;
1738	/** the SSL connection */
1739	SSL* ssl;
1740	/** the time now */
1741	uint32_t now;
1742};
1743
1744/** callback for every host element in the infra cache */
1745static void
1746dump_infra_host(struct lruhash_entry* e, void* arg)
1747{
1748	struct infra_arg* a = (struct infra_arg*)arg;
1749	struct infra_key* k = (struct infra_key*)e->key;
1750	struct infra_data* d = (struct infra_data*)e->data;
1751	char ip_str[1024];
1752	char name[257];
1753	addr_to_str(&k->addr, k->addrlen, ip_str, sizeof(ip_str));
1754	dname_str(k->zonename, name);
1755	/* skip expired stuff (only backed off) */
1756	if(d->ttl < a->now) {
1757		if(d->rtt.rto >= USEFUL_SERVER_TOP_TIMEOUT) {
1758			if(!ssl_printf(a->ssl, "%s %s expired rto %d\n", ip_str,
1759				name, d->rtt.rto)) return;
1760		}
1761		return;
1762	}
1763	if(!ssl_printf(a->ssl, "%s %s ttl %d ping %d var %d rtt %d rto %d "
1764		"tA %d tAAAA %d tother %d "
1765		"ednsknown %d edns %d delay %d lame dnssec %d rec %d A %d "
1766		"other %d\n", ip_str, name, (int)(d->ttl - a->now),
1767		d->rtt.srtt, d->rtt.rttvar, rtt_notimeout(&d->rtt), d->rtt.rto,
1768		d->timeout_A, d->timeout_AAAA, d->timeout_other,
1769		(int)d->edns_lame_known, (int)d->edns_version,
1770		(int)(a->now<d->probedelay?d->probedelay-a->now:0),
1771		(int)d->isdnsseclame, (int)d->rec_lame, (int)d->lame_type_A,
1772		(int)d->lame_other))
1773		return;
1774}
1775
1776/** do the dump_infra command */
1777static void
1778do_dump_infra(SSL* ssl, struct worker* worker)
1779{
1780	struct infra_arg arg;
1781	arg.infra = worker->env.infra_cache;
1782	arg.ssl = ssl;
1783	arg.now = *worker->env.now;
1784	slabhash_traverse(arg.infra->hosts, 0, &dump_infra_host, (void*)&arg);
1785}
1786
1787/** do the log_reopen command */
1788static void
1789do_log_reopen(SSL* ssl, struct worker* worker)
1790{
1791	struct config_file* cfg = worker->env.cfg;
1792	send_ok(ssl);
1793	log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
1794}
1795
1796/** do the set_option command */
1797static void
1798do_set_option(SSL* ssl, struct worker* worker, char* arg)
1799{
1800	char* arg2;
1801	if(!find_arg2(ssl, arg, &arg2))
1802		return;
1803	if(!config_set_option(worker->env.cfg, arg, arg2)) {
1804		(void)ssl_printf(ssl, "error setting option\n");
1805		return;
1806	}
1807	send_ok(ssl);
1808}
1809
1810/* routine to printout option values over SSL */
1811void remote_get_opt_ssl(char* line, void* arg)
1812{
1813	SSL* ssl = (SSL*)arg;
1814	(void)ssl_printf(ssl, "%s\n", line);
1815}
1816
1817/** do the get_option command */
1818static void
1819do_get_option(SSL* ssl, struct worker* worker, char* arg)
1820{
1821	int r;
1822	r = config_get_option(worker->env.cfg, arg, remote_get_opt_ssl, ssl);
1823	if(!r) {
1824		(void)ssl_printf(ssl, "error unknown option\n");
1825		return;
1826	}
1827}
1828
1829/** do the list_forwards command */
1830static void
1831do_list_forwards(SSL* ssl, struct worker* worker)
1832{
1833	/* since its a per-worker structure no locks needed */
1834	struct iter_forwards* fwds = worker->env.fwds;
1835	struct iter_forward_zone* z;
1836	RBTREE_FOR(z, struct iter_forward_zone*, fwds->tree) {
1837		if(!z->dp) continue; /* skip empty marker for stub */
1838		if(!ssl_print_name_dp(ssl, "forward", z->name, z->dclass,
1839			z->dp))
1840			return;
1841	}
1842}
1843
1844/** do the list_stubs command */
1845static void
1846do_list_stubs(SSL* ssl, struct worker* worker)
1847{
1848	struct iter_hints_stub* z;
1849	RBTREE_FOR(z, struct iter_hints_stub*, &worker->env.hints->tree) {
1850		if(!ssl_print_name_dp(ssl,
1851			z->noprime?"stub noprime":"stub prime", z->node.name,
1852			z->node.dclass, z->dp))
1853			return;
1854	}
1855}
1856
1857/** do the list_local_zones command */
1858static void
1859do_list_local_zones(SSL* ssl, struct worker* worker)
1860{
1861	struct local_zones* zones = worker->daemon->local_zones;
1862	struct local_zone* z;
1863	char buf[257];
1864	lock_quick_lock(&zones->lock);
1865	RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
1866		lock_rw_rdlock(&z->lock);
1867		dname_str(z->name, buf);
1868		(void)ssl_printf(ssl, "%s %s\n", buf,
1869			local_zone_type2str(z->type));
1870		lock_rw_unlock(&z->lock);
1871	}
1872	lock_quick_unlock(&zones->lock);
1873}
1874
1875/** do the list_local_data command */
1876static void
1877do_list_local_data(SSL* ssl, struct worker* worker)
1878{
1879	struct local_zones* zones = worker->daemon->local_zones;
1880	struct local_zone* z;
1881	struct local_data* d;
1882	struct local_rrset* p;
1883	lock_quick_lock(&zones->lock);
1884	RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
1885		lock_rw_rdlock(&z->lock);
1886		RBTREE_FOR(d, struct local_data*, &z->data) {
1887			for(p = d->rrsets; p; p = p->next) {
1888				ldns_rr_list* rr = packed_rrset_to_rr_list(
1889					p->rrset, worker->env.scratch_buffer);
1890				char* str = ldns_rr_list2str(rr);
1891				(void)ssl_printf(ssl, "%s", str);
1892				free(str);
1893				ldns_rr_list_free(rr);
1894			}
1895		}
1896		lock_rw_unlock(&z->lock);
1897	}
1898	lock_quick_unlock(&zones->lock);
1899}
1900
1901/** tell other processes to execute the command */
1902static void
1903distribute_cmd(struct daemon_remote* rc, SSL* ssl, char* cmd)
1904{
1905	int i;
1906	if(!cmd || !ssl)
1907		return;
1908	/* skip i=0 which is me */
1909	for(i=1; i<rc->worker->daemon->num; i++) {
1910		worker_send_cmd(rc->worker->daemon->workers[i],
1911			worker_cmd_remote);
1912		if(!tube_write_msg(rc->worker->daemon->workers[i]->cmd,
1913			(uint8_t*)cmd, strlen(cmd)+1, 0)) {
1914			ssl_printf(ssl, "error could not distribute cmd\n");
1915			return;
1916		}
1917	}
1918}
1919
1920/** check for name with end-of-string, space or tab after it */
1921static int
1922cmdcmp(char* p, const char* cmd, size_t len)
1923{
1924	return strncmp(p,cmd,len)==0 && (p[len]==0||p[len]==' '||p[len]=='\t');
1925}
1926
1927/** execute a remote control command */
1928static void
1929execute_cmd(struct daemon_remote* rc, SSL* ssl, char* cmd,
1930	struct worker* worker)
1931{
1932	char* p = skipwhite(cmd);
1933	/* compare command */
1934	if(cmdcmp(p, "stop", 4)) {
1935		do_stop(ssl, rc);
1936		return;
1937	} else if(cmdcmp(p, "reload", 6)) {
1938		do_reload(ssl, rc);
1939		return;
1940	} else if(cmdcmp(p, "stats_noreset", 13)) {
1941		do_stats(ssl, rc, 0);
1942		return;
1943	} else if(cmdcmp(p, "stats", 5)) {
1944		do_stats(ssl, rc, 1);
1945		return;
1946	} else if(cmdcmp(p, "status", 6)) {
1947		do_status(ssl, worker);
1948		return;
1949	} else if(cmdcmp(p, "dump_cache", 10)) {
1950		(void)dump_cache(ssl, worker);
1951		return;
1952	} else if(cmdcmp(p, "load_cache", 10)) {
1953		if(load_cache(ssl, worker)) send_ok(ssl);
1954		return;
1955	} else if(cmdcmp(p, "list_forwards", 13)) {
1956		do_list_forwards(ssl, worker);
1957		return;
1958	} else if(cmdcmp(p, "list_stubs", 10)) {
1959		do_list_stubs(ssl, worker);
1960		return;
1961	} else if(cmdcmp(p, "list_local_zones", 16)) {
1962		do_list_local_zones(ssl, worker);
1963		return;
1964	} else if(cmdcmp(p, "list_local_data", 15)) {
1965		do_list_local_data(ssl, worker);
1966		return;
1967	} else if(cmdcmp(p, "stub_add", 8)) {
1968		/* must always distribute this cmd */
1969		if(rc) distribute_cmd(rc, ssl, cmd);
1970		do_stub_add(ssl, worker, skipwhite(p+8));
1971		return;
1972	} else if(cmdcmp(p, "stub_remove", 11)) {
1973		/* must always distribute this cmd */
1974		if(rc) distribute_cmd(rc, ssl, cmd);
1975		do_stub_remove(ssl, worker, skipwhite(p+11));
1976		return;
1977	} else if(cmdcmp(p, "forward_add", 11)) {
1978		/* must always distribute this cmd */
1979		if(rc) distribute_cmd(rc, ssl, cmd);
1980		do_forward_add(ssl, worker, skipwhite(p+11));
1981		return;
1982	} else if(cmdcmp(p, "forward_remove", 14)) {
1983		/* must always distribute this cmd */
1984		if(rc) distribute_cmd(rc, ssl, cmd);
1985		do_forward_remove(ssl, worker, skipwhite(p+14));
1986		return;
1987	} else if(cmdcmp(p, "forward", 7)) {
1988		/* must always distribute this cmd */
1989		if(rc) distribute_cmd(rc, ssl, cmd);
1990		do_forward(ssl, worker, skipwhite(p+7));
1991		return;
1992	} else if(cmdcmp(p, "flush_stats", 11)) {
1993		/* must always distribute this cmd */
1994		if(rc) distribute_cmd(rc, ssl, cmd);
1995		do_flush_stats(ssl, worker);
1996		return;
1997	} else if(cmdcmp(p, "flush_requestlist", 17)) {
1998		/* must always distribute this cmd */
1999		if(rc) distribute_cmd(rc, ssl, cmd);
2000		do_flush_requestlist(ssl, worker);
2001		return;
2002	} else if(cmdcmp(p, "lookup", 6)) {
2003		do_lookup(ssl, worker, skipwhite(p+6));
2004		return;
2005	}
2006
2007#ifdef THREADS_DISABLED
2008	/* other processes must execute the command as well */
2009	/* commands that should not be distributed, returned above. */
2010	if(rc) { /* only if this thread is the master (rc) thread */
2011		/* done before the code below, which may split the string */
2012		distribute_cmd(rc, ssl, cmd);
2013	}
2014#endif
2015	if(cmdcmp(p, "verbosity", 9)) {
2016		do_verbosity(ssl, skipwhite(p+9));
2017	} else if(cmdcmp(p, "local_zone_remove", 17)) {
2018		do_zone_remove(ssl, worker, skipwhite(p+17));
2019	} else if(cmdcmp(p, "local_zone", 10)) {
2020		do_zone_add(ssl, worker, skipwhite(p+10));
2021	} else if(cmdcmp(p, "local_data_remove", 17)) {
2022		do_data_remove(ssl, worker, skipwhite(p+17));
2023	} else if(cmdcmp(p, "local_data", 10)) {
2024		do_data_add(ssl, worker, skipwhite(p+10));
2025	} else if(cmdcmp(p, "flush_zone", 10)) {
2026		do_flush_zone(ssl, worker, skipwhite(p+10));
2027	} else if(cmdcmp(p, "flush_type", 10)) {
2028		do_flush_type(ssl, worker, skipwhite(p+10));
2029	} else if(cmdcmp(p, "flush_infra", 11)) {
2030		do_flush_infra(ssl, worker, skipwhite(p+11));
2031	} else if(cmdcmp(p, "flush", 5)) {
2032		do_flush_name(ssl, worker, skipwhite(p+5));
2033	} else if(cmdcmp(p, "dump_requestlist", 16)) {
2034		do_dump_requestlist(ssl, worker);
2035	} else if(cmdcmp(p, "dump_infra", 10)) {
2036		do_dump_infra(ssl, worker);
2037	} else if(cmdcmp(p, "log_reopen", 10)) {
2038		do_log_reopen(ssl, worker);
2039	} else if(cmdcmp(p, "set_option", 10)) {
2040		do_set_option(ssl, worker, skipwhite(p+10));
2041	} else if(cmdcmp(p, "get_option", 10)) {
2042		do_get_option(ssl, worker, skipwhite(p+10));
2043	} else {
2044		(void)ssl_printf(ssl, "error unknown command '%s'\n", p);
2045	}
2046}
2047
2048void
2049daemon_remote_exec(struct worker* worker)
2050{
2051	/* read the cmd string */
2052	uint8_t* msg = NULL;
2053	uint32_t len = 0;
2054	if(!tube_read_msg(worker->cmd, &msg, &len, 0)) {
2055		log_err("daemon_remote_exec: tube_read_msg failed");
2056		return;
2057	}
2058	verbose(VERB_ALGO, "remote exec distributed: %s", (char*)msg);
2059	execute_cmd(NULL, NULL, (char*)msg, worker);
2060	free(msg);
2061}
2062
2063/** handle remote control request */
2064static void
2065handle_req(struct daemon_remote* rc, struct rc_state* s, SSL* ssl)
2066{
2067	int r;
2068	char pre[10];
2069	char magic[7];
2070	char buf[1024];
2071#ifdef USE_WINSOCK
2072	/* makes it possible to set the socket blocking again. */
2073	/* basically removes it from winsock_event ... */
2074	WSAEventSelect(s->c->fd, NULL, 0);
2075#endif
2076	fd_set_block(s->c->fd);
2077
2078	/* try to read magic UBCT[version]_space_ string */
2079	ERR_clear_error();
2080	if((r=SSL_read(ssl, magic, (int)sizeof(magic)-1)) <= 0) {
2081		if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN)
2082			return;
2083		log_crypto_err("could not SSL_read");
2084		return;
2085	}
2086	magic[6] = 0;
2087	if( r != 6 || strncmp(magic, "UBCT", 4) != 0) {
2088		verbose(VERB_QUERY, "control connection has bad magic string");
2089		/* probably wrong tool connected, ignore it completely */
2090		return;
2091	}
2092
2093	/* read the command line */
2094	if(!ssl_read_line(ssl, buf, sizeof(buf))) {
2095		return;
2096	}
2097	snprintf(pre, sizeof(pre), "UBCT%d ", UNBOUND_CONTROL_VERSION);
2098	if(strcmp(magic, pre) != 0) {
2099		verbose(VERB_QUERY, "control connection had bad "
2100			"version %s, cmd: %s", magic, buf);
2101		ssl_printf(ssl, "error version mismatch\n");
2102		return;
2103	}
2104	verbose(VERB_DETAIL, "control cmd: %s", buf);
2105
2106	/* figure out what to do */
2107	execute_cmd(rc, ssl, buf, rc->worker);
2108}
2109
2110int remote_control_callback(struct comm_point* c, void* arg, int err,
2111	struct comm_reply* ATTR_UNUSED(rep))
2112{
2113	struct rc_state* s = (struct rc_state*)arg;
2114	struct daemon_remote* rc = s->rc;
2115	int r;
2116	if(err != NETEVENT_NOERROR) {
2117		if(err==NETEVENT_TIMEOUT)
2118			log_err("remote control timed out");
2119		clean_point(rc, s);
2120		return 0;
2121	}
2122	/* (continue to) setup the SSL connection */
2123	ERR_clear_error();
2124	r = SSL_do_handshake(s->ssl);
2125	if(r != 1) {
2126		int r2 = SSL_get_error(s->ssl, r);
2127		if(r2 == SSL_ERROR_WANT_READ) {
2128			if(s->shake_state == rc_hs_read) {
2129				/* try again later */
2130				return 0;
2131			}
2132			s->shake_state = rc_hs_read;
2133			comm_point_listen_for_rw(c, 1, 0);
2134			return 0;
2135		} else if(r2 == SSL_ERROR_WANT_WRITE) {
2136			if(s->shake_state == rc_hs_write) {
2137				/* try again later */
2138				return 0;
2139			}
2140			s->shake_state = rc_hs_write;
2141			comm_point_listen_for_rw(c, 0, 1);
2142			return 0;
2143		} else {
2144			if(r == 0)
2145				log_err("remote control connection closed prematurely");
2146			log_addr(1, "failed connection from",
2147				&s->c->repinfo.addr, s->c->repinfo.addrlen);
2148			log_crypto_err("remote control failed ssl");
2149			clean_point(rc, s);
2150			return 0;
2151		}
2152	}
2153	s->shake_state = rc_none;
2154
2155	/* once handshake has completed, check authentication */
2156	if(SSL_get_verify_result(s->ssl) == X509_V_OK) {
2157		X509* x = SSL_get_peer_certificate(s->ssl);
2158		if(!x) {
2159			verbose(VERB_DETAIL, "remote control connection "
2160				"provided no client certificate");
2161			clean_point(rc, s);
2162			return 0;
2163		}
2164		verbose(VERB_ALGO, "remote control connection authenticated");
2165		X509_free(x);
2166	} else {
2167		verbose(VERB_DETAIL, "remote control connection failed to "
2168			"authenticate with client certificate");
2169		clean_point(rc, s);
2170		return 0;
2171	}
2172
2173	/* if OK start to actually handle the request */
2174	handle_req(rc, s, s->ssl);
2175
2176	verbose(VERB_ALGO, "remote control operation completed");
2177	clean_point(rc, s);
2178	return 0;
2179}
2180