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 LIMITED
25 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 * 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 <ldns/ldns.h>
51 #include "daemon/remote.h"
52 #include "daemon/worker.h"
53 #include "daemon/daemon.h"
54 #include "daemon/stats.h"
55 #include "daemon/cachedump.h"
57 #include "util/config_file.h"
58 #include "util/net_help.h"
59 #include "util/module.h"
60 #include "services/listen_dnsport.h"
61 #include "services/cache/rrset.h"
62 #include "services/cache/infra.h"
63 #include "services/mesh.h"
64 #include "services/localzone.h"
65 #include "util/storage/slabhash.h"
66 #include "util/fptr_wlist.h"
67 #include "util/data/dname.h"
68 #include "validator/validator.h"
69 #include "validator/val_kcache.h"
70 #include "validator/val_kentry.h"
71 #include "validator/val_anchor.h"
72 #include "iterator/iterator.h"
73 #include "iterator/iter_fwd.h"
74 #include "iterator/iter_hints.h"
75 #include "iterator/iter_delegpt.h"
76 #include "services/outbound_list.h"
77 #include "services/outside_network.h"
79 #ifdef HAVE_SYS_TYPES_H
80 # include <sys/types.h>
86 /* just for portability */
91 /** what to put on statistics lines between var and value, ": " or "=" */
93 /** if true, inhibits a lot of =0 lines from the stats output */
94 static const int inhibit_zero = 1;
96 /** subtract timers and the values do not overflow or become negative */
98 timeval_subtract(struct timeval* d, const struct timeval* end,
99 const struct timeval* start)
102 time_t end_usec = end->tv_usec;
103 d->tv_sec = end->tv_sec - start->tv_sec;
104 if(end_usec < start->tv_usec) {
108 d->tv_usec = end_usec - start->tv_usec;
112 /** divide sum of timers to get average */
114 timeval_divide(struct timeval* avg, const struct timeval* sum, size_t d)
123 avg->tv_sec = sum->tv_sec / d;
124 avg->tv_usec = sum->tv_usec / d;
125 /* handle fraction from seconds divide */
126 leftover = sum->tv_sec - avg->tv_sec*d;
127 avg->tv_usec += (leftover*1000000)/d;
131 struct daemon_remote*
132 daemon_remote_create(struct config_file* cfg)
136 struct daemon_remote* rc = (struct daemon_remote*)calloc(1,
139 log_err("out of memory in daemon_remote_create");
144 if(!cfg->remote_control_enable) {
148 rc->ctx = SSL_CTX_new(SSLv23_server_method());
150 log_crypto_err("could not SSL_CTX_new");
154 /* no SSLv2 because has defects */
155 if(!(SSL_CTX_set_options(rc->ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)){
156 log_crypto_err("could not set SSL_OP_NO_SSLv2");
157 daemon_remote_delete(rc);
160 s_cert = fname_after_chroot(cfg->server_cert_file, cfg, 1);
161 s_key = fname_after_chroot(cfg->server_key_file, cfg, 1);
162 if(!s_cert || !s_key) {
163 log_err("out of memory in remote control fname");
166 verbose(VERB_ALGO, "setup SSL certificates");
167 if (!SSL_CTX_use_certificate_file(rc->ctx,s_cert,SSL_FILETYPE_PEM)) {
168 log_err("Error for server-cert-file: %s", s_cert);
169 log_crypto_err("Error in SSL_CTX use_certificate_file");
172 if(!SSL_CTX_use_PrivateKey_file(rc->ctx,s_key,SSL_FILETYPE_PEM)) {
173 log_err("Error for server-key-file: %s", s_key);
174 log_crypto_err("Error in SSL_CTX use_PrivateKey_file");
177 if(!SSL_CTX_check_private_key(rc->ctx)) {
178 log_err("Error for server-key-file: %s", s_key);
179 log_crypto_err("Error in SSL_CTX check_private_key");
182 if(!SSL_CTX_load_verify_locations(rc->ctx, s_cert, NULL)) {
183 log_crypto_err("Error setting up SSL_CTX verify locations");
187 daemon_remote_delete(rc);
190 SSL_CTX_set_client_CA_list(rc->ctx, SSL_load_client_CA_file(s_cert));
191 SSL_CTX_set_verify(rc->ctx, SSL_VERIFY_PEER, NULL);
198 void daemon_remote_clear(struct daemon_remote* rc)
200 struct rc_state* p, *np;
202 /* but do not close the ports */
203 listen_list_delete(rc->accept_list);
204 rc->accept_list = NULL;
205 /* do close these sockets */
211 comm_point_delete(p->c);
215 rc->busy_list = NULL;
220 void daemon_remote_delete(struct daemon_remote* rc)
223 daemon_remote_clear(rc);
225 SSL_CTX_free(rc->ctx);
231 * Add and open a new control port
234 * @param list: list head
235 * @param noproto_is_err: if lack of protocol support is an error.
236 * @return false on failure.
239 add_open(const char* ip, int nr, struct listen_port** list, int noproto_is_err)
241 struct addrinfo hints;
242 struct addrinfo* res;
243 struct listen_port* n;
247 snprintf(port, sizeof(port), "%d", nr);
248 port[sizeof(port)-1]=0;
249 memset(&hints, 0, sizeof(hints));
250 hints.ai_socktype = SOCK_STREAM;
251 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
252 if((r = getaddrinfo(ip, port, &hints, &res)) != 0 || !res) {
254 if(!noproto_is_err && r == EAI_NONAME) {
255 /* tried to lookup the address as name */
256 return 1; /* return success, but do nothing */
258 #endif /* USE_WINSOCK */
259 log_err("control interface %s:%s getaddrinfo: %s %s",
260 ip?ip:"default", port, gai_strerror(r),
262 r==EAI_SYSTEM?(char*)strerror(errno):""
271 fd = create_tcp_accept_sock(res, 1, &noproto);
273 if(fd == -1 && noproto) {
275 return 1; /* return success, but do nothing */
276 log_err("cannot open control interface %s %d : "
277 "protocol not supported", ip, nr);
281 log_err("cannot open control interface %s %d", ip, nr);
286 n = (struct listen_port*)calloc(1, sizeof(*n));
293 log_err("out of memory");
302 struct listen_port* daemon_remote_open_ports(struct config_file* cfg)
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);
317 !add_open("::1", cfg->control_port, &l, 0)) {
318 listening_ports_free(l);
322 !add_open("127.0.0.1", cfg->control_port, &l, 1)) {
323 listening_ports_free(l);
330 /** open accept commpoint */
332 accept_open(struct daemon_remote* rc, int fd)
334 struct listen_list* n = (struct listen_list*)malloc(sizeof(*n));
336 log_err("out of memory");
339 n->next = rc->accept_list;
342 n->com = comm_point_create_raw(rc->worker->base, fd, 0,
343 &remote_accept_callback, rc);
346 /* keep this port open, its fd is kept in the rc portlist */
347 n->com->do_not_close = 1;
351 int daemon_remote_open_accept(struct daemon_remote* rc,
352 struct listen_port* ports, struct worker* worker)
354 struct listen_port* p;
356 for(p = ports; p; p = p->next) {
357 if(!accept_open(rc, p->fd)) {
358 log_err("could not create accept comm point");
365 void daemon_remote_stop_accept(struct daemon_remote* rc)
367 struct listen_list* p;
368 for(p=rc->accept_list; p; p=p->next) {
369 comm_point_stop_listening(p->com);
373 void daemon_remote_start_accept(struct daemon_remote* rc)
375 struct listen_list* p;
376 for(p=rc->accept_list; p; p=p->next) {
377 comm_point_start_listening(p->com, -1, -1);
381 int remote_accept_callback(struct comm_point* c, void* arg, int err,
382 struct comm_reply* ATTR_UNUSED(rep))
384 struct daemon_remote* rc = (struct daemon_remote*)arg;
385 struct sockaddr_storage addr;
389 if(err != NETEVENT_NOERROR) {
390 log_err("error %d on remote_accept_callback", err);
393 /* perform the accept */
394 newfd = comm_point_perform_accept(c, &addr, &addrlen);
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");
409 /* setup commpoint to service the remote control command */
410 n = (struct rc_state*)calloc(1, sizeof(*n));
412 log_err("out of memory");
415 /* start in reading state */
416 n->c = comm_point_create_raw(rc->worker->base, newfd, 0,
417 &remote_control_callback, n);
419 log_err("out of memory");
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);
432 log_crypto_err("could not SSL_new");
433 comm_point_delete(n->c);
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");
442 comm_point_delete(n->c);
448 n->next = rc->busy_list;
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);
458 /** delete from list */
460 state_list_remove_elem(struct rc_state** list, struct comm_point* c)
463 if( (*list)->c == c) {
464 *list = (*list)->next;
467 list = &(*list)->next;
471 /** decrease active count and remove commpoint from busy list */
473 clean_point(struct daemon_remote* rc, struct rc_state* s)
475 state_list_remove_elem(&rc->busy_list, s->c);
478 SSL_shutdown(s->ssl);
481 comm_point_delete(s->c);
486 ssl_print_text(SSL* ssl, const char* text)
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");
498 log_crypto_err("could not SSL_write");
504 /** print text over the ssl connection */
506 ssl_print_vmsg(SSL* ssl, const char* format, va_list args)
509 vsnprintf(msg, sizeof(msg), format, args);
510 return ssl_print_text(ssl, msg);
513 /** printf style printing to the ssl connection */
514 int ssl_printf(SSL* ssl, const char* format, ...)
518 va_start(args, format);
519 ret = ssl_print_vmsg(ssl, format, args);
525 ssl_read_line(SSL* ssl, char* buf, size_t max)
533 if((r=SSL_read(ssl, buf+len, 1)) <= 0) {
534 if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
538 log_crypto_err("could not SSL_read");
541 if(buf[len] == '\n') {
542 /* return string without \n */
549 log_err("control line too long (%d): %s", (int)max, buf);
553 /** skip whitespace, return new pointer into string */
557 /* EOS \0 is not a space */
558 while( isspace(*str) )
563 /** send the OK to the control client */
564 static void send_ok(SSL* ssl)
566 (void)ssl_printf(ssl, "ok\n");
569 /** do the stop command */
571 do_stop(SSL* ssl, struct daemon_remote* rc)
573 rc->worker->need_to_exit = 1;
574 comm_base_exit(rc->worker->base);
578 /** do the reload command */
580 do_reload(SSL* ssl, struct daemon_remote* rc)
582 rc->worker->need_to_exit = 0;
583 comm_base_exit(rc->worker->base);
587 /** do the verbosity command */
589 do_verbosity(SSL* ssl, char* str)
592 if(val == 0 && strcmp(str, "0") != 0) {
593 ssl_printf(ssl, "error in verbosity number syntax: %s\n", str);
600 /** print stats from statinfo */
602 print_stats(SSL* ssl, const char* nm, struct stats_info* s)
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;
639 /** print stats for one thread */
641 print_thread_stats(SSL* ssl, int i, struct stats_info* s)
644 snprintf(nm, sizeof(nm), "thread%d", i);
646 return print_stats(ssl, nm, s);
649 /** print long number */
651 print_longnum(SSL* ssl, const char* desc, size_t x)
653 if(x > 1024*1024*1024) {
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);
660 return ssl_printf(ssl, "%s%u\n", desc, (unsigned)x);
664 /** print mem stats */
666 print_mem(SSL* ssl, struct worker* worker, struct daemon* daemon)
669 size_t msg, rrset, val, iter;
671 extern void* unbound_start_brk;
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);
680 m = modstack_find(&worker->env.mesh->mods, "validator");
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)
687 m = modstack_find(&worker->env.mesh->mods, "iterator");
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)
695 if(!print_longnum(ssl, "mem.cache.rrset"SQ, rrset))
697 if(!print_longnum(ssl, "mem.cache.message"SQ, msg))
699 if(!print_longnum(ssl, "mem.mod.iterator"SQ, iter))
701 if(!print_longnum(ssl, "mem.mod.validator"SQ, val))
706 /** print uptime stats */
708 print_uptime(SSL* ssl, struct worker* worker, int reset)
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);
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;
725 /** print extended histogram */
727 print_hist(SSL* ssl, struct stats_info* s)
729 struct timehist* hist;
731 hist = timehist_setup();
733 log_err("out of memory");
736 timehist_import(hist, s->svr.hist, NUM_BUCKETS_HIST);
737 for(i=0; i<hist->num; i++) {
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);
749 timehist_delete(hist);
753 /** print extended stats */
755 print_ext(SSL* ssl, struct stats_info* s)
759 const ldns_rr_descriptor* desc;
760 const ldns_lookup_table* lt;
762 for(i=0; i<STATS_QTYPE_NUM; i++) {
763 if(inhibit_zero && s->svr.qtype[i] == 0)
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");
779 snprintf(nm, sizeof(nm), "TYPE%d", i);
781 if(!ssl_printf(ssl, "num.query.type.%s"SQ"%u\n",
782 nm, (unsigned)s->svr.qtype[i])) return 0;
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;
789 for(i=0; i<STATS_QCLASS_NUM; i++) {
790 if(inhibit_zero && s->svr.qclass[i] == 0)
792 lt = ldns_lookup_by_id(ldns_rr_classes, i);
794 snprintf(nm, sizeof(nm), "%s", lt->name);
796 snprintf(nm, sizeof(nm), "CLASS%d", i);
798 if(!ssl_printf(ssl, "num.query.class.%s"SQ"%u\n",
799 nm, (unsigned)s->svr.qclass[i])) return 0;
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;
806 for(i=0; i<STATS_OPCODE_NUM; i++) {
807 if(inhibit_zero && s->svr.qopcode[i] == 0)
809 lt = ldns_lookup_by_id(ldns_opcodes, i);
811 snprintf(nm, sizeof(nm), "%s", lt->name);
813 snprintf(nm, sizeof(nm), "OPCODE%d", i);
815 if(!ssl_printf(ssl, "num.query.opcode.%s"SQ"%u\n",
816 nm, (unsigned)s->svr.qopcode[i])) return 0;
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;
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;
846 for(i=0; i<STATS_RCODE_NUM; i++) {
847 if(inhibit_zero && s->svr.ans_rcode[i] == 0)
849 lt = ldns_lookup_by_id(ldns_rcodes, i);
851 snprintf(nm, sizeof(nm), "%s", lt->name);
853 snprintf(nm, sizeof(nm), "RCODE%d", i);
855 if(!ssl_printf(ssl, "num.answer.rcode.%s"SQ"%u\n",
856 nm, (unsigned)s->svr.ans_rcode[i])) return 0;
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;
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;
877 /** do the stats command */
879 do_stats(SSL* ssl, struct daemon_remote* rc, int reset)
881 struct daemon* daemon = rc->worker->daemon;
882 struct stats_info total;
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))
893 else server_stats_add(&total, &s);
895 /* print the thread statistics */
896 total.mesh_time_median /= (double)daemon->num;
897 if(!print_stats(ssl, "total", &total))
899 if(!print_uptime(ssl, rc->worker, reset))
901 if(daemon->cfg->stat_extended) {
902 if(!print_mem(ssl, rc->worker, daemon))
904 if(!print_hist(ssl, &total))
906 if(!print_ext(ssl, &total))
911 /** parse commandline argument domain name */
913 parse_arg_name(SSL* ssl, char* str, uint8_t** res, size_t* len, int* labs)
919 rdf = ldns_dname_new_frm_str(str);
921 ssl_printf(ssl, "error cannot parse name %s\n", str);
924 *res = memdup(ldns_rdf_data(rdf), ldns_rdf_size(rdf));
925 ldns_rdf_deep_free(rdf);
927 ssl_printf(ssl, "error out of memory\n");
930 *labs = dname_count_size_labels(*res, len);
934 /** find second argument, modifies string */
936 find_arg2(SSL* ssl, char* arg, char** arg2)
938 char* as = strchr(arg, ' ');
939 char* at = strchr(arg, '\t');
944 *arg2 = skipwhite(as+1);
947 *arg2 = skipwhite(as+1);
950 *arg2 = skipwhite(at+1);
952 ssl_printf(ssl, "error could not find next argument "
959 /** Add a new zone */
961 do_zone_add(SSL* ssl, struct worker* worker, char* arg)
967 enum localzone_type t;
968 struct local_zone* z;
969 if(!find_arg2(ssl, arg, &arg2))
971 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
973 if(!local_zone_str2type(arg2, &t)) {
974 ssl_printf(ssl, "error not a zone type. %s\n", arg2);
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);
986 lock_quick_unlock(&worker->daemon->local_zones->lock);
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");
996 lock_quick_unlock(&worker->daemon->local_zones->lock);
1000 /** Remove a zone */
1002 do_zone_remove(SSL* ssl, struct worker* worker, char* arg)
1007 struct local_zone* z;
1008 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
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);
1016 lock_quick_unlock(&worker->daemon->local_zones->lock);
1021 /** Add new RR data */
1023 do_data_add(SSL* ssl, struct worker* worker, char* arg)
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);
1033 /** Remove RR data */
1035 do_data_remove(SSL* ssl, struct worker* worker, char* arg)
1040 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1042 local_zones_del_data(worker->daemon->local_zones, nm,
1043 nmlen, nmlabs, LDNS_RR_CLASS_IN);
1048 /** cache lookup of nameservers */
1050 do_lookup(SSL* ssl, struct worker* worker, char* arg)
1055 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1057 (void)print_deleg_lookup(ssl, worker, nm, nmlen, nmlabs);
1061 /** flush something from rrset and msg caches */
1063 do_cache_remove(struct worker* worker, uint8_t* nm, size_t nmlen,
1064 uint16_t t, uint16_t c)
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);
1073 k.qname_len = nmlen;
1076 h = query_info_hash(&k);
1077 slabhash_remove(worker->env.msg_cache, h, &k);
1082 do_flush_type(SSL* ssl, struct worker* worker, char* arg)
1089 if(!find_arg2(ssl, arg, &arg2))
1091 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1093 t = ldns_get_rr_type_by_name(arg2);
1094 do_cache_remove(worker, nm, nmlen, t, LDNS_RR_CLASS_IN);
1100 /** flush statistics */
1102 do_flush_stats(SSL* ssl, struct worker* worker)
1104 worker_stats_clear(worker);
1109 * Local info for deletion functions
1113 struct worker* worker;
1114 /** name to delete */
1122 /** time to invalidate to */
1124 /** number of rrsets removed */
1126 /** number of msgs removed */
1128 /** number of key entries removed */
1130 /** length of addr */
1132 /** socket address for host deletion */
1133 struct sockaddr_storage addr;
1136 /** callback to delete hosts in infra cache */
1138 infra_del_host(struct lruhash_entry* e, void* arg)
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;
1147 d->timeout_AAAA = 0;
1148 d->timeout_other = 0;
1150 if(d->ttl >= inf->now) {
1151 d->ttl = inf->expired;
1157 /** flush infra cache */
1159 do_flush_infra(SSL* ssl, struct worker* worker, char* arg)
1161 struct sockaddr_storage addr;
1163 struct del_info inf;
1164 if(strcmp(arg, "all") == 0) {
1165 slabhash_clear(worker->env.infra_cache->hosts);
1169 if(!ipstrtoaddr(arg, UNBOUND_DNS_PORT, &addr, &len)) {
1170 (void)ssl_printf(ssl, "error parsing ip addr: '%s'\n", arg);
1173 /* delete all entries from cache */
1174 /* what we do is to set them all expired */
1175 inf.worker = worker;
1179 inf.now = *worker->env.now;
1180 inf.expired = *worker->env.now;
1181 inf.expired -= 3; /* handle 3 seconds skew between threads */
1186 memmove(&inf.addr, &addr, len);
1187 slabhash_traverse(worker->env.infra_cache->hosts, 1, &infra_del_host,
1192 /** flush requestlist */
1194 do_flush_requestlist(SSL* ssl, struct worker* worker)
1196 mesh_delete_all(worker->env.mesh);
1200 /** callback to delete rrsets in a zone */
1202 zone_del_rrset(struct lruhash_entry* e, void* arg)
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;
1217 /** callback to delete messages in a zone */
1219 zone_del_msg(struct lruhash_entry* e, void* arg)
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;
1233 /** callback to delete keys in zone */
1235 zone_del_kcache(struct lruhash_entry* e, void* arg)
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;
1249 /** remove all rrsets and keys from zone from cache */
1251 do_flush_zone(SSL* ssl, struct worker* worker, char* arg)
1256 struct del_info inf;
1257 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1259 /* delete all RRs and key entries from zone */
1260 /* what we do is to set them all expired */
1261 inf.worker = worker;
1265 inf.now = *worker->env.now;
1266 inf.expired = *worker->env.now;
1267 inf.expired -= 3; /* handle 3 seconds skew between threads */
1271 slabhash_traverse(&worker->env.rrset_cache->table, 1,
1272 &zone_del_rrset, &inf);
1274 slabhash_traverse(worker->env.msg_cache, 1, &zone_del_msg, &inf);
1276 /* and validator cache */
1277 if(worker->env.key_cache) {
1278 slabhash_traverse(worker->env.key_cache->slab, 1,
1279 &zone_del_kcache, &inf);
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);
1289 /** callback to delete bogus rrsets */
1291 bogus_del_rrset(struct lruhash_entry* e, void* arg)
1293 /* entry is locked */
1294 struct del_info* inf = (struct del_info*)arg;
1295 struct packed_rrset_data* d = (struct packed_rrset_data*)e->data;
1296 if(d->security == sec_status_bogus) {
1297 d->ttl = inf->expired;
1302 /** callback to delete bogus messages */
1304 bogus_del_msg(struct lruhash_entry* e, void* arg)
1306 /* entry is locked */
1307 struct del_info* inf = (struct del_info*)arg;
1308 struct reply_info* d = (struct reply_info*)e->data;
1309 if(d->security == sec_status_bogus) {
1310 d->ttl = inf->expired;
1315 /** callback to delete bogus keys */
1317 bogus_del_kcache(struct lruhash_entry* e, void* arg)
1319 /* entry is locked */
1320 struct del_info* inf = (struct del_info*)arg;
1321 struct key_entry_data* d = (struct key_entry_data*)e->data;
1323 d->ttl = inf->expired;
1328 /** remove all rrsets and keys from zone from cache */
1330 do_flush_bogus(SSL* ssl, struct worker* worker)
1332 struct del_info inf;
1333 /* what we do is to set them all expired */
1334 inf.worker = worker;
1335 inf.now = *worker->env.now;
1336 inf.expired = *worker->env.now;
1337 inf.expired -= 3; /* handle 3 seconds skew between threads */
1341 slabhash_traverse(&worker->env.rrset_cache->table, 1,
1342 &bogus_del_rrset, &inf);
1344 slabhash_traverse(worker->env.msg_cache, 1, &bogus_del_msg, &inf);
1346 /* and validator cache */
1347 if(worker->env.key_cache) {
1348 slabhash_traverse(worker->env.key_cache->slab, 1,
1349 &bogus_del_kcache, &inf);
1352 (void)ssl_printf(ssl, "ok removed %u rrsets, %u messages "
1353 "and %u key entries\n", (unsigned)inf.num_rrsets,
1354 (unsigned)inf.num_msgs, (unsigned)inf.num_keys);
1357 /** remove name rrset from cache */
1359 do_flush_name(SSL* ssl, struct worker* w, char* arg)
1364 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1366 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_A, LDNS_RR_CLASS_IN);
1367 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_AAAA, LDNS_RR_CLASS_IN);
1368 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_NS, LDNS_RR_CLASS_IN);
1369 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SOA, LDNS_RR_CLASS_IN);
1370 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_CNAME, LDNS_RR_CLASS_IN);
1371 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_DNAME, LDNS_RR_CLASS_IN);
1372 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_MX, LDNS_RR_CLASS_IN);
1373 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_PTR, LDNS_RR_CLASS_IN);
1374 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SRV, LDNS_RR_CLASS_IN);
1375 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_NAPTR, LDNS_RR_CLASS_IN);
1381 /** printout a delegation point info */
1383 ssl_print_name_dp(SSL* ssl, const char* str, uint8_t* nm, uint16_t dclass,
1387 struct delegpt_ns* ns;
1388 struct delegpt_addr* a;
1390 if(str) { /* print header for forward, stub */
1391 char* c = ldns_rr_class2str(dclass);
1393 if(!ssl_printf(ssl, "%s %s %s: ", buf, c, str)) {
1399 for(ns = dp->nslist; ns; ns = ns->next) {
1400 dname_str(ns->name, buf);
1401 if(!ssl_printf(ssl, "%s%s", (f?" ":""), buf))
1405 for(a = dp->target_list; a; a = a->next_target) {
1406 addr_to_str(&a->addr, a->addrlen, buf, sizeof(buf));
1407 if(!ssl_printf(ssl, "%s%s", (f?" ":""), buf))
1411 return ssl_printf(ssl, "\n");
1415 /** print root forwards */
1417 print_root_fwds(SSL* ssl, struct iter_forwards* fwds, uint8_t* root)
1420 dp = forwards_lookup(fwds, root, LDNS_RR_CLASS_IN);
1422 return ssl_printf(ssl, "off (using root hints)\n");
1423 /* if dp is returned it must be the root */
1424 log_assert(query_dname_compare(dp->name, root)==0);
1425 return ssl_print_name_dp(ssl, NULL, root, LDNS_RR_CLASS_IN, dp);
1428 /** parse args into delegpt */
1429 static struct delegpt*
1430 parse_delegpt(SSL* ssl, char* args, uint8_t* nm, int allow_names)
1432 /* parse args and add in */
1435 struct delegpt* dp = delegpt_create_mlc(nm);
1436 struct sockaddr_storage addr;
1439 (void)ssl_printf(ssl, "error out of memory\n");
1444 p = strchr(p, ' '); /* find next spot, if any */
1446 *p++ = 0; /* end this spot */
1447 p = skipwhite(p); /* position at next spot */
1450 if(!extstrtoaddr(todo, &addr, &addrlen)) {
1455 if(!parse_arg_name(ssl, todo, &n, &ln, &lb)) {
1456 (void)ssl_printf(ssl, "error cannot "
1457 "parse IP address or name "
1459 delegpt_free_mlc(dp);
1462 if(!delegpt_add_ns_mlc(dp, n, 0)) {
1463 (void)ssl_printf(ssl, "error out of memory\n");
1465 delegpt_free_mlc(dp);
1471 (void)ssl_printf(ssl, "error cannot parse"
1472 " IP address '%s'\n", todo);
1473 delegpt_free_mlc(dp);
1478 if(!delegpt_add_addr_mlc(dp, &addr, addrlen, 0, 0)) {
1479 (void)ssl_printf(ssl, "error out of memory\n");
1480 delegpt_free_mlc(dp);
1488 /** do the status command */
1490 do_forward(SSL* ssl, struct worker* worker, char* args)
1492 struct iter_forwards* fwd = worker->env.fwds;
1493 uint8_t* root = (uint8_t*)"\000";
1495 (void)ssl_printf(ssl, "error: structure not allocated\n");
1498 if(args == NULL || args[0] == 0) {
1499 (void)print_root_fwds(ssl, fwd, root);
1502 /* set root forwards for this thread. since we are in remote control
1503 * the actual mesh is not running, so we can freely edit it. */
1504 /* delete all the existing queries first */
1505 mesh_delete_all(worker->env.mesh);
1506 if(strcmp(args, "off") == 0) {
1507 forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, root);
1510 if(!(dp = parse_delegpt(ssl, args, root, 0)))
1512 if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp)) {
1513 (void)ssl_printf(ssl, "error out of memory\n");
1521 parse_fs_args(SSL* ssl, char* args, uint8_t** nm, struct delegpt** dp,
1522 int* insecure, int* prime)
1528 /* parse all -x args */
1529 while(args[0] == '+') {
1530 if(!find_arg2(ssl, args, &rest))
1532 while(*(++args) != 0) {
1533 if(*args == 'i' && insecure)
1535 else if(*args == 'p' && prime)
1538 (void)ssl_printf(ssl, "error: unknown option %s\n", args);
1546 if(!find_arg2(ssl, args, &rest))
1550 } else zonename = args;
1551 if(!parse_arg_name(ssl, zonename, nm, &nmlen, &nmlabs))
1556 if(!(*dp = parse_delegpt(ssl, args, *nm, 1))) {
1564 /** do the forward_add command */
1566 do_forward_add(SSL* ssl, struct worker* worker, char* args)
1568 struct iter_forwards* fwd = worker->env.fwds;
1571 struct delegpt* dp = NULL;
1572 if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, NULL))
1575 if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
1577 (void)ssl_printf(ssl, "error out of memory\n");
1578 delegpt_free_mlc(dp);
1583 if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp)) {
1584 (void)ssl_printf(ssl, "error out of memory\n");
1592 /** do the forward_remove command */
1594 do_forward_remove(SSL* ssl, struct worker* worker, char* args)
1596 struct iter_forwards* fwd = worker->env.fwds;
1599 if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL))
1602 anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
1604 forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, nm);
1609 /** do the stub_add command */
1611 do_stub_add(SSL* ssl, struct worker* worker, char* args)
1613 struct iter_forwards* fwd = worker->env.fwds;
1614 int insecure = 0, prime = 0;
1616 struct delegpt* dp = NULL;
1617 if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, &prime))
1620 if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
1622 (void)ssl_printf(ssl, "error out of memory\n");
1623 delegpt_free_mlc(dp);
1628 if(!forwards_add_stub_hole(fwd, LDNS_RR_CLASS_IN, nm)) {
1629 if(insecure) anchors_delete_insecure(worker->env.anchors,
1630 LDNS_RR_CLASS_IN, nm);
1631 (void)ssl_printf(ssl, "error out of memory\n");
1632 delegpt_free_mlc(dp);
1636 if(!hints_add_stub(worker->env.hints, LDNS_RR_CLASS_IN, dp, !prime)) {
1637 (void)ssl_printf(ssl, "error out of memory\n");
1638 forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm);
1639 if(insecure) anchors_delete_insecure(worker->env.anchors,
1640 LDNS_RR_CLASS_IN, nm);
1648 /** do the stub_remove command */
1650 do_stub_remove(SSL* ssl, struct worker* worker, char* args)
1652 struct iter_forwards* fwd = worker->env.fwds;
1655 if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL))
1658 anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
1660 forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm);
1661 hints_delete_stub(worker->env.hints, LDNS_RR_CLASS_IN, nm);
1666 /** do the status command */
1668 do_status(SSL* ssl, struct worker* worker)
1672 if(!ssl_printf(ssl, "version: %s\n", PACKAGE_VERSION))
1674 if(!ssl_printf(ssl, "verbosity: %d\n", verbosity))
1676 if(!ssl_printf(ssl, "threads: %d\n", worker->daemon->num))
1678 if(!ssl_printf(ssl, "modules: %d [", worker->daemon->mods.num))
1680 for(i=0; i<worker->daemon->mods.num; i++) {
1681 if(!ssl_printf(ssl, " %s", worker->daemon->mods.mod[i]->name))
1684 if(!ssl_printf(ssl, " ]\n"))
1686 uptime = (time_t)time(NULL) - (time_t)worker->daemon->time_boot.tv_sec;
1687 if(!ssl_printf(ssl, "uptime: %u seconds\n", (unsigned)uptime))
1689 if(!ssl_printf(ssl, "unbound (pid %d) is running...\n",
1694 /** get age for the mesh state */
1696 get_mesh_age(struct mesh_state* m, char* buf, size_t len,
1697 struct module_env* env)
1701 struct mesh_reply* r = m->reply_list;
1702 /* last reply is the oldest */
1705 timeval_subtract(&d, env->now_tv, &r->start_time);
1706 snprintf(buf, len, "%d.%6.6d", (int)d.tv_sec, (int)d.tv_usec);
1708 snprintf(buf, len, "-");
1712 /** get status of a mesh state */
1714 get_mesh_status(struct mesh_area* mesh, struct mesh_state* m,
1715 char* buf, size_t len)
1717 enum module_ext_state s = m->s.ext_state[m->s.curmod];
1718 const char *modname = mesh->mods.mod[m->s.curmod]->name;
1720 if(strcmp(modname, "iterator") == 0 && s == module_wait_reply &&
1721 m->s.minfo[m->s.curmod]) {
1722 /* break into iterator to find out who its waiting for */
1723 struct iter_qstate* qstate = (struct iter_qstate*)
1724 m->s.minfo[m->s.curmod];
1725 struct outbound_list* ol = &qstate->outlist;
1726 struct outbound_entry* e;
1727 snprintf(buf, len, "%s wait for", modname);
1730 if(ol->first == NULL)
1731 snprintf(buf, len, " (empty_list)");
1732 for(e = ol->first; e; e = e->next) {
1733 snprintf(buf, len, " ");
1736 addr_to_str(&e->qsent->addr, e->qsent->addrlen,
1741 } else if(s == module_wait_subquery) {
1742 /* look in subs from mesh state to see what */
1744 struct mesh_state_ref* sub;
1745 snprintf(buf, len, "%s wants", modname);
1748 if(m->sub_set.count == 0)
1749 snprintf(buf, len, " (empty_list)");
1750 RBTREE_FOR(sub, struct mesh_state_ref*, &m->sub_set) {
1751 char* t = ldns_rr_type2str(sub->s->s.qinfo.qtype);
1752 char* c = ldns_rr_class2str(sub->s->s.qinfo.qclass);
1753 dname_str(sub->s->s.qinfo.qname, nm);
1754 snprintf(buf, len, " %s %s %s", t, c, nm);
1761 snprintf(buf, len, "%s is %s", modname, strextstate(s));
1765 /** do the dump_requestlist command */
1767 do_dump_requestlist(SSL* ssl, struct worker* worker)
1769 struct mesh_area* mesh;
1770 struct mesh_state* m;
1774 char statbuf[10240];
1775 if(!ssl_printf(ssl, "thread #%d\n", worker->thread_num))
1777 if(!ssl_printf(ssl, "# type cl name seconds module status\n"))
1779 /* show worker mesh contents */
1780 mesh = worker->env.mesh;
1782 RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
1783 char* t = ldns_rr_type2str(m->s.qinfo.qtype);
1784 char* c = ldns_rr_class2str(m->s.qinfo.qclass);
1785 dname_str(m->s.qinfo.qname, buf);
1786 get_mesh_age(m, timebuf, sizeof(timebuf), &worker->env);
1787 get_mesh_status(mesh, m, statbuf, sizeof(statbuf));
1788 if(!ssl_printf(ssl, "%3d %4s %2s %s %s %s\n",
1789 num, t, c, buf, timebuf, statbuf)) {
1800 /** structure for argument data for dump infra host */
1802 /** the infra cache */
1803 struct infra_cache* infra;
1804 /** the SSL connection */
1810 /** callback for every host element in the infra cache */
1812 dump_infra_host(struct lruhash_entry* e, void* arg)
1814 struct infra_arg* a = (struct infra_arg*)arg;
1815 struct infra_key* k = (struct infra_key*)e->key;
1816 struct infra_data* d = (struct infra_data*)e->data;
1819 addr_to_str(&k->addr, k->addrlen, ip_str, sizeof(ip_str));
1820 dname_str(k->zonename, name);
1821 /* skip expired stuff (only backed off) */
1822 if(d->ttl < a->now) {
1823 if(d->rtt.rto >= USEFUL_SERVER_TOP_TIMEOUT) {
1824 if(!ssl_printf(a->ssl, "%s %s expired rto %d\n", ip_str,
1825 name, d->rtt.rto)) return;
1829 if(!ssl_printf(a->ssl, "%s %s ttl %d ping %d var %d rtt %d rto %d "
1830 "tA %d tAAAA %d tother %d "
1831 "ednsknown %d edns %d delay %d lame dnssec %d rec %d A %d "
1832 "other %d\n", ip_str, name, (int)(d->ttl - a->now),
1833 d->rtt.srtt, d->rtt.rttvar, rtt_notimeout(&d->rtt), d->rtt.rto,
1834 d->timeout_A, d->timeout_AAAA, d->timeout_other,
1835 (int)d->edns_lame_known, (int)d->edns_version,
1836 (int)(a->now<d->probedelay?d->probedelay-a->now:0),
1837 (int)d->isdnsseclame, (int)d->rec_lame, (int)d->lame_type_A,
1838 (int)d->lame_other))
1842 /** do the dump_infra command */
1844 do_dump_infra(SSL* ssl, struct worker* worker)
1846 struct infra_arg arg;
1847 arg.infra = worker->env.infra_cache;
1849 arg.now = *worker->env.now;
1850 slabhash_traverse(arg.infra->hosts, 0, &dump_infra_host, (void*)&arg);
1853 /** do the log_reopen command */
1855 do_log_reopen(SSL* ssl, struct worker* worker)
1857 struct config_file* cfg = worker->env.cfg;
1859 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
1862 /** do the set_option command */
1864 do_set_option(SSL* ssl, struct worker* worker, char* arg)
1867 if(!find_arg2(ssl, arg, &arg2))
1869 if(!config_set_option(worker->env.cfg, arg, arg2)) {
1870 (void)ssl_printf(ssl, "error setting option\n");
1876 /* routine to printout option values over SSL */
1877 void remote_get_opt_ssl(char* line, void* arg)
1879 SSL* ssl = (SSL*)arg;
1880 (void)ssl_printf(ssl, "%s\n", line);
1883 /** do the get_option command */
1885 do_get_option(SSL* ssl, struct worker* worker, char* arg)
1888 r = config_get_option(worker->env.cfg, arg, remote_get_opt_ssl, ssl);
1890 (void)ssl_printf(ssl, "error unknown option\n");
1895 /** do the list_forwards command */
1897 do_list_forwards(SSL* ssl, struct worker* worker)
1899 /* since its a per-worker structure no locks needed */
1900 struct iter_forwards* fwds = worker->env.fwds;
1901 struct iter_forward_zone* z;
1902 RBTREE_FOR(z, struct iter_forward_zone*, fwds->tree) {
1903 if(!z->dp) continue; /* skip empty marker for stub */
1904 if(!ssl_print_name_dp(ssl, "forward", z->name, z->dclass,
1910 /** do the list_stubs command */
1912 do_list_stubs(SSL* ssl, struct worker* worker)
1914 struct iter_hints_stub* z;
1915 RBTREE_FOR(z, struct iter_hints_stub*, &worker->env.hints->tree) {
1916 if(!ssl_print_name_dp(ssl,
1917 z->noprime?"stub noprime":"stub prime", z->node.name,
1918 z->node.dclass, z->dp))
1923 /** do the list_local_zones command */
1925 do_list_local_zones(SSL* ssl, struct worker* worker)
1927 struct local_zones* zones = worker->daemon->local_zones;
1928 struct local_zone* z;
1930 lock_quick_lock(&zones->lock);
1931 RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
1932 lock_rw_rdlock(&z->lock);
1933 dname_str(z->name, buf);
1934 (void)ssl_printf(ssl, "%s %s\n", buf,
1935 local_zone_type2str(z->type));
1936 lock_rw_unlock(&z->lock);
1938 lock_quick_unlock(&zones->lock);
1941 /** do the list_local_data command */
1943 do_list_local_data(SSL* ssl, struct worker* worker)
1945 struct local_zones* zones = worker->daemon->local_zones;
1946 struct local_zone* z;
1947 struct local_data* d;
1948 struct local_rrset* p;
1949 lock_quick_lock(&zones->lock);
1950 RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
1951 lock_rw_rdlock(&z->lock);
1952 RBTREE_FOR(d, struct local_data*, &z->data) {
1953 for(p = d->rrsets; p; p = p->next) {
1954 ldns_rr_list* rr = packed_rrset_to_rr_list(
1955 p->rrset, worker->env.scratch_buffer);
1956 char* str = ldns_rr_list2str(rr);
1957 (void)ssl_printf(ssl, "%s", str);
1959 ldns_rr_list_free(rr);
1962 lock_rw_unlock(&z->lock);
1964 lock_quick_unlock(&zones->lock);
1967 /** tell other processes to execute the command */
1969 distribute_cmd(struct daemon_remote* rc, SSL* ssl, char* cmd)
1974 /* skip i=0 which is me */
1975 for(i=1; i<rc->worker->daemon->num; i++) {
1976 worker_send_cmd(rc->worker->daemon->workers[i],
1978 if(!tube_write_msg(rc->worker->daemon->workers[i]->cmd,
1979 (uint8_t*)cmd, strlen(cmd)+1, 0)) {
1980 ssl_printf(ssl, "error could not distribute cmd\n");
1986 /** check for name with end-of-string, space or tab after it */
1988 cmdcmp(char* p, const char* cmd, size_t len)
1990 return strncmp(p,cmd,len)==0 && (p[len]==0||p[len]==' '||p[len]=='\t');
1993 /** execute a remote control command */
1995 execute_cmd(struct daemon_remote* rc, SSL* ssl, char* cmd,
1996 struct worker* worker)
1998 char* p = skipwhite(cmd);
1999 /* compare command */
2000 if(cmdcmp(p, "stop", 4)) {
2003 } else if(cmdcmp(p, "reload", 6)) {
2006 } else if(cmdcmp(p, "stats_noreset", 13)) {
2007 do_stats(ssl, rc, 0);
2009 } else if(cmdcmp(p, "stats", 5)) {
2010 do_stats(ssl, rc, 1);
2012 } else if(cmdcmp(p, "status", 6)) {
2013 do_status(ssl, worker);
2015 } else if(cmdcmp(p, "dump_cache", 10)) {
2016 (void)dump_cache(ssl, worker);
2018 } else if(cmdcmp(p, "load_cache", 10)) {
2019 if(load_cache(ssl, worker)) send_ok(ssl);
2021 } else if(cmdcmp(p, "list_forwards", 13)) {
2022 do_list_forwards(ssl, worker);
2024 } else if(cmdcmp(p, "list_stubs", 10)) {
2025 do_list_stubs(ssl, worker);
2027 } else if(cmdcmp(p, "list_local_zones", 16)) {
2028 do_list_local_zones(ssl, worker);
2030 } else if(cmdcmp(p, "list_local_data", 15)) {
2031 do_list_local_data(ssl, worker);
2033 } else if(cmdcmp(p, "stub_add", 8)) {
2034 /* must always distribute this cmd */
2035 if(rc) distribute_cmd(rc, ssl, cmd);
2036 do_stub_add(ssl, worker, skipwhite(p+8));
2038 } else if(cmdcmp(p, "stub_remove", 11)) {
2039 /* must always distribute this cmd */
2040 if(rc) distribute_cmd(rc, ssl, cmd);
2041 do_stub_remove(ssl, worker, skipwhite(p+11));
2043 } else if(cmdcmp(p, "forward_add", 11)) {
2044 /* must always distribute this cmd */
2045 if(rc) distribute_cmd(rc, ssl, cmd);
2046 do_forward_add(ssl, worker, skipwhite(p+11));
2048 } else if(cmdcmp(p, "forward_remove", 14)) {
2049 /* must always distribute this cmd */
2050 if(rc) distribute_cmd(rc, ssl, cmd);
2051 do_forward_remove(ssl, worker, skipwhite(p+14));
2053 } else if(cmdcmp(p, "forward", 7)) {
2054 /* must always distribute this cmd */
2055 if(rc) distribute_cmd(rc, ssl, cmd);
2056 do_forward(ssl, worker, skipwhite(p+7));
2058 } else if(cmdcmp(p, "flush_stats", 11)) {
2059 /* must always distribute this cmd */
2060 if(rc) distribute_cmd(rc, ssl, cmd);
2061 do_flush_stats(ssl, worker);
2063 } else if(cmdcmp(p, "flush_requestlist", 17)) {
2064 /* must always distribute this cmd */
2065 if(rc) distribute_cmd(rc, ssl, cmd);
2066 do_flush_requestlist(ssl, worker);
2068 } else if(cmdcmp(p, "lookup", 6)) {
2069 do_lookup(ssl, worker, skipwhite(p+6));
2073 #ifdef THREADS_DISABLED
2074 /* other processes must execute the command as well */
2075 /* commands that should not be distributed, returned above. */
2076 if(rc) { /* only if this thread is the master (rc) thread */
2077 /* done before the code below, which may split the string */
2078 distribute_cmd(rc, ssl, cmd);
2081 if(cmdcmp(p, "verbosity", 9)) {
2082 do_verbosity(ssl, skipwhite(p+9));
2083 } else if(cmdcmp(p, "local_zone_remove", 17)) {
2084 do_zone_remove(ssl, worker, skipwhite(p+17));
2085 } else if(cmdcmp(p, "local_zone", 10)) {
2086 do_zone_add(ssl, worker, skipwhite(p+10));
2087 } else if(cmdcmp(p, "local_data_remove", 17)) {
2088 do_data_remove(ssl, worker, skipwhite(p+17));
2089 } else if(cmdcmp(p, "local_data", 10)) {
2090 do_data_add(ssl, worker, skipwhite(p+10));
2091 } else if(cmdcmp(p, "flush_zone", 10)) {
2092 do_flush_zone(ssl, worker, skipwhite(p+10));
2093 } else if(cmdcmp(p, "flush_type", 10)) {
2094 do_flush_type(ssl, worker, skipwhite(p+10));
2095 } else if(cmdcmp(p, "flush_infra", 11)) {
2096 do_flush_infra(ssl, worker, skipwhite(p+11));
2097 } else if(cmdcmp(p, "flush", 5)) {
2098 do_flush_name(ssl, worker, skipwhite(p+5));
2099 } else if(cmdcmp(p, "dump_requestlist", 16)) {
2100 do_dump_requestlist(ssl, worker);
2101 } else if(cmdcmp(p, "dump_infra", 10)) {
2102 do_dump_infra(ssl, worker);
2103 } else if(cmdcmp(p, "log_reopen", 10)) {
2104 do_log_reopen(ssl, worker);
2105 } else if(cmdcmp(p, "set_option", 10)) {
2106 do_set_option(ssl, worker, skipwhite(p+10));
2107 } else if(cmdcmp(p, "get_option", 10)) {
2108 do_get_option(ssl, worker, skipwhite(p+10));
2109 } else if(cmdcmp(p, "flush_bogus", 11)) {
2110 do_flush_bogus(ssl, worker);
2112 (void)ssl_printf(ssl, "error unknown command '%s'\n", p);
2117 daemon_remote_exec(struct worker* worker)
2119 /* read the cmd string */
2120 uint8_t* msg = NULL;
2122 if(!tube_read_msg(worker->cmd, &msg, &len, 0)) {
2123 log_err("daemon_remote_exec: tube_read_msg failed");
2126 verbose(VERB_ALGO, "remote exec distributed: %s", (char*)msg);
2127 execute_cmd(NULL, NULL, (char*)msg, worker);
2131 /** handle remote control request */
2133 handle_req(struct daemon_remote* rc, struct rc_state* s, SSL* ssl)
2140 /* makes it possible to set the socket blocking again. */
2141 /* basically removes it from winsock_event ... */
2142 WSAEventSelect(s->c->fd, NULL, 0);
2144 fd_set_block(s->c->fd);
2146 /* try to read magic UBCT[version]_space_ string */
2148 if((r=SSL_read(ssl, magic, (int)sizeof(magic)-1)) <= 0) {
2149 if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN)
2151 log_crypto_err("could not SSL_read");
2155 if( r != 6 || strncmp(magic, "UBCT", 4) != 0) {
2156 verbose(VERB_QUERY, "control connection has bad magic string");
2157 /* probably wrong tool connected, ignore it completely */
2161 /* read the command line */
2162 if(!ssl_read_line(ssl, buf, sizeof(buf))) {
2165 snprintf(pre, sizeof(pre), "UBCT%d ", UNBOUND_CONTROL_VERSION);
2166 if(strcmp(magic, pre) != 0) {
2167 verbose(VERB_QUERY, "control connection had bad "
2168 "version %s, cmd: %s", magic, buf);
2169 ssl_printf(ssl, "error version mismatch\n");
2172 verbose(VERB_DETAIL, "control cmd: %s", buf);
2174 /* figure out what to do */
2175 execute_cmd(rc, ssl, buf, rc->worker);
2178 int remote_control_callback(struct comm_point* c, void* arg, int err,
2179 struct comm_reply* ATTR_UNUSED(rep))
2181 struct rc_state* s = (struct rc_state*)arg;
2182 struct daemon_remote* rc = s->rc;
2184 if(err != NETEVENT_NOERROR) {
2185 if(err==NETEVENT_TIMEOUT)
2186 log_err("remote control timed out");
2190 /* (continue to) setup the SSL connection */
2192 r = SSL_do_handshake(s->ssl);
2194 int r2 = SSL_get_error(s->ssl, r);
2195 if(r2 == SSL_ERROR_WANT_READ) {
2196 if(s->shake_state == rc_hs_read) {
2197 /* try again later */
2200 s->shake_state = rc_hs_read;
2201 comm_point_listen_for_rw(c, 1, 0);
2203 } else if(r2 == SSL_ERROR_WANT_WRITE) {
2204 if(s->shake_state == rc_hs_write) {
2205 /* try again later */
2208 s->shake_state = rc_hs_write;
2209 comm_point_listen_for_rw(c, 0, 1);
2213 log_err("remote control connection closed prematurely");
2214 log_addr(1, "failed connection from",
2215 &s->c->repinfo.addr, s->c->repinfo.addrlen);
2216 log_crypto_err("remote control failed ssl");
2221 s->shake_state = rc_none;
2223 /* once handshake has completed, check authentication */
2224 if(SSL_get_verify_result(s->ssl) == X509_V_OK) {
2225 X509* x = SSL_get_peer_certificate(s->ssl);
2227 verbose(VERB_DETAIL, "remote control connection "
2228 "provided no client certificate");
2232 verbose(VERB_ALGO, "remote control connection authenticated");
2235 verbose(VERB_DETAIL, "remote control connection failed to "
2236 "authenticate with client certificate");
2241 /* if OK start to actually handle the request */
2242 handle_req(rc, s, s->ssl);
2244 verbose(VERB_ALGO, "remote control operation completed");