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 TLS capable web browser.
42 * The channel is secured using TLSv1, and certificates.
43 * Both the server and the client(control tool) have their own keys.
46 #ifdef HAVE_OPENSSL_ERR_H
47 #include <openssl/err.h>
49 #ifdef HAVE_OPENSSL_DH_H
50 #include <openssl/dh.h>
52 #ifdef HAVE_OPENSSL_BN_H
53 #include <openssl/bn.h>
57 #include "daemon/remote.h"
58 #include "daemon/worker.h"
59 #include "daemon/daemon.h"
60 #include "daemon/stats.h"
61 #include "daemon/cachedump.h"
63 #include "util/config_file.h"
64 #include "util/net_help.h"
65 #include "util/module.h"
66 #include "services/listen_dnsport.h"
67 #include "services/cache/rrset.h"
68 #include "services/cache/infra.h"
69 #include "services/mesh.h"
70 #include "services/localzone.h"
71 #include "services/authzone.h"
72 #include "util/storage/slabhash.h"
73 #include "util/fptr_wlist.h"
74 #include "util/data/dname.h"
75 #include "validator/validator.h"
76 #include "validator/val_kcache.h"
77 #include "validator/val_kentry.h"
78 #include "validator/val_anchor.h"
79 #include "iterator/iterator.h"
80 #include "iterator/iter_fwd.h"
81 #include "iterator/iter_hints.h"
82 #include "iterator/iter_delegpt.h"
83 #include "services/outbound_list.h"
84 #include "services/outside_network.h"
85 #include "sldns/str2wire.h"
86 #include "sldns/parseutil.h"
87 #include "sldns/wire2str.h"
88 #include "sldns/sbuffer.h"
90 #ifdef HAVE_SYS_TYPES_H
91 # include <sys/types.h>
93 #ifdef HAVE_SYS_STAT_H
100 /* just for portability */
105 /** what to put on statistics lines between var and value, ": " or "=" */
107 /** if true, inhibits a lot of =0 lines from the stats output */
108 static const int inhibit_zero = 1;
110 /** subtract timers and the values do not overflow or become negative */
112 timeval_subtract(struct timeval* d, const struct timeval* end,
113 const struct timeval* start)
116 time_t end_usec = end->tv_usec;
117 d->tv_sec = end->tv_sec - start->tv_sec;
118 if(end_usec < start->tv_usec) {
122 d->tv_usec = end_usec - start->tv_usec;
126 /** divide sum of timers to get average */
128 timeval_divide(struct timeval* avg, const struct timeval* sum, long long d)
137 avg->tv_sec = sum->tv_sec / d;
138 avg->tv_usec = sum->tv_usec / d;
139 /* handle fraction from seconds divide */
140 leftover = sum->tv_sec - avg->tv_sec*d;
141 avg->tv_usec += (leftover*1000000)/d;
146 remote_setup_ctx(struct daemon_remote* rc, struct config_file* cfg)
150 rc->ctx = SSL_CTX_new(SSLv23_server_method());
152 log_crypto_err("could not SSL_CTX_new");
155 if(!listen_sslctx_setup(rc->ctx)) {
159 s_cert = fname_after_chroot(cfg->server_cert_file, cfg, 1);
160 s_key = fname_after_chroot(cfg->server_key_file, cfg, 1);
161 if(!s_cert || !s_key) {
162 log_err("out of memory in remote control fname");
165 verbose(VERB_ALGO, "setup SSL certificates");
166 if (!SSL_CTX_use_certificate_chain_file(rc->ctx,s_cert)) {
167 log_err("Error for server-cert-file: %s", s_cert);
168 log_crypto_err("Error in SSL_CTX use_certificate_chain_file");
171 if(!SSL_CTX_use_PrivateKey_file(rc->ctx,s_key,SSL_FILETYPE_PEM)) {
172 log_err("Error for server-key-file: %s", s_key);
173 log_crypto_err("Error in SSL_CTX use_PrivateKey_file");
176 if(!SSL_CTX_check_private_key(rc->ctx)) {
177 log_err("Error for server-key-file: %s", s_key);
178 log_crypto_err("Error in SSL_CTX check_private_key");
181 listen_sslctx_setup_2(rc->ctx);
182 if(!SSL_CTX_load_verify_locations(rc->ctx, s_cert, NULL)) {
183 log_crypto_err("Error setting up SSL_CTX verify locations");
189 SSL_CTX_set_client_CA_list(rc->ctx, SSL_load_client_CA_file(s_cert));
190 SSL_CTX_set_verify(rc->ctx, SSL_VERIFY_PEER, NULL);
196 struct daemon_remote*
197 daemon_remote_create(struct config_file* cfg)
199 struct daemon_remote* rc = (struct daemon_remote*)calloc(1,
202 log_err("out of memory in daemon_remote_create");
207 if(!cfg->remote_control_enable) {
211 if(options_remote_is_address(cfg) && cfg->control_use_cert) {
212 if(!remote_setup_ctx(rc, cfg)) {
213 daemon_remote_delete(rc);
218 struct config_strlist* p;
221 if(!options_remote_is_address(cfg))
222 for(p = cfg->control_ifs.first; p; p = p->next) {
223 if(p->str && p->str[0] != '/')
224 log_warn("control-interface %s is not using TLS, but plain transfer, because first control-interface in config file is a local socket (starts with a /).", p->str);
230 void daemon_remote_clear(struct daemon_remote* rc)
232 struct rc_state* p, *np;
234 /* but do not close the ports */
235 listen_list_delete(rc->accept_list);
236 rc->accept_list = NULL;
237 /* do close these sockets */
243 comm_point_delete(p->c);
247 rc->busy_list = NULL;
252 void daemon_remote_delete(struct daemon_remote* rc)
255 daemon_remote_clear(rc);
257 SSL_CTX_free(rc->ctx);
263 * Add and open a new control port
266 * @param list: list head
267 * @param noproto_is_err: if lack of protocol support is an error.
268 * @param cfg: config with username for chown of unix-sockets.
269 * @return false on failure.
272 add_open(const char* ip, int nr, struct listen_port** list, int noproto_is_err,
273 struct config_file* cfg)
275 struct addrinfo hints;
276 struct addrinfo* res;
277 struct listen_port* n;
281 snprintf(port, sizeof(port), "%d", nr);
282 port[sizeof(port)-1]=0;
283 memset(&hints, 0, sizeof(hints));
286 /* This looks like a local socket */
287 fd = create_local_accept_sock(ip, &noproto, cfg->use_systemd);
289 * Change socket ownership and permissions so users other
290 * than root can access it provided they are in the same
291 * group as the user we run as.
295 if (cfg->username && cfg->username[0] &&
296 cfg_uid != (uid_t)-1) {
297 if(chown(ip, cfg_uid, cfg_gid) == -1)
298 verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
299 (unsigned)cfg_uid, (unsigned)cfg_gid,
300 ip, strerror(errno));
302 chmod(ip, (mode_t)(S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP));
308 hints.ai_socktype = SOCK_STREAM;
309 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
310 if((r = getaddrinfo(ip, port, &hints, &res)) != 0 || !res) {
312 if(!noproto_is_err && r == EAI_NONAME) {
313 /* tried to lookup the address as name */
314 return 1; /* return success, but do nothing */
316 #endif /* USE_WINSOCK */
317 log_err("control interface %s:%s getaddrinfo: %s %s",
318 ip?ip:"default", port, gai_strerror(r),
320 r==EAI_SYSTEM?(char*)strerror(errno):""
329 fd = create_tcp_accept_sock(res, 1, &noproto, 0,
330 cfg->ip_transparent, 0, cfg->ip_freebind, cfg->use_systemd);
334 if(fd == -1 && noproto) {
336 return 1; /* return success, but do nothing */
337 log_err("cannot open control interface %s %d : "
338 "protocol not supported", ip, nr);
342 log_err("cannot open control interface %s %d", ip, nr);
347 n = (struct listen_port*)calloc(1, sizeof(*n));
354 log_err("out of memory");
363 struct listen_port* daemon_remote_open_ports(struct config_file* cfg)
365 struct listen_port* l = NULL;
366 log_assert(cfg->remote_control_enable && cfg->control_port);
367 if(cfg->control_ifs.first) {
368 struct config_strlist* p;
369 for(p = cfg->control_ifs.first; p; p = p->next) {
370 if(!add_open(p->str, cfg->control_port, &l, 1, cfg)) {
371 listening_ports_free(l);
378 !add_open("::1", cfg->control_port, &l, 0, cfg)) {
379 listening_ports_free(l);
383 !add_open("127.0.0.1", cfg->control_port, &l, 1, cfg)) {
384 listening_ports_free(l);
391 /** open accept commpoint */
393 accept_open(struct daemon_remote* rc, int fd)
395 struct listen_list* n = (struct listen_list*)malloc(sizeof(*n));
397 log_err("out of memory");
400 n->next = rc->accept_list;
403 n->com = comm_point_create_raw(rc->worker->base, fd, 0,
404 &remote_accept_callback, rc);
407 /* keep this port open, its fd is kept in the rc portlist */
408 n->com->do_not_close = 1;
412 int daemon_remote_open_accept(struct daemon_remote* rc,
413 struct listen_port* ports, struct worker* worker)
415 struct listen_port* p;
417 for(p = ports; p; p = p->next) {
418 if(!accept_open(rc, p->fd)) {
419 log_err("could not create accept comm point");
426 void daemon_remote_stop_accept(struct daemon_remote* rc)
428 struct listen_list* p;
429 for(p=rc->accept_list; p; p=p->next) {
430 comm_point_stop_listening(p->com);
434 void daemon_remote_start_accept(struct daemon_remote* rc)
436 struct listen_list* p;
437 for(p=rc->accept_list; p; p=p->next) {
438 comm_point_start_listening(p->com, -1, -1);
442 int remote_accept_callback(struct comm_point* c, void* arg, int err,
443 struct comm_reply* ATTR_UNUSED(rep))
445 struct daemon_remote* rc = (struct daemon_remote*)arg;
446 struct sockaddr_storage addr;
450 if(err != NETEVENT_NOERROR) {
451 log_err("error %d on remote_accept_callback", err);
454 /* perform the accept */
455 newfd = comm_point_perform_accept(c, &addr, &addrlen);
458 /* create new commpoint unless we are servicing already */
459 if(rc->active >= rc->max_active) {
460 log_warn("drop incoming remote control: too many connections");
470 /* setup commpoint to service the remote control command */
471 n = (struct rc_state*)calloc(1, sizeof(*n));
473 log_err("out of memory");
477 /* start in reading state */
478 n->c = comm_point_create_raw(rc->worker->base, newfd, 0,
479 &remote_control_callback, n);
481 log_err("out of memory");
485 log_addr(VERB_QUERY, "new control connection from", &addr, addrlen);
486 n->c->do_not_close = 0;
487 comm_point_stop_listening(n->c);
488 comm_point_start_listening(n->c, -1, REMOTE_CONTROL_TCP_TIMEOUT);
489 memcpy(&n->c->repinfo.addr, &addr, addrlen);
490 n->c->repinfo.addrlen = addrlen;
492 n->shake_state = rc_hs_read;
493 n->ssl = SSL_new(rc->ctx);
495 log_crypto_err("could not SSL_new");
496 comm_point_delete(n->c);
500 SSL_set_accept_state(n->ssl);
501 (void)SSL_set_mode(n->ssl, SSL_MODE_AUTO_RETRY);
502 if(!SSL_set_fd(n->ssl, newfd)) {
503 log_crypto_err("could not SSL_set_fd");
505 comm_point_delete(n->c);
514 n->next = rc->busy_list;
518 /* perform the first nonblocking read already, for windows,
519 * so it can return wouldblock. could be faster too. */
520 (void)remote_control_callback(n->c, n, NETEVENT_NOERROR, NULL);
524 /** delete from list */
526 state_list_remove_elem(struct rc_state** list, struct comm_point* c)
529 if( (*list)->c == c) {
530 *list = (*list)->next;
533 list = &(*list)->next;
537 /** decrease active count and remove commpoint from busy list */
539 clean_point(struct daemon_remote* rc, struct rc_state* s)
541 state_list_remove_elem(&rc->busy_list, s->c);
544 SSL_shutdown(s->ssl);
547 comm_point_delete(s->c);
552 ssl_print_text(RES* res, const char* text)
559 if((r=SSL_write(res->ssl, text, (int)strlen(text))) <= 0) {
560 if(SSL_get_error(res->ssl, r) == SSL_ERROR_ZERO_RETURN) {
561 verbose(VERB_QUERY, "warning, in SSL_write, peer "
562 "closed connection");
565 log_crypto_err("could not SSL_write");
570 while(at < strlen(text)) {
571 ssize_t r = send(res->fd, text+at, strlen(text)-at, 0);
573 if(errno == EAGAIN || errno == EINTR)
576 log_err("could not send: %s", strerror(errno));
578 log_err("could not send: %s", wsa_strerror(WSAGetLastError()));
588 /** print text over the ssl connection */
590 ssl_print_vmsg(RES* ssl, const char* format, va_list args)
593 vsnprintf(msg, sizeof(msg), format, args);
594 return ssl_print_text(ssl, msg);
597 /** printf style printing to the ssl connection */
598 int ssl_printf(RES* ssl, const char* format, ...)
602 va_start(args, format);
603 ret = ssl_print_vmsg(ssl, format, args);
609 ssl_read_line(RES* res, char* buf, size_t max)
618 if((r=SSL_read(res->ssl, buf+len, 1)) <= 0) {
619 if(SSL_get_error(res->ssl, r) == SSL_ERROR_ZERO_RETURN) {
623 log_crypto_err("could not SSL_read");
628 ssize_t rr = recv(res->fd, buf+len, 1, 0);
634 if(errno == EINTR || errno == EAGAIN)
637 log_err("could not recv: %s", strerror(errno));
639 log_err("could not recv: %s", wsa_strerror(WSAGetLastError()));
646 if(buf[len] == '\n') {
647 /* return string without \n */
654 log_err("control line too long (%d): %s", (int)max, buf);
658 /** skip whitespace, return new pointer into string */
662 /* EOS \0 is not a space */
663 while( isspace((unsigned char)*str) )
668 /** send the OK to the control client */
669 static void send_ok(RES* ssl)
671 (void)ssl_printf(ssl, "ok\n");
674 /** do the stop command */
676 do_stop(RES* ssl, struct daemon_remote* rc)
678 rc->worker->need_to_exit = 1;
679 comm_base_exit(rc->worker->base);
683 /** do the reload command */
685 do_reload(RES* ssl, struct daemon_remote* rc)
687 rc->worker->need_to_exit = 0;
688 comm_base_exit(rc->worker->base);
692 /** do the verbosity command */
694 do_verbosity(RES* ssl, char* str)
697 if(val == 0 && strcmp(str, "0") != 0) {
698 ssl_printf(ssl, "error in verbosity number syntax: %s\n", str);
705 /** print stats from statinfo */
707 print_stats(RES* ssl, const char* nm, struct ub_stats_info* s)
709 struct timeval sumwait, avg;
710 if(!ssl_printf(ssl, "%s.num.queries"SQ"%lu\n", nm,
711 (unsigned long)s->svr.num_queries)) return 0;
712 if(!ssl_printf(ssl, "%s.num.queries_ip_ratelimited"SQ"%lu\n", nm,
713 (unsigned long)s->svr.num_queries_ip_ratelimited)) return 0;
714 if(!ssl_printf(ssl, "%s.num.cachehits"SQ"%lu\n", nm,
715 (unsigned long)(s->svr.num_queries
716 - s->svr.num_queries_missed_cache))) return 0;
717 if(!ssl_printf(ssl, "%s.num.cachemiss"SQ"%lu\n", nm,
718 (unsigned long)s->svr.num_queries_missed_cache)) return 0;
719 if(!ssl_printf(ssl, "%s.num.prefetch"SQ"%lu\n", nm,
720 (unsigned long)s->svr.num_queries_prefetch)) return 0;
721 if(!ssl_printf(ssl, "%s.num.zero_ttl"SQ"%lu\n", nm,
722 (unsigned long)s->svr.zero_ttl_responses)) return 0;
723 if(!ssl_printf(ssl, "%s.num.recursivereplies"SQ"%lu\n", nm,
724 (unsigned long)s->mesh_replies_sent)) return 0;
726 if(!ssl_printf(ssl, "%s.num.dnscrypt.crypted"SQ"%lu\n", nm,
727 (unsigned long)s->svr.num_query_dnscrypt_crypted)) return 0;
728 if(!ssl_printf(ssl, "%s.num.dnscrypt.cert"SQ"%lu\n", nm,
729 (unsigned long)s->svr.num_query_dnscrypt_cert)) return 0;
730 if(!ssl_printf(ssl, "%s.num.dnscrypt.cleartext"SQ"%lu\n", nm,
731 (unsigned long)s->svr.num_query_dnscrypt_cleartext)) return 0;
732 if(!ssl_printf(ssl, "%s.num.dnscrypt.malformed"SQ"%lu\n", nm,
733 (unsigned long)s->svr.num_query_dnscrypt_crypted_malformed)) return 0;
735 if(!ssl_printf(ssl, "%s.requestlist.avg"SQ"%g\n", nm,
736 (s->svr.num_queries_missed_cache+s->svr.num_queries_prefetch)?
737 (double)s->svr.sum_query_list_size/
738 (double)(s->svr.num_queries_missed_cache+
739 s->svr.num_queries_prefetch) : 0.0)) return 0;
740 if(!ssl_printf(ssl, "%s.requestlist.max"SQ"%lu\n", nm,
741 (unsigned long)s->svr.max_query_list_size)) return 0;
742 if(!ssl_printf(ssl, "%s.requestlist.overwritten"SQ"%lu\n", nm,
743 (unsigned long)s->mesh_jostled)) return 0;
744 if(!ssl_printf(ssl, "%s.requestlist.exceeded"SQ"%lu\n", nm,
745 (unsigned long)s->mesh_dropped)) return 0;
746 if(!ssl_printf(ssl, "%s.requestlist.current.all"SQ"%lu\n", nm,
747 (unsigned long)s->mesh_num_states)) return 0;
748 if(!ssl_printf(ssl, "%s.requestlist.current.user"SQ"%lu\n", nm,
749 (unsigned long)s->mesh_num_reply_states)) return 0;
751 sumwait.tv_sec = s->mesh_replies_sum_wait_sec;
752 sumwait.tv_usec = s->mesh_replies_sum_wait_usec;
754 timeval_divide(&avg, &sumwait, s->mesh_replies_sent);
755 if(!ssl_printf(ssl, "%s.recursion.time.avg"SQ ARG_LL "d.%6.6d\n", nm,
756 (long long)avg.tv_sec, (int)avg.tv_usec)) return 0;
757 if(!ssl_printf(ssl, "%s.recursion.time.median"SQ"%g\n", nm,
758 s->mesh_time_median)) return 0;
759 if(!ssl_printf(ssl, "%s.tcpusage"SQ"%lu\n", nm,
760 (unsigned long)s->svr.tcp_accept_usage)) return 0;
764 /** print stats for one thread */
766 print_thread_stats(RES* ssl, int i, struct ub_stats_info* s)
769 snprintf(nm, sizeof(nm), "thread%d", i);
771 return print_stats(ssl, nm, s);
774 /** print long number */
776 print_longnum(RES* ssl, const char* desc, size_t x)
778 if(x > 1024*1024*1024) {
780 size_t front = x / (size_t)1000000;
781 size_t back = x % (size_t)1000000;
782 return ssl_printf(ssl, "%s%u%6.6u\n", desc,
783 (unsigned)front, (unsigned)back);
785 return ssl_printf(ssl, "%s%lu\n", desc, (unsigned long)x);
789 /** print mem stats */
791 print_mem(RES* ssl, struct worker* worker, struct daemon* daemon)
793 size_t msg, rrset, val, iter, respip;
796 #endif /* CLIENT_SUBNET */
799 #endif /* USE_IPSECMOD */
801 size_t dnscrypt_shared_secret = 0;
802 size_t dnscrypt_nonce = 0;
803 #endif /* USE_DNSCRYPT */
804 msg = slabhash_get_mem(daemon->env->msg_cache);
805 rrset = slabhash_get_mem(&daemon->env->rrset_cache->table);
806 val = mod_get_mem(&worker->env, "validator");
807 iter = mod_get_mem(&worker->env, "iterator");
808 respip = mod_get_mem(&worker->env, "respip");
810 subnet = mod_get_mem(&worker->env, "subnet");
811 #endif /* CLIENT_SUBNET */
813 ipsecmod = mod_get_mem(&worker->env, "ipsecmod");
814 #endif /* USE_IPSECMOD */
816 if(daemon->dnscenv) {
817 dnscrypt_shared_secret = slabhash_get_mem(
818 daemon->dnscenv->shared_secrets_cache);
819 dnscrypt_nonce = slabhash_get_mem(daemon->dnscenv->nonces_cache);
821 #endif /* USE_DNSCRYPT */
823 if(!print_longnum(ssl, "mem.cache.rrset"SQ, rrset))
825 if(!print_longnum(ssl, "mem.cache.message"SQ, msg))
827 if(!print_longnum(ssl, "mem.mod.iterator"SQ, iter))
829 if(!print_longnum(ssl, "mem.mod.validator"SQ, val))
831 if(!print_longnum(ssl, "mem.mod.respip"SQ, respip))
834 if(!print_longnum(ssl, "mem.mod.subnet"SQ, subnet))
836 #endif /* CLIENT_SUBNET */
838 if(!print_longnum(ssl, "mem.mod.ipsecmod"SQ, ipsecmod))
840 #endif /* USE_IPSECMOD */
842 if(!print_longnum(ssl, "mem.cache.dnscrypt_shared_secret"SQ,
843 dnscrypt_shared_secret))
845 if(!print_longnum(ssl, "mem.cache.dnscrypt_nonce"SQ,
848 #endif /* USE_DNSCRYPT */
852 /** print uptime stats */
854 print_uptime(RES* ssl, struct worker* worker, int reset)
856 struct timeval now = *worker->env.now_tv;
857 struct timeval up, dt;
858 timeval_subtract(&up, &now, &worker->daemon->time_boot);
859 timeval_subtract(&dt, &now, &worker->daemon->time_last_stat);
861 worker->daemon->time_last_stat = now;
862 if(!ssl_printf(ssl, "time.now"SQ ARG_LL "d.%6.6d\n",
863 (long long)now.tv_sec, (unsigned)now.tv_usec)) return 0;
864 if(!ssl_printf(ssl, "time.up"SQ ARG_LL "d.%6.6d\n",
865 (long long)up.tv_sec, (unsigned)up.tv_usec)) return 0;
866 if(!ssl_printf(ssl, "time.elapsed"SQ ARG_LL "d.%6.6d\n",
867 (long long)dt.tv_sec, (unsigned)dt.tv_usec)) return 0;
871 /** print extended histogram */
873 print_hist(RES* ssl, struct ub_stats_info* s)
875 struct timehist* hist;
877 hist = timehist_setup();
879 log_err("out of memory");
882 timehist_import(hist, s->svr.hist, NUM_BUCKETS_HIST);
883 for(i=0; i<hist->num; i++) {
885 "histogram.%6.6d.%6.6d.to.%6.6d.%6.6d=%lu\n",
886 (int)hist->buckets[i].lower.tv_sec,
887 (int)hist->buckets[i].lower.tv_usec,
888 (int)hist->buckets[i].upper.tv_sec,
889 (int)hist->buckets[i].upper.tv_usec,
890 (unsigned long)hist->buckets[i].count)) {
891 timehist_delete(hist);
895 timehist_delete(hist);
899 /** print extended stats */
901 print_ext(RES* ssl, struct ub_stats_info* s)
905 const sldns_rr_descriptor* desc;
906 const sldns_lookup_table* lt;
908 for(i=0; i<UB_STATS_QTYPE_NUM; i++) {
909 if(inhibit_zero && s->svr.qtype[i] == 0)
911 desc = sldns_rr_descript((uint16_t)i);
912 if(desc && desc->_name) {
913 snprintf(nm, sizeof(nm), "%s", desc->_name);
914 } else if (i == LDNS_RR_TYPE_IXFR) {
915 snprintf(nm, sizeof(nm), "IXFR");
916 } else if (i == LDNS_RR_TYPE_AXFR) {
917 snprintf(nm, sizeof(nm), "AXFR");
918 } else if (i == LDNS_RR_TYPE_MAILA) {
919 snprintf(nm, sizeof(nm), "MAILA");
920 } else if (i == LDNS_RR_TYPE_MAILB) {
921 snprintf(nm, sizeof(nm), "MAILB");
922 } else if (i == LDNS_RR_TYPE_ANY) {
923 snprintf(nm, sizeof(nm), "ANY");
925 snprintf(nm, sizeof(nm), "TYPE%d", i);
927 if(!ssl_printf(ssl, "num.query.type.%s"SQ"%lu\n",
928 nm, (unsigned long)s->svr.qtype[i])) return 0;
930 if(!inhibit_zero || s->svr.qtype_big) {
931 if(!ssl_printf(ssl, "num.query.type.other"SQ"%lu\n",
932 (unsigned long)s->svr.qtype_big)) return 0;
935 for(i=0; i<UB_STATS_QCLASS_NUM; i++) {
936 if(inhibit_zero && s->svr.qclass[i] == 0)
938 lt = sldns_lookup_by_id(sldns_rr_classes, i);
940 snprintf(nm, sizeof(nm), "%s", lt->name);
942 snprintf(nm, sizeof(nm), "CLASS%d", i);
944 if(!ssl_printf(ssl, "num.query.class.%s"SQ"%lu\n",
945 nm, (unsigned long)s->svr.qclass[i])) return 0;
947 if(!inhibit_zero || s->svr.qclass_big) {
948 if(!ssl_printf(ssl, "num.query.class.other"SQ"%lu\n",
949 (unsigned long)s->svr.qclass_big)) return 0;
952 for(i=0; i<UB_STATS_OPCODE_NUM; i++) {
953 if(inhibit_zero && s->svr.qopcode[i] == 0)
955 lt = sldns_lookup_by_id(sldns_opcodes, i);
957 snprintf(nm, sizeof(nm), "%s", lt->name);
959 snprintf(nm, sizeof(nm), "OPCODE%d", i);
961 if(!ssl_printf(ssl, "num.query.opcode.%s"SQ"%lu\n",
962 nm, (unsigned long)s->svr.qopcode[i])) return 0;
965 if(!ssl_printf(ssl, "num.query.tcp"SQ"%lu\n",
966 (unsigned long)s->svr.qtcp)) return 0;
967 if(!ssl_printf(ssl, "num.query.tcpout"SQ"%lu\n",
968 (unsigned long)s->svr.qtcp_outgoing)) return 0;
969 if(!ssl_printf(ssl, "num.query.ipv6"SQ"%lu\n",
970 (unsigned long)s->svr.qipv6)) return 0;
972 if(!ssl_printf(ssl, "num.query.flags.QR"SQ"%lu\n",
973 (unsigned long)s->svr.qbit_QR)) return 0;
974 if(!ssl_printf(ssl, "num.query.flags.AA"SQ"%lu\n",
975 (unsigned long)s->svr.qbit_AA)) return 0;
976 if(!ssl_printf(ssl, "num.query.flags.TC"SQ"%lu\n",
977 (unsigned long)s->svr.qbit_TC)) return 0;
978 if(!ssl_printf(ssl, "num.query.flags.RD"SQ"%lu\n",
979 (unsigned long)s->svr.qbit_RD)) return 0;
980 if(!ssl_printf(ssl, "num.query.flags.RA"SQ"%lu\n",
981 (unsigned long)s->svr.qbit_RA)) return 0;
982 if(!ssl_printf(ssl, "num.query.flags.Z"SQ"%lu\n",
983 (unsigned long)s->svr.qbit_Z)) return 0;
984 if(!ssl_printf(ssl, "num.query.flags.AD"SQ"%lu\n",
985 (unsigned long)s->svr.qbit_AD)) return 0;
986 if(!ssl_printf(ssl, "num.query.flags.CD"SQ"%lu\n",
987 (unsigned long)s->svr.qbit_CD)) return 0;
988 if(!ssl_printf(ssl, "num.query.edns.present"SQ"%lu\n",
989 (unsigned long)s->svr.qEDNS)) return 0;
990 if(!ssl_printf(ssl, "num.query.edns.DO"SQ"%lu\n",
991 (unsigned long)s->svr.qEDNS_DO)) return 0;
994 for(i=0; i<UB_STATS_RCODE_NUM; i++) {
995 /* Always include RCODEs 0-5 */
996 if(inhibit_zero && i > LDNS_RCODE_REFUSED && s->svr.ans_rcode[i] == 0)
998 lt = sldns_lookup_by_id(sldns_rcodes, i);
1000 snprintf(nm, sizeof(nm), "%s", lt->name);
1002 snprintf(nm, sizeof(nm), "RCODE%d", i);
1004 if(!ssl_printf(ssl, "num.answer.rcode.%s"SQ"%lu\n",
1005 nm, (unsigned long)s->svr.ans_rcode[i])) return 0;
1007 if(!inhibit_zero || s->svr.ans_rcode_nodata) {
1008 if(!ssl_printf(ssl, "num.answer.rcode.nodata"SQ"%lu\n",
1009 (unsigned long)s->svr.ans_rcode_nodata)) return 0;
1012 if(!ssl_printf(ssl, "num.query.ratelimited"SQ"%lu\n",
1013 (unsigned long)s->svr.queries_ratelimited)) return 0;
1015 if(!ssl_printf(ssl, "num.answer.secure"SQ"%lu\n",
1016 (unsigned long)s->svr.ans_secure)) return 0;
1017 if(!ssl_printf(ssl, "num.answer.bogus"SQ"%lu\n",
1018 (unsigned long)s->svr.ans_bogus)) return 0;
1019 if(!ssl_printf(ssl, "num.rrset.bogus"SQ"%lu\n",
1020 (unsigned long)s->svr.rrset_bogus)) return 0;
1021 if(!ssl_printf(ssl, "num.query.aggressive.NOERROR"SQ"%lu\n",
1022 (unsigned long)s->svr.num_neg_cache_noerror)) return 0;
1023 if(!ssl_printf(ssl, "num.query.aggressive.NXDOMAIN"SQ"%lu\n",
1024 (unsigned long)s->svr.num_neg_cache_nxdomain)) return 0;
1025 /* threat detection */
1026 if(!ssl_printf(ssl, "unwanted.queries"SQ"%lu\n",
1027 (unsigned long)s->svr.unwanted_queries)) return 0;
1028 if(!ssl_printf(ssl, "unwanted.replies"SQ"%lu\n",
1029 (unsigned long)s->svr.unwanted_replies)) return 0;
1031 if(!ssl_printf(ssl, "msg.cache.count"SQ"%u\n",
1032 (unsigned)s->svr.msg_cache_count)) return 0;
1033 if(!ssl_printf(ssl, "rrset.cache.count"SQ"%u\n",
1034 (unsigned)s->svr.rrset_cache_count)) return 0;
1035 if(!ssl_printf(ssl, "infra.cache.count"SQ"%u\n",
1036 (unsigned)s->svr.infra_cache_count)) return 0;
1037 if(!ssl_printf(ssl, "key.cache.count"SQ"%u\n",
1038 (unsigned)s->svr.key_cache_count)) return 0;
1040 if(!ssl_printf(ssl, "dnscrypt_shared_secret.cache.count"SQ"%u\n",
1041 (unsigned)s->svr.shared_secret_cache_count)) return 0;
1042 if(!ssl_printf(ssl, "dnscrypt_nonce.cache.count"SQ"%u\n",
1043 (unsigned)s->svr.nonce_cache_count)) return 0;
1044 if(!ssl_printf(ssl, "num.query.dnscrypt.shared_secret.cachemiss"SQ"%lu\n",
1045 (unsigned long)s->svr.num_query_dnscrypt_secret_missed_cache)) return 0;
1046 if(!ssl_printf(ssl, "num.query.dnscrypt.replay"SQ"%lu\n",
1047 (unsigned long)s->svr.num_query_dnscrypt_replay)) return 0;
1048 #endif /* USE_DNSCRYPT */
1049 if(!ssl_printf(ssl, "num.query.authzone.up"SQ"%lu\n",
1050 (unsigned long)s->svr.num_query_authzone_up)) return 0;
1051 if(!ssl_printf(ssl, "num.query.authzone.down"SQ"%lu\n",
1052 (unsigned long)s->svr.num_query_authzone_down)) return 0;
1056 /** do the stats command */
1058 do_stats(RES* ssl, struct daemon_remote* rc, int reset)
1060 struct daemon* daemon = rc->worker->daemon;
1061 struct ub_stats_info total;
1062 struct ub_stats_info s;
1064 log_assert(daemon->num > 0);
1065 /* gather all thread statistics in one place */
1066 for(i=0; i<daemon->num; i++) {
1067 server_stats_obtain(rc->worker, daemon->workers[i], &s, reset);
1068 if(!print_thread_stats(ssl, i, &s))
1072 else server_stats_add(&total, &s);
1074 /* print the thread statistics */
1075 total.mesh_time_median /= (double)daemon->num;
1076 if(!print_stats(ssl, "total", &total))
1078 if(!print_uptime(ssl, rc->worker, reset))
1080 if(daemon->cfg->stat_extended) {
1081 if(!print_mem(ssl, rc->worker, daemon))
1083 if(!print_hist(ssl, &total))
1085 if(!print_ext(ssl, &total))
1090 /** parse commandline argument domain name */
1092 parse_arg_name(RES* ssl, char* str, uint8_t** res, size_t* len, int* labs)
1094 uint8_t nm[LDNS_MAX_DOMAINLEN+1];
1095 size_t nmlen = sizeof(nm);
1100 status = sldns_str2wire_dname_buf(str, nm, &nmlen);
1102 ssl_printf(ssl, "error cannot parse name %s at %d: %s\n", str,
1103 LDNS_WIREPARSE_OFFSET(status),
1104 sldns_get_errorstr_parse(status));
1107 *res = memdup(nm, nmlen);
1109 ssl_printf(ssl, "error out of memory\n");
1112 *labs = dname_count_size_labels(*res, len);
1116 /** find second argument, modifies string */
1118 find_arg2(RES* ssl, char* arg, char** arg2)
1120 char* as = strchr(arg, ' ');
1121 char* at = strchr(arg, '\t');
1126 *arg2 = skipwhite(as+1);
1129 *arg2 = skipwhite(as+1);
1132 *arg2 = skipwhite(at+1);
1134 ssl_printf(ssl, "error could not find next argument "
1141 /** Add a new zone */
1143 perform_zone_add(RES* ssl, struct local_zones* zones, char* arg)
1149 enum localzone_type t;
1150 struct local_zone* z;
1151 if(!find_arg2(ssl, arg, &arg2))
1153 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1155 if(!local_zone_str2type(arg2, &t)) {
1156 ssl_printf(ssl, "error not a zone type. %s\n", arg2);
1160 lock_rw_wrlock(&zones->lock);
1161 if((z=local_zones_find(zones, nm, nmlen,
1162 nmlabs, LDNS_RR_CLASS_IN))) {
1163 /* already present in tree */
1164 lock_rw_wrlock(&z->lock);
1165 z->type = t; /* update type anyway */
1166 lock_rw_unlock(&z->lock);
1168 lock_rw_unlock(&zones->lock);
1171 if(!local_zones_add_zone(zones, nm, nmlen,
1172 nmlabs, LDNS_RR_CLASS_IN, t)) {
1173 lock_rw_unlock(&zones->lock);
1174 ssl_printf(ssl, "error out of memory\n");
1177 lock_rw_unlock(&zones->lock);
1181 /** Do the local_zone command */
1183 do_zone_add(RES* ssl, struct local_zones* zones, char* arg)
1185 if(!perform_zone_add(ssl, zones, arg))
1190 /** Do the local_zones command */
1192 do_zones_add(RES* ssl, struct local_zones* zones)
1196 while(ssl_read_line(ssl, buf, sizeof(buf))) {
1197 if(buf[0] == 0x04 && buf[1] == 0)
1198 break; /* end of transmission */
1199 if(!perform_zone_add(ssl, zones, buf)) {
1200 if(!ssl_printf(ssl, "error for input line: %s\n", buf))
1206 (void)ssl_printf(ssl, "added %d zones\n", num);
1209 /** Remove a zone */
1211 perform_zone_remove(RES* ssl, struct local_zones* zones, char* arg)
1216 struct local_zone* z;
1217 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1219 lock_rw_wrlock(&zones->lock);
1220 if((z=local_zones_find(zones, nm, nmlen,
1221 nmlabs, LDNS_RR_CLASS_IN))) {
1222 /* present in tree */
1223 local_zones_del_zone(zones, z);
1225 lock_rw_unlock(&zones->lock);
1230 /** Do the local_zone_remove command */
1232 do_zone_remove(RES* ssl, struct local_zones* zones, char* arg)
1234 if(!perform_zone_remove(ssl, zones, arg))
1239 /** Do the local_zones_remove command */
1241 do_zones_remove(RES* ssl, struct local_zones* zones)
1245 while(ssl_read_line(ssl, buf, sizeof(buf))) {
1246 if(buf[0] == 0x04 && buf[1] == 0)
1247 break; /* end of transmission */
1248 if(!perform_zone_remove(ssl, zones, buf)) {
1249 if(!ssl_printf(ssl, "error for input line: %s\n", buf))
1255 (void)ssl_printf(ssl, "removed %d zones\n", num);
1258 /** Add new RR data */
1260 perform_data_add(RES* ssl, struct local_zones* zones, char* arg)
1262 if(!local_zones_add_RR(zones, arg)) {
1263 ssl_printf(ssl,"error in syntax or out of memory, %s\n", arg);
1269 /** Do the local_data command */
1271 do_data_add(RES* ssl, struct local_zones* zones, char* arg)
1273 if(!perform_data_add(ssl, zones, arg))
1278 /** Do the local_datas command */
1280 do_datas_add(RES* ssl, struct local_zones* zones)
1284 while(ssl_read_line(ssl, buf, sizeof(buf))) {
1285 if(buf[0] == 0x04 && buf[1] == 0)
1286 break; /* end of transmission */
1287 if(!perform_data_add(ssl, zones, buf)) {
1288 if(!ssl_printf(ssl, "error for input line: %s\n", buf))
1294 (void)ssl_printf(ssl, "added %d datas\n", num);
1297 /** Remove RR data */
1299 perform_data_remove(RES* ssl, struct local_zones* zones, char* arg)
1304 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1306 local_zones_del_data(zones, nm,
1307 nmlen, nmlabs, LDNS_RR_CLASS_IN);
1312 /** Do the local_data_remove command */
1314 do_data_remove(RES* ssl, struct local_zones* zones, char* arg)
1316 if(!perform_data_remove(ssl, zones, arg))
1321 /** Do the local_datas_remove command */
1323 do_datas_remove(RES* ssl, struct local_zones* zones)
1327 while(ssl_read_line(ssl, buf, sizeof(buf))) {
1328 if(buf[0] == 0x04 && buf[1] == 0)
1329 break; /* end of transmission */
1330 if(!perform_data_remove(ssl, zones, buf)) {
1331 if(!ssl_printf(ssl, "error for input line: %s\n", buf))
1337 (void)ssl_printf(ssl, "removed %d datas\n", num);
1340 /** Add a new zone to view */
1342 do_view_zone_add(RES* ssl, struct worker* worker, char* arg)
1346 if(!find_arg2(ssl, arg, &arg2))
1348 v = views_find_view(worker->daemon->views,
1349 arg, 1 /* get write lock*/);
1351 ssl_printf(ssl,"no view with name: %s\n", arg);
1354 if(!v->local_zones) {
1355 if(!(v->local_zones = local_zones_create())){
1356 lock_rw_unlock(&v->lock);
1357 ssl_printf(ssl,"error out of memory\n");
1361 /* Global local-zone is not used for this view,
1362 * therefore add defaults to this view-specic
1364 struct config_file lz_cfg;
1365 memset(&lz_cfg, 0, sizeof(lz_cfg));
1366 local_zone_enter_defaults(v->local_zones, &lz_cfg);
1369 do_zone_add(ssl, v->local_zones, arg2);
1370 lock_rw_unlock(&v->lock);
1373 /** Remove a zone from view */
1375 do_view_zone_remove(RES* ssl, struct worker* worker, char* arg)
1379 if(!find_arg2(ssl, arg, &arg2))
1381 v = views_find_view(worker->daemon->views,
1382 arg, 1 /* get write lock*/);
1384 ssl_printf(ssl,"no view with name: %s\n", arg);
1387 if(!v->local_zones) {
1388 lock_rw_unlock(&v->lock);
1392 do_zone_remove(ssl, v->local_zones, arg2);
1393 lock_rw_unlock(&v->lock);
1396 /** Add new RR data to view */
1398 do_view_data_add(RES* ssl, struct worker* worker, char* arg)
1402 if(!find_arg2(ssl, arg, &arg2))
1404 v = views_find_view(worker->daemon->views,
1405 arg, 1 /* get write lock*/);
1407 ssl_printf(ssl,"no view with name: %s\n", arg);
1410 if(!v->local_zones) {
1411 if(!(v->local_zones = local_zones_create())){
1412 lock_rw_unlock(&v->lock);
1413 ssl_printf(ssl,"error out of memory\n");
1417 do_data_add(ssl, v->local_zones, arg2);
1418 lock_rw_unlock(&v->lock);
1421 /** Remove RR data from view */
1423 do_view_data_remove(RES* ssl, struct worker* worker, char* arg)
1427 if(!find_arg2(ssl, arg, &arg2))
1429 v = views_find_view(worker->daemon->views,
1430 arg, 1 /* get write lock*/);
1432 ssl_printf(ssl,"no view with name: %s\n", arg);
1435 if(!v->local_zones) {
1436 lock_rw_unlock(&v->lock);
1440 do_data_remove(ssl, v->local_zones, arg2);
1441 lock_rw_unlock(&v->lock);
1444 /** cache lookup of nameservers */
1446 do_lookup(RES* ssl, struct worker* worker, char* arg)
1451 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1453 (void)print_deleg_lookup(ssl, worker, nm, nmlen, nmlabs);
1457 /** flush something from rrset and msg caches */
1459 do_cache_remove(struct worker* worker, uint8_t* nm, size_t nmlen,
1460 uint16_t t, uint16_t c)
1463 struct query_info k;
1464 rrset_cache_remove(worker->env.rrset_cache, nm, nmlen, t, c, 0);
1465 if(t == LDNS_RR_TYPE_SOA)
1466 rrset_cache_remove(worker->env.rrset_cache, nm, nmlen, t, c,
1467 PACKED_RRSET_SOA_NEG);
1469 k.qname_len = nmlen;
1472 k.local_alias = NULL;
1473 h = query_info_hash(&k, 0);
1474 slabhash_remove(worker->env.msg_cache, h, &k);
1475 if(t == LDNS_RR_TYPE_AAAA) {
1476 /* for AAAA also flush dns64 bit_cd packet */
1477 h = query_info_hash(&k, BIT_CD);
1478 slabhash_remove(worker->env.msg_cache, h, &k);
1484 do_flush_type(RES* ssl, struct worker* worker, char* arg)
1491 if(!find_arg2(ssl, arg, &arg2))
1493 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1495 t = sldns_get_rr_type_by_name(arg2);
1496 do_cache_remove(worker, nm, nmlen, t, LDNS_RR_CLASS_IN);
1502 /** flush statistics */
1504 do_flush_stats(RES* ssl, struct worker* worker)
1506 worker_stats_clear(worker);
1511 * Local info for deletion functions
1515 struct worker* worker;
1516 /** name to delete */
1522 /** time to invalidate to */
1524 /** number of rrsets removed */
1526 /** number of msgs removed */
1528 /** number of key entries removed */
1530 /** length of addr */
1532 /** socket address for host deletion */
1533 struct sockaddr_storage addr;
1536 /** callback to delete hosts in infra cache */
1538 infra_del_host(struct lruhash_entry* e, void* arg)
1540 /* entry is locked */
1541 struct del_info* inf = (struct del_info*)arg;
1542 struct infra_key* k = (struct infra_key*)e->key;
1543 if(sockaddr_cmp(&inf->addr, inf->addrlen, &k->addr, k->addrlen) == 0) {
1544 struct infra_data* d = (struct infra_data*)e->data;
1547 d->timeout_AAAA = 0;
1548 d->timeout_other = 0;
1550 if(d->ttl > inf->expired) {
1551 d->ttl = inf->expired;
1557 /** flush infra cache */
1559 do_flush_infra(RES* ssl, struct worker* worker, char* arg)
1561 struct sockaddr_storage addr;
1563 struct del_info inf;
1564 if(strcmp(arg, "all") == 0) {
1565 slabhash_clear(worker->env.infra_cache->hosts);
1569 if(!ipstrtoaddr(arg, UNBOUND_DNS_PORT, &addr, &len)) {
1570 (void)ssl_printf(ssl, "error parsing ip addr: '%s'\n", arg);
1573 /* delete all entries from cache */
1574 /* what we do is to set them all expired */
1575 inf.worker = worker;
1579 inf.expired = *worker->env.now;
1580 inf.expired -= 3; /* handle 3 seconds skew between threads */
1585 memmove(&inf.addr, &addr, len);
1586 slabhash_traverse(worker->env.infra_cache->hosts, 1, &infra_del_host,
1591 /** flush requestlist */
1593 do_flush_requestlist(RES* ssl, struct worker* worker)
1595 mesh_delete_all(worker->env.mesh);
1599 /** callback to delete rrsets in a zone */
1601 zone_del_rrset(struct lruhash_entry* e, void* arg)
1603 /* entry is locked */
1604 struct del_info* inf = (struct del_info*)arg;
1605 struct ub_packed_rrset_key* k = (struct ub_packed_rrset_key*)e->key;
1606 if(dname_subdomain_c(k->rk.dname, inf->name)) {
1607 struct packed_rrset_data* d =
1608 (struct packed_rrset_data*)e->data;
1609 if(d->ttl > inf->expired) {
1610 d->ttl = inf->expired;
1616 /** callback to delete messages in a zone */
1618 zone_del_msg(struct lruhash_entry* e, void* arg)
1620 /* entry is locked */
1621 struct del_info* inf = (struct del_info*)arg;
1622 struct msgreply_entry* k = (struct msgreply_entry*)e->key;
1623 if(dname_subdomain_c(k->key.qname, inf->name)) {
1624 struct reply_info* d = (struct reply_info*)e->data;
1625 if(d->ttl > inf->expired) {
1626 d->ttl = inf->expired;
1627 d->prefetch_ttl = inf->expired;
1633 /** callback to delete keys in zone */
1635 zone_del_kcache(struct lruhash_entry* e, void* arg)
1637 /* entry is locked */
1638 struct del_info* inf = (struct del_info*)arg;
1639 struct key_entry_key* k = (struct key_entry_key*)e->key;
1640 if(dname_subdomain_c(k->name, inf->name)) {
1641 struct key_entry_data* d = (struct key_entry_data*)e->data;
1642 if(d->ttl > inf->expired) {
1643 d->ttl = inf->expired;
1649 /** remove all rrsets and keys from zone from cache */
1651 do_flush_zone(RES* ssl, struct worker* worker, char* arg)
1656 struct del_info inf;
1657 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1659 /* delete all RRs and key entries from zone */
1660 /* what we do is to set them all expired */
1661 inf.worker = worker;
1665 inf.expired = *worker->env.now;
1666 inf.expired -= 3; /* handle 3 seconds skew between threads */
1670 slabhash_traverse(&worker->env.rrset_cache->table, 1,
1671 &zone_del_rrset, &inf);
1673 slabhash_traverse(worker->env.msg_cache, 1, &zone_del_msg, &inf);
1675 /* and validator cache */
1676 if(worker->env.key_cache) {
1677 slabhash_traverse(worker->env.key_cache->slab, 1,
1678 &zone_del_kcache, &inf);
1683 (void)ssl_printf(ssl, "ok removed %lu rrsets, %lu messages "
1684 "and %lu key entries\n", (unsigned long)inf.num_rrsets,
1685 (unsigned long)inf.num_msgs, (unsigned long)inf.num_keys);
1688 /** callback to delete bogus rrsets */
1690 bogus_del_rrset(struct lruhash_entry* e, void* arg)
1692 /* entry is locked */
1693 struct del_info* inf = (struct del_info*)arg;
1694 struct packed_rrset_data* d = (struct packed_rrset_data*)e->data;
1695 if(d->security == sec_status_bogus) {
1696 d->ttl = inf->expired;
1701 /** callback to delete bogus messages */
1703 bogus_del_msg(struct lruhash_entry* e, void* arg)
1705 /* entry is locked */
1706 struct del_info* inf = (struct del_info*)arg;
1707 struct reply_info* d = (struct reply_info*)e->data;
1708 if(d->security == sec_status_bogus) {
1709 d->ttl = inf->expired;
1714 /** callback to delete bogus keys */
1716 bogus_del_kcache(struct lruhash_entry* e, void* arg)
1718 /* entry is locked */
1719 struct del_info* inf = (struct del_info*)arg;
1720 struct key_entry_data* d = (struct key_entry_data*)e->data;
1722 d->ttl = inf->expired;
1727 /** remove all bogus rrsets, msgs and keys from cache */
1729 do_flush_bogus(RES* ssl, struct worker* worker)
1731 struct del_info inf;
1732 /* what we do is to set them all expired */
1733 inf.worker = worker;
1734 inf.expired = *worker->env.now;
1735 inf.expired -= 3; /* handle 3 seconds skew between threads */
1739 slabhash_traverse(&worker->env.rrset_cache->table, 1,
1740 &bogus_del_rrset, &inf);
1742 slabhash_traverse(worker->env.msg_cache, 1, &bogus_del_msg, &inf);
1744 /* and validator cache */
1745 if(worker->env.key_cache) {
1746 slabhash_traverse(worker->env.key_cache->slab, 1,
1747 &bogus_del_kcache, &inf);
1750 (void)ssl_printf(ssl, "ok removed %lu rrsets, %lu messages "
1751 "and %lu key entries\n", (unsigned long)inf.num_rrsets,
1752 (unsigned long)inf.num_msgs, (unsigned long)inf.num_keys);
1755 /** callback to delete negative and servfail rrsets */
1757 negative_del_rrset(struct lruhash_entry* e, void* arg)
1759 /* entry is locked */
1760 struct del_info* inf = (struct del_info*)arg;
1761 struct ub_packed_rrset_key* k = (struct ub_packed_rrset_key*)e->key;
1762 struct packed_rrset_data* d = (struct packed_rrset_data*)e->data;
1763 /* delete the parentside negative cache rrsets,
1764 * these are nameserver rrsets that failed lookup, rdata empty */
1765 if((k->rk.flags & PACKED_RRSET_PARENT_SIDE) && d->count == 1 &&
1766 d->rrsig_count == 0 && d->rr_len[0] == 0) {
1767 d->ttl = inf->expired;
1772 /** callback to delete negative and servfail messages */
1774 negative_del_msg(struct lruhash_entry* e, void* arg)
1776 /* entry is locked */
1777 struct del_info* inf = (struct del_info*)arg;
1778 struct reply_info* d = (struct reply_info*)e->data;
1779 /* rcode not NOERROR: NXDOMAIN, SERVFAIL, ..: an nxdomain or error
1780 * or NOERROR rcode with ANCOUNT==0: a NODATA answer */
1781 if(FLAGS_GET_RCODE(d->flags) != 0 || d->an_numrrsets == 0) {
1782 d->ttl = inf->expired;
1787 /** callback to delete negative key entries */
1789 negative_del_kcache(struct lruhash_entry* e, void* arg)
1791 /* entry is locked */
1792 struct del_info* inf = (struct del_info*)arg;
1793 struct key_entry_data* d = (struct key_entry_data*)e->data;
1794 /* could be bad because of lookup failure on the DS, DNSKEY, which
1795 * was nxdomain or servfail, and thus a result of negative lookups */
1797 d->ttl = inf->expired;
1802 /** remove all negative(NODATA,NXDOMAIN), and servfail messages from cache */
1804 do_flush_negative(RES* ssl, struct worker* worker)
1806 struct del_info inf;
1807 /* what we do is to set them all expired */
1808 inf.worker = worker;
1809 inf.expired = *worker->env.now;
1810 inf.expired -= 3; /* handle 3 seconds skew between threads */
1814 slabhash_traverse(&worker->env.rrset_cache->table, 1,
1815 &negative_del_rrset, &inf);
1817 slabhash_traverse(worker->env.msg_cache, 1, &negative_del_msg, &inf);
1819 /* and validator cache */
1820 if(worker->env.key_cache) {
1821 slabhash_traverse(worker->env.key_cache->slab, 1,
1822 &negative_del_kcache, &inf);
1825 (void)ssl_printf(ssl, "ok removed %lu rrsets, %lu messages "
1826 "and %lu key entries\n", (unsigned long)inf.num_rrsets,
1827 (unsigned long)inf.num_msgs, (unsigned long)inf.num_keys);
1830 /** remove name rrset from cache */
1832 do_flush_name(RES* ssl, struct worker* w, char* arg)
1837 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1839 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_A, LDNS_RR_CLASS_IN);
1840 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_AAAA, LDNS_RR_CLASS_IN);
1841 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_NS, LDNS_RR_CLASS_IN);
1842 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SOA, LDNS_RR_CLASS_IN);
1843 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_CNAME, LDNS_RR_CLASS_IN);
1844 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_DNAME, LDNS_RR_CLASS_IN);
1845 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_MX, LDNS_RR_CLASS_IN);
1846 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_PTR, LDNS_RR_CLASS_IN);
1847 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SRV, LDNS_RR_CLASS_IN);
1848 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_NAPTR, LDNS_RR_CLASS_IN);
1854 /** printout a delegation point info */
1856 ssl_print_name_dp(RES* ssl, const char* str, uint8_t* nm, uint16_t dclass,
1860 struct delegpt_ns* ns;
1861 struct delegpt_addr* a;
1863 if(str) { /* print header for forward, stub */
1864 char* c = sldns_wire2str_class(dclass);
1866 if(!ssl_printf(ssl, "%s %s %s ", buf, (c?c:"CLASS??"), str)) {
1872 for(ns = dp->nslist; ns; ns = ns->next) {
1873 dname_str(ns->name, buf);
1874 if(!ssl_printf(ssl, "%s%s", (f?" ":""), buf))
1878 for(a = dp->target_list; a; a = a->next_target) {
1879 addr_to_str(&a->addr, a->addrlen, buf, sizeof(buf));
1880 if(!ssl_printf(ssl, "%s%s", (f?" ":""), buf))
1884 return ssl_printf(ssl, "\n");
1888 /** print root forwards */
1890 print_root_fwds(RES* ssl, struct iter_forwards* fwds, uint8_t* root)
1893 dp = forwards_lookup(fwds, root, LDNS_RR_CLASS_IN);
1895 return ssl_printf(ssl, "off (using root hints)\n");
1896 /* if dp is returned it must be the root */
1897 log_assert(query_dname_compare(dp->name, root)==0);
1898 return ssl_print_name_dp(ssl, NULL, root, LDNS_RR_CLASS_IN, dp);
1901 /** parse args into delegpt */
1902 static struct delegpt*
1903 parse_delegpt(RES* ssl, char* args, uint8_t* nm, int allow_names)
1905 /* parse args and add in */
1908 struct delegpt* dp = delegpt_create_mlc(nm);
1909 struct sockaddr_storage addr;
1913 (void)ssl_printf(ssl, "error out of memory\n");
1918 p = strchr(p, ' '); /* find next spot, if any */
1920 *p++ = 0; /* end this spot */
1921 p = skipwhite(p); /* position at next spot */
1924 if(!authextstrtoaddr(todo, &addr, &addrlen, &auth_name)) {
1929 if(!parse_arg_name(ssl, todo, &n, &ln, &lb)) {
1930 (void)ssl_printf(ssl, "error cannot "
1931 "parse IP address or name "
1933 delegpt_free_mlc(dp);
1936 if(!delegpt_add_ns_mlc(dp, n, 0)) {
1937 (void)ssl_printf(ssl, "error out of memory\n");
1939 delegpt_free_mlc(dp);
1945 (void)ssl_printf(ssl, "error cannot parse"
1946 " IP address '%s'\n", todo);
1947 delegpt_free_mlc(dp);
1952 if(!delegpt_add_addr_mlc(dp, &addr, addrlen, 0, 0,
1954 (void)ssl_printf(ssl, "error out of memory\n");
1955 delegpt_free_mlc(dp);
1960 dp->has_parent_side_NS = 1;
1964 /** do the status command */
1966 do_forward(RES* ssl, struct worker* worker, char* args)
1968 struct iter_forwards* fwd = worker->env.fwds;
1969 uint8_t* root = (uint8_t*)"\000";
1971 (void)ssl_printf(ssl, "error: structure not allocated\n");
1974 if(args == NULL || args[0] == 0) {
1975 (void)print_root_fwds(ssl, fwd, root);
1978 /* set root forwards for this thread. since we are in remote control
1979 * the actual mesh is not running, so we can freely edit it. */
1980 /* delete all the existing queries first */
1981 mesh_delete_all(worker->env.mesh);
1982 if(strcmp(args, "off") == 0) {
1983 forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, root);
1986 if(!(dp = parse_delegpt(ssl, args, root, 0)))
1988 if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp)) {
1989 (void)ssl_printf(ssl, "error out of memory\n");
1997 parse_fs_args(RES* ssl, char* args, uint8_t** nm, struct delegpt** dp,
1998 int* insecure, int* prime)
2004 /* parse all -x args */
2005 while(args[0] == '+') {
2006 if(!find_arg2(ssl, args, &rest))
2008 while(*(++args) != 0) {
2009 if(*args == 'i' && insecure)
2011 else if(*args == 'p' && prime)
2014 (void)ssl_printf(ssl, "error: unknown option %s\n", args);
2022 if(!find_arg2(ssl, args, &rest))
2026 } else zonename = args;
2027 if(!parse_arg_name(ssl, zonename, nm, &nmlen, &nmlabs))
2032 if(!(*dp = parse_delegpt(ssl, args, *nm, 1))) {
2040 /** do the forward_add command */
2042 do_forward_add(RES* ssl, struct worker* worker, char* args)
2044 struct iter_forwards* fwd = worker->env.fwds;
2047 struct delegpt* dp = NULL;
2048 if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, NULL))
2050 if(insecure && worker->env.anchors) {
2051 if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2053 (void)ssl_printf(ssl, "error out of memory\n");
2054 delegpt_free_mlc(dp);
2059 if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp)) {
2060 (void)ssl_printf(ssl, "error out of memory\n");
2068 /** do the forward_remove command */
2070 do_forward_remove(RES* ssl, struct worker* worker, char* args)
2072 struct iter_forwards* fwd = worker->env.fwds;
2075 if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL))
2077 if(insecure && worker->env.anchors)
2078 anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2080 forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, nm);
2085 /** do the stub_add command */
2087 do_stub_add(RES* ssl, struct worker* worker, char* args)
2089 struct iter_forwards* fwd = worker->env.fwds;
2090 int insecure = 0, prime = 0;
2092 struct delegpt* dp = NULL;
2093 if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, &prime))
2095 if(insecure && worker->env.anchors) {
2096 if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2098 (void)ssl_printf(ssl, "error out of memory\n");
2099 delegpt_free_mlc(dp);
2104 if(!forwards_add_stub_hole(fwd, LDNS_RR_CLASS_IN, nm)) {
2105 if(insecure && worker->env.anchors)
2106 anchors_delete_insecure(worker->env.anchors,
2107 LDNS_RR_CLASS_IN, nm);
2108 (void)ssl_printf(ssl, "error out of memory\n");
2109 delegpt_free_mlc(dp);
2113 if(!hints_add_stub(worker->env.hints, LDNS_RR_CLASS_IN, dp, !prime)) {
2114 (void)ssl_printf(ssl, "error out of memory\n");
2115 forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm);
2116 if(insecure && worker->env.anchors)
2117 anchors_delete_insecure(worker->env.anchors,
2118 LDNS_RR_CLASS_IN, nm);
2126 /** do the stub_remove command */
2128 do_stub_remove(RES* ssl, struct worker* worker, char* args)
2130 struct iter_forwards* fwd = worker->env.fwds;
2133 if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL))
2135 if(insecure && worker->env.anchors)
2136 anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2138 forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm);
2139 hints_delete_stub(worker->env.hints, LDNS_RR_CLASS_IN, nm);
2144 /** do the insecure_add command */
2146 do_insecure_add(RES* ssl, struct worker* worker, char* arg)
2151 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
2153 if(worker->env.anchors) {
2154 if(!anchors_add_insecure(worker->env.anchors,
2155 LDNS_RR_CLASS_IN, nm)) {
2156 (void)ssl_printf(ssl, "error out of memory\n");
2165 /** do the insecure_remove command */
2167 do_insecure_remove(RES* ssl, struct worker* worker, char* arg)
2172 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
2174 if(worker->env.anchors)
2175 anchors_delete_insecure(worker->env.anchors,
2176 LDNS_RR_CLASS_IN, nm);
2182 do_insecure_list(RES* ssl, struct worker* worker)
2185 struct trust_anchor* a;
2186 if(worker->env.anchors) {
2187 RBTREE_FOR(a, struct trust_anchor*, worker->env.anchors->tree) {
2188 if(a->numDS == 0 && a->numDNSKEY == 0) {
2189 dname_str(a->name, buf);
2190 ssl_printf(ssl, "%s\n", buf);
2196 /** do the status command */
2198 do_status(RES* ssl, struct worker* worker)
2202 if(!ssl_printf(ssl, "version: %s\n", PACKAGE_VERSION))
2204 if(!ssl_printf(ssl, "verbosity: %d\n", verbosity))
2206 if(!ssl_printf(ssl, "threads: %d\n", worker->daemon->num))
2208 if(!ssl_printf(ssl, "modules: %d [", worker->daemon->mods.num))
2210 for(i=0; i<worker->daemon->mods.num; i++) {
2211 if(!ssl_printf(ssl, " %s", worker->daemon->mods.mod[i]->name))
2214 if(!ssl_printf(ssl, " ]\n"))
2216 uptime = (time_t)time(NULL) - (time_t)worker->daemon->time_boot.tv_sec;
2217 if(!ssl_printf(ssl, "uptime: " ARG_LL "d seconds\n", (long long)uptime))
2219 if(!ssl_printf(ssl, "options:%s%s%s%s\n" ,
2220 (worker->daemon->reuseport?" reuseport":""),
2221 (worker->daemon->rc->accept_list?" control":""),
2222 (worker->daemon->rc->accept_list && worker->daemon->rc->use_cert?"(ssl)":""),
2223 (worker->daemon->rc->accept_list && worker->daemon->cfg->control_ifs.first && worker->daemon->cfg->control_ifs.first->str && worker->daemon->cfg->control_ifs.first->str[0] == '/'?"(namedpipe)":"")
2226 if(!ssl_printf(ssl, "unbound (pid %d) is running...\n",
2231 /** get age for the mesh state */
2233 get_mesh_age(struct mesh_state* m, char* buf, size_t len,
2234 struct module_env* env)
2238 struct mesh_reply* r = m->reply_list;
2239 /* last reply is the oldest */
2242 timeval_subtract(&d, env->now_tv, &r->start_time);
2243 snprintf(buf, len, ARG_LL "d.%6.6d",
2244 (long long)d.tv_sec, (int)d.tv_usec);
2246 snprintf(buf, len, "-");
2250 /** get status of a mesh state */
2252 get_mesh_status(struct mesh_area* mesh, struct mesh_state* m,
2253 char* buf, size_t len)
2255 enum module_ext_state s = m->s.ext_state[m->s.curmod];
2256 const char *modname = mesh->mods.mod[m->s.curmod]->name;
2258 if(strcmp(modname, "iterator") == 0 && s == module_wait_reply &&
2259 m->s.minfo[m->s.curmod]) {
2260 /* break into iterator to find out who its waiting for */
2261 struct iter_qstate* qstate = (struct iter_qstate*)
2262 m->s.minfo[m->s.curmod];
2263 struct outbound_list* ol = &qstate->outlist;
2264 struct outbound_entry* e;
2265 snprintf(buf, len, "%s wait for", modname);
2268 if(ol->first == NULL)
2269 snprintf(buf, len, " (empty_list)");
2270 for(e = ol->first; e; e = e->next) {
2271 snprintf(buf, len, " ");
2274 addr_to_str(&e->qsent->addr, e->qsent->addrlen,
2279 } else if(s == module_wait_subquery) {
2280 /* look in subs from mesh state to see what */
2282 struct mesh_state_ref* sub;
2283 snprintf(buf, len, "%s wants", modname);
2286 if(m->sub_set.count == 0)
2287 snprintf(buf, len, " (empty_list)");
2288 RBTREE_FOR(sub, struct mesh_state_ref*, &m->sub_set) {
2289 char* t = sldns_wire2str_type(sub->s->s.qinfo.qtype);
2290 char* c = sldns_wire2str_class(sub->s->s.qinfo.qclass);
2291 dname_str(sub->s->s.qinfo.qname, nm);
2292 snprintf(buf, len, " %s %s %s", (t?t:"TYPE??"),
2293 (c?c:"CLASS??"), nm);
2300 snprintf(buf, len, "%s is %s", modname, strextstate(s));
2304 /** do the dump_requestlist command */
2306 do_dump_requestlist(RES* ssl, struct worker* worker)
2308 struct mesh_area* mesh;
2309 struct mesh_state* m;
2313 char statbuf[10240];
2314 if(!ssl_printf(ssl, "thread #%d\n", worker->thread_num))
2316 if(!ssl_printf(ssl, "# type cl name seconds module status\n"))
2318 /* show worker mesh contents */
2319 mesh = worker->env.mesh;
2321 RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
2322 char* t = sldns_wire2str_type(m->s.qinfo.qtype);
2323 char* c = sldns_wire2str_class(m->s.qinfo.qclass);
2324 dname_str(m->s.qinfo.qname, buf);
2325 get_mesh_age(m, timebuf, sizeof(timebuf), &worker->env);
2326 get_mesh_status(mesh, m, statbuf, sizeof(statbuf));
2327 if(!ssl_printf(ssl, "%3d %4s %2s %s %s %s\n",
2328 num, (t?t:"TYPE??"), (c?c:"CLASS??"), buf, timebuf,
2340 /** structure for argument data for dump infra host */
2342 /** the infra cache */
2343 struct infra_cache* infra;
2344 /** the SSL connection */
2348 /** ssl failure? stop writing and skip the rest. If the tcp
2349 * connection is broken, and writes fail, we then stop writing. */
2353 /** callback for every host element in the infra cache */
2355 dump_infra_host(struct lruhash_entry* e, void* arg)
2357 struct infra_arg* a = (struct infra_arg*)arg;
2358 struct infra_key* k = (struct infra_key*)e->key;
2359 struct infra_data* d = (struct infra_data*)e->data;
2365 addr_to_str(&k->addr, k->addrlen, ip_str, sizeof(ip_str));
2366 dname_str(k->zonename, name);
2367 port = (int)ntohs(((struct sockaddr_in*)&k->addr)->sin_port);
2368 if(port != UNBOUND_DNS_PORT) {
2369 snprintf(ip_str+strlen(ip_str), sizeof(ip_str)-strlen(ip_str),
2372 /* skip expired stuff (only backed off) */
2373 if(d->ttl < a->now) {
2374 if(d->rtt.rto >= USEFUL_SERVER_TOP_TIMEOUT) {
2375 if(!ssl_printf(a->ssl, "%s %s expired rto %d\n", ip_str,
2376 name, d->rtt.rto)) {
2383 if(!ssl_printf(a->ssl, "%s %s ttl %lu ping %d var %d rtt %d rto %d "
2384 "tA %d tAAAA %d tother %d "
2385 "ednsknown %d edns %d delay %d lame dnssec %d rec %d A %d "
2386 "other %d\n", ip_str, name, (unsigned long)(d->ttl - a->now),
2387 d->rtt.srtt, d->rtt.rttvar, rtt_notimeout(&d->rtt), d->rtt.rto,
2388 d->timeout_A, d->timeout_AAAA, d->timeout_other,
2389 (int)d->edns_lame_known, (int)d->edns_version,
2390 (int)(a->now<d->probedelay?(d->probedelay - a->now):0),
2391 (int)d->isdnsseclame, (int)d->rec_lame, (int)d->lame_type_A,
2392 (int)d->lame_other)) {
2398 /** do the dump_infra command */
2400 do_dump_infra(RES* ssl, struct worker* worker)
2402 struct infra_arg arg;
2403 arg.infra = worker->env.infra_cache;
2405 arg.now = *worker->env.now;
2407 slabhash_traverse(arg.infra->hosts, 0, &dump_infra_host, (void*)&arg);
2410 /** do the log_reopen command */
2412 do_log_reopen(RES* ssl, struct worker* worker)
2414 struct config_file* cfg = worker->env.cfg;
2416 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
2419 /** do the set_option command */
2421 do_set_option(RES* ssl, struct worker* worker, char* arg)
2424 if(!find_arg2(ssl, arg, &arg2))
2426 if(!config_set_option(worker->env.cfg, arg, arg2)) {
2427 (void)ssl_printf(ssl, "error setting option\n");
2430 /* effectuate some arguments */
2431 if(strcmp(arg, "val-override-date:") == 0) {
2432 int m = modstack_find(&worker->env.mesh->mods, "validator");
2433 struct val_env* val_env = NULL;
2434 if(m != -1) val_env = (struct val_env*)worker->env.modinfo[m];
2436 val_env->date_override = worker->env.cfg->val_date_override;
2441 /* routine to printout option values over SSL */
2442 void remote_get_opt_ssl(char* line, void* arg)
2444 RES* ssl = (RES*)arg;
2445 (void)ssl_printf(ssl, "%s\n", line);
2448 /** do the get_option command */
2450 do_get_option(RES* ssl, struct worker* worker, char* arg)
2453 r = config_get_option(worker->env.cfg, arg, remote_get_opt_ssl, ssl);
2455 (void)ssl_printf(ssl, "error unknown option\n");
2460 /** do the list_forwards command */
2462 do_list_forwards(RES* ssl, struct worker* worker)
2464 /* since its a per-worker structure no locks needed */
2465 struct iter_forwards* fwds = worker->env.fwds;
2466 struct iter_forward_zone* z;
2467 struct trust_anchor* a;
2469 RBTREE_FOR(z, struct iter_forward_zone*, fwds->tree) {
2470 if(!z->dp) continue; /* skip empty marker for stub */
2472 /* see if it is insecure */
2474 if(worker->env.anchors &&
2475 (a=anchor_find(worker->env.anchors, z->name,
2476 z->namelabs, z->namelen, z->dclass))) {
2477 if(!a->keylist && !a->numDS && !a->numDNSKEY)
2479 lock_basic_unlock(&a->lock);
2482 if(!ssl_print_name_dp(ssl, (insecure?"forward +i":"forward"),
2483 z->name, z->dclass, z->dp))
2488 /** do the list_stubs command */
2490 do_list_stubs(RES* ssl, struct worker* worker)
2492 struct iter_hints_stub* z;
2493 struct trust_anchor* a;
2496 RBTREE_FOR(z, struct iter_hints_stub*, &worker->env.hints->tree) {
2498 /* see if it is insecure */
2500 if(worker->env.anchors &&
2501 (a=anchor_find(worker->env.anchors, z->node.name,
2502 z->node.labs, z->node.len, z->node.dclass))) {
2503 if(!a->keylist && !a->numDS && !a->numDNSKEY)
2505 lock_basic_unlock(&a->lock);
2508 snprintf(str, sizeof(str), "stub %sprime%s",
2509 (z->noprime?"no":""), (insecure?" +i":""));
2510 if(!ssl_print_name_dp(ssl, str, z->node.name,
2511 z->node.dclass, z->dp))
2516 /** do the list_auth_zones command */
2518 do_list_auth_zones(RES* ssl, struct auth_zones* az)
2520 struct auth_zone* z;
2521 char buf[257], buf2[256];
2522 lock_rw_rdlock(&az->lock);
2523 RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
2524 lock_rw_rdlock(&z->lock);
2525 dname_str(z->name, buf);
2527 snprintf(buf2, sizeof(buf2), "expired");
2529 uint32_t serial = 0;
2530 if(auth_zone_get_serial(z, &serial))
2531 snprintf(buf2, sizeof(buf2), "serial %u",
2533 else snprintf(buf2, sizeof(buf2), "no serial");
2535 if(!ssl_printf(ssl, "%s\t%s\n", buf, buf2)) {
2536 /* failure to print */
2537 lock_rw_unlock(&z->lock);
2538 lock_rw_unlock(&az->lock);
2541 lock_rw_unlock(&z->lock);
2543 lock_rw_unlock(&az->lock);
2546 /** do the list_local_zones command */
2548 do_list_local_zones(RES* ssl, struct local_zones* zones)
2550 struct local_zone* z;
2552 lock_rw_rdlock(&zones->lock);
2553 RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
2554 lock_rw_rdlock(&z->lock);
2555 dname_str(z->name, buf);
2556 if(!ssl_printf(ssl, "%s %s\n", buf,
2557 local_zone_type2str(z->type))) {
2558 /* failure to print */
2559 lock_rw_unlock(&z->lock);
2560 lock_rw_unlock(&zones->lock);
2563 lock_rw_unlock(&z->lock);
2565 lock_rw_unlock(&zones->lock);
2568 /** do the list_local_data command */
2570 do_list_local_data(RES* ssl, struct worker* worker, struct local_zones* zones)
2572 struct local_zone* z;
2573 struct local_data* d;
2574 struct local_rrset* p;
2575 char* s = (char*)sldns_buffer_begin(worker->env.scratch_buffer);
2576 size_t slen = sldns_buffer_capacity(worker->env.scratch_buffer);
2577 lock_rw_rdlock(&zones->lock);
2578 RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
2579 lock_rw_rdlock(&z->lock);
2580 RBTREE_FOR(d, struct local_data*, &z->data) {
2581 for(p = d->rrsets; p; p = p->next) {
2582 struct packed_rrset_data* d =
2583 (struct packed_rrset_data*)p->rrset->entry.data;
2585 for(i=0; i<d->count + d->rrsig_count; i++) {
2586 if(!packed_rr_to_string(p->rrset, i,
2588 if(!ssl_printf(ssl, "BADRR\n")) {
2589 lock_rw_unlock(&z->lock);
2590 lock_rw_unlock(&zones->lock);
2594 if(!ssl_printf(ssl, "%s\n", s)) {
2595 lock_rw_unlock(&z->lock);
2596 lock_rw_unlock(&zones->lock);
2602 lock_rw_unlock(&z->lock);
2604 lock_rw_unlock(&zones->lock);
2607 /** do the view_list_local_zones command */
2609 do_view_list_local_zones(RES* ssl, struct worker* worker, char* arg)
2611 struct view* v = views_find_view(worker->daemon->views,
2612 arg, 0 /* get read lock*/);
2614 ssl_printf(ssl,"no view with name: %s\n", arg);
2617 if(v->local_zones) {
2618 do_list_local_zones(ssl, v->local_zones);
2620 lock_rw_unlock(&v->lock);
2623 /** do the view_list_local_data command */
2625 do_view_list_local_data(RES* ssl, struct worker* worker, char* arg)
2627 struct view* v = views_find_view(worker->daemon->views,
2628 arg, 0 /* get read lock*/);
2630 ssl_printf(ssl,"no view with name: %s\n", arg);
2633 if(v->local_zones) {
2634 do_list_local_data(ssl, worker, v->local_zones);
2636 lock_rw_unlock(&v->lock);
2639 /** struct for user arg ratelimit list */
2640 struct ratelimit_list_arg {
2641 /** the infra cache */
2642 struct infra_cache* infra;
2643 /** the SSL to print to */
2645 /** all or only ratelimited */
2651 #define ip_ratelimit_list_arg ratelimit_list_arg
2653 /** list items in the ratelimit table */
2655 rate_list(struct lruhash_entry* e, void* arg)
2657 struct ratelimit_list_arg* a = (struct ratelimit_list_arg*)arg;
2658 struct rate_key* k = (struct rate_key*)e->key;
2659 struct rate_data* d = (struct rate_data*)e->data;
2661 int lim = infra_find_ratelimit(a->infra, k->name, k->namelen);
2662 int max = infra_rate_max(d, a->now);
2667 dname_str(k->name, buf);
2668 ssl_printf(a->ssl, "%s %d limit %d\n", buf, max, lim);
2671 /** list items in the ip_ratelimit table */
2673 ip_rate_list(struct lruhash_entry* e, void* arg)
2676 struct ip_ratelimit_list_arg* a = (struct ip_ratelimit_list_arg*)arg;
2677 struct ip_rate_key* k = (struct ip_rate_key*)e->key;
2678 struct ip_rate_data* d = (struct ip_rate_data*)e->data;
2679 int lim = infra_ip_ratelimit;
2680 int max = infra_rate_max(d, a->now);
2685 addr_to_str(&k->addr, k->addrlen, ip, sizeof(ip));
2686 ssl_printf(a->ssl, "%s %d limit %d\n", ip, max, lim);
2689 /** do the ratelimit_list command */
2691 do_ratelimit_list(RES* ssl, struct worker* worker, char* arg)
2693 struct ratelimit_list_arg a;
2695 a.infra = worker->env.infra_cache;
2696 a.now = *worker->env.now;
2698 arg = skipwhite(arg);
2699 if(strcmp(arg, "+a") == 0)
2701 if(a.infra->domain_rates==NULL ||
2702 (a.all == 0 && infra_dp_ratelimit == 0))
2704 slabhash_traverse(a.infra->domain_rates, 0, rate_list, &a);
2707 /** do the ip_ratelimit_list command */
2709 do_ip_ratelimit_list(RES* ssl, struct worker* worker, char* arg)
2711 struct ip_ratelimit_list_arg a;
2713 a.infra = worker->env.infra_cache;
2714 a.now = *worker->env.now;
2716 arg = skipwhite(arg);
2717 if(strcmp(arg, "+a") == 0)
2719 if(a.infra->client_ip_rates==NULL ||
2720 (a.all == 0 && infra_ip_ratelimit == 0))
2722 slabhash_traverse(a.infra->client_ip_rates, 0, ip_rate_list, &a);
2725 /** tell other processes to execute the command */
2727 distribute_cmd(struct daemon_remote* rc, RES* ssl, char* cmd)
2732 /* skip i=0 which is me */
2733 for(i=1; i<rc->worker->daemon->num; i++) {
2734 worker_send_cmd(rc->worker->daemon->workers[i],
2736 if(!tube_write_msg(rc->worker->daemon->workers[i]->cmd,
2737 (uint8_t*)cmd, strlen(cmd)+1, 0)) {
2738 ssl_printf(ssl, "error could not distribute cmd\n");
2744 /** check for name with end-of-string, space or tab after it */
2746 cmdcmp(char* p, const char* cmd, size_t len)
2748 return strncmp(p,cmd,len)==0 && (p[len]==0||p[len]==' '||p[len]=='\t');
2751 /** execute a remote control command */
2753 execute_cmd(struct daemon_remote* rc, RES* ssl, char* cmd,
2754 struct worker* worker)
2756 char* p = skipwhite(cmd);
2757 /* compare command */
2758 if(cmdcmp(p, "stop", 4)) {
2761 } else if(cmdcmp(p, "reload", 6)) {
2764 } else if(cmdcmp(p, "stats_noreset", 13)) {
2765 do_stats(ssl, rc, 0);
2767 } else if(cmdcmp(p, "stats", 5)) {
2768 do_stats(ssl, rc, 1);
2770 } else if(cmdcmp(p, "status", 6)) {
2771 do_status(ssl, worker);
2773 } else if(cmdcmp(p, "dump_cache", 10)) {
2774 (void)dump_cache(ssl, worker);
2776 } else if(cmdcmp(p, "load_cache", 10)) {
2777 if(load_cache(ssl, worker)) send_ok(ssl);
2779 } else if(cmdcmp(p, "list_forwards", 13)) {
2780 do_list_forwards(ssl, worker);
2782 } else if(cmdcmp(p, "list_stubs", 10)) {
2783 do_list_stubs(ssl, worker);
2785 } else if(cmdcmp(p, "list_insecure", 13)) {
2786 do_insecure_list(ssl, worker);
2788 } else if(cmdcmp(p, "list_local_zones", 16)) {
2789 do_list_local_zones(ssl, worker->daemon->local_zones);
2791 } else if(cmdcmp(p, "list_local_data", 15)) {
2792 do_list_local_data(ssl, worker, worker->daemon->local_zones);
2794 } else if(cmdcmp(p, "view_list_local_zones", 21)) {
2795 do_view_list_local_zones(ssl, worker, skipwhite(p+21));
2797 } else if(cmdcmp(p, "view_list_local_data", 20)) {
2798 do_view_list_local_data(ssl, worker, skipwhite(p+20));
2800 } else if(cmdcmp(p, "ratelimit_list", 14)) {
2801 do_ratelimit_list(ssl, worker, p+14);
2803 } else if(cmdcmp(p, "ip_ratelimit_list", 17)) {
2804 do_ip_ratelimit_list(ssl, worker, p+17);
2806 } else if(cmdcmp(p, "list_auth_zones", 15)) {
2807 do_list_auth_zones(ssl, worker->env.auth_zones);
2809 } else if(cmdcmp(p, "stub_add", 8)) {
2810 /* must always distribute this cmd */
2811 if(rc) distribute_cmd(rc, ssl, cmd);
2812 do_stub_add(ssl, worker, skipwhite(p+8));
2814 } else if(cmdcmp(p, "stub_remove", 11)) {
2815 /* must always distribute this cmd */
2816 if(rc) distribute_cmd(rc, ssl, cmd);
2817 do_stub_remove(ssl, worker, skipwhite(p+11));
2819 } else if(cmdcmp(p, "forward_add", 11)) {
2820 /* must always distribute this cmd */
2821 if(rc) distribute_cmd(rc, ssl, cmd);
2822 do_forward_add(ssl, worker, skipwhite(p+11));
2824 } else if(cmdcmp(p, "forward_remove", 14)) {
2825 /* must always distribute this cmd */
2826 if(rc) distribute_cmd(rc, ssl, cmd);
2827 do_forward_remove(ssl, worker, skipwhite(p+14));
2829 } else if(cmdcmp(p, "insecure_add", 12)) {
2830 /* must always distribute this cmd */
2831 if(rc) distribute_cmd(rc, ssl, cmd);
2832 do_insecure_add(ssl, worker, skipwhite(p+12));
2834 } else if(cmdcmp(p, "insecure_remove", 15)) {
2835 /* must always distribute this cmd */
2836 if(rc) distribute_cmd(rc, ssl, cmd);
2837 do_insecure_remove(ssl, worker, skipwhite(p+15));
2839 } else if(cmdcmp(p, "forward", 7)) {
2840 /* must always distribute this cmd */
2841 if(rc) distribute_cmd(rc, ssl, cmd);
2842 do_forward(ssl, worker, skipwhite(p+7));
2844 } else if(cmdcmp(p, "flush_stats", 11)) {
2845 /* must always distribute this cmd */
2846 if(rc) distribute_cmd(rc, ssl, cmd);
2847 do_flush_stats(ssl, worker);
2849 } else if(cmdcmp(p, "flush_requestlist", 17)) {
2850 /* must always distribute this cmd */
2851 if(rc) distribute_cmd(rc, ssl, cmd);
2852 do_flush_requestlist(ssl, worker);
2854 } else if(cmdcmp(p, "lookup", 6)) {
2855 do_lookup(ssl, worker, skipwhite(p+6));
2859 #ifdef THREADS_DISABLED
2860 /* other processes must execute the command as well */
2861 /* commands that should not be distributed, returned above. */
2862 if(rc) { /* only if this thread is the master (rc) thread */
2863 /* done before the code below, which may split the string */
2864 distribute_cmd(rc, ssl, cmd);
2867 if(cmdcmp(p, "verbosity", 9)) {
2868 do_verbosity(ssl, skipwhite(p+9));
2869 } else if(cmdcmp(p, "local_zone_remove", 17)) {
2870 do_zone_remove(ssl, worker->daemon->local_zones, skipwhite(p+17));
2871 } else if(cmdcmp(p, "local_zones_remove", 18)) {
2872 do_zones_remove(ssl, worker->daemon->local_zones);
2873 } else if(cmdcmp(p, "local_zone", 10)) {
2874 do_zone_add(ssl, worker->daemon->local_zones, skipwhite(p+10));
2875 } else if(cmdcmp(p, "local_zones", 11)) {
2876 do_zones_add(ssl, worker->daemon->local_zones);
2877 } else if(cmdcmp(p, "local_data_remove", 17)) {
2878 do_data_remove(ssl, worker->daemon->local_zones, skipwhite(p+17));
2879 } else if(cmdcmp(p, "local_datas_remove", 18)) {
2880 do_datas_remove(ssl, worker->daemon->local_zones);
2881 } else if(cmdcmp(p, "local_data", 10)) {
2882 do_data_add(ssl, worker->daemon->local_zones, skipwhite(p+10));
2883 } else if(cmdcmp(p, "local_datas", 11)) {
2884 do_datas_add(ssl, worker->daemon->local_zones);
2885 } else if(cmdcmp(p, "view_local_zone_remove", 22)) {
2886 do_view_zone_remove(ssl, worker, skipwhite(p+22));
2887 } else if(cmdcmp(p, "view_local_zone", 15)) {
2888 do_view_zone_add(ssl, worker, skipwhite(p+15));
2889 } else if(cmdcmp(p, "view_local_data_remove", 22)) {
2890 do_view_data_remove(ssl, worker, skipwhite(p+22));
2891 } else if(cmdcmp(p, "view_local_data", 15)) {
2892 do_view_data_add(ssl, worker, skipwhite(p+15));
2893 } else if(cmdcmp(p, "flush_zone", 10)) {
2894 do_flush_zone(ssl, worker, skipwhite(p+10));
2895 } else if(cmdcmp(p, "flush_type", 10)) {
2896 do_flush_type(ssl, worker, skipwhite(p+10));
2897 } else if(cmdcmp(p, "flush_infra", 11)) {
2898 do_flush_infra(ssl, worker, skipwhite(p+11));
2899 } else if(cmdcmp(p, "flush", 5)) {
2900 do_flush_name(ssl, worker, skipwhite(p+5));
2901 } else if(cmdcmp(p, "dump_requestlist", 16)) {
2902 do_dump_requestlist(ssl, worker);
2903 } else if(cmdcmp(p, "dump_infra", 10)) {
2904 do_dump_infra(ssl, worker);
2905 } else if(cmdcmp(p, "log_reopen", 10)) {
2906 do_log_reopen(ssl, worker);
2907 } else if(cmdcmp(p, "set_option", 10)) {
2908 do_set_option(ssl, worker, skipwhite(p+10));
2909 } else if(cmdcmp(p, "get_option", 10)) {
2910 do_get_option(ssl, worker, skipwhite(p+10));
2911 } else if(cmdcmp(p, "flush_bogus", 11)) {
2912 do_flush_bogus(ssl, worker);
2913 } else if(cmdcmp(p, "flush_negative", 14)) {
2914 do_flush_negative(ssl, worker);
2916 (void)ssl_printf(ssl, "error unknown command '%s'\n", p);
2921 daemon_remote_exec(struct worker* worker)
2923 /* read the cmd string */
2924 uint8_t* msg = NULL;
2926 if(!tube_read_msg(worker->cmd, &msg, &len, 0)) {
2927 log_err("daemon_remote_exec: tube_read_msg failed");
2930 verbose(VERB_ALGO, "remote exec distributed: %s", (char*)msg);
2931 execute_cmd(NULL, NULL, (char*)msg, worker);
2935 /** handle remote control request */
2937 handle_req(struct daemon_remote* rc, struct rc_state* s, RES* res)
2944 /* makes it possible to set the socket blocking again. */
2945 /* basically removes it from winsock_event ... */
2946 WSAEventSelect(s->c->fd, NULL, 0);
2948 fd_set_block(s->c->fd);
2950 /* try to read magic UBCT[version]_space_ string */
2953 if((r=SSL_read(res->ssl, magic, (int)sizeof(magic)-1)) <= 0) {
2954 if(SSL_get_error(res->ssl, r) == SSL_ERROR_ZERO_RETURN)
2956 log_crypto_err("could not SSL_read");
2961 ssize_t rr = recv(res->fd, magic, sizeof(magic)-1, 0);
2964 if(errno == EINTR || errno == EAGAIN)
2967 log_err("could not recv: %s", strerror(errno));
2969 log_err("could not recv: %s", wsa_strerror(WSAGetLastError()));
2978 if( r != 6 || strncmp(magic, "UBCT", 4) != 0) {
2979 verbose(VERB_QUERY, "control connection has bad magic string");
2980 /* probably wrong tool connected, ignore it completely */
2984 /* read the command line */
2985 if(!ssl_read_line(res, buf, sizeof(buf))) {
2988 snprintf(pre, sizeof(pre), "UBCT%d ", UNBOUND_CONTROL_VERSION);
2989 if(strcmp(magic, pre) != 0) {
2990 verbose(VERB_QUERY, "control connection had bad "
2991 "version %s, cmd: %s", magic, buf);
2992 ssl_printf(res, "error version mismatch\n");
2995 verbose(VERB_DETAIL, "control cmd: %s", buf);
2997 /* figure out what to do */
2998 execute_cmd(rc, res, buf, rc->worker);
3001 /** handle SSL_do_handshake changes to the file descriptor to wait for later */
3003 remote_handshake_later(struct daemon_remote* rc, struct rc_state* s,
3004 struct comm_point* c, int r, int r2)
3006 if(r2 == SSL_ERROR_WANT_READ) {
3007 if(s->shake_state == rc_hs_read) {
3008 /* try again later */
3011 s->shake_state = rc_hs_read;
3012 comm_point_listen_for_rw(c, 1, 0);
3014 } else if(r2 == SSL_ERROR_WANT_WRITE) {
3015 if(s->shake_state == rc_hs_write) {
3016 /* try again later */
3019 s->shake_state = rc_hs_write;
3020 comm_point_listen_for_rw(c, 0, 1);
3024 log_err("remote control connection closed prematurely");
3025 log_addr(1, "failed connection from",
3026 &s->c->repinfo.addr, s->c->repinfo.addrlen);
3027 log_crypto_err("remote control failed ssl");
3033 int remote_control_callback(struct comm_point* c, void* arg, int err,
3034 struct comm_reply* ATTR_UNUSED(rep))
3037 struct rc_state* s = (struct rc_state*)arg;
3038 struct daemon_remote* rc = s->rc;
3040 if(err != NETEVENT_NOERROR) {
3041 if(err==NETEVENT_TIMEOUT)
3042 log_err("remote control timed out");
3047 /* (continue to) setup the SSL connection */
3049 r = SSL_do_handshake(s->ssl);
3051 int r2 = SSL_get_error(s->ssl, r);
3052 return remote_handshake_later(rc, s, c, r, r2);
3054 s->shake_state = rc_none;
3057 /* once handshake has completed, check authentication */
3058 if (!rc->use_cert) {
3059 verbose(VERB_ALGO, "unauthenticated remote control connection");
3060 } else if(SSL_get_verify_result(s->ssl) == X509_V_OK) {
3061 X509* x = SSL_get_peer_certificate(s->ssl);
3063 verbose(VERB_DETAIL, "remote control connection "
3064 "provided no client certificate");
3068 verbose(VERB_ALGO, "remote control connection authenticated");
3071 verbose(VERB_DETAIL, "remote control connection failed to "
3072 "authenticate with client certificate");
3077 /* if OK start to actually handle the request */
3080 handle_req(rc, s, &res);
3082 verbose(VERB_ALGO, "remote control operation completed");