]> git.saurik.com Git - apple/network_cmds.git/blob - unbound/daemon/remote.c
65cc4cbfcab80eff76e5cec12b0aab361f8f01f0
[apple/network_cmds.git] / unbound / daemon / remote.c
1 /*
2 * daemon/remote.c - remote control for the unbound daemon.
3 *
4 * Copyright (c) 2008, NLnet Labs. All rights reserved.
5 *
6 * This software is open source.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
14 *
15 * Redistributions in binary form must reproduce the above copyright notice,
16 * this list of conditions and the following disclaimer in the documentation
17 * and/or other materials provided with the distribution.
18 *
19 * Neither the name of the NLNET LABS nor the names of its contributors may
20 * be used to endorse or promote products derived from this software without
21 * specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 */
35
36 /**
37 * \file
38 *
39 * This file contains the remote control functionality for the daemon.
40 * The remote control can be performed using either the commandline
41 * unbound-control tool, or a TLS capable web browser.
42 * The channel is secured using TLSv1, and certificates.
43 * Both the server and the client(control tool) have their own keys.
44 */
45 #include "config.h"
46 #ifdef HAVE_OPENSSL_ERR_H
47 #include <openssl/err.h>
48 #endif
49 #include <ctype.h>
50 #include "daemon/remote.h"
51 #include "daemon/worker.h"
52 #include "daemon/daemon.h"
53 #include "daemon/stats.h"
54 #include "daemon/cachedump.h"
55 #include "util/log.h"
56 #include "util/config_file.h"
57 #include "util/net_help.h"
58 #include "util/module.h"
59 #include "services/listen_dnsport.h"
60 #include "services/cache/rrset.h"
61 #include "services/cache/infra.h"
62 #include "services/mesh.h"
63 #include "services/localzone.h"
64 #include "util/storage/slabhash.h"
65 #include "util/fptr_wlist.h"
66 #include "util/data/dname.h"
67 #include "validator/validator.h"
68 #include "validator/val_kcache.h"
69 #include "validator/val_kentry.h"
70 #include "validator/val_anchor.h"
71 #include "iterator/iterator.h"
72 #include "iterator/iter_fwd.h"
73 #include "iterator/iter_hints.h"
74 #include "iterator/iter_delegpt.h"
75 #include "services/outbound_list.h"
76 #include "services/outside_network.h"
77 #include "ldns/str2wire.h"
78 #include "ldns/parseutil.h"
79 #include "ldns/wire2str.h"
80 #include "ldns/sbuffer.h"
81
82 #ifdef HAVE_SYS_TYPES_H
83 # include <sys/types.h>
84 #endif
85 #ifdef HAVE_NETDB_H
86 #include <netdb.h>
87 #endif
88
89 /* just for portability */
90 #ifdef SQ
91 #undef SQ
92 #endif
93
94 /** what to put on statistics lines between var and value, ": " or "=" */
95 #define SQ "="
96 /** if true, inhibits a lot of =0 lines from the stats output */
97 static const int inhibit_zero = 1;
98
99 /** subtract timers and the values do not overflow or become negative */
100 static void
101 timeval_subtract(struct timeval* d, const struct timeval* end,
102 const struct timeval* start)
103 {
104 #ifndef S_SPLINT_S
105 time_t end_usec = end->tv_usec;
106 d->tv_sec = end->tv_sec - start->tv_sec;
107 if(end_usec < start->tv_usec) {
108 end_usec += 1000000;
109 d->tv_sec--;
110 }
111 d->tv_usec = end_usec - start->tv_usec;
112 #endif
113 }
114
115 /** divide sum of timers to get average */
116 static void
117 timeval_divide(struct timeval* avg, const struct timeval* sum, size_t d)
118 {
119 #ifndef S_SPLINT_S
120 size_t leftover;
121 if(d == 0) {
122 avg->tv_sec = 0;
123 avg->tv_usec = 0;
124 return;
125 }
126 avg->tv_sec = sum->tv_sec / d;
127 avg->tv_usec = sum->tv_usec / d;
128 /* handle fraction from seconds divide */
129 leftover = sum->tv_sec - avg->tv_sec*d;
130 avg->tv_usec += (leftover*1000000)/d;
131 #endif
132 }
133
134 struct daemon_remote*
135 daemon_remote_create(struct config_file* cfg)
136 {
137 char* s_cert;
138 char* s_key;
139 struct daemon_remote* rc = (struct daemon_remote*)calloc(1,
140 sizeof(*rc));
141 if(!rc) {
142 log_err("out of memory in daemon_remote_create");
143 return NULL;
144 }
145 rc->max_active = 10;
146
147 if(!cfg->remote_control_enable) {
148 rc->ctx = NULL;
149 return rc;
150 }
151 rc->ctx = SSL_CTX_new(SSLv23_server_method());
152 if(!rc->ctx) {
153 log_crypto_err("could not SSL_CTX_new");
154 free(rc);
155 return NULL;
156 }
157 s_cert = fname_after_chroot(cfg->server_cert_file, cfg, 1);
158 s_key = fname_after_chroot(cfg->server_key_file, cfg, 1);
159 if(!s_cert || !s_key) {
160 log_err("out of memory in remote control fname");
161 goto setup_error;
162 }
163 verbose(VERB_ALGO, "setup SSL certificates");
164 if (!SSL_CTX_use_certificate_file(rc->ctx,s_cert,SSL_FILETYPE_PEM)) {
165 log_err("Error for server-cert-file: %s", s_cert);
166 log_crypto_err("Error in SSL_CTX use_certificate_file");
167 goto setup_error;
168 }
169 if(!SSL_CTX_use_PrivateKey_file(rc->ctx,s_key,SSL_FILETYPE_PEM)) {
170 log_err("Error for server-key-file: %s", s_key);
171 log_crypto_err("Error in SSL_CTX use_PrivateKey_file");
172 goto setup_error;
173 }
174 if(!SSL_CTX_check_private_key(rc->ctx)) {
175 log_err("Error for server-key-file: %s", s_key);
176 log_crypto_err("Error in SSL_CTX check_private_key");
177 goto setup_error;
178 }
179 if(!SSL_CTX_load_verify_locations(rc->ctx, s_cert, NULL)) {
180 log_crypto_err("Error setting up SSL_CTX verify locations");
181 setup_error:
182 free(s_cert);
183 free(s_key);
184 daemon_remote_delete(rc);
185 return NULL;
186 }
187 SSL_CTX_set_client_CA_list(rc->ctx, SSL_load_client_CA_file(s_cert));
188 SSL_CTX_set_verify(rc->ctx, SSL_VERIFY_PEER, NULL);
189 free(s_cert);
190 free(s_key);
191
192 return rc;
193 }
194
195 void daemon_remote_clear(struct daemon_remote* rc)
196 {
197 struct rc_state* p, *np;
198 if(!rc) return;
199 /* but do not close the ports */
200 listen_list_delete(rc->accept_list);
201 rc->accept_list = NULL;
202 /* do close these sockets */
203 p = rc->busy_list;
204 while(p) {
205 np = p->next;
206 if(p->ssl)
207 SSL_free(p->ssl);
208 comm_point_delete(p->c);
209 free(p);
210 p = np;
211 }
212 rc->busy_list = NULL;
213 rc->active = 0;
214 rc->worker = NULL;
215 }
216
217 void daemon_remote_delete(struct daemon_remote* rc)
218 {
219 if(!rc) return;
220 daemon_remote_clear(rc);
221 if(rc->ctx) {
222 SSL_CTX_free(rc->ctx);
223 }
224 free(rc);
225 }
226
227 /**
228 * Add and open a new control port
229 * @param ip: ip str
230 * @param nr: port nr
231 * @param list: list head
232 * @param noproto_is_err: if lack of protocol support is an error.
233 * @return false on failure.
234 */
235 static int
236 add_open(const char* ip, int nr, struct listen_port** list, int noproto_is_err)
237 {
238 struct addrinfo hints;
239 struct addrinfo* res;
240 struct listen_port* n;
241 int noproto;
242 int fd, r;
243 char port[15];
244 snprintf(port, sizeof(port), "%d", nr);
245 port[sizeof(port)-1]=0;
246 memset(&hints, 0, sizeof(hints));
247 hints.ai_socktype = SOCK_STREAM;
248 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
249 if((r = getaddrinfo(ip, port, &hints, &res)) != 0 || !res) {
250 #ifdef USE_WINSOCK
251 if(!noproto_is_err && r == EAI_NONAME) {
252 /* tried to lookup the address as name */
253 return 1; /* return success, but do nothing */
254 }
255 #endif /* USE_WINSOCK */
256 log_err("control interface %s:%s getaddrinfo: %s %s",
257 ip?ip:"default", port, gai_strerror(r),
258 #ifdef EAI_SYSTEM
259 r==EAI_SYSTEM?(char*)strerror(errno):""
260 #else
261 ""
262 #endif
263 );
264 return 0;
265 }
266
267 /* open fd */
268 fd = create_tcp_accept_sock(res, 1, &noproto, 0);
269 freeaddrinfo(res);
270 if(fd == -1 && noproto) {
271 if(!noproto_is_err)
272 return 1; /* return success, but do nothing */
273 log_err("cannot open control interface %s %d : "
274 "protocol not supported", ip, nr);
275 return 0;
276 }
277 if(fd == -1) {
278 log_err("cannot open control interface %s %d", ip, nr);
279 return 0;
280 }
281
282 /* alloc */
283 n = (struct listen_port*)calloc(1, sizeof(*n));
284 if(!n) {
285 #ifndef USE_WINSOCK
286 close(fd);
287 #else
288 closesocket(fd);
289 #endif
290 log_err("out of memory");
291 return 0;
292 }
293 n->next = *list;
294 *list = n;
295 n->fd = fd;
296 return 1;
297 }
298
299 struct listen_port* daemon_remote_open_ports(struct config_file* cfg)
300 {
301 struct listen_port* l = NULL;
302 log_assert(cfg->remote_control_enable && cfg->control_port);
303 if(cfg->control_ifs) {
304 struct config_strlist* p;
305 for(p = cfg->control_ifs; p; p = p->next) {
306 if(!add_open(p->str, cfg->control_port, &l, 1)) {
307 listening_ports_free(l);
308 return NULL;
309 }
310 }
311 } else {
312 /* defaults */
313 if(cfg->do_ip6 &&
314 !add_open("::1", cfg->control_port, &l, 0)) {
315 listening_ports_free(l);
316 return NULL;
317 }
318 if(cfg->do_ip4 &&
319 !add_open("127.0.0.1", cfg->control_port, &l, 1)) {
320 listening_ports_free(l);
321 return NULL;
322 }
323 }
324 return l;
325 }
326
327 /** open accept commpoint */
328 static int
329 accept_open(struct daemon_remote* rc, int fd)
330 {
331 struct listen_list* n = (struct listen_list*)malloc(sizeof(*n));
332 if(!n) {
333 log_err("out of memory");
334 return 0;
335 }
336 n->next = rc->accept_list;
337 rc->accept_list = n;
338 /* open commpt */
339 n->com = comm_point_create_raw(rc->worker->base, fd, 0,
340 &remote_accept_callback, rc);
341 if(!n->com)
342 return 0;
343 /* keep this port open, its fd is kept in the rc portlist */
344 n->com->do_not_close = 1;
345 return 1;
346 }
347
348 int daemon_remote_open_accept(struct daemon_remote* rc,
349 struct listen_port* ports, struct worker* worker)
350 {
351 struct listen_port* p;
352 rc->worker = worker;
353 for(p = ports; p; p = p->next) {
354 if(!accept_open(rc, p->fd)) {
355 log_err("could not create accept comm point");
356 return 0;
357 }
358 }
359 return 1;
360 }
361
362 void daemon_remote_stop_accept(struct daemon_remote* rc)
363 {
364 struct listen_list* p;
365 for(p=rc->accept_list; p; p=p->next) {
366 comm_point_stop_listening(p->com);
367 }
368 }
369
370 void daemon_remote_start_accept(struct daemon_remote* rc)
371 {
372 struct listen_list* p;
373 for(p=rc->accept_list; p; p=p->next) {
374 comm_point_start_listening(p->com, -1, -1);
375 }
376 }
377
378 int remote_accept_callback(struct comm_point* c, void* arg, int err,
379 struct comm_reply* ATTR_UNUSED(rep))
380 {
381 struct daemon_remote* rc = (struct daemon_remote*)arg;
382 struct sockaddr_storage addr;
383 socklen_t addrlen;
384 int newfd;
385 struct rc_state* n;
386 if(err != NETEVENT_NOERROR) {
387 log_err("error %d on remote_accept_callback", err);
388 return 0;
389 }
390 /* perform the accept */
391 newfd = comm_point_perform_accept(c, &addr, &addrlen);
392 if(newfd == -1)
393 return 0;
394 /* create new commpoint unless we are servicing already */
395 if(rc->active >= rc->max_active) {
396 log_warn("drop incoming remote control: too many connections");
397 close_exit:
398 #ifndef USE_WINSOCK
399 close(newfd);
400 #else
401 closesocket(newfd);
402 #endif
403 return 0;
404 }
405
406 /* setup commpoint to service the remote control command */
407 n = (struct rc_state*)calloc(1, sizeof(*n));
408 if(!n) {
409 log_err("out of memory");
410 goto close_exit;
411 }
412 /* start in reading state */
413 n->c = comm_point_create_raw(rc->worker->base, newfd, 0,
414 &remote_control_callback, n);
415 if(!n->c) {
416 log_err("out of memory");
417 free(n);
418 goto close_exit;
419 }
420 log_addr(VERB_QUERY, "new control connection from", &addr, addrlen);
421 n->c->do_not_close = 0;
422 comm_point_stop_listening(n->c);
423 comm_point_start_listening(n->c, -1, REMOTE_CONTROL_TCP_TIMEOUT);
424 memcpy(&n->c->repinfo.addr, &addr, addrlen);
425 n->c->repinfo.addrlen = addrlen;
426 n->shake_state = rc_hs_read;
427 n->ssl = SSL_new(rc->ctx);
428 if(!n->ssl) {
429 log_crypto_err("could not SSL_new");
430 comm_point_delete(n->c);
431 free(n);
432 goto close_exit;
433 }
434 SSL_set_accept_state(n->ssl);
435 (void)SSL_set_mode(n->ssl, SSL_MODE_AUTO_RETRY);
436 if(!SSL_set_fd(n->ssl, newfd)) {
437 log_crypto_err("could not SSL_set_fd");
438 SSL_free(n->ssl);
439 comm_point_delete(n->c);
440 free(n);
441 goto close_exit;
442 }
443
444 n->rc = rc;
445 n->next = rc->busy_list;
446 rc->busy_list = n;
447 rc->active ++;
448
449 /* perform the first nonblocking read already, for windows,
450 * so it can return wouldblock. could be faster too. */
451 (void)remote_control_callback(n->c, n, NETEVENT_NOERROR, NULL);
452 return 0;
453 }
454
455 /** delete from list */
456 static void
457 state_list_remove_elem(struct rc_state** list, struct comm_point* c)
458 {
459 while(*list) {
460 if( (*list)->c == c) {
461 *list = (*list)->next;
462 return;
463 }
464 list = &(*list)->next;
465 }
466 }
467
468 /** decrease active count and remove commpoint from busy list */
469 static void
470 clean_point(struct daemon_remote* rc, struct rc_state* s)
471 {
472 state_list_remove_elem(&rc->busy_list, s->c);
473 rc->active --;
474 if(s->ssl) {
475 SSL_shutdown(s->ssl);
476 SSL_free(s->ssl);
477 }
478 comm_point_delete(s->c);
479 free(s);
480 }
481
482 int
483 ssl_print_text(SSL* ssl, const char* text)
484 {
485 int r;
486 if(!ssl)
487 return 0;
488 ERR_clear_error();
489 if((r=SSL_write(ssl, text, (int)strlen(text))) <= 0) {
490 if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
491 verbose(VERB_QUERY, "warning, in SSL_write, peer "
492 "closed connection");
493 return 0;
494 }
495 log_crypto_err("could not SSL_write");
496 return 0;
497 }
498 return 1;
499 }
500
501 /** print text over the ssl connection */
502 static int
503 ssl_print_vmsg(SSL* ssl, const char* format, va_list args)
504 {
505 char msg[1024];
506 vsnprintf(msg, sizeof(msg), format, args);
507 return ssl_print_text(ssl, msg);
508 }
509
510 /** printf style printing to the ssl connection */
511 int ssl_printf(SSL* ssl, const char* format, ...)
512 {
513 va_list args;
514 int ret;
515 va_start(args, format);
516 ret = ssl_print_vmsg(ssl, format, args);
517 va_end(args);
518 return ret;
519 }
520
521 int
522 ssl_read_line(SSL* ssl, char* buf, size_t max)
523 {
524 int r;
525 size_t len = 0;
526 if(!ssl)
527 return 0;
528 while(len < max) {
529 ERR_clear_error();
530 if((r=SSL_read(ssl, buf+len, 1)) <= 0) {
531 if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
532 buf[len] = 0;
533 return 1;
534 }
535 log_crypto_err("could not SSL_read");
536 return 0;
537 }
538 if(buf[len] == '\n') {
539 /* return string without \n */
540 buf[len] = 0;
541 return 1;
542 }
543 len++;
544 }
545 buf[max-1] = 0;
546 log_err("control line too long (%d): %s", (int)max, buf);
547 return 0;
548 }
549
550 /** skip whitespace, return new pointer into string */
551 static char*
552 skipwhite(char* str)
553 {
554 /* EOS \0 is not a space */
555 while( isspace((unsigned char)*str) )
556 str++;
557 return str;
558 }
559
560 /** send the OK to the control client */
561 static void send_ok(SSL* ssl)
562 {
563 (void)ssl_printf(ssl, "ok\n");
564 }
565
566 /** do the stop command */
567 static void
568 do_stop(SSL* ssl, struct daemon_remote* rc)
569 {
570 rc->worker->need_to_exit = 1;
571 comm_base_exit(rc->worker->base);
572 send_ok(ssl);
573 }
574
575 /** do the reload command */
576 static void
577 do_reload(SSL* ssl, struct daemon_remote* rc)
578 {
579 rc->worker->need_to_exit = 0;
580 comm_base_exit(rc->worker->base);
581 send_ok(ssl);
582 }
583
584 /** do the verbosity command */
585 static void
586 do_verbosity(SSL* ssl, char* str)
587 {
588 int val = atoi(str);
589 if(val == 0 && strcmp(str, "0") != 0) {
590 ssl_printf(ssl, "error in verbosity number syntax: %s\n", str);
591 return;
592 }
593 verbosity = val;
594 send_ok(ssl);
595 }
596
597 /** print stats from statinfo */
598 static int
599 print_stats(SSL* ssl, const char* nm, struct stats_info* s)
600 {
601 struct timeval avg;
602 if(!ssl_printf(ssl, "%s.num.queries"SQ"%lu\n", nm,
603 (unsigned long)s->svr.num_queries)) return 0;
604 if(!ssl_printf(ssl, "%s.num.cachehits"SQ"%lu\n", nm,
605 (unsigned long)(s->svr.num_queries
606 - s->svr.num_queries_missed_cache))) return 0;
607 if(!ssl_printf(ssl, "%s.num.cachemiss"SQ"%lu\n", nm,
608 (unsigned long)s->svr.num_queries_missed_cache)) return 0;
609 if(!ssl_printf(ssl, "%s.num.prefetch"SQ"%lu\n", nm,
610 (unsigned long)s->svr.num_queries_prefetch)) return 0;
611 if(!ssl_printf(ssl, "%s.num.recursivereplies"SQ"%lu\n", nm,
612 (unsigned long)s->mesh_replies_sent)) return 0;
613 if(!ssl_printf(ssl, "%s.requestlist.avg"SQ"%g\n", nm,
614 (s->svr.num_queries_missed_cache+s->svr.num_queries_prefetch)?
615 (double)s->svr.sum_query_list_size/
616 (s->svr.num_queries_missed_cache+
617 s->svr.num_queries_prefetch) : 0.0)) return 0;
618 if(!ssl_printf(ssl, "%s.requestlist.max"SQ"%lu\n", nm,
619 (unsigned long)s->svr.max_query_list_size)) return 0;
620 if(!ssl_printf(ssl, "%s.requestlist.overwritten"SQ"%lu\n", nm,
621 (unsigned long)s->mesh_jostled)) return 0;
622 if(!ssl_printf(ssl, "%s.requestlist.exceeded"SQ"%lu\n", nm,
623 (unsigned long)s->mesh_dropped)) return 0;
624 if(!ssl_printf(ssl, "%s.requestlist.current.all"SQ"%lu\n", nm,
625 (unsigned long)s->mesh_num_states)) return 0;
626 if(!ssl_printf(ssl, "%s.requestlist.current.user"SQ"%lu\n", nm,
627 (unsigned long)s->mesh_num_reply_states)) return 0;
628 timeval_divide(&avg, &s->mesh_replies_sum_wait, s->mesh_replies_sent);
629 if(!ssl_printf(ssl, "%s.recursion.time.avg"SQ ARG_LL "d.%6.6d\n", nm,
630 (long long)avg.tv_sec, (int)avg.tv_usec)) return 0;
631 if(!ssl_printf(ssl, "%s.recursion.time.median"SQ"%g\n", nm,
632 s->mesh_time_median)) return 0;
633 return 1;
634 }
635
636 /** print stats for one thread */
637 static int
638 print_thread_stats(SSL* ssl, int i, struct stats_info* s)
639 {
640 char nm[16];
641 snprintf(nm, sizeof(nm), "thread%d", i);
642 nm[sizeof(nm)-1]=0;
643 return print_stats(ssl, nm, s);
644 }
645
646 /** print long number */
647 static int
648 print_longnum(SSL* ssl, const char* desc, size_t x)
649 {
650 if(x > 1024*1024*1024) {
651 /* more than a Gb */
652 size_t front = x / (size_t)1000000;
653 size_t back = x % (size_t)1000000;
654 return ssl_printf(ssl, "%s%u%6.6u\n", desc,
655 (unsigned)front, (unsigned)back);
656 } else {
657 return ssl_printf(ssl, "%s%lu\n", desc, (unsigned long)x);
658 }
659 }
660
661 /** print mem stats */
662 static int
663 print_mem(SSL* ssl, struct worker* worker, struct daemon* daemon)
664 {
665 int m;
666 size_t msg, rrset, val, iter;
667 #ifdef HAVE_SBRK
668 extern void* unbound_start_brk;
669 void* cur = sbrk(0);
670 if(!print_longnum(ssl, "mem.total.sbrk"SQ,
671 (size_t)((char*)cur - (char*)unbound_start_brk))) return 0;
672 #endif /* HAVE_SBRK */
673 msg = slabhash_get_mem(daemon->env->msg_cache);
674 rrset = slabhash_get_mem(&daemon->env->rrset_cache->table);
675 val=0;
676 iter=0;
677 m = modstack_find(&worker->env.mesh->mods, "validator");
678 if(m != -1) {
679 fptr_ok(fptr_whitelist_mod_get_mem(worker->env.mesh->
680 mods.mod[m]->get_mem));
681 val = (*worker->env.mesh->mods.mod[m]->get_mem)
682 (&worker->env, m);
683 }
684 m = modstack_find(&worker->env.mesh->mods, "iterator");
685 if(m != -1) {
686 fptr_ok(fptr_whitelist_mod_get_mem(worker->env.mesh->
687 mods.mod[m]->get_mem));
688 iter = (*worker->env.mesh->mods.mod[m]->get_mem)
689 (&worker->env, m);
690 }
691
692 if(!print_longnum(ssl, "mem.cache.rrset"SQ, rrset))
693 return 0;
694 if(!print_longnum(ssl, "mem.cache.message"SQ, msg))
695 return 0;
696 if(!print_longnum(ssl, "mem.mod.iterator"SQ, iter))
697 return 0;
698 if(!print_longnum(ssl, "mem.mod.validator"SQ, val))
699 return 0;
700 return 1;
701 }
702
703 /** print uptime stats */
704 static int
705 print_uptime(SSL* ssl, struct worker* worker, int reset)
706 {
707 struct timeval now = *worker->env.now_tv;
708 struct timeval up, dt;
709 timeval_subtract(&up, &now, &worker->daemon->time_boot);
710 timeval_subtract(&dt, &now, &worker->daemon->time_last_stat);
711 if(reset)
712 worker->daemon->time_last_stat = now;
713 if(!ssl_printf(ssl, "time.now"SQ ARG_LL "d.%6.6d\n",
714 (long long)now.tv_sec, (unsigned)now.tv_usec)) return 0;
715 if(!ssl_printf(ssl, "time.up"SQ ARG_LL "d.%6.6d\n",
716 (long long)up.tv_sec, (unsigned)up.tv_usec)) return 0;
717 if(!ssl_printf(ssl, "time.elapsed"SQ ARG_LL "d.%6.6d\n",
718 (long long)dt.tv_sec, (unsigned)dt.tv_usec)) return 0;
719 return 1;
720 }
721
722 /** print extended histogram */
723 static int
724 print_hist(SSL* ssl, struct stats_info* s)
725 {
726 struct timehist* hist;
727 size_t i;
728 hist = timehist_setup();
729 if(!hist) {
730 log_err("out of memory");
731 return 0;
732 }
733 timehist_import(hist, s->svr.hist, NUM_BUCKETS_HIST);
734 for(i=0; i<hist->num; i++) {
735 if(!ssl_printf(ssl,
736 "histogram.%6.6d.%6.6d.to.%6.6d.%6.6d=%lu\n",
737 (int)hist->buckets[i].lower.tv_sec,
738 (int)hist->buckets[i].lower.tv_usec,
739 (int)hist->buckets[i].upper.tv_sec,
740 (int)hist->buckets[i].upper.tv_usec,
741 (unsigned long)hist->buckets[i].count)) {
742 timehist_delete(hist);
743 return 0;
744 }
745 }
746 timehist_delete(hist);
747 return 1;
748 }
749
750 /** print extended stats */
751 static int
752 print_ext(SSL* ssl, struct stats_info* s)
753 {
754 int i;
755 char nm[16];
756 const sldns_rr_descriptor* desc;
757 const sldns_lookup_table* lt;
758 /* TYPE */
759 for(i=0; i<STATS_QTYPE_NUM; i++) {
760 if(inhibit_zero && s->svr.qtype[i] == 0)
761 continue;
762 desc = sldns_rr_descript((uint16_t)i);
763 if(desc && desc->_name) {
764 snprintf(nm, sizeof(nm), "%s", desc->_name);
765 } else if (i == LDNS_RR_TYPE_IXFR) {
766 snprintf(nm, sizeof(nm), "IXFR");
767 } else if (i == LDNS_RR_TYPE_AXFR) {
768 snprintf(nm, sizeof(nm), "AXFR");
769 } else if (i == LDNS_RR_TYPE_MAILA) {
770 snprintf(nm, sizeof(nm), "MAILA");
771 } else if (i == LDNS_RR_TYPE_MAILB) {
772 snprintf(nm, sizeof(nm), "MAILB");
773 } else if (i == LDNS_RR_TYPE_ANY) {
774 snprintf(nm, sizeof(nm), "ANY");
775 } else {
776 snprintf(nm, sizeof(nm), "TYPE%d", i);
777 }
778 if(!ssl_printf(ssl, "num.query.type.%s"SQ"%lu\n",
779 nm, (unsigned long)s->svr.qtype[i])) return 0;
780 }
781 if(!inhibit_zero || s->svr.qtype_big) {
782 if(!ssl_printf(ssl, "num.query.type.other"SQ"%lu\n",
783 (unsigned long)s->svr.qtype_big)) return 0;
784 }
785 /* CLASS */
786 for(i=0; i<STATS_QCLASS_NUM; i++) {
787 if(inhibit_zero && s->svr.qclass[i] == 0)
788 continue;
789 lt = sldns_lookup_by_id(sldns_rr_classes, i);
790 if(lt && lt->name) {
791 snprintf(nm, sizeof(nm), "%s", lt->name);
792 } else {
793 snprintf(nm, sizeof(nm), "CLASS%d", i);
794 }
795 if(!ssl_printf(ssl, "num.query.class.%s"SQ"%lu\n",
796 nm, (unsigned long)s->svr.qclass[i])) return 0;
797 }
798 if(!inhibit_zero || s->svr.qclass_big) {
799 if(!ssl_printf(ssl, "num.query.class.other"SQ"%lu\n",
800 (unsigned long)s->svr.qclass_big)) return 0;
801 }
802 /* OPCODE */
803 for(i=0; i<STATS_OPCODE_NUM; i++) {
804 if(inhibit_zero && s->svr.qopcode[i] == 0)
805 continue;
806 lt = sldns_lookup_by_id(sldns_opcodes, i);
807 if(lt && lt->name) {
808 snprintf(nm, sizeof(nm), "%s", lt->name);
809 } else {
810 snprintf(nm, sizeof(nm), "OPCODE%d", i);
811 }
812 if(!ssl_printf(ssl, "num.query.opcode.%s"SQ"%lu\n",
813 nm, (unsigned long)s->svr.qopcode[i])) return 0;
814 }
815 /* transport */
816 if(!ssl_printf(ssl, "num.query.tcp"SQ"%lu\n",
817 (unsigned long)s->svr.qtcp)) return 0;
818 if(!ssl_printf(ssl, "num.query.tcpout"SQ"%lu\n",
819 (unsigned long)s->svr.qtcp_outgoing)) return 0;
820 if(!ssl_printf(ssl, "num.query.ipv6"SQ"%lu\n",
821 (unsigned long)s->svr.qipv6)) return 0;
822 /* flags */
823 if(!ssl_printf(ssl, "num.query.flags.QR"SQ"%lu\n",
824 (unsigned long)s->svr.qbit_QR)) return 0;
825 if(!ssl_printf(ssl, "num.query.flags.AA"SQ"%lu\n",
826 (unsigned long)s->svr.qbit_AA)) return 0;
827 if(!ssl_printf(ssl, "num.query.flags.TC"SQ"%lu\n",
828 (unsigned long)s->svr.qbit_TC)) return 0;
829 if(!ssl_printf(ssl, "num.query.flags.RD"SQ"%lu\n",
830 (unsigned long)s->svr.qbit_RD)) return 0;
831 if(!ssl_printf(ssl, "num.query.flags.RA"SQ"%lu\n",
832 (unsigned long)s->svr.qbit_RA)) return 0;
833 if(!ssl_printf(ssl, "num.query.flags.Z"SQ"%lu\n",
834 (unsigned long)s->svr.qbit_Z)) return 0;
835 if(!ssl_printf(ssl, "num.query.flags.AD"SQ"%lu\n",
836 (unsigned long)s->svr.qbit_AD)) return 0;
837 if(!ssl_printf(ssl, "num.query.flags.CD"SQ"%lu\n",
838 (unsigned long)s->svr.qbit_CD)) return 0;
839 if(!ssl_printf(ssl, "num.query.edns.present"SQ"%lu\n",
840 (unsigned long)s->svr.qEDNS)) return 0;
841 if(!ssl_printf(ssl, "num.query.edns.DO"SQ"%lu\n",
842 (unsigned long)s->svr.qEDNS_DO)) return 0;
843
844 /* RCODE */
845 for(i=0; i<STATS_RCODE_NUM; i++) {
846 /* Always include RCODEs 0-5 */
847 if(inhibit_zero && i > LDNS_RCODE_REFUSED && s->svr.ans_rcode[i] == 0)
848 continue;
849 lt = sldns_lookup_by_id(sldns_rcodes, i);
850 if(lt && lt->name) {
851 snprintf(nm, sizeof(nm), "%s", lt->name);
852 } else {
853 snprintf(nm, sizeof(nm), "RCODE%d", i);
854 }
855 if(!ssl_printf(ssl, "num.answer.rcode.%s"SQ"%lu\n",
856 nm, (unsigned long)s->svr.ans_rcode[i])) return 0;
857 }
858 if(!inhibit_zero || s->svr.ans_rcode_nodata) {
859 if(!ssl_printf(ssl, "num.answer.rcode.nodata"SQ"%lu\n",
860 (unsigned long)s->svr.ans_rcode_nodata)) return 0;
861 }
862 /* validation */
863 if(!ssl_printf(ssl, "num.answer.secure"SQ"%lu\n",
864 (unsigned long)s->svr.ans_secure)) return 0;
865 if(!ssl_printf(ssl, "num.answer.bogus"SQ"%lu\n",
866 (unsigned long)s->svr.ans_bogus)) return 0;
867 if(!ssl_printf(ssl, "num.rrset.bogus"SQ"%lu\n",
868 (unsigned long)s->svr.rrset_bogus)) return 0;
869 /* threat detection */
870 if(!ssl_printf(ssl, "unwanted.queries"SQ"%lu\n",
871 (unsigned long)s->svr.unwanted_queries)) return 0;
872 if(!ssl_printf(ssl, "unwanted.replies"SQ"%lu\n",
873 (unsigned long)s->svr.unwanted_replies)) return 0;
874 /* cache counts */
875 if(!ssl_printf(ssl, "msg.cache.count"SQ"%u\n",
876 (unsigned)s->svr.msg_cache_count)) return 0;
877 if(!ssl_printf(ssl, "rrset.cache.count"SQ"%u\n",
878 (unsigned)s->svr.rrset_cache_count)) return 0;
879 if(!ssl_printf(ssl, "infra.cache.count"SQ"%u\n",
880 (unsigned)s->svr.infra_cache_count)) return 0;
881 if(!ssl_printf(ssl, "key.cache.count"SQ"%u\n",
882 (unsigned)s->svr.key_cache_count)) return 0;
883 return 1;
884 }
885
886 /** do the stats command */
887 static void
888 do_stats(SSL* ssl, struct daemon_remote* rc, int reset)
889 {
890 struct daemon* daemon = rc->worker->daemon;
891 struct stats_info total;
892 struct stats_info s;
893 int i;
894 log_assert(daemon->num > 0);
895 /* gather all thread statistics in one place */
896 for(i=0; i<daemon->num; i++) {
897 server_stats_obtain(rc->worker, daemon->workers[i], &s, reset);
898 if(!print_thread_stats(ssl, i, &s))
899 return;
900 if(i == 0)
901 total = s;
902 else server_stats_add(&total, &s);
903 }
904 /* print the thread statistics */
905 total.mesh_time_median /= (double)daemon->num;
906 if(!print_stats(ssl, "total", &total))
907 return;
908 if(!print_uptime(ssl, rc->worker, reset))
909 return;
910 if(daemon->cfg->stat_extended) {
911 if(!print_mem(ssl, rc->worker, daemon))
912 return;
913 if(!print_hist(ssl, &total))
914 return;
915 if(!print_ext(ssl, &total))
916 return;
917 }
918 }
919
920 /** parse commandline argument domain name */
921 static int
922 parse_arg_name(SSL* ssl, char* str, uint8_t** res, size_t* len, int* labs)
923 {
924 uint8_t nm[LDNS_MAX_DOMAINLEN+1];
925 size_t nmlen = sizeof(nm);
926 int status;
927 *res = NULL;
928 *len = 0;
929 *labs = 0;
930 status = sldns_str2wire_dname_buf(str, nm, &nmlen);
931 if(status != 0) {
932 ssl_printf(ssl, "error cannot parse name %s at %d: %s\n", str,
933 LDNS_WIREPARSE_OFFSET(status),
934 sldns_get_errorstr_parse(status));
935 return 0;
936 }
937 *res = memdup(nm, nmlen);
938 if(!*res) {
939 ssl_printf(ssl, "error out of memory\n");
940 return 0;
941 }
942 *labs = dname_count_size_labels(*res, len);
943 return 1;
944 }
945
946 /** find second argument, modifies string */
947 static int
948 find_arg2(SSL* ssl, char* arg, char** arg2)
949 {
950 char* as = strchr(arg, ' ');
951 char* at = strchr(arg, '\t');
952 if(as && at) {
953 if(at < as)
954 as = at;
955 as[0]=0;
956 *arg2 = skipwhite(as+1);
957 } else if(as) {
958 as[0]=0;
959 *arg2 = skipwhite(as+1);
960 } else if(at) {
961 at[0]=0;
962 *arg2 = skipwhite(at+1);
963 } else {
964 ssl_printf(ssl, "error could not find next argument "
965 "after %s\n", arg);
966 return 0;
967 }
968 return 1;
969 }
970
971 /** Add a new zone */
972 static void
973 do_zone_add(SSL* ssl, struct worker* worker, char* arg)
974 {
975 uint8_t* nm;
976 int nmlabs;
977 size_t nmlen;
978 char* arg2;
979 enum localzone_type t;
980 struct local_zone* z;
981 if(!find_arg2(ssl, arg, &arg2))
982 return;
983 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
984 return;
985 if(!local_zone_str2type(arg2, &t)) {
986 ssl_printf(ssl, "error not a zone type. %s\n", arg2);
987 free(nm);
988 return;
989 }
990 lock_rw_wrlock(&worker->daemon->local_zones->lock);
991 if((z=local_zones_find(worker->daemon->local_zones, nm, nmlen,
992 nmlabs, LDNS_RR_CLASS_IN))) {
993 /* already present in tree */
994 lock_rw_wrlock(&z->lock);
995 z->type = t; /* update type anyway */
996 lock_rw_unlock(&z->lock);
997 free(nm);
998 lock_rw_unlock(&worker->daemon->local_zones->lock);
999 send_ok(ssl);
1000 return;
1001 }
1002 if(!local_zones_add_zone(worker->daemon->local_zones, nm, nmlen,
1003 nmlabs, LDNS_RR_CLASS_IN, t)) {
1004 lock_rw_unlock(&worker->daemon->local_zones->lock);
1005 ssl_printf(ssl, "error out of memory\n");
1006 return;
1007 }
1008 lock_rw_unlock(&worker->daemon->local_zones->lock);
1009 send_ok(ssl);
1010 }
1011
1012 /** Remove a zone */
1013 static void
1014 do_zone_remove(SSL* ssl, struct worker* worker, char* arg)
1015 {
1016 uint8_t* nm;
1017 int nmlabs;
1018 size_t nmlen;
1019 struct local_zone* z;
1020 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1021 return;
1022 lock_rw_wrlock(&worker->daemon->local_zones->lock);
1023 if((z=local_zones_find(worker->daemon->local_zones, nm, nmlen,
1024 nmlabs, LDNS_RR_CLASS_IN))) {
1025 /* present in tree */
1026 local_zones_del_zone(worker->daemon->local_zones, z);
1027 }
1028 lock_rw_unlock(&worker->daemon->local_zones->lock);
1029 free(nm);
1030 send_ok(ssl);
1031 }
1032
1033 /** Add new RR data */
1034 static void
1035 do_data_add(SSL* ssl, struct worker* worker, char* arg)
1036 {
1037 if(!local_zones_add_RR(worker->daemon->local_zones, arg)) {
1038 ssl_printf(ssl,"error in syntax or out of memory, %s\n", arg);
1039 return;
1040 }
1041 send_ok(ssl);
1042 }
1043
1044 /** Remove RR data */
1045 static void
1046 do_data_remove(SSL* ssl, struct worker* worker, char* arg)
1047 {
1048 uint8_t* nm;
1049 int nmlabs;
1050 size_t nmlen;
1051 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1052 return;
1053 local_zones_del_data(worker->daemon->local_zones, nm,
1054 nmlen, nmlabs, LDNS_RR_CLASS_IN);
1055 free(nm);
1056 send_ok(ssl);
1057 }
1058
1059 /** cache lookup of nameservers */
1060 static void
1061 do_lookup(SSL* ssl, struct worker* worker, char* arg)
1062 {
1063 uint8_t* nm;
1064 int nmlabs;
1065 size_t nmlen;
1066 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1067 return;
1068 (void)print_deleg_lookup(ssl, worker, nm, nmlen, nmlabs);
1069 free(nm);
1070 }
1071
1072 /** flush something from rrset and msg caches */
1073 static void
1074 do_cache_remove(struct worker* worker, uint8_t* nm, size_t nmlen,
1075 uint16_t t, uint16_t c)
1076 {
1077 hashvalue_t h;
1078 struct query_info k;
1079 rrset_cache_remove(worker->env.rrset_cache, nm, nmlen, t, c, 0);
1080 if(t == LDNS_RR_TYPE_SOA)
1081 rrset_cache_remove(worker->env.rrset_cache, nm, nmlen, t, c,
1082 PACKED_RRSET_SOA_NEG);
1083 k.qname = nm;
1084 k.qname_len = nmlen;
1085 k.qtype = t;
1086 k.qclass = c;
1087 h = query_info_hash(&k, 0);
1088 slabhash_remove(worker->env.msg_cache, h, &k);
1089 if(t == LDNS_RR_TYPE_AAAA) {
1090 /* for AAAA also flush dns64 bit_cd packet */
1091 h = query_info_hash(&k, BIT_CD);
1092 slabhash_remove(worker->env.msg_cache, h, &k);
1093 }
1094 }
1095
1096 /** flush a type */
1097 static void
1098 do_flush_type(SSL* ssl, struct worker* worker, char* arg)
1099 {
1100 uint8_t* nm;
1101 int nmlabs;
1102 size_t nmlen;
1103 char* arg2;
1104 uint16_t t;
1105 if(!find_arg2(ssl, arg, &arg2))
1106 return;
1107 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1108 return;
1109 t = sldns_get_rr_type_by_name(arg2);
1110 do_cache_remove(worker, nm, nmlen, t, LDNS_RR_CLASS_IN);
1111
1112 free(nm);
1113 send_ok(ssl);
1114 }
1115
1116 /** flush statistics */
1117 static void
1118 do_flush_stats(SSL* ssl, struct worker* worker)
1119 {
1120 worker_stats_clear(worker);
1121 send_ok(ssl);
1122 }
1123
1124 /**
1125 * Local info for deletion functions
1126 */
1127 struct del_info {
1128 /** worker */
1129 struct worker* worker;
1130 /** name to delete */
1131 uint8_t* name;
1132 /** length */
1133 size_t len;
1134 /** labels */
1135 int labs;
1136 /** now */
1137 time_t now;
1138 /** time to invalidate to */
1139 time_t expired;
1140 /** number of rrsets removed */
1141 size_t num_rrsets;
1142 /** number of msgs removed */
1143 size_t num_msgs;
1144 /** number of key entries removed */
1145 size_t num_keys;
1146 /** length of addr */
1147 socklen_t addrlen;
1148 /** socket address for host deletion */
1149 struct sockaddr_storage addr;
1150 };
1151
1152 /** callback to delete hosts in infra cache */
1153 static void
1154 infra_del_host(struct lruhash_entry* e, void* arg)
1155 {
1156 /* entry is locked */
1157 struct del_info* inf = (struct del_info*)arg;
1158 struct infra_key* k = (struct infra_key*)e->key;
1159 if(sockaddr_cmp(&inf->addr, inf->addrlen, &k->addr, k->addrlen) == 0) {
1160 struct infra_data* d = (struct infra_data*)e->data;
1161 d->probedelay = 0;
1162 d->timeout_A = 0;
1163 d->timeout_AAAA = 0;
1164 d->timeout_other = 0;
1165 rtt_init(&d->rtt);
1166 if(d->ttl >= inf->now) {
1167 d->ttl = inf->expired;
1168 inf->num_keys++;
1169 }
1170 }
1171 }
1172
1173 /** flush infra cache */
1174 static void
1175 do_flush_infra(SSL* ssl, struct worker* worker, char* arg)
1176 {
1177 struct sockaddr_storage addr;
1178 socklen_t len;
1179 struct del_info inf;
1180 if(strcmp(arg, "all") == 0) {
1181 slabhash_clear(worker->env.infra_cache->hosts);
1182 send_ok(ssl);
1183 return;
1184 }
1185 if(!ipstrtoaddr(arg, UNBOUND_DNS_PORT, &addr, &len)) {
1186 (void)ssl_printf(ssl, "error parsing ip addr: '%s'\n", arg);
1187 return;
1188 }
1189 /* delete all entries from cache */
1190 /* what we do is to set them all expired */
1191 inf.worker = worker;
1192 inf.name = 0;
1193 inf.len = 0;
1194 inf.labs = 0;
1195 inf.now = *worker->env.now;
1196 inf.expired = *worker->env.now;
1197 inf.expired -= 3; /* handle 3 seconds skew between threads */
1198 inf.num_rrsets = 0;
1199 inf.num_msgs = 0;
1200 inf.num_keys = 0;
1201 inf.addrlen = len;
1202 memmove(&inf.addr, &addr, len);
1203 slabhash_traverse(worker->env.infra_cache->hosts, 1, &infra_del_host,
1204 &inf);
1205 send_ok(ssl);
1206 }
1207
1208 /** flush requestlist */
1209 static void
1210 do_flush_requestlist(SSL* ssl, struct worker* worker)
1211 {
1212 mesh_delete_all(worker->env.mesh);
1213 send_ok(ssl);
1214 }
1215
1216 /** callback to delete rrsets in a zone */
1217 static void
1218 zone_del_rrset(struct lruhash_entry* e, void* arg)
1219 {
1220 /* entry is locked */
1221 struct del_info* inf = (struct del_info*)arg;
1222 struct ub_packed_rrset_key* k = (struct ub_packed_rrset_key*)e->key;
1223 if(dname_subdomain_c(k->rk.dname, inf->name)) {
1224 struct packed_rrset_data* d =
1225 (struct packed_rrset_data*)e->data;
1226 if(d->ttl >= inf->now) {
1227 d->ttl = inf->expired;
1228 inf->num_rrsets++;
1229 }
1230 }
1231 }
1232
1233 /** callback to delete messages in a zone */
1234 static void
1235 zone_del_msg(struct lruhash_entry* e, void* arg)
1236 {
1237 /* entry is locked */
1238 struct del_info* inf = (struct del_info*)arg;
1239 struct msgreply_entry* k = (struct msgreply_entry*)e->key;
1240 if(dname_subdomain_c(k->key.qname, inf->name)) {
1241 struct reply_info* d = (struct reply_info*)e->data;
1242 if(d->ttl >= inf->now) {
1243 d->ttl = inf->expired;
1244 inf->num_msgs++;
1245 }
1246 }
1247 }
1248
1249 /** callback to delete keys in zone */
1250 static void
1251 zone_del_kcache(struct lruhash_entry* e, void* arg)
1252 {
1253 /* entry is locked */
1254 struct del_info* inf = (struct del_info*)arg;
1255 struct key_entry_key* k = (struct key_entry_key*)e->key;
1256 if(dname_subdomain_c(k->name, inf->name)) {
1257 struct key_entry_data* d = (struct key_entry_data*)e->data;
1258 if(d->ttl >= inf->now) {
1259 d->ttl = inf->expired;
1260 inf->num_keys++;
1261 }
1262 }
1263 }
1264
1265 /** remove all rrsets and keys from zone from cache */
1266 static void
1267 do_flush_zone(SSL* ssl, struct worker* worker, char* arg)
1268 {
1269 uint8_t* nm;
1270 int nmlabs;
1271 size_t nmlen;
1272 struct del_info inf;
1273 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1274 return;
1275 /* delete all RRs and key entries from zone */
1276 /* what we do is to set them all expired */
1277 inf.worker = worker;
1278 inf.name = nm;
1279 inf.len = nmlen;
1280 inf.labs = nmlabs;
1281 inf.now = *worker->env.now;
1282 inf.expired = *worker->env.now;
1283 inf.expired -= 3; /* handle 3 seconds skew between threads */
1284 inf.num_rrsets = 0;
1285 inf.num_msgs = 0;
1286 inf.num_keys = 0;
1287 slabhash_traverse(&worker->env.rrset_cache->table, 1,
1288 &zone_del_rrset, &inf);
1289
1290 slabhash_traverse(worker->env.msg_cache, 1, &zone_del_msg, &inf);
1291
1292 /* and validator cache */
1293 if(worker->env.key_cache) {
1294 slabhash_traverse(worker->env.key_cache->slab, 1,
1295 &zone_del_kcache, &inf);
1296 }
1297
1298 free(nm);
1299
1300 (void)ssl_printf(ssl, "ok removed %lu rrsets, %lu messages "
1301 "and %lu key entries\n", (unsigned long)inf.num_rrsets,
1302 (unsigned long)inf.num_msgs, (unsigned long)inf.num_keys);
1303 }
1304
1305 /** callback to delete bogus rrsets */
1306 static void
1307 bogus_del_rrset(struct lruhash_entry* e, void* arg)
1308 {
1309 /* entry is locked */
1310 struct del_info* inf = (struct del_info*)arg;
1311 struct packed_rrset_data* d = (struct packed_rrset_data*)e->data;
1312 if(d->security == sec_status_bogus) {
1313 d->ttl = inf->expired;
1314 inf->num_rrsets++;
1315 }
1316 }
1317
1318 /** callback to delete bogus messages */
1319 static void
1320 bogus_del_msg(struct lruhash_entry* e, void* arg)
1321 {
1322 /* entry is locked */
1323 struct del_info* inf = (struct del_info*)arg;
1324 struct reply_info* d = (struct reply_info*)e->data;
1325 if(d->security == sec_status_bogus) {
1326 d->ttl = inf->expired;
1327 inf->num_msgs++;
1328 }
1329 }
1330
1331 /** callback to delete bogus keys */
1332 static void
1333 bogus_del_kcache(struct lruhash_entry* e, void* arg)
1334 {
1335 /* entry is locked */
1336 struct del_info* inf = (struct del_info*)arg;
1337 struct key_entry_data* d = (struct key_entry_data*)e->data;
1338 if(d->isbad) {
1339 d->ttl = inf->expired;
1340 inf->num_keys++;
1341 }
1342 }
1343
1344 /** remove all bogus rrsets, msgs and keys from cache */
1345 static void
1346 do_flush_bogus(SSL* ssl, struct worker* worker)
1347 {
1348 struct del_info inf;
1349 /* what we do is to set them all expired */
1350 inf.worker = worker;
1351 inf.now = *worker->env.now;
1352 inf.expired = *worker->env.now;
1353 inf.expired -= 3; /* handle 3 seconds skew between threads */
1354 inf.num_rrsets = 0;
1355 inf.num_msgs = 0;
1356 inf.num_keys = 0;
1357 slabhash_traverse(&worker->env.rrset_cache->table, 1,
1358 &bogus_del_rrset, &inf);
1359
1360 slabhash_traverse(worker->env.msg_cache, 1, &bogus_del_msg, &inf);
1361
1362 /* and validator cache */
1363 if(worker->env.key_cache) {
1364 slabhash_traverse(worker->env.key_cache->slab, 1,
1365 &bogus_del_kcache, &inf);
1366 }
1367
1368 (void)ssl_printf(ssl, "ok removed %lu rrsets, %lu messages "
1369 "and %lu key entries\n", (unsigned long)inf.num_rrsets,
1370 (unsigned long)inf.num_msgs, (unsigned long)inf.num_keys);
1371 }
1372
1373 /** callback to delete negative and servfail rrsets */
1374 static void
1375 negative_del_rrset(struct lruhash_entry* e, void* arg)
1376 {
1377 /* entry is locked */
1378 struct del_info* inf = (struct del_info*)arg;
1379 struct ub_packed_rrset_key* k = (struct ub_packed_rrset_key*)e->key;
1380 struct packed_rrset_data* d = (struct packed_rrset_data*)e->data;
1381 /* delete the parentside negative cache rrsets,
1382 * these are namerserver rrsets that failed lookup, rdata empty */
1383 if((k->rk.flags & PACKED_RRSET_PARENT_SIDE) && d->count == 1 &&
1384 d->rrsig_count == 0 && d->rr_len[0] == 0) {
1385 d->ttl = inf->expired;
1386 inf->num_rrsets++;
1387 }
1388 }
1389
1390 /** callback to delete negative and servfail messages */
1391 static void
1392 negative_del_msg(struct lruhash_entry* e, void* arg)
1393 {
1394 /* entry is locked */
1395 struct del_info* inf = (struct del_info*)arg;
1396 struct reply_info* d = (struct reply_info*)e->data;
1397 /* rcode not NOERROR: NXDOMAIN, SERVFAIL, ..: an nxdomain or error
1398 * or NOERROR rcode with ANCOUNT==0: a NODATA answer */
1399 if(FLAGS_GET_RCODE(d->flags) != 0 || d->an_numrrsets == 0) {
1400 d->ttl = inf->expired;
1401 inf->num_msgs++;
1402 }
1403 }
1404
1405 /** callback to delete negative key entries */
1406 static void
1407 negative_del_kcache(struct lruhash_entry* e, void* arg)
1408 {
1409 /* entry is locked */
1410 struct del_info* inf = (struct del_info*)arg;
1411 struct key_entry_data* d = (struct key_entry_data*)e->data;
1412 /* could be bad because of lookup failure on the DS, DNSKEY, which
1413 * was nxdomain or servfail, and thus a result of negative lookups */
1414 if(d->isbad) {
1415 d->ttl = inf->expired;
1416 inf->num_keys++;
1417 }
1418 }
1419
1420 /** remove all negative(NODATA,NXDOMAIN), and servfail messages from cache */
1421 static void
1422 do_flush_negative(SSL* ssl, struct worker* worker)
1423 {
1424 struct del_info inf;
1425 /* what we do is to set them all expired */
1426 inf.worker = worker;
1427 inf.now = *worker->env.now;
1428 inf.expired = *worker->env.now;
1429 inf.expired -= 3; /* handle 3 seconds skew between threads */
1430 inf.num_rrsets = 0;
1431 inf.num_msgs = 0;
1432 inf.num_keys = 0;
1433 slabhash_traverse(&worker->env.rrset_cache->table, 1,
1434 &negative_del_rrset, &inf);
1435
1436 slabhash_traverse(worker->env.msg_cache, 1, &negative_del_msg, &inf);
1437
1438 /* and validator cache */
1439 if(worker->env.key_cache) {
1440 slabhash_traverse(worker->env.key_cache->slab, 1,
1441 &negative_del_kcache, &inf);
1442 }
1443
1444 (void)ssl_printf(ssl, "ok removed %lu rrsets, %lu messages "
1445 "and %lu key entries\n", (unsigned long)inf.num_rrsets,
1446 (unsigned long)inf.num_msgs, (unsigned long)inf.num_keys);
1447 }
1448
1449 /** remove name rrset from cache */
1450 static void
1451 do_flush_name(SSL* ssl, struct worker* w, char* arg)
1452 {
1453 uint8_t* nm;
1454 int nmlabs;
1455 size_t nmlen;
1456 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1457 return;
1458 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_A, LDNS_RR_CLASS_IN);
1459 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_AAAA, LDNS_RR_CLASS_IN);
1460 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_NS, LDNS_RR_CLASS_IN);
1461 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SOA, LDNS_RR_CLASS_IN);
1462 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_CNAME, LDNS_RR_CLASS_IN);
1463 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_DNAME, LDNS_RR_CLASS_IN);
1464 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_MX, LDNS_RR_CLASS_IN);
1465 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_PTR, LDNS_RR_CLASS_IN);
1466 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SRV, LDNS_RR_CLASS_IN);
1467 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_NAPTR, LDNS_RR_CLASS_IN);
1468
1469 free(nm);
1470 send_ok(ssl);
1471 }
1472
1473 /** printout a delegation point info */
1474 static int
1475 ssl_print_name_dp(SSL* ssl, const char* str, uint8_t* nm, uint16_t dclass,
1476 struct delegpt* dp)
1477 {
1478 char buf[257];
1479 struct delegpt_ns* ns;
1480 struct delegpt_addr* a;
1481 int f = 0;
1482 if(str) { /* print header for forward, stub */
1483 char* c = sldns_wire2str_class(dclass);
1484 dname_str(nm, buf);
1485 if(!ssl_printf(ssl, "%s %s %s ", buf, (c?c:"CLASS??"), str)) {
1486 free(c);
1487 return 0;
1488 }
1489 free(c);
1490 }
1491 for(ns = dp->nslist; ns; ns = ns->next) {
1492 dname_str(ns->name, buf);
1493 if(!ssl_printf(ssl, "%s%s", (f?" ":""), buf))
1494 return 0;
1495 f = 1;
1496 }
1497 for(a = dp->target_list; a; a = a->next_target) {
1498 addr_to_str(&a->addr, a->addrlen, buf, sizeof(buf));
1499 if(!ssl_printf(ssl, "%s%s", (f?" ":""), buf))
1500 return 0;
1501 f = 1;
1502 }
1503 return ssl_printf(ssl, "\n");
1504 }
1505
1506
1507 /** print root forwards */
1508 static int
1509 print_root_fwds(SSL* ssl, struct iter_forwards* fwds, uint8_t* root)
1510 {
1511 struct delegpt* dp;
1512 dp = forwards_lookup(fwds, root, LDNS_RR_CLASS_IN);
1513 if(!dp)
1514 return ssl_printf(ssl, "off (using root hints)\n");
1515 /* if dp is returned it must be the root */
1516 log_assert(query_dname_compare(dp->name, root)==0);
1517 return ssl_print_name_dp(ssl, NULL, root, LDNS_RR_CLASS_IN, dp);
1518 }
1519
1520 /** parse args into delegpt */
1521 static struct delegpt*
1522 parse_delegpt(SSL* ssl, char* args, uint8_t* nm, int allow_names)
1523 {
1524 /* parse args and add in */
1525 char* p = args;
1526 char* todo;
1527 struct delegpt* dp = delegpt_create_mlc(nm);
1528 struct sockaddr_storage addr;
1529 socklen_t addrlen;
1530 if(!dp) {
1531 (void)ssl_printf(ssl, "error out of memory\n");
1532 return NULL;
1533 }
1534 while(p) {
1535 todo = p;
1536 p = strchr(p, ' '); /* find next spot, if any */
1537 if(p) {
1538 *p++ = 0; /* end this spot */
1539 p = skipwhite(p); /* position at next spot */
1540 }
1541 /* parse address */
1542 if(!extstrtoaddr(todo, &addr, &addrlen)) {
1543 if(allow_names) {
1544 uint8_t* n = NULL;
1545 size_t ln;
1546 int lb;
1547 if(!parse_arg_name(ssl, todo, &n, &ln, &lb)) {
1548 (void)ssl_printf(ssl, "error cannot "
1549 "parse IP address or name "
1550 "'%s'\n", todo);
1551 delegpt_free_mlc(dp);
1552 return NULL;
1553 }
1554 if(!delegpt_add_ns_mlc(dp, n, 0)) {
1555 (void)ssl_printf(ssl, "error out of memory\n");
1556 free(n);
1557 delegpt_free_mlc(dp);
1558 return NULL;
1559 }
1560 free(n);
1561
1562 } else {
1563 (void)ssl_printf(ssl, "error cannot parse"
1564 " IP address '%s'\n", todo);
1565 delegpt_free_mlc(dp);
1566 return NULL;
1567 }
1568 } else {
1569 /* add address */
1570 if(!delegpt_add_addr_mlc(dp, &addr, addrlen, 0, 0)) {
1571 (void)ssl_printf(ssl, "error out of memory\n");
1572 delegpt_free_mlc(dp);
1573 return NULL;
1574 }
1575 }
1576 }
1577 return dp;
1578 }
1579
1580 /** do the status command */
1581 static void
1582 do_forward(SSL* ssl, struct worker* worker, char* args)
1583 {
1584 struct iter_forwards* fwd = worker->env.fwds;
1585 uint8_t* root = (uint8_t*)"\000";
1586 if(!fwd) {
1587 (void)ssl_printf(ssl, "error: structure not allocated\n");
1588 return;
1589 }
1590 if(args == NULL || args[0] == 0) {
1591 (void)print_root_fwds(ssl, fwd, root);
1592 return;
1593 }
1594 /* set root forwards for this thread. since we are in remote control
1595 * the actual mesh is not running, so we can freely edit it. */
1596 /* delete all the existing queries first */
1597 mesh_delete_all(worker->env.mesh);
1598 if(strcmp(args, "off") == 0) {
1599 forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, root);
1600 } else {
1601 struct delegpt* dp;
1602 if(!(dp = parse_delegpt(ssl, args, root, 0)))
1603 return;
1604 if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp)) {
1605 (void)ssl_printf(ssl, "error out of memory\n");
1606 return;
1607 }
1608 }
1609 send_ok(ssl);
1610 }
1611
1612 static int
1613 parse_fs_args(SSL* ssl, char* args, uint8_t** nm, struct delegpt** dp,
1614 int* insecure, int* prime)
1615 {
1616 char* zonename;
1617 char* rest;
1618 size_t nmlen;
1619 int nmlabs;
1620 /* parse all -x args */
1621 while(args[0] == '+') {
1622 if(!find_arg2(ssl, args, &rest))
1623 return 0;
1624 while(*(++args) != 0) {
1625 if(*args == 'i' && insecure)
1626 *insecure = 1;
1627 else if(*args == 'p' && prime)
1628 *prime = 1;
1629 else {
1630 (void)ssl_printf(ssl, "error: unknown option %s\n", args);
1631 return 0;
1632 }
1633 }
1634 args = rest;
1635 }
1636 /* parse name */
1637 if(dp) {
1638 if(!find_arg2(ssl, args, &rest))
1639 return 0;
1640 zonename = args;
1641 args = rest;
1642 } else zonename = args;
1643 if(!parse_arg_name(ssl, zonename, nm, &nmlen, &nmlabs))
1644 return 0;
1645
1646 /* parse dp */
1647 if(dp) {
1648 if(!(*dp = parse_delegpt(ssl, args, *nm, 1))) {
1649 free(*nm);
1650 return 0;
1651 }
1652 }
1653 return 1;
1654 }
1655
1656 /** do the forward_add command */
1657 static void
1658 do_forward_add(SSL* ssl, struct worker* worker, char* args)
1659 {
1660 struct iter_forwards* fwd = worker->env.fwds;
1661 int insecure = 0;
1662 uint8_t* nm = NULL;
1663 struct delegpt* dp = NULL;
1664 if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, NULL))
1665 return;
1666 if(insecure && worker->env.anchors) {
1667 if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
1668 nm)) {
1669 (void)ssl_printf(ssl, "error out of memory\n");
1670 delegpt_free_mlc(dp);
1671 free(nm);
1672 return;
1673 }
1674 }
1675 if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp)) {
1676 (void)ssl_printf(ssl, "error out of memory\n");
1677 free(nm);
1678 return;
1679 }
1680 free(nm);
1681 send_ok(ssl);
1682 }
1683
1684 /** do the forward_remove command */
1685 static void
1686 do_forward_remove(SSL* ssl, struct worker* worker, char* args)
1687 {
1688 struct iter_forwards* fwd = worker->env.fwds;
1689 int insecure = 0;
1690 uint8_t* nm = NULL;
1691 if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL))
1692 return;
1693 if(insecure && worker->env.anchors)
1694 anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
1695 nm);
1696 forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, nm);
1697 free(nm);
1698 send_ok(ssl);
1699 }
1700
1701 /** do the stub_add command */
1702 static void
1703 do_stub_add(SSL* ssl, struct worker* worker, char* args)
1704 {
1705 struct iter_forwards* fwd = worker->env.fwds;
1706 int insecure = 0, prime = 0;
1707 uint8_t* nm = NULL;
1708 struct delegpt* dp = NULL;
1709 if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, &prime))
1710 return;
1711 if(insecure && worker->env.anchors) {
1712 if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
1713 nm)) {
1714 (void)ssl_printf(ssl, "error out of memory\n");
1715 delegpt_free_mlc(dp);
1716 free(nm);
1717 return;
1718 }
1719 }
1720 if(!forwards_add_stub_hole(fwd, LDNS_RR_CLASS_IN, nm)) {
1721 if(insecure && worker->env.anchors)
1722 anchors_delete_insecure(worker->env.anchors,
1723 LDNS_RR_CLASS_IN, nm);
1724 (void)ssl_printf(ssl, "error out of memory\n");
1725 delegpt_free_mlc(dp);
1726 free(nm);
1727 return;
1728 }
1729 if(!hints_add_stub(worker->env.hints, LDNS_RR_CLASS_IN, dp, !prime)) {
1730 (void)ssl_printf(ssl, "error out of memory\n");
1731 forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm);
1732 if(insecure && worker->env.anchors)
1733 anchors_delete_insecure(worker->env.anchors,
1734 LDNS_RR_CLASS_IN, nm);
1735 free(nm);
1736 return;
1737 }
1738 free(nm);
1739 send_ok(ssl);
1740 }
1741
1742 /** do the stub_remove command */
1743 static void
1744 do_stub_remove(SSL* ssl, struct worker* worker, char* args)
1745 {
1746 struct iter_forwards* fwd = worker->env.fwds;
1747 int insecure = 0;
1748 uint8_t* nm = NULL;
1749 if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL))
1750 return;
1751 if(insecure && worker->env.anchors)
1752 anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
1753 nm);
1754 forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm);
1755 hints_delete_stub(worker->env.hints, LDNS_RR_CLASS_IN, nm);
1756 free(nm);
1757 send_ok(ssl);
1758 }
1759
1760 /** do the insecure_add command */
1761 static void
1762 do_insecure_add(SSL* ssl, struct worker* worker, char* arg)
1763 {
1764 size_t nmlen;
1765 int nmlabs;
1766 uint8_t* nm = NULL;
1767 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1768 return;
1769 if(worker->env.anchors) {
1770 if(!anchors_add_insecure(worker->env.anchors,
1771 LDNS_RR_CLASS_IN, nm)) {
1772 (void)ssl_printf(ssl, "error out of memory\n");
1773 free(nm);
1774 return;
1775 }
1776 }
1777 free(nm);
1778 send_ok(ssl);
1779 }
1780
1781 /** do the insecure_remove command */
1782 static void
1783 do_insecure_remove(SSL* ssl, struct worker* worker, char* arg)
1784 {
1785 size_t nmlen;
1786 int nmlabs;
1787 uint8_t* nm = NULL;
1788 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1789 return;
1790 if(worker->env.anchors)
1791 anchors_delete_insecure(worker->env.anchors,
1792 LDNS_RR_CLASS_IN, nm);
1793 free(nm);
1794 send_ok(ssl);
1795 }
1796
1797 /** do the status command */
1798 static void
1799 do_status(SSL* ssl, struct worker* worker)
1800 {
1801 int i;
1802 time_t uptime;
1803 if(!ssl_printf(ssl, "version: %s\n", PACKAGE_VERSION))
1804 return;
1805 if(!ssl_printf(ssl, "verbosity: %d\n", verbosity))
1806 return;
1807 if(!ssl_printf(ssl, "threads: %d\n", worker->daemon->num))
1808 return;
1809 if(!ssl_printf(ssl, "modules: %d [", worker->daemon->mods.num))
1810 return;
1811 for(i=0; i<worker->daemon->mods.num; i++) {
1812 if(!ssl_printf(ssl, " %s", worker->daemon->mods.mod[i]->name))
1813 return;
1814 }
1815 if(!ssl_printf(ssl, " ]\n"))
1816 return;
1817 uptime = (time_t)time(NULL) - (time_t)worker->daemon->time_boot.tv_sec;
1818 if(!ssl_printf(ssl, "uptime: " ARG_LL "d seconds\n", (long long)uptime))
1819 return;
1820 if(!ssl_printf(ssl, "options:%s%s\n" ,
1821 (worker->daemon->reuseport?" reuseport":""),
1822 (worker->daemon->rc->accept_list?" control(ssl)":"")))
1823 return;
1824 if(!ssl_printf(ssl, "unbound (pid %d) is running...\n",
1825 (int)getpid()))
1826 return;
1827 }
1828
1829 /** get age for the mesh state */
1830 static void
1831 get_mesh_age(struct mesh_state* m, char* buf, size_t len,
1832 struct module_env* env)
1833 {
1834 if(m->reply_list) {
1835 struct timeval d;
1836 struct mesh_reply* r = m->reply_list;
1837 /* last reply is the oldest */
1838 while(r && r->next)
1839 r = r->next;
1840 timeval_subtract(&d, env->now_tv, &r->start_time);
1841 snprintf(buf, len, ARG_LL "d.%6.6d",
1842 (long long)d.tv_sec, (int)d.tv_usec);
1843 } else {
1844 snprintf(buf, len, "-");
1845 }
1846 }
1847
1848 /** get status of a mesh state */
1849 static void
1850 get_mesh_status(struct mesh_area* mesh, struct mesh_state* m,
1851 char* buf, size_t len)
1852 {
1853 enum module_ext_state s = m->s.ext_state[m->s.curmod];
1854 const char *modname = mesh->mods.mod[m->s.curmod]->name;
1855 size_t l;
1856 if(strcmp(modname, "iterator") == 0 && s == module_wait_reply &&
1857 m->s.minfo[m->s.curmod]) {
1858 /* break into iterator to find out who its waiting for */
1859 struct iter_qstate* qstate = (struct iter_qstate*)
1860 m->s.minfo[m->s.curmod];
1861 struct outbound_list* ol = &qstate->outlist;
1862 struct outbound_entry* e;
1863 snprintf(buf, len, "%s wait for", modname);
1864 l = strlen(buf);
1865 buf += l; len -= l;
1866 if(ol->first == NULL)
1867 snprintf(buf, len, " (empty_list)");
1868 for(e = ol->first; e; e = e->next) {
1869 snprintf(buf, len, " ");
1870 l = strlen(buf);
1871 buf += l; len -= l;
1872 addr_to_str(&e->qsent->addr, e->qsent->addrlen,
1873 buf, len);
1874 l = strlen(buf);
1875 buf += l; len -= l;
1876 }
1877 } else if(s == module_wait_subquery) {
1878 /* look in subs from mesh state to see what */
1879 char nm[257];
1880 struct mesh_state_ref* sub;
1881 snprintf(buf, len, "%s wants", modname);
1882 l = strlen(buf);
1883 buf += l; len -= l;
1884 if(m->sub_set.count == 0)
1885 snprintf(buf, len, " (empty_list)");
1886 RBTREE_FOR(sub, struct mesh_state_ref*, &m->sub_set) {
1887 char* t = sldns_wire2str_type(sub->s->s.qinfo.qtype);
1888 char* c = sldns_wire2str_class(sub->s->s.qinfo.qclass);
1889 dname_str(sub->s->s.qinfo.qname, nm);
1890 snprintf(buf, len, " %s %s %s", (t?t:"TYPE??"),
1891 (c?c:"CLASS??"), nm);
1892 l = strlen(buf);
1893 buf += l; len -= l;
1894 free(t);
1895 free(c);
1896 }
1897 } else {
1898 snprintf(buf, len, "%s is %s", modname, strextstate(s));
1899 }
1900 }
1901
1902 /** do the dump_requestlist command */
1903 static void
1904 do_dump_requestlist(SSL* ssl, struct worker* worker)
1905 {
1906 struct mesh_area* mesh;
1907 struct mesh_state* m;
1908 int num = 0;
1909 char buf[257];
1910 char timebuf[32];
1911 char statbuf[10240];
1912 if(!ssl_printf(ssl, "thread #%d\n", worker->thread_num))
1913 return;
1914 if(!ssl_printf(ssl, "# type cl name seconds module status\n"))
1915 return;
1916 /* show worker mesh contents */
1917 mesh = worker->env.mesh;
1918 if(!mesh) return;
1919 RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
1920 char* t = sldns_wire2str_type(m->s.qinfo.qtype);
1921 char* c = sldns_wire2str_class(m->s.qinfo.qclass);
1922 dname_str(m->s.qinfo.qname, buf);
1923 get_mesh_age(m, timebuf, sizeof(timebuf), &worker->env);
1924 get_mesh_status(mesh, m, statbuf, sizeof(statbuf));
1925 if(!ssl_printf(ssl, "%3d %4s %2s %s %s %s\n",
1926 num, (t?t:"TYPE??"), (c?c:"CLASS??"), buf, timebuf,
1927 statbuf)) {
1928 free(t);
1929 free(c);
1930 return;
1931 }
1932 num++;
1933 free(t);
1934 free(c);
1935 }
1936 }
1937
1938 /** structure for argument data for dump infra host */
1939 struct infra_arg {
1940 /** the infra cache */
1941 struct infra_cache* infra;
1942 /** the SSL connection */
1943 SSL* ssl;
1944 /** the time now */
1945 time_t now;
1946 /** ssl failure? stop writing and skip the rest. If the tcp
1947 * connection is broken, and writes fail, we then stop writing. */
1948 int ssl_failed;
1949 };
1950
1951 /** callback for every host element in the infra cache */
1952 static void
1953 dump_infra_host(struct lruhash_entry* e, void* arg)
1954 {
1955 struct infra_arg* a = (struct infra_arg*)arg;
1956 struct infra_key* k = (struct infra_key*)e->key;
1957 struct infra_data* d = (struct infra_data*)e->data;
1958 char ip_str[1024];
1959 char name[257];
1960 if(a->ssl_failed)
1961 return;
1962 addr_to_str(&k->addr, k->addrlen, ip_str, sizeof(ip_str));
1963 dname_str(k->zonename, name);
1964 /* skip expired stuff (only backed off) */
1965 if(d->ttl < a->now) {
1966 if(d->rtt.rto >= USEFUL_SERVER_TOP_TIMEOUT) {
1967 if(!ssl_printf(a->ssl, "%s %s expired rto %d\n", ip_str,
1968 name, d->rtt.rto)) {
1969 a->ssl_failed = 1;
1970 return;
1971 }
1972 }
1973 return;
1974 }
1975 if(!ssl_printf(a->ssl, "%s %s ttl %lu ping %d var %d rtt %d rto %d "
1976 "tA %d tAAAA %d tother %d "
1977 "ednsknown %d edns %d delay %d lame dnssec %d rec %d A %d "
1978 "other %d\n", ip_str, name, (unsigned long)(d->ttl - a->now),
1979 d->rtt.srtt, d->rtt.rttvar, rtt_notimeout(&d->rtt), d->rtt.rto,
1980 d->timeout_A, d->timeout_AAAA, d->timeout_other,
1981 (int)d->edns_lame_known, (int)d->edns_version,
1982 (int)(a->now<d->probedelay?d->probedelay-a->now:0),
1983 (int)d->isdnsseclame, (int)d->rec_lame, (int)d->lame_type_A,
1984 (int)d->lame_other)) {
1985 a->ssl_failed = 1;
1986 return;
1987 }
1988 }
1989
1990 /** do the dump_infra command */
1991 static void
1992 do_dump_infra(SSL* ssl, struct worker* worker)
1993 {
1994 struct infra_arg arg;
1995 arg.infra = worker->env.infra_cache;
1996 arg.ssl = ssl;
1997 arg.now = *worker->env.now;
1998 arg.ssl_failed = 0;
1999 slabhash_traverse(arg.infra->hosts, 0, &dump_infra_host, (void*)&arg);
2000 }
2001
2002 /** do the log_reopen command */
2003 static void
2004 do_log_reopen(SSL* ssl, struct worker* worker)
2005 {
2006 struct config_file* cfg = worker->env.cfg;
2007 send_ok(ssl);
2008 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
2009 }
2010
2011 /** do the set_option command */
2012 static void
2013 do_set_option(SSL* ssl, struct worker* worker, char* arg)
2014 {
2015 char* arg2;
2016 if(!find_arg2(ssl, arg, &arg2))
2017 return;
2018 if(!config_set_option(worker->env.cfg, arg, arg2)) {
2019 (void)ssl_printf(ssl, "error setting option\n");
2020 return;
2021 }
2022 send_ok(ssl);
2023 }
2024
2025 /* routine to printout option values over SSL */
2026 void remote_get_opt_ssl(char* line, void* arg)
2027 {
2028 SSL* ssl = (SSL*)arg;
2029 (void)ssl_printf(ssl, "%s\n", line);
2030 }
2031
2032 /** do the get_option command */
2033 static void
2034 do_get_option(SSL* ssl, struct worker* worker, char* arg)
2035 {
2036 int r;
2037 r = config_get_option(worker->env.cfg, arg, remote_get_opt_ssl, ssl);
2038 if(!r) {
2039 (void)ssl_printf(ssl, "error unknown option\n");
2040 return;
2041 }
2042 }
2043
2044 /** do the list_forwards command */
2045 static void
2046 do_list_forwards(SSL* ssl, struct worker* worker)
2047 {
2048 /* since its a per-worker structure no locks needed */
2049 struct iter_forwards* fwds = worker->env.fwds;
2050 struct iter_forward_zone* z;
2051 struct trust_anchor* a;
2052 int insecure;
2053 RBTREE_FOR(z, struct iter_forward_zone*, fwds->tree) {
2054 if(!z->dp) continue; /* skip empty marker for stub */
2055
2056 /* see if it is insecure */
2057 insecure = 0;
2058 if(worker->env.anchors &&
2059 (a=anchor_find(worker->env.anchors, z->name,
2060 z->namelabs, z->namelen, z->dclass))) {
2061 if(!a->keylist && !a->numDS && !a->numDNSKEY)
2062 insecure = 1;
2063 lock_basic_unlock(&a->lock);
2064 }
2065
2066 if(!ssl_print_name_dp(ssl, (insecure?"forward +i":"forward"),
2067 z->name, z->dclass, z->dp))
2068 return;
2069 }
2070 }
2071
2072 /** do the list_stubs command */
2073 static void
2074 do_list_stubs(SSL* ssl, struct worker* worker)
2075 {
2076 struct iter_hints_stub* z;
2077 struct trust_anchor* a;
2078 int insecure;
2079 char str[32];
2080 RBTREE_FOR(z, struct iter_hints_stub*, &worker->env.hints->tree) {
2081
2082 /* see if it is insecure */
2083 insecure = 0;
2084 if(worker->env.anchors &&
2085 (a=anchor_find(worker->env.anchors, z->node.name,
2086 z->node.labs, z->node.len, z->node.dclass))) {
2087 if(!a->keylist && !a->numDS && !a->numDNSKEY)
2088 insecure = 1;
2089 lock_basic_unlock(&a->lock);
2090 }
2091
2092 snprintf(str, sizeof(str), "stub %sprime%s",
2093 (z->noprime?"no":""), (insecure?" +i":""));
2094 if(!ssl_print_name_dp(ssl, str, z->node.name,
2095 z->node.dclass, z->dp))
2096 return;
2097 }
2098 }
2099
2100 /** do the list_local_zones command */
2101 static void
2102 do_list_local_zones(SSL* ssl, struct worker* worker)
2103 {
2104 struct local_zones* zones = worker->daemon->local_zones;
2105 struct local_zone* z;
2106 char buf[257];
2107 lock_rw_rdlock(&zones->lock);
2108 RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
2109 lock_rw_rdlock(&z->lock);
2110 dname_str(z->name, buf);
2111 if(!ssl_printf(ssl, "%s %s\n", buf,
2112 local_zone_type2str(z->type))) {
2113 /* failure to print */
2114 lock_rw_unlock(&z->lock);
2115 lock_rw_unlock(&zones->lock);
2116 return;
2117 }
2118 lock_rw_unlock(&z->lock);
2119 }
2120 lock_rw_unlock(&zones->lock);
2121 }
2122
2123 /** do the list_local_data command */
2124 static void
2125 do_list_local_data(SSL* ssl, struct worker* worker)
2126 {
2127 struct local_zones* zones = worker->daemon->local_zones;
2128 struct local_zone* z;
2129 struct local_data* d;
2130 struct local_rrset* p;
2131 char* s = (char*)sldns_buffer_begin(worker->env.scratch_buffer);
2132 size_t slen = sldns_buffer_capacity(worker->env.scratch_buffer);
2133 lock_rw_rdlock(&zones->lock);
2134 RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
2135 lock_rw_rdlock(&z->lock);
2136 RBTREE_FOR(d, struct local_data*, &z->data) {
2137 for(p = d->rrsets; p; p = p->next) {
2138 struct packed_rrset_data* d =
2139 (struct packed_rrset_data*)p->rrset->entry.data;
2140 size_t i;
2141 for(i=0; i<d->count + d->rrsig_count; i++) {
2142 if(!packed_rr_to_string(p->rrset, i,
2143 0, s, slen)) {
2144 if(!ssl_printf(ssl, "BADRR\n"))
2145 return;
2146 }
2147 if(!ssl_printf(ssl, "%s\n", s))
2148 return;
2149 }
2150 }
2151 }
2152 lock_rw_unlock(&z->lock);
2153 }
2154 lock_rw_unlock(&zones->lock);
2155 }
2156
2157 /** tell other processes to execute the command */
2158 static void
2159 distribute_cmd(struct daemon_remote* rc, SSL* ssl, char* cmd)
2160 {
2161 int i;
2162 if(!cmd || !ssl)
2163 return;
2164 /* skip i=0 which is me */
2165 for(i=1; i<rc->worker->daemon->num; i++) {
2166 worker_send_cmd(rc->worker->daemon->workers[i],
2167 worker_cmd_remote);
2168 if(!tube_write_msg(rc->worker->daemon->workers[i]->cmd,
2169 (uint8_t*)cmd, strlen(cmd)+1, 0)) {
2170 ssl_printf(ssl, "error could not distribute cmd\n");
2171 return;
2172 }
2173 }
2174 }
2175
2176 /** check for name with end-of-string, space or tab after it */
2177 static int
2178 cmdcmp(char* p, const char* cmd, size_t len)
2179 {
2180 return strncmp(p,cmd,len)==0 && (p[len]==0||p[len]==' '||p[len]=='\t');
2181 }
2182
2183 /** execute a remote control command */
2184 static void
2185 execute_cmd(struct daemon_remote* rc, SSL* ssl, char* cmd,
2186 struct worker* worker)
2187 {
2188 char* p = skipwhite(cmd);
2189 /* compare command */
2190 if(cmdcmp(p, "stop", 4)) {
2191 do_stop(ssl, rc);
2192 return;
2193 } else if(cmdcmp(p, "reload", 6)) {
2194 do_reload(ssl, rc);
2195 return;
2196 } else if(cmdcmp(p, "stats_noreset", 13)) {
2197 do_stats(ssl, rc, 0);
2198 return;
2199 } else if(cmdcmp(p, "stats", 5)) {
2200 do_stats(ssl, rc, 1);
2201 return;
2202 } else if(cmdcmp(p, "status", 6)) {
2203 do_status(ssl, worker);
2204 return;
2205 } else if(cmdcmp(p, "dump_cache", 10)) {
2206 (void)dump_cache(ssl, worker);
2207 return;
2208 } else if(cmdcmp(p, "load_cache", 10)) {
2209 if(load_cache(ssl, worker)) send_ok(ssl);
2210 return;
2211 } else if(cmdcmp(p, "list_forwards", 13)) {
2212 do_list_forwards(ssl, worker);
2213 return;
2214 } else if(cmdcmp(p, "list_stubs", 10)) {
2215 do_list_stubs(ssl, worker);
2216 return;
2217 } else if(cmdcmp(p, "list_local_zones", 16)) {
2218 do_list_local_zones(ssl, worker);
2219 return;
2220 } else if(cmdcmp(p, "list_local_data", 15)) {
2221 do_list_local_data(ssl, worker);
2222 return;
2223 } else if(cmdcmp(p, "stub_add", 8)) {
2224 /* must always distribute this cmd */
2225 if(rc) distribute_cmd(rc, ssl, cmd);
2226 do_stub_add(ssl, worker, skipwhite(p+8));
2227 return;
2228 } else if(cmdcmp(p, "stub_remove", 11)) {
2229 /* must always distribute this cmd */
2230 if(rc) distribute_cmd(rc, ssl, cmd);
2231 do_stub_remove(ssl, worker, skipwhite(p+11));
2232 return;
2233 } else if(cmdcmp(p, "forward_add", 11)) {
2234 /* must always distribute this cmd */
2235 if(rc) distribute_cmd(rc, ssl, cmd);
2236 do_forward_add(ssl, worker, skipwhite(p+11));
2237 return;
2238 } else if(cmdcmp(p, "forward_remove", 14)) {
2239 /* must always distribute this cmd */
2240 if(rc) distribute_cmd(rc, ssl, cmd);
2241 do_forward_remove(ssl, worker, skipwhite(p+14));
2242 return;
2243 } else if(cmdcmp(p, "insecure_add", 12)) {
2244 /* must always distribute this cmd */
2245 if(rc) distribute_cmd(rc, ssl, cmd);
2246 do_insecure_add(ssl, worker, skipwhite(p+12));
2247 return;
2248 } else if(cmdcmp(p, "insecure_remove", 15)) {
2249 /* must always distribute this cmd */
2250 if(rc) distribute_cmd(rc, ssl, cmd);
2251 do_insecure_remove(ssl, worker, skipwhite(p+15));
2252 return;
2253 } else if(cmdcmp(p, "forward", 7)) {
2254 /* must always distribute this cmd */
2255 if(rc) distribute_cmd(rc, ssl, cmd);
2256 do_forward(ssl, worker, skipwhite(p+7));
2257 return;
2258 } else if(cmdcmp(p, "flush_stats", 11)) {
2259 /* must always distribute this cmd */
2260 if(rc) distribute_cmd(rc, ssl, cmd);
2261 do_flush_stats(ssl, worker);
2262 return;
2263 } else if(cmdcmp(p, "flush_requestlist", 17)) {
2264 /* must always distribute this cmd */
2265 if(rc) distribute_cmd(rc, ssl, cmd);
2266 do_flush_requestlist(ssl, worker);
2267 return;
2268 } else if(cmdcmp(p, "lookup", 6)) {
2269 do_lookup(ssl, worker, skipwhite(p+6));
2270 return;
2271 }
2272
2273 #ifdef THREADS_DISABLED
2274 /* other processes must execute the command as well */
2275 /* commands that should not be distributed, returned above. */
2276 if(rc) { /* only if this thread is the master (rc) thread */
2277 /* done before the code below, which may split the string */
2278 distribute_cmd(rc, ssl, cmd);
2279 }
2280 #endif
2281 if(cmdcmp(p, "verbosity", 9)) {
2282 do_verbosity(ssl, skipwhite(p+9));
2283 } else if(cmdcmp(p, "local_zone_remove", 17)) {
2284 do_zone_remove(ssl, worker, skipwhite(p+17));
2285 } else if(cmdcmp(p, "local_zone", 10)) {
2286 do_zone_add(ssl, worker, skipwhite(p+10));
2287 } else if(cmdcmp(p, "local_data_remove", 17)) {
2288 do_data_remove(ssl, worker, skipwhite(p+17));
2289 } else if(cmdcmp(p, "local_data", 10)) {
2290 do_data_add(ssl, worker, skipwhite(p+10));
2291 } else if(cmdcmp(p, "flush_zone", 10)) {
2292 do_flush_zone(ssl, worker, skipwhite(p+10));
2293 } else if(cmdcmp(p, "flush_type", 10)) {
2294 do_flush_type(ssl, worker, skipwhite(p+10));
2295 } else if(cmdcmp(p, "flush_infra", 11)) {
2296 do_flush_infra(ssl, worker, skipwhite(p+11));
2297 } else if(cmdcmp(p, "flush", 5)) {
2298 do_flush_name(ssl, worker, skipwhite(p+5));
2299 } else if(cmdcmp(p, "dump_requestlist", 16)) {
2300 do_dump_requestlist(ssl, worker);
2301 } else if(cmdcmp(p, "dump_infra", 10)) {
2302 do_dump_infra(ssl, worker);
2303 } else if(cmdcmp(p, "log_reopen", 10)) {
2304 do_log_reopen(ssl, worker);
2305 } else if(cmdcmp(p, "set_option", 10)) {
2306 do_set_option(ssl, worker, skipwhite(p+10));
2307 } else if(cmdcmp(p, "get_option", 10)) {
2308 do_get_option(ssl, worker, skipwhite(p+10));
2309 } else if(cmdcmp(p, "flush_bogus", 11)) {
2310 do_flush_bogus(ssl, worker);
2311 } else if(cmdcmp(p, "flush_negative", 14)) {
2312 do_flush_negative(ssl, worker);
2313 } else {
2314 (void)ssl_printf(ssl, "error unknown command '%s'\n", p);
2315 }
2316 }
2317
2318 void
2319 daemon_remote_exec(struct worker* worker)
2320 {
2321 /* read the cmd string */
2322 uint8_t* msg = NULL;
2323 uint32_t len = 0;
2324 if(!tube_read_msg(worker->cmd, &msg, &len, 0)) {
2325 log_err("daemon_remote_exec: tube_read_msg failed");
2326 return;
2327 }
2328 verbose(VERB_ALGO, "remote exec distributed: %s", (char*)msg);
2329 execute_cmd(NULL, NULL, (char*)msg, worker);
2330 free(msg);
2331 }
2332
2333 /** handle remote control request */
2334 static void
2335 handle_req(struct daemon_remote* rc, struct rc_state* s, SSL* ssl)
2336 {
2337 int r;
2338 char pre[10];
2339 char magic[7];
2340 char buf[1024];
2341 #ifdef USE_WINSOCK
2342 /* makes it possible to set the socket blocking again. */
2343 /* basically removes it from winsock_event ... */
2344 WSAEventSelect(s->c->fd, NULL, 0);
2345 #endif
2346 fd_set_block(s->c->fd);
2347
2348 /* try to read magic UBCT[version]_space_ string */
2349 ERR_clear_error();
2350 if((r=SSL_read(ssl, magic, (int)sizeof(magic)-1)) <= 0) {
2351 if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN)
2352 return;
2353 log_crypto_err("could not SSL_read");
2354 return;
2355 }
2356 magic[6] = 0;
2357 if( r != 6 || strncmp(magic, "UBCT", 4) != 0) {
2358 verbose(VERB_QUERY, "control connection has bad magic string");
2359 /* probably wrong tool connected, ignore it completely */
2360 return;
2361 }
2362
2363 /* read the command line */
2364 if(!ssl_read_line(ssl, buf, sizeof(buf))) {
2365 return;
2366 }
2367 snprintf(pre, sizeof(pre), "UBCT%d ", UNBOUND_CONTROL_VERSION);
2368 if(strcmp(magic, pre) != 0) {
2369 verbose(VERB_QUERY, "control connection had bad "
2370 "version %s, cmd: %s", magic, buf);
2371 ssl_printf(ssl, "error version mismatch\n");
2372 return;
2373 }
2374 verbose(VERB_DETAIL, "control cmd: %s", buf);
2375
2376 /* figure out what to do */
2377 execute_cmd(rc, ssl, buf, rc->worker);
2378 }
2379
2380 int remote_control_callback(struct comm_point* c, void* arg, int err,
2381 struct comm_reply* ATTR_UNUSED(rep))
2382 {
2383 struct rc_state* s = (struct rc_state*)arg;
2384 struct daemon_remote* rc = s->rc;
2385 int r;
2386 if(err != NETEVENT_NOERROR) {
2387 if(err==NETEVENT_TIMEOUT)
2388 log_err("remote control timed out");
2389 clean_point(rc, s);
2390 return 0;
2391 }
2392 /* (continue to) setup the SSL connection */
2393 ERR_clear_error();
2394 r = SSL_do_handshake(s->ssl);
2395 if(r != 1) {
2396 int r2 = SSL_get_error(s->ssl, r);
2397 if(r2 == SSL_ERROR_WANT_READ) {
2398 if(s->shake_state == rc_hs_read) {
2399 /* try again later */
2400 return 0;
2401 }
2402 s->shake_state = rc_hs_read;
2403 comm_point_listen_for_rw(c, 1, 0);
2404 return 0;
2405 } else if(r2 == SSL_ERROR_WANT_WRITE) {
2406 if(s->shake_state == rc_hs_write) {
2407 /* try again later */
2408 return 0;
2409 }
2410 s->shake_state = rc_hs_write;
2411 comm_point_listen_for_rw(c, 0, 1);
2412 return 0;
2413 } else {
2414 if(r == 0)
2415 log_err("remote control connection closed prematurely");
2416 log_addr(1, "failed connection from",
2417 &s->c->repinfo.addr, s->c->repinfo.addrlen);
2418 log_crypto_err("remote control failed ssl");
2419 clean_point(rc, s);
2420 return 0;
2421 }
2422 }
2423 s->shake_state = rc_none;
2424
2425 /* once handshake has completed, check authentication */
2426 if(SSL_get_verify_result(s->ssl) == X509_V_OK) {
2427 X509* x = SSL_get_peer_certificate(s->ssl);
2428 if(!x) {
2429 verbose(VERB_DETAIL, "remote control connection "
2430 "provided no client certificate");
2431 clean_point(rc, s);
2432 return 0;
2433 }
2434 verbose(VERB_ALGO, "remote control connection authenticated");
2435 X509_free(x);
2436 } else {
2437 verbose(VERB_DETAIL, "remote control connection failed to "
2438 "authenticate with client certificate");
2439 clean_point(rc, s);
2440 return 0;
2441 }
2442
2443 /* if OK start to actually handle the request */
2444 handle_req(rc, s, s->ssl);
2445
2446 verbose(VERB_ALGO, "remote control operation completed");
2447 clean_point(rc, s);
2448 return 0;
2449 }