2 * daemon/remote.c - remote control for the unbound daemon.
4 * Copyright (c) 2008, NLnet Labs. All rights reserved.
6 * This software is open source.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
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.
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.
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.
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 SSLv3/TLS capable web browser.
42 * The channel is secured using SSLv3 or TLSv1, and certificates.
43 * Both the server and the client(control tool) have their own keys.
46 #ifdef HAVE_OPENSSL_ERR_H
47 #include <openssl/err.h>
50 #include "daemon/remote.h"
51 #include "daemon/worker.h"
52 #include "daemon/daemon.h"
53 #include "daemon/stats.h"
54 #include "daemon/cachedump.h"
56 #include "util/config_file.h"
57 #include "util/net_help.h"
58 #include "util/module.h"
59 #include "services/listen_dnsport.h"
60 #include "services/cache/rrset.h"
61 #include "services/cache/infra.h"
62 #include "services/mesh.h"
63 #include "services/localzone.h"
64 #include "util/storage/slabhash.h"
65 #include "util/fptr_wlist.h"
66 #include "util/data/dname.h"
67 #include "validator/validator.h"
68 #include "validator/val_kcache.h"
69 #include "validator/val_kentry.h"
70 #include "validator/val_anchor.h"
71 #include "iterator/iterator.h"
72 #include "iterator/iter_fwd.h"
73 #include "iterator/iter_hints.h"
74 #include "iterator/iter_delegpt.h"
75 #include "services/outbound_list.h"
76 #include "services/outside_network.h"
77 #include "ldns/str2wire.h"
78 #include "ldns/parseutil.h"
79 #include "ldns/wire2str.h"
80 #include "ldns/sbuffer.h"
82 #ifdef HAVE_SYS_TYPES_H
83 # include <sys/types.h>
89 /* just for portability */
94 /** what to put on statistics lines between var and value, ": " or "=" */
96 /** if true, inhibits a lot of =0 lines from the stats output */
97 static const int inhibit_zero = 1;
99 /** subtract timers and the values do not overflow or become negative */
101 timeval_subtract(struct timeval* d, const struct timeval* end,
102 const struct timeval* start)
105 time_t end_usec = end->tv_usec;
106 d->tv_sec = end->tv_sec - start->tv_sec;
107 if(end_usec < start->tv_usec) {
111 d->tv_usec = end_usec - start->tv_usec;
115 /** divide sum of timers to get average */
117 timeval_divide(struct timeval* avg, const struct timeval* sum, size_t d)
126 avg->tv_sec = sum->tv_sec / d;
127 avg->tv_usec = sum->tv_usec / d;
128 /* handle fraction from seconds divide */
129 leftover = sum->tv_sec - avg->tv_sec*d;
130 avg->tv_usec += (leftover*1000000)/d;
134 struct daemon_remote*
135 daemon_remote_create(struct config_file* cfg)
139 struct daemon_remote* rc = (struct daemon_remote*)calloc(1,
142 log_err("out of memory in daemon_remote_create");
147 if(!cfg->remote_control_enable) {
151 rc->ctx = SSL_CTX_new(SSLv23_server_method());
153 log_crypto_err("could not SSL_CTX_new");
157 /* no SSLv2 because has defects */
158 if(!(SSL_CTX_set_options(rc->ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)){
159 log_crypto_err("could not set SSL_OP_NO_SSLv2");
160 daemon_remote_delete(rc);
163 s_cert = fname_after_chroot(cfg->server_cert_file, cfg, 1);
164 s_key = fname_after_chroot(cfg->server_key_file, cfg, 1);
165 if(!s_cert || !s_key) {
166 log_err("out of memory in remote control fname");
169 verbose(VERB_ALGO, "setup SSL certificates");
170 if (!SSL_CTX_use_certificate_file(rc->ctx,s_cert,SSL_FILETYPE_PEM)) {
171 log_err("Error for server-cert-file: %s", s_cert);
172 log_crypto_err("Error in SSL_CTX use_certificate_file");
175 if(!SSL_CTX_use_PrivateKey_file(rc->ctx,s_key,SSL_FILETYPE_PEM)) {
176 log_err("Error for server-key-file: %s", s_key);
177 log_crypto_err("Error in SSL_CTX use_PrivateKey_file");
180 if(!SSL_CTX_check_private_key(rc->ctx)) {
181 log_err("Error for server-key-file: %s", s_key);
182 log_crypto_err("Error in SSL_CTX check_private_key");
185 if(!SSL_CTX_load_verify_locations(rc->ctx, s_cert, NULL)) {
186 log_crypto_err("Error setting up SSL_CTX verify locations");
190 daemon_remote_delete(rc);
193 SSL_CTX_set_client_CA_list(rc->ctx, SSL_load_client_CA_file(s_cert));
194 SSL_CTX_set_verify(rc->ctx, SSL_VERIFY_PEER, NULL);
201 void daemon_remote_clear(struct daemon_remote* rc)
203 struct rc_state* p, *np;
205 /* but do not close the ports */
206 listen_list_delete(rc->accept_list);
207 rc->accept_list = NULL;
208 /* do close these sockets */
214 comm_point_delete(p->c);
218 rc->busy_list = NULL;
223 void daemon_remote_delete(struct daemon_remote* rc)
226 daemon_remote_clear(rc);
228 SSL_CTX_free(rc->ctx);
234 * Add and open a new control port
237 * @param list: list head
238 * @param noproto_is_err: if lack of protocol support is an error.
239 * @return false on failure.
242 add_open(const char* ip, int nr, struct listen_port** list, int noproto_is_err)
244 struct addrinfo hints;
245 struct addrinfo* res;
246 struct listen_port* n;
250 snprintf(port, sizeof(port), "%d", nr);
251 port[sizeof(port)-1]=0;
252 memset(&hints, 0, sizeof(hints));
253 hints.ai_socktype = SOCK_STREAM;
254 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
255 if((r = getaddrinfo(ip, port, &hints, &res)) != 0 || !res) {
257 if(!noproto_is_err && r == EAI_NONAME) {
258 /* tried to lookup the address as name */
259 return 1; /* return success, but do nothing */
261 #endif /* USE_WINSOCK */
262 log_err("control interface %s:%s getaddrinfo: %s %s",
263 ip?ip:"default", port, gai_strerror(r),
265 r==EAI_SYSTEM?(char*)strerror(errno):""
274 fd = create_tcp_accept_sock(res, 1, &noproto, 0);
276 if(fd == -1 && noproto) {
278 return 1; /* return success, but do nothing */
279 log_err("cannot open control interface %s %d : "
280 "protocol not supported", ip, nr);
284 log_err("cannot open control interface %s %d", ip, nr);
289 n = (struct listen_port*)calloc(1, sizeof(*n));
296 log_err("out of memory");
305 struct listen_port* daemon_remote_open_ports(struct config_file* cfg)
307 struct listen_port* l = NULL;
308 log_assert(cfg->remote_control_enable && cfg->control_port);
309 if(cfg->control_ifs) {
310 struct config_strlist* p;
311 for(p = cfg->control_ifs; p; p = p->next) {
312 if(!add_open(p->str, cfg->control_port, &l, 1)) {
313 listening_ports_free(l);
320 !add_open("::1", cfg->control_port, &l, 0)) {
321 listening_ports_free(l);
325 !add_open("127.0.0.1", cfg->control_port, &l, 1)) {
326 listening_ports_free(l);
333 /** open accept commpoint */
335 accept_open(struct daemon_remote* rc, int fd)
337 struct listen_list* n = (struct listen_list*)malloc(sizeof(*n));
339 log_err("out of memory");
342 n->next = rc->accept_list;
345 n->com = comm_point_create_raw(rc->worker->base, fd, 0,
346 &remote_accept_callback, rc);
349 /* keep this port open, its fd is kept in the rc portlist */
350 n->com->do_not_close = 1;
354 int daemon_remote_open_accept(struct daemon_remote* rc,
355 struct listen_port* ports, struct worker* worker)
357 struct listen_port* p;
359 for(p = ports; p; p = p->next) {
360 if(!accept_open(rc, p->fd)) {
361 log_err("could not create accept comm point");
368 void daemon_remote_stop_accept(struct daemon_remote* rc)
370 struct listen_list* p;
371 for(p=rc->accept_list; p; p=p->next) {
372 comm_point_stop_listening(p->com);
376 void daemon_remote_start_accept(struct daemon_remote* rc)
378 struct listen_list* p;
379 for(p=rc->accept_list; p; p=p->next) {
380 comm_point_start_listening(p->com, -1, -1);
384 int remote_accept_callback(struct comm_point* c, void* arg, int err,
385 struct comm_reply* ATTR_UNUSED(rep))
387 struct daemon_remote* rc = (struct daemon_remote*)arg;
388 struct sockaddr_storage addr;
392 if(err != NETEVENT_NOERROR) {
393 log_err("error %d on remote_accept_callback", err);
396 /* perform the accept */
397 newfd = comm_point_perform_accept(c, &addr, &addrlen);
400 /* create new commpoint unless we are servicing already */
401 if(rc->active >= rc->max_active) {
402 log_warn("drop incoming remote control: too many connections");
412 /* setup commpoint to service the remote control command */
413 n = (struct rc_state*)calloc(1, sizeof(*n));
415 log_err("out of memory");
418 /* start in reading state */
419 n->c = comm_point_create_raw(rc->worker->base, newfd, 0,
420 &remote_control_callback, n);
422 log_err("out of memory");
426 log_addr(VERB_QUERY, "new control connection from", &addr, addrlen);
427 n->c->do_not_close = 0;
428 comm_point_stop_listening(n->c);
429 comm_point_start_listening(n->c, -1, REMOTE_CONTROL_TCP_TIMEOUT);
430 memcpy(&n->c->repinfo.addr, &addr, addrlen);
431 n->c->repinfo.addrlen = addrlen;
432 n->shake_state = rc_hs_read;
433 n->ssl = SSL_new(rc->ctx);
435 log_crypto_err("could not SSL_new");
436 comm_point_delete(n->c);
440 SSL_set_accept_state(n->ssl);
441 (void)SSL_set_mode(n->ssl, SSL_MODE_AUTO_RETRY);
442 if(!SSL_set_fd(n->ssl, newfd)) {
443 log_crypto_err("could not SSL_set_fd");
445 comm_point_delete(n->c);
451 n->next = rc->busy_list;
455 /* perform the first nonblocking read already, for windows,
456 * so it can return wouldblock. could be faster too. */
457 (void)remote_control_callback(n->c, n, NETEVENT_NOERROR, NULL);
461 /** delete from list */
463 state_list_remove_elem(struct rc_state** list, struct comm_point* c)
466 if( (*list)->c == c) {
467 *list = (*list)->next;
470 list = &(*list)->next;
474 /** decrease active count and remove commpoint from busy list */
476 clean_point(struct daemon_remote* rc, struct rc_state* s)
478 state_list_remove_elem(&rc->busy_list, s->c);
481 SSL_shutdown(s->ssl);
484 comm_point_delete(s->c);
489 ssl_print_text(SSL* ssl, const char* text)
495 if((r=SSL_write(ssl, text, (int)strlen(text))) <= 0) {
496 if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
497 verbose(VERB_QUERY, "warning, in SSL_write, peer "
498 "closed connection");
501 log_crypto_err("could not SSL_write");
507 /** print text over the ssl connection */
509 ssl_print_vmsg(SSL* ssl, const char* format, va_list args)
512 vsnprintf(msg, sizeof(msg), format, args);
513 return ssl_print_text(ssl, msg);
516 /** printf style printing to the ssl connection */
517 int ssl_printf(SSL* ssl, const char* format, ...)
521 va_start(args, format);
522 ret = ssl_print_vmsg(ssl, format, args);
528 ssl_read_line(SSL* ssl, char* buf, size_t max)
536 if((r=SSL_read(ssl, buf+len, 1)) <= 0) {
537 if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
541 log_crypto_err("could not SSL_read");
544 if(buf[len] == '\n') {
545 /* return string without \n */
552 log_err("control line too long (%d): %s", (int)max, buf);
556 /** skip whitespace, return new pointer into string */
560 /* EOS \0 is not a space */
561 while( isspace(*str) )
566 /** send the OK to the control client */
567 static void send_ok(SSL* ssl)
569 (void)ssl_printf(ssl, "ok\n");
572 /** do the stop command */
574 do_stop(SSL* ssl, struct daemon_remote* rc)
576 rc->worker->need_to_exit = 1;
577 comm_base_exit(rc->worker->base);
581 /** do the reload command */
583 do_reload(SSL* ssl, struct daemon_remote* rc)
585 rc->worker->need_to_exit = 0;
586 comm_base_exit(rc->worker->base);
590 /** do the verbosity command */
592 do_verbosity(SSL* ssl, char* str)
595 if(val == 0 && strcmp(str, "0") != 0) {
596 ssl_printf(ssl, "error in verbosity number syntax: %s\n", str);
603 /** print stats from statinfo */
605 print_stats(SSL* ssl, const char* nm, struct stats_info* s)
608 if(!ssl_printf(ssl, "%s.num.queries"SQ"%u\n", nm,
609 (unsigned)s->svr.num_queries)) return 0;
610 if(!ssl_printf(ssl, "%s.num.cachehits"SQ"%u\n", nm,
611 (unsigned)(s->svr.num_queries
612 - s->svr.num_queries_missed_cache))) return 0;
613 if(!ssl_printf(ssl, "%s.num.cachemiss"SQ"%u\n", nm,
614 (unsigned)s->svr.num_queries_missed_cache)) return 0;
615 if(!ssl_printf(ssl, "%s.num.prefetch"SQ"%u\n", nm,
616 (unsigned)s->svr.num_queries_prefetch)) return 0;
617 if(!ssl_printf(ssl, "%s.num.recursivereplies"SQ"%u\n", nm,
618 (unsigned)s->mesh_replies_sent)) return 0;
619 if(!ssl_printf(ssl, "%s.requestlist.avg"SQ"%g\n", nm,
620 (s->svr.num_queries_missed_cache+s->svr.num_queries_prefetch)?
621 (double)s->svr.sum_query_list_size/
622 (s->svr.num_queries_missed_cache+
623 s->svr.num_queries_prefetch) : 0.0)) return 0;
624 if(!ssl_printf(ssl, "%s.requestlist.max"SQ"%u\n", nm,
625 (unsigned)s->svr.max_query_list_size)) return 0;
626 if(!ssl_printf(ssl, "%s.requestlist.overwritten"SQ"%u\n", nm,
627 (unsigned)s->mesh_jostled)) return 0;
628 if(!ssl_printf(ssl, "%s.requestlist.exceeded"SQ"%u\n", nm,
629 (unsigned)s->mesh_dropped)) return 0;
630 if(!ssl_printf(ssl, "%s.requestlist.current.all"SQ"%u\n", nm,
631 (unsigned)s->mesh_num_states)) return 0;
632 if(!ssl_printf(ssl, "%s.requestlist.current.user"SQ"%u\n", nm,
633 (unsigned)s->mesh_num_reply_states)) return 0;
634 timeval_divide(&avg, &s->mesh_replies_sum_wait, s->mesh_replies_sent);
635 if(!ssl_printf(ssl, "%s.recursion.time.avg"SQ ARG_LL "d.%6.6d\n", nm,
636 (long long)avg.tv_sec, (int)avg.tv_usec)) return 0;
637 if(!ssl_printf(ssl, "%s.recursion.time.median"SQ"%g\n", nm,
638 s->mesh_time_median)) return 0;
642 /** print stats for one thread */
644 print_thread_stats(SSL* ssl, int i, struct stats_info* s)
647 snprintf(nm, sizeof(nm), "thread%d", i);
649 return print_stats(ssl, nm, s);
652 /** print long number */
654 print_longnum(SSL* ssl, const char* desc, size_t x)
656 if(x > 1024*1024*1024) {
658 size_t front = x / (size_t)1000000;
659 size_t back = x % (size_t)1000000;
660 return ssl_printf(ssl, "%s%u%6.6u\n", desc,
661 (unsigned)front, (unsigned)back);
663 return ssl_printf(ssl, "%s%u\n", desc, (unsigned)x);
667 /** print mem stats */
669 print_mem(SSL* ssl, struct worker* worker, struct daemon* daemon)
672 size_t msg, rrset, val, iter;
674 extern void* unbound_start_brk;
676 if(!print_longnum(ssl, "mem.total.sbrk"SQ,
677 (size_t)((char*)cur - (char*)unbound_start_brk))) return 0;
678 #endif /* HAVE_SBRK */
679 msg = slabhash_get_mem(daemon->env->msg_cache);
680 rrset = slabhash_get_mem(&daemon->env->rrset_cache->table);
683 m = modstack_find(&worker->env.mesh->mods, "validator");
685 fptr_ok(fptr_whitelist_mod_get_mem(worker->env.mesh->
686 mods.mod[m]->get_mem));
687 val = (*worker->env.mesh->mods.mod[m]->get_mem)
690 m = modstack_find(&worker->env.mesh->mods, "iterator");
692 fptr_ok(fptr_whitelist_mod_get_mem(worker->env.mesh->
693 mods.mod[m]->get_mem));
694 iter = (*worker->env.mesh->mods.mod[m]->get_mem)
698 if(!print_longnum(ssl, "mem.cache.rrset"SQ, rrset))
700 if(!print_longnum(ssl, "mem.cache.message"SQ, msg))
702 if(!print_longnum(ssl, "mem.mod.iterator"SQ, iter))
704 if(!print_longnum(ssl, "mem.mod.validator"SQ, val))
709 /** print uptime stats */
711 print_uptime(SSL* ssl, struct worker* worker, int reset)
713 struct timeval now = *worker->env.now_tv;
714 struct timeval up, dt;
715 timeval_subtract(&up, &now, &worker->daemon->time_boot);
716 timeval_subtract(&dt, &now, &worker->daemon->time_last_stat);
718 worker->daemon->time_last_stat = now;
719 if(!ssl_printf(ssl, "time.now"SQ ARG_LL "d.%6.6d\n",
720 (long long)now.tv_sec, (unsigned)now.tv_usec)) return 0;
721 if(!ssl_printf(ssl, "time.up"SQ ARG_LL "d.%6.6d\n",
722 (long long)up.tv_sec, (unsigned)up.tv_usec)) return 0;
723 if(!ssl_printf(ssl, "time.elapsed"SQ ARG_LL "d.%6.6d\n",
724 (long long)dt.tv_sec, (unsigned)dt.tv_usec)) return 0;
728 /** print extended histogram */
730 print_hist(SSL* ssl, struct stats_info* s)
732 struct timehist* hist;
734 hist = timehist_setup();
736 log_err("out of memory");
739 timehist_import(hist, s->svr.hist, NUM_BUCKETS_HIST);
740 for(i=0; i<hist->num; i++) {
742 "histogram.%6.6d.%6.6d.to.%6.6d.%6.6d=%u\n",
743 (int)hist->buckets[i].lower.tv_sec,
744 (int)hist->buckets[i].lower.tv_usec,
745 (int)hist->buckets[i].upper.tv_sec,
746 (int)hist->buckets[i].upper.tv_usec,
747 (unsigned)hist->buckets[i].count)) {
748 timehist_delete(hist);
752 timehist_delete(hist);
756 /** print extended stats */
758 print_ext(SSL* ssl, struct stats_info* s)
762 const sldns_rr_descriptor* desc;
763 const sldns_lookup_table* lt;
765 for(i=0; i<STATS_QTYPE_NUM; i++) {
766 if(inhibit_zero && s->svr.qtype[i] == 0)
768 desc = sldns_rr_descript((uint16_t)i);
769 if(desc && desc->_name) {
770 snprintf(nm, sizeof(nm), "%s", desc->_name);
771 } else if (i == LDNS_RR_TYPE_IXFR) {
772 snprintf(nm, sizeof(nm), "IXFR");
773 } else if (i == LDNS_RR_TYPE_AXFR) {
774 snprintf(nm, sizeof(nm), "AXFR");
775 } else if (i == LDNS_RR_TYPE_MAILA) {
776 snprintf(nm, sizeof(nm), "MAILA");
777 } else if (i == LDNS_RR_TYPE_MAILB) {
778 snprintf(nm, sizeof(nm), "MAILB");
779 } else if (i == LDNS_RR_TYPE_ANY) {
780 snprintf(nm, sizeof(nm), "ANY");
782 snprintf(nm, sizeof(nm), "TYPE%d", i);
784 if(!ssl_printf(ssl, "num.query.type.%s"SQ"%u\n",
785 nm, (unsigned)s->svr.qtype[i])) return 0;
787 if(!inhibit_zero || s->svr.qtype_big) {
788 if(!ssl_printf(ssl, "num.query.type.other"SQ"%u\n",
789 (unsigned)s->svr.qtype_big)) return 0;
792 for(i=0; i<STATS_QCLASS_NUM; i++) {
793 if(inhibit_zero && s->svr.qclass[i] == 0)
795 lt = sldns_lookup_by_id(sldns_rr_classes, i);
797 snprintf(nm, sizeof(nm), "%s", lt->name);
799 snprintf(nm, sizeof(nm), "CLASS%d", i);
801 if(!ssl_printf(ssl, "num.query.class.%s"SQ"%u\n",
802 nm, (unsigned)s->svr.qclass[i])) return 0;
804 if(!inhibit_zero || s->svr.qclass_big) {
805 if(!ssl_printf(ssl, "num.query.class.other"SQ"%u\n",
806 (unsigned)s->svr.qclass_big)) return 0;
809 for(i=0; i<STATS_OPCODE_NUM; i++) {
810 if(inhibit_zero && s->svr.qopcode[i] == 0)
812 lt = sldns_lookup_by_id(sldns_opcodes, i);
814 snprintf(nm, sizeof(nm), "%s", lt->name);
816 snprintf(nm, sizeof(nm), "OPCODE%d", i);
818 if(!ssl_printf(ssl, "num.query.opcode.%s"SQ"%u\n",
819 nm, (unsigned)s->svr.qopcode[i])) return 0;
822 if(!ssl_printf(ssl, "num.query.tcp"SQ"%u\n",
823 (unsigned)s->svr.qtcp)) return 0;
824 if(!ssl_printf(ssl, "num.query.ipv6"SQ"%u\n",
825 (unsigned)s->svr.qipv6)) return 0;
827 if(!ssl_printf(ssl, "num.query.flags.QR"SQ"%u\n",
828 (unsigned)s->svr.qbit_QR)) return 0;
829 if(!ssl_printf(ssl, "num.query.flags.AA"SQ"%u\n",
830 (unsigned)s->svr.qbit_AA)) return 0;
831 if(!ssl_printf(ssl, "num.query.flags.TC"SQ"%u\n",
832 (unsigned)s->svr.qbit_TC)) return 0;
833 if(!ssl_printf(ssl, "num.query.flags.RD"SQ"%u\n",
834 (unsigned)s->svr.qbit_RD)) return 0;
835 if(!ssl_printf(ssl, "num.query.flags.RA"SQ"%u\n",
836 (unsigned)s->svr.qbit_RA)) return 0;
837 if(!ssl_printf(ssl, "num.query.flags.Z"SQ"%u\n",
838 (unsigned)s->svr.qbit_Z)) return 0;
839 if(!ssl_printf(ssl, "num.query.flags.AD"SQ"%u\n",
840 (unsigned)s->svr.qbit_AD)) return 0;
841 if(!ssl_printf(ssl, "num.query.flags.CD"SQ"%u\n",
842 (unsigned)s->svr.qbit_CD)) return 0;
843 if(!ssl_printf(ssl, "num.query.edns.present"SQ"%u\n",
844 (unsigned)s->svr.qEDNS)) return 0;
845 if(!ssl_printf(ssl, "num.query.edns.DO"SQ"%u\n",
846 (unsigned)s->svr.qEDNS_DO)) return 0;
849 for(i=0; i<STATS_RCODE_NUM; i++) {
850 if(inhibit_zero && s->svr.ans_rcode[i] == 0)
852 lt = sldns_lookup_by_id(sldns_rcodes, i);
854 snprintf(nm, sizeof(nm), "%s", lt->name);
856 snprintf(nm, sizeof(nm), "RCODE%d", i);
858 if(!ssl_printf(ssl, "num.answer.rcode.%s"SQ"%u\n",
859 nm, (unsigned)s->svr.ans_rcode[i])) return 0;
861 if(!inhibit_zero || s->svr.ans_rcode_nodata) {
862 if(!ssl_printf(ssl, "num.answer.rcode.nodata"SQ"%u\n",
863 (unsigned)s->svr.ans_rcode_nodata)) return 0;
866 if(!ssl_printf(ssl, "num.answer.secure"SQ"%u\n",
867 (unsigned)s->svr.ans_secure)) return 0;
868 if(!ssl_printf(ssl, "num.answer.bogus"SQ"%u\n",
869 (unsigned)s->svr.ans_bogus)) return 0;
870 if(!ssl_printf(ssl, "num.rrset.bogus"SQ"%u\n",
871 (unsigned)s->svr.rrset_bogus)) return 0;
872 /* threat detection */
873 if(!ssl_printf(ssl, "unwanted.queries"SQ"%u\n",
874 (unsigned)s->svr.unwanted_queries)) return 0;
875 if(!ssl_printf(ssl, "unwanted.replies"SQ"%u\n",
876 (unsigned)s->svr.unwanted_replies)) return 0;
880 /** do the stats command */
882 do_stats(SSL* ssl, struct daemon_remote* rc, int reset)
884 struct daemon* daemon = rc->worker->daemon;
885 struct stats_info total;
888 log_assert(daemon->num > 0);
889 /* gather all thread statistics in one place */
890 for(i=0; i<daemon->num; i++) {
891 server_stats_obtain(rc->worker, daemon->workers[i], &s, reset);
892 if(!print_thread_stats(ssl, i, &s))
896 else server_stats_add(&total, &s);
898 /* print the thread statistics */
899 total.mesh_time_median /= (double)daemon->num;
900 if(!print_stats(ssl, "total", &total))
902 if(!print_uptime(ssl, rc->worker, reset))
904 if(daemon->cfg->stat_extended) {
905 if(!print_mem(ssl, rc->worker, daemon))
907 if(!print_hist(ssl, &total))
909 if(!print_ext(ssl, &total))
914 /** parse commandline argument domain name */
916 parse_arg_name(SSL* ssl, char* str, uint8_t** res, size_t* len, int* labs)
918 uint8_t nm[LDNS_MAX_DOMAINLEN+1];
919 size_t nmlen = sizeof(nm);
924 status = sldns_str2wire_dname_buf(str, nm, &nmlen);
926 ssl_printf(ssl, "error cannot parse name %s at %d: %s\n", str,
927 LDNS_WIREPARSE_OFFSET(status),
928 sldns_get_errorstr_parse(status));
931 *res = memdup(nm, nmlen);
933 ssl_printf(ssl, "error out of memory\n");
936 *labs = dname_count_size_labels(*res, len);
940 /** find second argument, modifies string */
942 find_arg2(SSL* ssl, char* arg, char** arg2)
944 char* as = strchr(arg, ' ');
945 char* at = strchr(arg, '\t');
950 *arg2 = skipwhite(as+1);
953 *arg2 = skipwhite(as+1);
956 *arg2 = skipwhite(at+1);
958 ssl_printf(ssl, "error could not find next argument "
965 /** Add a new zone */
967 do_zone_add(SSL* ssl, struct worker* worker, char* arg)
973 enum localzone_type t;
974 struct local_zone* z;
975 if(!find_arg2(ssl, arg, &arg2))
977 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
979 if(!local_zone_str2type(arg2, &t)) {
980 ssl_printf(ssl, "error not a zone type. %s\n", arg2);
984 lock_rw_wrlock(&worker->daemon->local_zones->lock);
985 if((z=local_zones_find(worker->daemon->local_zones, nm, nmlen,
986 nmlabs, LDNS_RR_CLASS_IN))) {
987 /* already present in tree */
988 lock_rw_wrlock(&z->lock);
989 z->type = t; /* update type anyway */
990 lock_rw_unlock(&z->lock);
992 lock_rw_unlock(&worker->daemon->local_zones->lock);
996 if(!local_zones_add_zone(worker->daemon->local_zones, nm, nmlen,
997 nmlabs, LDNS_RR_CLASS_IN, t)) {
998 lock_rw_unlock(&worker->daemon->local_zones->lock);
999 ssl_printf(ssl, "error out of memory\n");
1002 lock_rw_unlock(&worker->daemon->local_zones->lock);
1006 /** Remove a zone */
1008 do_zone_remove(SSL* ssl, struct worker* worker, char* arg)
1013 struct local_zone* z;
1014 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1016 lock_rw_wrlock(&worker->daemon->local_zones->lock);
1017 if((z=local_zones_find(worker->daemon->local_zones, nm, nmlen,
1018 nmlabs, LDNS_RR_CLASS_IN))) {
1019 /* present in tree */
1020 local_zones_del_zone(worker->daemon->local_zones, z);
1022 lock_rw_unlock(&worker->daemon->local_zones->lock);
1027 /** Add new RR data */
1029 do_data_add(SSL* ssl, struct worker* worker, char* arg)
1031 if(!local_zones_add_RR(worker->daemon->local_zones, arg)) {
1032 ssl_printf(ssl,"error in syntax or out of memory, %s\n", arg);
1038 /** Remove RR data */
1040 do_data_remove(SSL* ssl, struct worker* worker, char* arg)
1045 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1047 local_zones_del_data(worker->daemon->local_zones, nm,
1048 nmlen, nmlabs, LDNS_RR_CLASS_IN);
1053 /** cache lookup of nameservers */
1055 do_lookup(SSL* ssl, struct worker* worker, char* arg)
1060 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1062 (void)print_deleg_lookup(ssl, worker, nm, nmlen, nmlabs);
1066 /** flush something from rrset and msg caches */
1068 do_cache_remove(struct worker* worker, uint8_t* nm, size_t nmlen,
1069 uint16_t t, uint16_t c)
1072 struct query_info k;
1073 rrset_cache_remove(worker->env.rrset_cache, nm, nmlen, t, c, 0);
1074 if(t == LDNS_RR_TYPE_SOA)
1075 rrset_cache_remove(worker->env.rrset_cache, nm, nmlen, t, c,
1076 PACKED_RRSET_SOA_NEG);
1078 k.qname_len = nmlen;
1081 h = query_info_hash(&k);
1082 slabhash_remove(worker->env.msg_cache, h, &k);
1087 do_flush_type(SSL* ssl, struct worker* worker, char* arg)
1094 if(!find_arg2(ssl, arg, &arg2))
1096 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1098 t = sldns_get_rr_type_by_name(arg2);
1099 do_cache_remove(worker, nm, nmlen, t, LDNS_RR_CLASS_IN);
1105 /** flush statistics */
1107 do_flush_stats(SSL* ssl, struct worker* worker)
1109 worker_stats_clear(worker);
1114 * Local info for deletion functions
1118 struct worker* worker;
1119 /** name to delete */
1127 /** time to invalidate to */
1129 /** number of rrsets removed */
1131 /** number of msgs removed */
1133 /** number of key entries removed */
1135 /** length of addr */
1137 /** socket address for host deletion */
1138 struct sockaddr_storage addr;
1141 /** callback to delete hosts in infra cache */
1143 infra_del_host(struct lruhash_entry* e, void* arg)
1145 /* entry is locked */
1146 struct del_info* inf = (struct del_info*)arg;
1147 struct infra_key* k = (struct infra_key*)e->key;
1148 if(sockaddr_cmp(&inf->addr, inf->addrlen, &k->addr, k->addrlen) == 0) {
1149 struct infra_data* d = (struct infra_data*)e->data;
1152 d->timeout_AAAA = 0;
1153 d->timeout_other = 0;
1155 if(d->ttl >= inf->now) {
1156 d->ttl = inf->expired;
1162 /** flush infra cache */
1164 do_flush_infra(SSL* ssl, struct worker* worker, char* arg)
1166 struct sockaddr_storage addr;
1168 struct del_info inf;
1169 if(strcmp(arg, "all") == 0) {
1170 slabhash_clear(worker->env.infra_cache->hosts);
1174 if(!ipstrtoaddr(arg, UNBOUND_DNS_PORT, &addr, &len)) {
1175 (void)ssl_printf(ssl, "error parsing ip addr: '%s'\n", arg);
1178 /* delete all entries from cache */
1179 /* what we do is to set them all expired */
1180 inf.worker = worker;
1184 inf.now = *worker->env.now;
1185 inf.expired = *worker->env.now;
1186 inf.expired -= 3; /* handle 3 seconds skew between threads */
1191 memmove(&inf.addr, &addr, len);
1192 slabhash_traverse(worker->env.infra_cache->hosts, 1, &infra_del_host,
1197 /** flush requestlist */
1199 do_flush_requestlist(SSL* ssl, struct worker* worker)
1201 mesh_delete_all(worker->env.mesh);
1205 /** callback to delete rrsets in a zone */
1207 zone_del_rrset(struct lruhash_entry* e, void* arg)
1209 /* entry is locked */
1210 struct del_info* inf = (struct del_info*)arg;
1211 struct ub_packed_rrset_key* k = (struct ub_packed_rrset_key*)e->key;
1212 if(dname_subdomain_c(k->rk.dname, inf->name)) {
1213 struct packed_rrset_data* d =
1214 (struct packed_rrset_data*)e->data;
1215 if(d->ttl >= inf->now) {
1216 d->ttl = inf->expired;
1222 /** callback to delete messages in a zone */
1224 zone_del_msg(struct lruhash_entry* e, void* arg)
1226 /* entry is locked */
1227 struct del_info* inf = (struct del_info*)arg;
1228 struct msgreply_entry* k = (struct msgreply_entry*)e->key;
1229 if(dname_subdomain_c(k->key.qname, inf->name)) {
1230 struct reply_info* d = (struct reply_info*)e->data;
1231 if(d->ttl >= inf->now) {
1232 d->ttl = inf->expired;
1238 /** callback to delete keys in zone */
1240 zone_del_kcache(struct lruhash_entry* e, void* arg)
1242 /* entry is locked */
1243 struct del_info* inf = (struct del_info*)arg;
1244 struct key_entry_key* k = (struct key_entry_key*)e->key;
1245 if(dname_subdomain_c(k->name, inf->name)) {
1246 struct key_entry_data* d = (struct key_entry_data*)e->data;
1247 if(d->ttl >= inf->now) {
1248 d->ttl = inf->expired;
1254 /** remove all rrsets and keys from zone from cache */
1256 do_flush_zone(SSL* ssl, struct worker* worker, char* arg)
1261 struct del_info inf;
1262 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1264 /* delete all RRs and key entries from zone */
1265 /* what we do is to set them all expired */
1266 inf.worker = worker;
1270 inf.now = *worker->env.now;
1271 inf.expired = *worker->env.now;
1272 inf.expired -= 3; /* handle 3 seconds skew between threads */
1276 slabhash_traverse(&worker->env.rrset_cache->table, 1,
1277 &zone_del_rrset, &inf);
1279 slabhash_traverse(worker->env.msg_cache, 1, &zone_del_msg, &inf);
1281 /* and validator cache */
1282 if(worker->env.key_cache) {
1283 slabhash_traverse(worker->env.key_cache->slab, 1,
1284 &zone_del_kcache, &inf);
1289 (void)ssl_printf(ssl, "ok removed %u rrsets, %u messages "
1290 "and %u key entries\n", (unsigned)inf.num_rrsets,
1291 (unsigned)inf.num_msgs, (unsigned)inf.num_keys);
1294 /** callback to delete bogus rrsets */
1296 bogus_del_rrset(struct lruhash_entry* e, void* arg)
1298 /* entry is locked */
1299 struct del_info* inf = (struct del_info*)arg;
1300 struct packed_rrset_data* d = (struct packed_rrset_data*)e->data;
1301 if(d->security == sec_status_bogus) {
1302 d->ttl = inf->expired;
1307 /** callback to delete bogus messages */
1309 bogus_del_msg(struct lruhash_entry* e, void* arg)
1311 /* entry is locked */
1312 struct del_info* inf = (struct del_info*)arg;
1313 struct reply_info* d = (struct reply_info*)e->data;
1314 if(d->security == sec_status_bogus) {
1315 d->ttl = inf->expired;
1320 /** callback to delete bogus keys */
1322 bogus_del_kcache(struct lruhash_entry* e, void* arg)
1324 /* entry is locked */
1325 struct del_info* inf = (struct del_info*)arg;
1326 struct key_entry_data* d = (struct key_entry_data*)e->data;
1328 d->ttl = inf->expired;
1333 /** remove all rrsets and keys from zone from cache */
1335 do_flush_bogus(SSL* ssl, struct worker* worker)
1337 struct del_info inf;
1338 /* what we do is to set them all expired */
1339 inf.worker = worker;
1340 inf.now = *worker->env.now;
1341 inf.expired = *worker->env.now;
1342 inf.expired -= 3; /* handle 3 seconds skew between threads */
1346 slabhash_traverse(&worker->env.rrset_cache->table, 1,
1347 &bogus_del_rrset, &inf);
1349 slabhash_traverse(worker->env.msg_cache, 1, &bogus_del_msg, &inf);
1351 /* and validator cache */
1352 if(worker->env.key_cache) {
1353 slabhash_traverse(worker->env.key_cache->slab, 1,
1354 &bogus_del_kcache, &inf);
1357 (void)ssl_printf(ssl, "ok removed %u rrsets, %u messages "
1358 "and %u key entries\n", (unsigned)inf.num_rrsets,
1359 (unsigned)inf.num_msgs, (unsigned)inf.num_keys);
1362 /** remove name rrset from cache */
1364 do_flush_name(SSL* ssl, struct worker* w, char* arg)
1369 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1371 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_A, LDNS_RR_CLASS_IN);
1372 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_AAAA, LDNS_RR_CLASS_IN);
1373 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_NS, LDNS_RR_CLASS_IN);
1374 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SOA, LDNS_RR_CLASS_IN);
1375 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_CNAME, LDNS_RR_CLASS_IN);
1376 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_DNAME, LDNS_RR_CLASS_IN);
1377 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_MX, LDNS_RR_CLASS_IN);
1378 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_PTR, LDNS_RR_CLASS_IN);
1379 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SRV, LDNS_RR_CLASS_IN);
1380 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_NAPTR, LDNS_RR_CLASS_IN);
1386 /** printout a delegation point info */
1388 ssl_print_name_dp(SSL* ssl, const char* str, uint8_t* nm, uint16_t dclass,
1392 struct delegpt_ns* ns;
1393 struct delegpt_addr* a;
1395 if(str) { /* print header for forward, stub */
1396 char* c = sldns_wire2str_class(dclass);
1398 if(!ssl_printf(ssl, "%s %s %s: ", buf, (c?c:"CLASS??"), str)) {
1404 for(ns = dp->nslist; ns; ns = ns->next) {
1405 dname_str(ns->name, buf);
1406 if(!ssl_printf(ssl, "%s%s", (f?" ":""), buf))
1410 for(a = dp->target_list; a; a = a->next_target) {
1411 addr_to_str(&a->addr, a->addrlen, buf, sizeof(buf));
1412 if(!ssl_printf(ssl, "%s%s", (f?" ":""), buf))
1416 return ssl_printf(ssl, "\n");
1420 /** print root forwards */
1422 print_root_fwds(SSL* ssl, struct iter_forwards* fwds, uint8_t* root)
1425 dp = forwards_lookup(fwds, root, LDNS_RR_CLASS_IN);
1427 return ssl_printf(ssl, "off (using root hints)\n");
1428 /* if dp is returned it must be the root */
1429 log_assert(query_dname_compare(dp->name, root)==0);
1430 return ssl_print_name_dp(ssl, NULL, root, LDNS_RR_CLASS_IN, dp);
1433 /** parse args into delegpt */
1434 static struct delegpt*
1435 parse_delegpt(SSL* ssl, char* args, uint8_t* nm, int allow_names)
1437 /* parse args and add in */
1440 struct delegpt* dp = delegpt_create_mlc(nm);
1441 struct sockaddr_storage addr;
1444 (void)ssl_printf(ssl, "error out of memory\n");
1449 p = strchr(p, ' '); /* find next spot, if any */
1451 *p++ = 0; /* end this spot */
1452 p = skipwhite(p); /* position at next spot */
1455 if(!extstrtoaddr(todo, &addr, &addrlen)) {
1460 if(!parse_arg_name(ssl, todo, &n, &ln, &lb)) {
1461 (void)ssl_printf(ssl, "error cannot "
1462 "parse IP address or name "
1464 delegpt_free_mlc(dp);
1467 if(!delegpt_add_ns_mlc(dp, n, 0)) {
1468 (void)ssl_printf(ssl, "error out of memory\n");
1470 delegpt_free_mlc(dp);
1476 (void)ssl_printf(ssl, "error cannot parse"
1477 " IP address '%s'\n", todo);
1478 delegpt_free_mlc(dp);
1483 if(!delegpt_add_addr_mlc(dp, &addr, addrlen, 0, 0)) {
1484 (void)ssl_printf(ssl, "error out of memory\n");
1485 delegpt_free_mlc(dp);
1493 /** do the status command */
1495 do_forward(SSL* ssl, struct worker* worker, char* args)
1497 struct iter_forwards* fwd = worker->env.fwds;
1498 uint8_t* root = (uint8_t*)"\000";
1500 (void)ssl_printf(ssl, "error: structure not allocated\n");
1503 if(args == NULL || args[0] == 0) {
1504 (void)print_root_fwds(ssl, fwd, root);
1507 /* set root forwards for this thread. since we are in remote control
1508 * the actual mesh is not running, so we can freely edit it. */
1509 /* delete all the existing queries first */
1510 mesh_delete_all(worker->env.mesh);
1511 if(strcmp(args, "off") == 0) {
1512 forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, root);
1515 if(!(dp = parse_delegpt(ssl, args, root, 0)))
1517 if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp)) {
1518 (void)ssl_printf(ssl, "error out of memory\n");
1526 parse_fs_args(SSL* ssl, char* args, uint8_t** nm, struct delegpt** dp,
1527 int* insecure, int* prime)
1533 /* parse all -x args */
1534 while(args[0] == '+') {
1535 if(!find_arg2(ssl, args, &rest))
1537 while(*(++args) != 0) {
1538 if(*args == 'i' && insecure)
1540 else if(*args == 'p' && prime)
1543 (void)ssl_printf(ssl, "error: unknown option %s\n", args);
1551 if(!find_arg2(ssl, args, &rest))
1555 } else zonename = args;
1556 if(!parse_arg_name(ssl, zonename, nm, &nmlen, &nmlabs))
1561 if(!(*dp = parse_delegpt(ssl, args, *nm, 1))) {
1569 /** do the forward_add command */
1571 do_forward_add(SSL* ssl, struct worker* worker, char* args)
1573 struct iter_forwards* fwd = worker->env.fwds;
1576 struct delegpt* dp = NULL;
1577 if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, NULL))
1579 if(insecure && worker->env.anchors) {
1580 if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
1582 (void)ssl_printf(ssl, "error out of memory\n");
1583 delegpt_free_mlc(dp);
1588 if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp)) {
1589 (void)ssl_printf(ssl, "error out of memory\n");
1597 /** do the forward_remove command */
1599 do_forward_remove(SSL* ssl, struct worker* worker, char* args)
1601 struct iter_forwards* fwd = worker->env.fwds;
1604 if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL))
1606 if(insecure && worker->env.anchors)
1607 anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
1609 forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, nm);
1614 /** do the stub_add command */
1616 do_stub_add(SSL* ssl, struct worker* worker, char* args)
1618 struct iter_forwards* fwd = worker->env.fwds;
1619 int insecure = 0, prime = 0;
1621 struct delegpt* dp = NULL;
1622 if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, &prime))
1624 if(insecure && worker->env.anchors) {
1625 if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
1627 (void)ssl_printf(ssl, "error out of memory\n");
1628 delegpt_free_mlc(dp);
1633 if(!forwards_add_stub_hole(fwd, LDNS_RR_CLASS_IN, nm)) {
1634 if(insecure && worker->env.anchors)
1635 anchors_delete_insecure(worker->env.anchors,
1636 LDNS_RR_CLASS_IN, nm);
1637 (void)ssl_printf(ssl, "error out of memory\n");
1638 delegpt_free_mlc(dp);
1642 if(!hints_add_stub(worker->env.hints, LDNS_RR_CLASS_IN, dp, !prime)) {
1643 (void)ssl_printf(ssl, "error out of memory\n");
1644 forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm);
1645 if(insecure && worker->env.anchors)
1646 anchors_delete_insecure(worker->env.anchors,
1647 LDNS_RR_CLASS_IN, nm);
1655 /** do the stub_remove command */
1657 do_stub_remove(SSL* ssl, struct worker* worker, char* args)
1659 struct iter_forwards* fwd = worker->env.fwds;
1662 if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL))
1664 if(insecure && worker->env.anchors)
1665 anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
1667 forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm);
1668 hints_delete_stub(worker->env.hints, LDNS_RR_CLASS_IN, nm);
1673 /** do the insecure_add command */
1675 do_insecure_add(SSL* ssl, struct worker* worker, char* arg)
1680 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1682 if(worker->env.anchors) {
1683 if(!anchors_add_insecure(worker->env.anchors,
1684 LDNS_RR_CLASS_IN, nm)) {
1685 (void)ssl_printf(ssl, "error out of memory\n");
1694 /** do the insecure_remove command */
1696 do_insecure_remove(SSL* ssl, struct worker* worker, char* arg)
1701 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1703 if(worker->env.anchors)
1704 anchors_delete_insecure(worker->env.anchors,
1705 LDNS_RR_CLASS_IN, nm);
1710 /** do the status command */
1712 do_status(SSL* ssl, struct worker* worker)
1716 if(!ssl_printf(ssl, "version: %s\n", PACKAGE_VERSION))
1718 if(!ssl_printf(ssl, "verbosity: %d\n", verbosity))
1720 if(!ssl_printf(ssl, "threads: %d\n", worker->daemon->num))
1722 if(!ssl_printf(ssl, "modules: %d [", worker->daemon->mods.num))
1724 for(i=0; i<worker->daemon->mods.num; i++) {
1725 if(!ssl_printf(ssl, " %s", worker->daemon->mods.mod[i]->name))
1728 if(!ssl_printf(ssl, " ]\n"))
1730 uptime = (time_t)time(NULL) - (time_t)worker->daemon->time_boot.tv_sec;
1731 if(!ssl_printf(ssl, "uptime: " ARG_LL "d seconds\n", (long long)uptime))
1733 if(!ssl_printf(ssl, "unbound (pid %d) is running...\n",
1738 /** get age for the mesh state */
1740 get_mesh_age(struct mesh_state* m, char* buf, size_t len,
1741 struct module_env* env)
1745 struct mesh_reply* r = m->reply_list;
1746 /* last reply is the oldest */
1749 timeval_subtract(&d, env->now_tv, &r->start_time);
1750 snprintf(buf, len, ARG_LL "d.%6.6d",
1751 (long long)d.tv_sec, (int)d.tv_usec);
1753 snprintf(buf, len, "-");
1757 /** get status of a mesh state */
1759 get_mesh_status(struct mesh_area* mesh, struct mesh_state* m,
1760 char* buf, size_t len)
1762 enum module_ext_state s = m->s.ext_state[m->s.curmod];
1763 const char *modname = mesh->mods.mod[m->s.curmod]->name;
1765 if(strcmp(modname, "iterator") == 0 && s == module_wait_reply &&
1766 m->s.minfo[m->s.curmod]) {
1767 /* break into iterator to find out who its waiting for */
1768 struct iter_qstate* qstate = (struct iter_qstate*)
1769 m->s.minfo[m->s.curmod];
1770 struct outbound_list* ol = &qstate->outlist;
1771 struct outbound_entry* e;
1772 snprintf(buf, len, "%s wait for", modname);
1775 if(ol->first == NULL)
1776 snprintf(buf, len, " (empty_list)");
1777 for(e = ol->first; e; e = e->next) {
1778 snprintf(buf, len, " ");
1781 addr_to_str(&e->qsent->addr, e->qsent->addrlen,
1786 } else if(s == module_wait_subquery) {
1787 /* look in subs from mesh state to see what */
1789 struct mesh_state_ref* sub;
1790 snprintf(buf, len, "%s wants", modname);
1793 if(m->sub_set.count == 0)
1794 snprintf(buf, len, " (empty_list)");
1795 RBTREE_FOR(sub, struct mesh_state_ref*, &m->sub_set) {
1796 char* t = sldns_wire2str_type(sub->s->s.qinfo.qtype);
1797 char* c = sldns_wire2str_class(sub->s->s.qinfo.qclass);
1798 dname_str(sub->s->s.qinfo.qname, nm);
1799 snprintf(buf, len, " %s %s %s", (t?t:"TYPE??"),
1800 (c?c:"CLASS??"), nm);
1807 snprintf(buf, len, "%s is %s", modname, strextstate(s));
1811 /** do the dump_requestlist command */
1813 do_dump_requestlist(SSL* ssl, struct worker* worker)
1815 struct mesh_area* mesh;
1816 struct mesh_state* m;
1820 char statbuf[10240];
1821 if(!ssl_printf(ssl, "thread #%d\n", worker->thread_num))
1823 if(!ssl_printf(ssl, "# type cl name seconds module status\n"))
1825 /* show worker mesh contents */
1826 mesh = worker->env.mesh;
1828 RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
1829 char* t = sldns_wire2str_type(m->s.qinfo.qtype);
1830 char* c = sldns_wire2str_class(m->s.qinfo.qclass);
1831 dname_str(m->s.qinfo.qname, buf);
1832 get_mesh_age(m, timebuf, sizeof(timebuf), &worker->env);
1833 get_mesh_status(mesh, m, statbuf, sizeof(statbuf));
1834 if(!ssl_printf(ssl, "%3d %4s %2s %s %s %s\n",
1835 num, (t?t:"TYPE??"), (c?c:"CLASS??"), buf, timebuf,
1847 /** structure for argument data for dump infra host */
1849 /** the infra cache */
1850 struct infra_cache* infra;
1851 /** the SSL connection */
1857 /** callback for every host element in the infra cache */
1859 dump_infra_host(struct lruhash_entry* e, void* arg)
1861 struct infra_arg* a = (struct infra_arg*)arg;
1862 struct infra_key* k = (struct infra_key*)e->key;
1863 struct infra_data* d = (struct infra_data*)e->data;
1866 addr_to_str(&k->addr, k->addrlen, ip_str, sizeof(ip_str));
1867 dname_str(k->zonename, name);
1868 /* skip expired stuff (only backed off) */
1869 if(d->ttl < a->now) {
1870 if(d->rtt.rto >= USEFUL_SERVER_TOP_TIMEOUT) {
1871 if(!ssl_printf(a->ssl, "%s %s expired rto %d\n", ip_str,
1872 name, d->rtt.rto)) return;
1876 if(!ssl_printf(a->ssl, "%s %s ttl %d ping %d var %d rtt %d rto %d "
1877 "tA %d tAAAA %d tother %d "
1878 "ednsknown %d edns %d delay %d lame dnssec %d rec %d A %d "
1879 "other %d\n", ip_str, name, (int)(d->ttl - a->now),
1880 d->rtt.srtt, d->rtt.rttvar, rtt_notimeout(&d->rtt), d->rtt.rto,
1881 d->timeout_A, d->timeout_AAAA, d->timeout_other,
1882 (int)d->edns_lame_known, (int)d->edns_version,
1883 (int)(a->now<d->probedelay?d->probedelay-a->now:0),
1884 (int)d->isdnsseclame, (int)d->rec_lame, (int)d->lame_type_A,
1885 (int)d->lame_other))
1889 /** do the dump_infra command */
1891 do_dump_infra(SSL* ssl, struct worker* worker)
1893 struct infra_arg arg;
1894 arg.infra = worker->env.infra_cache;
1896 arg.now = *worker->env.now;
1897 slabhash_traverse(arg.infra->hosts, 0, &dump_infra_host, (void*)&arg);
1900 /** do the log_reopen command */
1902 do_log_reopen(SSL* ssl, struct worker* worker)
1904 struct config_file* cfg = worker->env.cfg;
1906 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
1909 /** do the set_option command */
1911 do_set_option(SSL* ssl, struct worker* worker, char* arg)
1914 if(!find_arg2(ssl, arg, &arg2))
1916 if(!config_set_option(worker->env.cfg, arg, arg2)) {
1917 (void)ssl_printf(ssl, "error setting option\n");
1923 /* routine to printout option values over SSL */
1924 void remote_get_opt_ssl(char* line, void* arg)
1926 SSL* ssl = (SSL*)arg;
1927 (void)ssl_printf(ssl, "%s\n", line);
1930 /** do the get_option command */
1932 do_get_option(SSL* ssl, struct worker* worker, char* arg)
1935 r = config_get_option(worker->env.cfg, arg, remote_get_opt_ssl, ssl);
1937 (void)ssl_printf(ssl, "error unknown option\n");
1942 /** do the list_forwards command */
1944 do_list_forwards(SSL* ssl, struct worker* worker)
1946 /* since its a per-worker structure no locks needed */
1947 struct iter_forwards* fwds = worker->env.fwds;
1948 struct iter_forward_zone* z;
1949 RBTREE_FOR(z, struct iter_forward_zone*, fwds->tree) {
1950 if(!z->dp) continue; /* skip empty marker for stub */
1951 if(!ssl_print_name_dp(ssl, "forward", z->name, z->dclass,
1957 /** do the list_stubs command */
1959 do_list_stubs(SSL* ssl, struct worker* worker)
1961 struct iter_hints_stub* z;
1962 RBTREE_FOR(z, struct iter_hints_stub*, &worker->env.hints->tree) {
1963 if(!ssl_print_name_dp(ssl,
1964 z->noprime?"stub noprime":"stub prime", z->node.name,
1965 z->node.dclass, z->dp))
1970 /** do the list_local_zones command */
1972 do_list_local_zones(SSL* ssl, struct worker* worker)
1974 struct local_zones* zones = worker->daemon->local_zones;
1975 struct local_zone* z;
1977 lock_rw_rdlock(&zones->lock);
1978 RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
1979 lock_rw_rdlock(&z->lock);
1980 dname_str(z->name, buf);
1981 (void)ssl_printf(ssl, "%s %s\n", buf,
1982 local_zone_type2str(z->type));
1983 lock_rw_unlock(&z->lock);
1985 lock_rw_unlock(&zones->lock);
1988 /** do the list_local_data command */
1990 do_list_local_data(SSL* ssl, struct worker* worker)
1992 struct local_zones* zones = worker->daemon->local_zones;
1993 struct local_zone* z;
1994 struct local_data* d;
1995 struct local_rrset* p;
1996 char* s = (char*)sldns_buffer_begin(worker->env.scratch_buffer);
1997 size_t slen = sldns_buffer_capacity(worker->env.scratch_buffer);
1998 lock_rw_rdlock(&zones->lock);
1999 RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
2000 lock_rw_rdlock(&z->lock);
2001 RBTREE_FOR(d, struct local_data*, &z->data) {
2002 for(p = d->rrsets; p; p = p->next) {
2003 struct packed_rrset_data* d =
2004 (struct packed_rrset_data*)p->rrset->entry.data;
2006 for(i=0; i<d->count + d->rrsig_count; i++) {
2007 if(!packed_rr_to_string(p->rrset, i,
2009 if(!ssl_printf(ssl, "BADRR\n"))
2012 if(!ssl_printf(ssl, "%s\n", s))
2017 lock_rw_unlock(&z->lock);
2019 lock_rw_unlock(&zones->lock);
2022 /** tell other processes to execute the command */
2024 distribute_cmd(struct daemon_remote* rc, SSL* ssl, char* cmd)
2029 /* skip i=0 which is me */
2030 for(i=1; i<rc->worker->daemon->num; i++) {
2031 worker_send_cmd(rc->worker->daemon->workers[i],
2033 if(!tube_write_msg(rc->worker->daemon->workers[i]->cmd,
2034 (uint8_t*)cmd, strlen(cmd)+1, 0)) {
2035 ssl_printf(ssl, "error could not distribute cmd\n");
2041 /** check for name with end-of-string, space or tab after it */
2043 cmdcmp(char* p, const char* cmd, size_t len)
2045 return strncmp(p,cmd,len)==0 && (p[len]==0||p[len]==' '||p[len]=='\t');
2048 /** execute a remote control command */
2050 execute_cmd(struct daemon_remote* rc, SSL* ssl, char* cmd,
2051 struct worker* worker)
2053 char* p = skipwhite(cmd);
2054 /* compare command */
2055 if(cmdcmp(p, "stop", 4)) {
2058 } else if(cmdcmp(p, "reload", 6)) {
2061 } else if(cmdcmp(p, "stats_noreset", 13)) {
2062 do_stats(ssl, rc, 0);
2064 } else if(cmdcmp(p, "stats", 5)) {
2065 do_stats(ssl, rc, 1);
2067 } else if(cmdcmp(p, "status", 6)) {
2068 do_status(ssl, worker);
2070 } else if(cmdcmp(p, "dump_cache", 10)) {
2071 (void)dump_cache(ssl, worker);
2073 } else if(cmdcmp(p, "load_cache", 10)) {
2074 if(load_cache(ssl, worker)) send_ok(ssl);
2076 } else if(cmdcmp(p, "list_forwards", 13)) {
2077 do_list_forwards(ssl, worker);
2079 } else if(cmdcmp(p, "list_stubs", 10)) {
2080 do_list_stubs(ssl, worker);
2082 } else if(cmdcmp(p, "list_local_zones", 16)) {
2083 do_list_local_zones(ssl, worker);
2085 } else if(cmdcmp(p, "list_local_data", 15)) {
2086 do_list_local_data(ssl, worker);
2088 } else if(cmdcmp(p, "stub_add", 8)) {
2089 /* must always distribute this cmd */
2090 if(rc) distribute_cmd(rc, ssl, cmd);
2091 do_stub_add(ssl, worker, skipwhite(p+8));
2093 } else if(cmdcmp(p, "stub_remove", 11)) {
2094 /* must always distribute this cmd */
2095 if(rc) distribute_cmd(rc, ssl, cmd);
2096 do_stub_remove(ssl, worker, skipwhite(p+11));
2098 } else if(cmdcmp(p, "forward_add", 11)) {
2099 /* must always distribute this cmd */
2100 if(rc) distribute_cmd(rc, ssl, cmd);
2101 do_forward_add(ssl, worker, skipwhite(p+11));
2103 } else if(cmdcmp(p, "forward_remove", 14)) {
2104 /* must always distribute this cmd */
2105 if(rc) distribute_cmd(rc, ssl, cmd);
2106 do_forward_remove(ssl, worker, skipwhite(p+14));
2108 } else if(cmdcmp(p, "insecure_add", 12)) {
2109 /* must always distribute this cmd */
2110 if(rc) distribute_cmd(rc, ssl, cmd);
2111 do_insecure_add(ssl, worker, skipwhite(p+12));
2113 } else if(cmdcmp(p, "insecure_remove", 15)) {
2114 /* must always distribute this cmd */
2115 if(rc) distribute_cmd(rc, ssl, cmd);
2116 do_insecure_remove(ssl, worker, skipwhite(p+15));
2118 } else if(cmdcmp(p, "forward", 7)) {
2119 /* must always distribute this cmd */
2120 if(rc) distribute_cmd(rc, ssl, cmd);
2121 do_forward(ssl, worker, skipwhite(p+7));
2123 } else if(cmdcmp(p, "flush_stats", 11)) {
2124 /* must always distribute this cmd */
2125 if(rc) distribute_cmd(rc, ssl, cmd);
2126 do_flush_stats(ssl, worker);
2128 } else if(cmdcmp(p, "flush_requestlist", 17)) {
2129 /* must always distribute this cmd */
2130 if(rc) distribute_cmd(rc, ssl, cmd);
2131 do_flush_requestlist(ssl, worker);
2133 } else if(cmdcmp(p, "lookup", 6)) {
2134 do_lookup(ssl, worker, skipwhite(p+6));
2138 #ifdef THREADS_DISABLED
2139 /* other processes must execute the command as well */
2140 /* commands that should not be distributed, returned above. */
2141 if(rc) { /* only if this thread is the master (rc) thread */
2142 /* done before the code below, which may split the string */
2143 distribute_cmd(rc, ssl, cmd);
2146 if(cmdcmp(p, "verbosity", 9)) {
2147 do_verbosity(ssl, skipwhite(p+9));
2148 } else if(cmdcmp(p, "local_zone_remove", 17)) {
2149 do_zone_remove(ssl, worker, skipwhite(p+17));
2150 } else if(cmdcmp(p, "local_zone", 10)) {
2151 do_zone_add(ssl, worker, skipwhite(p+10));
2152 } else if(cmdcmp(p, "local_data_remove", 17)) {
2153 do_data_remove(ssl, worker, skipwhite(p+17));
2154 } else if(cmdcmp(p, "local_data", 10)) {
2155 do_data_add(ssl, worker, skipwhite(p+10));
2156 } else if(cmdcmp(p, "flush_zone", 10)) {
2157 do_flush_zone(ssl, worker, skipwhite(p+10));
2158 } else if(cmdcmp(p, "flush_type", 10)) {
2159 do_flush_type(ssl, worker, skipwhite(p+10));
2160 } else if(cmdcmp(p, "flush_infra", 11)) {
2161 do_flush_infra(ssl, worker, skipwhite(p+11));
2162 } else if(cmdcmp(p, "flush", 5)) {
2163 do_flush_name(ssl, worker, skipwhite(p+5));
2164 } else if(cmdcmp(p, "dump_requestlist", 16)) {
2165 do_dump_requestlist(ssl, worker);
2166 } else if(cmdcmp(p, "dump_infra", 10)) {
2167 do_dump_infra(ssl, worker);
2168 } else if(cmdcmp(p, "log_reopen", 10)) {
2169 do_log_reopen(ssl, worker);
2170 } else if(cmdcmp(p, "set_option", 10)) {
2171 do_set_option(ssl, worker, skipwhite(p+10));
2172 } else if(cmdcmp(p, "get_option", 10)) {
2173 do_get_option(ssl, worker, skipwhite(p+10));
2174 } else if(cmdcmp(p, "flush_bogus", 11)) {
2175 do_flush_bogus(ssl, worker);
2177 (void)ssl_printf(ssl, "error unknown command '%s'\n", p);
2182 daemon_remote_exec(struct worker* worker)
2184 /* read the cmd string */
2185 uint8_t* msg = NULL;
2187 if(!tube_read_msg(worker->cmd, &msg, &len, 0)) {
2188 log_err("daemon_remote_exec: tube_read_msg failed");
2191 verbose(VERB_ALGO, "remote exec distributed: %s", (char*)msg);
2192 execute_cmd(NULL, NULL, (char*)msg, worker);
2196 /** handle remote control request */
2198 handle_req(struct daemon_remote* rc, struct rc_state* s, SSL* ssl)
2205 /* makes it possible to set the socket blocking again. */
2206 /* basically removes it from winsock_event ... */
2207 WSAEventSelect(s->c->fd, NULL, 0);
2209 fd_set_block(s->c->fd);
2211 /* try to read magic UBCT[version]_space_ string */
2213 if((r=SSL_read(ssl, magic, (int)sizeof(magic)-1)) <= 0) {
2214 if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN)
2216 log_crypto_err("could not SSL_read");
2220 if( r != 6 || strncmp(magic, "UBCT", 4) != 0) {
2221 verbose(VERB_QUERY, "control connection has bad magic string");
2222 /* probably wrong tool connected, ignore it completely */
2226 /* read the command line */
2227 if(!ssl_read_line(ssl, buf, sizeof(buf))) {
2230 snprintf(pre, sizeof(pre), "UBCT%d ", UNBOUND_CONTROL_VERSION);
2231 if(strcmp(magic, pre) != 0) {
2232 verbose(VERB_QUERY, "control connection had bad "
2233 "version %s, cmd: %s", magic, buf);
2234 ssl_printf(ssl, "error version mismatch\n");
2237 verbose(VERB_DETAIL, "control cmd: %s", buf);
2239 /* figure out what to do */
2240 execute_cmd(rc, ssl, buf, rc->worker);
2243 int remote_control_callback(struct comm_point* c, void* arg, int err,
2244 struct comm_reply* ATTR_UNUSED(rep))
2246 struct rc_state* s = (struct rc_state*)arg;
2247 struct daemon_remote* rc = s->rc;
2249 if(err != NETEVENT_NOERROR) {
2250 if(err==NETEVENT_TIMEOUT)
2251 log_err("remote control timed out");
2255 /* (continue to) setup the SSL connection */
2257 r = SSL_do_handshake(s->ssl);
2259 int r2 = SSL_get_error(s->ssl, r);
2260 if(r2 == SSL_ERROR_WANT_READ) {
2261 if(s->shake_state == rc_hs_read) {
2262 /* try again later */
2265 s->shake_state = rc_hs_read;
2266 comm_point_listen_for_rw(c, 1, 0);
2268 } else if(r2 == SSL_ERROR_WANT_WRITE) {
2269 if(s->shake_state == rc_hs_write) {
2270 /* try again later */
2273 s->shake_state = rc_hs_write;
2274 comm_point_listen_for_rw(c, 0, 1);
2278 log_err("remote control connection closed prematurely");
2279 log_addr(1, "failed connection from",
2280 &s->c->repinfo.addr, s->c->repinfo.addrlen);
2281 log_crypto_err("remote control failed ssl");
2286 s->shake_state = rc_none;
2288 /* once handshake has completed, check authentication */
2289 if(SSL_get_verify_result(s->ssl) == X509_V_OK) {
2290 X509* x = SSL_get_peer_certificate(s->ssl);
2292 verbose(VERB_DETAIL, "remote control connection "
2293 "provided no client certificate");
2297 verbose(VERB_ALGO, "remote control connection authenticated");
2300 verbose(VERB_DETAIL, "remote control connection failed to "
2301 "authenticate with client certificate");
2306 /* if OK start to actually handle the request */
2307 handle_req(rc, s, s->ssl);
2309 verbose(VERB_ALGO, "remote control operation completed");