]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/unbound/daemon/remote.c
MFV r359442: bmake: import -fno-common fix build back from upstream
[FreeBSD/FreeBSD.git] / contrib / 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 #ifdef HAVE_OPENSSL_DH_H
50 #include <openssl/dh.h>
51 #endif
52 #ifdef HAVE_OPENSSL_BN_H
53 #include <openssl/bn.h>
54 #endif
55
56 #include <ctype.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"
62 #include "util/log.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"
89
90 #ifdef HAVE_SYS_TYPES_H
91 #  include <sys/types.h>
92 #endif
93 #ifdef HAVE_SYS_STAT_H
94 #include <sys/stat.h>
95 #endif
96 #ifdef HAVE_NETDB_H
97 #include <netdb.h>
98 #endif
99
100 /* just for portability */
101 #ifdef SQ
102 #undef SQ
103 #endif
104
105 /** what to put on statistics lines between var and value, ": " or "=" */
106 #define SQ "="
107 /** if true, inhibits a lot of =0 lines from the stats output */
108 static const int inhibit_zero = 1;
109
110 /** subtract timers and the values do not overflow or become negative */
111 static void
112 timeval_subtract(struct timeval* d, const struct timeval* end, 
113         const struct timeval* start)
114 {
115 #ifndef S_SPLINT_S
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) {
119                 end_usec += 1000000;
120                 d->tv_sec--;
121         }
122         d->tv_usec = end_usec - start->tv_usec;
123 #endif
124 }
125
126 /** divide sum of timers to get average */
127 static void
128 timeval_divide(struct timeval* avg, const struct timeval* sum, long long d)
129 {
130 #ifndef S_SPLINT_S
131         size_t leftover;
132         if(d == 0) {
133                 avg->tv_sec = 0;
134                 avg->tv_usec = 0;
135                 return;
136         }
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;
142 #endif
143 }
144
145 static int
146 remote_setup_ctx(struct daemon_remote* rc, struct config_file* cfg)
147 {
148         char* s_cert;
149         char* s_key;
150         rc->ctx = SSL_CTX_new(SSLv23_server_method());
151         if(!rc->ctx) {
152                 log_crypto_err("could not SSL_CTX_new");
153                 return 0;
154         }
155         if(!listen_sslctx_setup(rc->ctx)) {
156                 return 0;
157         }
158
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");
163                 goto setup_error;
164         }
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");
169                 goto setup_error;
170         }
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");
174                 goto setup_error;
175         }
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");
179                 goto setup_error;
180         }
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");
184         setup_error:
185                 free(s_cert);
186                 free(s_key);
187                 return 0;
188         }
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);
191         free(s_cert);
192         free(s_key);
193         return 1;
194 }
195
196 struct daemon_remote*
197 daemon_remote_create(struct config_file* cfg)
198 {
199         struct daemon_remote* rc = (struct daemon_remote*)calloc(1, 
200                 sizeof(*rc));
201         if(!rc) {
202                 log_err("out of memory in daemon_remote_create");
203                 return NULL;
204         }
205         rc->max_active = 10;
206
207         if(!cfg->remote_control_enable) {
208                 rc->ctx = NULL;
209                 return rc;
210         }
211         if(options_remote_is_address(cfg) && cfg->control_use_cert) {
212                 if(!remote_setup_ctx(rc, cfg)) {
213                         daemon_remote_delete(rc);
214                         return NULL;
215                 }
216                 rc->use_cert = 1;
217         } else {
218                 struct config_strlist* p;
219                 rc->ctx = NULL;
220                 rc->use_cert = 0;
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);
225                 }
226         }
227         return rc;
228 }
229
230 void daemon_remote_clear(struct daemon_remote* rc)
231 {
232         struct rc_state* p, *np;
233         if(!rc) return;
234         /* but do not close the ports */
235         listen_list_delete(rc->accept_list);
236         rc->accept_list = NULL;
237         /* do close these sockets */
238         p = rc->busy_list;
239         while(p) {
240                 np = p->next;
241                 if(p->ssl)
242                         SSL_free(p->ssl);
243                 comm_point_delete(p->c);
244                 free(p);
245                 p = np;
246         }
247         rc->busy_list = NULL;
248         rc->active = 0;
249         rc->worker = NULL;
250 }
251
252 void daemon_remote_delete(struct daemon_remote* rc)
253 {
254         if(!rc) return;
255         daemon_remote_clear(rc);
256         if(rc->ctx) {
257                 SSL_CTX_free(rc->ctx);
258         }
259         free(rc);
260 }
261
262 /**
263  * Add and open a new control port
264  * @param ip: ip str
265  * @param nr: port nr
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.
270  */
271 static int
272 add_open(const char* ip, int nr, struct listen_port** list, int noproto_is_err,
273         struct config_file* cfg)
274 {
275         struct addrinfo hints;
276         struct addrinfo* res;
277         struct listen_port* n;
278         int noproto = 0;
279         int fd, r;
280         char port[15];
281         snprintf(port, sizeof(port), "%d", nr);
282         port[sizeof(port)-1]=0;
283         memset(&hints, 0, sizeof(hints));
284         log_assert(ip);
285
286         if(ip[0] == '/') {
287                 /* This looks like a local socket */
288                 fd = create_local_accept_sock(ip, &noproto, cfg->use_systemd);
289                 /*
290                  * Change socket ownership and permissions so users other
291                  * than root can access it provided they are in the same
292                  * group as the user we run as.
293                  */
294                 if(fd != -1) {
295 #ifdef HAVE_CHOWN
296                         if (cfg->username && cfg->username[0] &&
297                                 cfg_uid != (uid_t)-1) {
298                                 if(chown(ip, cfg_uid, cfg_gid) == -1)
299                                         verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
300                                           (unsigned)cfg_uid, (unsigned)cfg_gid,
301                                           ip, strerror(errno));
302                         }
303                         chmod(ip, (mode_t)(S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP));
304 #else
305                         (void)cfg;
306 #endif
307                 }
308         } else {
309                 hints.ai_socktype = SOCK_STREAM;
310                 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
311                 if((r = getaddrinfo(ip, port, &hints, &res)) != 0 || !res) {
312 #ifdef USE_WINSOCK
313                         if(!noproto_is_err && r == EAI_NONAME) {
314                                 /* tried to lookup the address as name */
315                                 return 1; /* return success, but do nothing */
316                         }
317 #endif /* USE_WINSOCK */
318                         log_err("control interface %s:%s getaddrinfo: %s %s",
319                                 ip?ip:"default", port, gai_strerror(r),
320 #ifdef EAI_SYSTEM
321                                 r==EAI_SYSTEM?(char*)strerror(errno):""
322 #else
323                                 ""
324 #endif
325                         );
326                         return 0;
327                 }
328
329                 /* open fd */
330                 fd = create_tcp_accept_sock(res, 1, &noproto, 0,
331                         cfg->ip_transparent, 0, cfg->ip_freebind, cfg->use_systemd);
332                 freeaddrinfo(res);
333         }
334
335         if(fd == -1 && noproto) {
336                 if(!noproto_is_err)
337                         return 1; /* return success, but do nothing */
338                 log_err("cannot open control interface %s %d : "
339                         "protocol not supported", ip, nr);
340                 return 0;
341         }
342         if(fd == -1) {
343                 log_err("cannot open control interface %s %d", ip, nr);
344                 return 0;
345         }
346
347         /* alloc */
348         n = (struct listen_port*)calloc(1, sizeof(*n));
349         if(!n) {
350 #ifndef USE_WINSOCK
351                 close(fd);
352 #else
353                 closesocket(fd);
354 #endif
355                 log_err("out of memory");
356                 return 0;
357         }
358         n->next = *list;
359         *list = n;
360         n->fd = fd;
361         return 1;
362 }
363
364 struct listen_port* daemon_remote_open_ports(struct config_file* cfg)
365 {
366         struct listen_port* l = NULL;
367         log_assert(cfg->remote_control_enable && cfg->control_port);
368         if(cfg->control_ifs.first) {
369                 struct config_strlist* p;
370                 for(p = cfg->control_ifs.first; p; p = p->next) {
371                         if(!add_open(p->str, cfg->control_port, &l, 1, cfg)) {
372                                 listening_ports_free(l);
373                                 return NULL;
374                         }
375                 }
376         } else {
377                 /* defaults */
378                 if(cfg->do_ip6 &&
379                         !add_open("::1", cfg->control_port, &l, 0, cfg)) {
380                         listening_ports_free(l);
381                         return NULL;
382                 }
383                 if(cfg->do_ip4 &&
384                         !add_open("127.0.0.1", cfg->control_port, &l, 1, cfg)) {
385                         listening_ports_free(l);
386                         return NULL;
387                 }
388         }
389         return l;
390 }
391
392 /** open accept commpoint */
393 static int
394 accept_open(struct daemon_remote* rc, int fd)
395 {
396         struct listen_list* n = (struct listen_list*)malloc(sizeof(*n));
397         if(!n) {
398                 log_err("out of memory");
399                 return 0;
400         }
401         n->next = rc->accept_list;
402         rc->accept_list = n;
403         /* open commpt */
404         n->com = comm_point_create_raw(rc->worker->base, fd, 0, 
405                 &remote_accept_callback, rc);
406         if(!n->com)
407                 return 0;
408         /* keep this port open, its fd is kept in the rc portlist */
409         n->com->do_not_close = 1;
410         return 1;
411 }
412
413 int daemon_remote_open_accept(struct daemon_remote* rc, 
414         struct listen_port* ports, struct worker* worker)
415 {
416         struct listen_port* p;
417         rc->worker = worker;
418         for(p = ports; p; p = p->next) {
419                 if(!accept_open(rc, p->fd)) {
420                         log_err("could not create accept comm point");
421                         return 0;
422                 }
423         }
424         return 1;
425 }
426
427 void daemon_remote_stop_accept(struct daemon_remote* rc)
428 {
429         struct listen_list* p;
430         for(p=rc->accept_list; p; p=p->next) {
431                 comm_point_stop_listening(p->com);      
432         }
433 }
434
435 void daemon_remote_start_accept(struct daemon_remote* rc)
436 {
437         struct listen_list* p;
438         for(p=rc->accept_list; p; p=p->next) {
439                 comm_point_start_listening(p->com, -1, -1);     
440         }
441 }
442
443 int remote_accept_callback(struct comm_point* c, void* arg, int err, 
444         struct comm_reply* ATTR_UNUSED(rep))
445 {
446         struct daemon_remote* rc = (struct daemon_remote*)arg;
447         struct sockaddr_storage addr;
448         socklen_t addrlen;
449         int newfd;
450         struct rc_state* n;
451         if(err != NETEVENT_NOERROR) {
452                 log_err("error %d on remote_accept_callback", err);
453                 return 0;
454         }
455         /* perform the accept */
456         newfd = comm_point_perform_accept(c, &addr, &addrlen);
457         if(newfd == -1)
458                 return 0;
459         /* create new commpoint unless we are servicing already */
460         if(rc->active >= rc->max_active) {
461                 log_warn("drop incoming remote control: too many connections");
462         close_exit:
463 #ifndef USE_WINSOCK
464                 close(newfd);
465 #else
466                 closesocket(newfd);
467 #endif
468                 return 0;
469         }
470
471         /* setup commpoint to service the remote control command */
472         n = (struct rc_state*)calloc(1, sizeof(*n));
473         if(!n) {
474                 log_err("out of memory");
475                 goto close_exit;
476         }
477         n->fd = newfd;
478         /* start in reading state */
479         n->c = comm_point_create_raw(rc->worker->base, newfd, 0, 
480                 &remote_control_callback, n);
481         if(!n->c) {
482                 log_err("out of memory");
483                 free(n);
484                 goto close_exit;
485         }
486         log_addr(VERB_QUERY, "new control connection from", &addr, addrlen);
487         n->c->do_not_close = 0;
488         comm_point_stop_listening(n->c);
489         comm_point_start_listening(n->c, -1, REMOTE_CONTROL_TCP_TIMEOUT);
490         memcpy(&n->c->repinfo.addr, &addr, addrlen);
491         n->c->repinfo.addrlen = addrlen;
492         if(rc->use_cert) {
493                 n->shake_state = rc_hs_read;
494                 n->ssl = SSL_new(rc->ctx);
495                 if(!n->ssl) {
496                         log_crypto_err("could not SSL_new");
497                         comm_point_delete(n->c);
498                         free(n);
499                         goto close_exit;
500                 }
501                 SSL_set_accept_state(n->ssl);
502                 (void)SSL_set_mode(n->ssl, (long)SSL_MODE_AUTO_RETRY);
503                 if(!SSL_set_fd(n->ssl, newfd)) {
504                         log_crypto_err("could not SSL_set_fd");
505                         SSL_free(n->ssl);
506                         comm_point_delete(n->c);
507                         free(n);
508                         goto close_exit;
509                 }
510         } else {
511                 n->ssl = NULL;
512         }
513
514         n->rc = rc;
515         n->next = rc->busy_list;
516         rc->busy_list = n;
517         rc->active ++;
518
519         /* perform the first nonblocking read already, for windows, 
520          * so it can return wouldblock. could be faster too. */
521         (void)remote_control_callback(n->c, n, NETEVENT_NOERROR, NULL);
522         return 0;
523 }
524
525 /** delete from list */
526 static void
527 state_list_remove_elem(struct rc_state** list, struct comm_point* c)
528 {
529         while(*list) {
530                 if( (*list)->c == c) {
531                         *list = (*list)->next;
532                         return;
533                 }
534                 list = &(*list)->next;
535         }
536 }
537
538 /** decrease active count and remove commpoint from busy list */
539 static void
540 clean_point(struct daemon_remote* rc, struct rc_state* s)
541 {
542         state_list_remove_elem(&rc->busy_list, s->c);
543         rc->active --;
544         if(s->ssl) {
545                 SSL_shutdown(s->ssl);
546                 SSL_free(s->ssl);
547         }
548         comm_point_delete(s->c);
549         free(s);
550 }
551
552 int
553 ssl_print_text(RES* res, const char* text)
554 {
555         int r;
556         if(!res) 
557                 return 0;
558         if(res->ssl) {
559                 ERR_clear_error();
560                 if((r=SSL_write(res->ssl, text, (int)strlen(text))) <= 0) {
561                         if(SSL_get_error(res->ssl, r) == SSL_ERROR_ZERO_RETURN) {
562                                 verbose(VERB_QUERY, "warning, in SSL_write, peer "
563                                         "closed connection");
564                                 return 0;
565                         }
566                         log_crypto_err("could not SSL_write");
567                         return 0;
568                 }
569         } else {
570                 size_t at = 0;
571                 while(at < strlen(text)) {
572                         ssize_t r = send(res->fd, text+at, strlen(text)-at, 0);
573                         if(r == -1) {
574                                 if(errno == EAGAIN || errno == EINTR)
575                                         continue;
576 #ifndef USE_WINSOCK
577                                 log_err("could not send: %s", strerror(errno));
578 #else
579                                 log_err("could not send: %s", wsa_strerror(WSAGetLastError()));
580 #endif
581                                 return 0;
582                         }
583                         at += r;
584                 }
585         }
586         return 1;
587 }
588
589 /** print text over the ssl connection */
590 static int
591 ssl_print_vmsg(RES* ssl, const char* format, va_list args)
592 {
593         char msg[1024];
594         vsnprintf(msg, sizeof(msg), format, args);
595         return ssl_print_text(ssl, msg);
596 }
597
598 /** printf style printing to the ssl connection */
599 int ssl_printf(RES* ssl, const char* format, ...)
600 {
601         va_list args;
602         int ret;
603         va_start(args, format);
604         ret = ssl_print_vmsg(ssl, format, args);
605         va_end(args);
606         return ret;
607 }
608
609 int
610 ssl_read_line(RES* res, char* buf, size_t max)
611 {
612         int r;
613         size_t len = 0;
614         if(!res)
615                 return 0;
616         while(len < max) {
617                 if(res->ssl) {
618                         ERR_clear_error();
619                         if((r=SSL_read(res->ssl, buf+len, 1)) <= 0) {
620                                 if(SSL_get_error(res->ssl, r) == SSL_ERROR_ZERO_RETURN) {
621                                         buf[len] = 0;
622                                         return 1;
623                                 }
624                                 log_crypto_err("could not SSL_read");
625                                 return 0;
626                         }
627                 } else {
628                         while(1) {
629                                 ssize_t rr = recv(res->fd, buf+len, 1, 0);
630                                 if(rr <= 0) {
631                                         if(rr == 0) {
632                                                 buf[len] = 0;
633                                                 return 1;
634                                         }
635                                         if(errno == EINTR || errno == EAGAIN)
636                                                 continue;
637 #ifndef USE_WINSOCK
638                                         log_err("could not recv: %s", strerror(errno));
639 #else
640                                         log_err("could not recv: %s", wsa_strerror(WSAGetLastError()));
641 #endif
642                                         return 0;
643                                 }
644                                 break;
645                         }
646                 }
647                 if(buf[len] == '\n') {
648                         /* return string without \n */
649                         buf[len] = 0;
650                         return 1;
651                 }
652                 len++;
653         }
654         buf[max-1] = 0;
655         log_err("control line too long (%d): %s", (int)max, buf);
656         return 0;
657 }
658
659 /** skip whitespace, return new pointer into string */
660 static char*
661 skipwhite(char* str)
662 {
663         /* EOS \0 is not a space */
664         while( isspace((unsigned char)*str) ) 
665                 str++;
666         return str;
667 }
668
669 /** send the OK to the control client */
670 static void send_ok(RES* ssl)
671 {
672         (void)ssl_printf(ssl, "ok\n");
673 }
674
675 /** do the stop command */
676 static void
677 do_stop(RES* ssl, struct worker* worker)
678 {
679         worker->need_to_exit = 1;
680         comm_base_exit(worker->base);
681         send_ok(ssl);
682 }
683
684 /** do the reload command */
685 static void
686 do_reload(RES* ssl, struct worker* worker)
687 {
688         worker->need_to_exit = 0;
689         comm_base_exit(worker->base);
690         send_ok(ssl);
691 }
692
693 /** do the verbosity command */
694 static void
695 do_verbosity(RES* ssl, char* str)
696 {
697         int val = atoi(str);
698         if(val == 0 && strcmp(str, "0") != 0) {
699                 ssl_printf(ssl, "error in verbosity number syntax: %s\n", str);
700                 return;
701         }
702         verbosity = val;
703         send_ok(ssl);
704 }
705
706 /** print stats from statinfo */
707 static int
708 print_stats(RES* ssl, const char* nm, struct ub_stats_info* s)
709 {
710         struct timeval sumwait, avg;
711         if(!ssl_printf(ssl, "%s.num.queries"SQ"%lu\n", nm, 
712                 (unsigned long)s->svr.num_queries)) return 0;
713         if(!ssl_printf(ssl, "%s.num.queries_ip_ratelimited"SQ"%lu\n", nm,
714                 (unsigned long)s->svr.num_queries_ip_ratelimited)) return 0;
715         if(!ssl_printf(ssl, "%s.num.cachehits"SQ"%lu\n", nm, 
716                 (unsigned long)(s->svr.num_queries 
717                         - s->svr.num_queries_missed_cache))) return 0;
718         if(!ssl_printf(ssl, "%s.num.cachemiss"SQ"%lu\n", nm, 
719                 (unsigned long)s->svr.num_queries_missed_cache)) return 0;
720         if(!ssl_printf(ssl, "%s.num.prefetch"SQ"%lu\n", nm, 
721                 (unsigned long)s->svr.num_queries_prefetch)) return 0;
722         if(!ssl_printf(ssl, "%s.num.zero_ttl"SQ"%lu\n", nm,
723                 (unsigned long)s->svr.zero_ttl_responses)) return 0;
724         if(!ssl_printf(ssl, "%s.num.recursivereplies"SQ"%lu\n", nm, 
725                 (unsigned long)s->mesh_replies_sent)) return 0;
726 #ifdef USE_DNSCRYPT
727         if(!ssl_printf(ssl, "%s.num.dnscrypt.crypted"SQ"%lu\n", nm,
728                 (unsigned long)s->svr.num_query_dnscrypt_crypted)) return 0;
729         if(!ssl_printf(ssl, "%s.num.dnscrypt.cert"SQ"%lu\n", nm,
730                 (unsigned long)s->svr.num_query_dnscrypt_cert)) return 0;
731         if(!ssl_printf(ssl, "%s.num.dnscrypt.cleartext"SQ"%lu\n", nm,
732                 (unsigned long)s->svr.num_query_dnscrypt_cleartext)) return 0;
733         if(!ssl_printf(ssl, "%s.num.dnscrypt.malformed"SQ"%lu\n", nm,
734                 (unsigned long)s->svr.num_query_dnscrypt_crypted_malformed)) return 0;
735 #endif
736         if(!ssl_printf(ssl, "%s.requestlist.avg"SQ"%g\n", nm,
737                 (s->svr.num_queries_missed_cache+s->svr.num_queries_prefetch)?
738                         (double)s->svr.sum_query_list_size/
739                         (double)(s->svr.num_queries_missed_cache+
740                         s->svr.num_queries_prefetch) : 0.0)) return 0;
741         if(!ssl_printf(ssl, "%s.requestlist.max"SQ"%lu\n", nm,
742                 (unsigned long)s->svr.max_query_list_size)) return 0;
743         if(!ssl_printf(ssl, "%s.requestlist.overwritten"SQ"%lu\n", nm,
744                 (unsigned long)s->mesh_jostled)) return 0;
745         if(!ssl_printf(ssl, "%s.requestlist.exceeded"SQ"%lu\n", nm,
746                 (unsigned long)s->mesh_dropped)) return 0;
747         if(!ssl_printf(ssl, "%s.requestlist.current.all"SQ"%lu\n", nm,
748                 (unsigned long)s->mesh_num_states)) return 0;
749         if(!ssl_printf(ssl, "%s.requestlist.current.user"SQ"%lu\n", nm,
750                 (unsigned long)s->mesh_num_reply_states)) return 0;
751 #ifndef S_SPLINT_S
752         sumwait.tv_sec = s->mesh_replies_sum_wait_sec;
753         sumwait.tv_usec = s->mesh_replies_sum_wait_usec;
754 #endif
755         timeval_divide(&avg, &sumwait, s->mesh_replies_sent);
756         if(!ssl_printf(ssl, "%s.recursion.time.avg"SQ ARG_LL "d.%6.6d\n", nm,
757                 (long long)avg.tv_sec, (int)avg.tv_usec)) return 0;
758         if(!ssl_printf(ssl, "%s.recursion.time.median"SQ"%g\n", nm, 
759                 s->mesh_time_median)) return 0;
760         if(!ssl_printf(ssl, "%s.tcpusage"SQ"%lu\n", nm,
761                 (unsigned long)s->svr.tcp_accept_usage)) return 0;
762         return 1;
763 }
764
765 /** print stats for one thread */
766 static int
767 print_thread_stats(RES* ssl, int i, struct ub_stats_info* s)
768 {
769         char nm[32];
770         snprintf(nm, sizeof(nm), "thread%d", i);
771         nm[sizeof(nm)-1]=0;
772         return print_stats(ssl, nm, s);
773 }
774
775 /** print long number */
776 static int
777 print_longnum(RES* ssl, const char* desc, size_t x)
778 {
779         if(x > 1024*1024*1024) {
780                 /* more than a Gb */
781                 size_t front = x / (size_t)1000000;
782                 size_t back = x % (size_t)1000000;
783                 return ssl_printf(ssl, "%s%u%6.6u\n", desc, 
784                         (unsigned)front, (unsigned)back);
785         } else {
786                 return ssl_printf(ssl, "%s%lu\n", desc, (unsigned long)x);
787         }
788 }
789
790 /** print mem stats */
791 static int
792 print_mem(RES* ssl, struct worker* worker, struct daemon* daemon,
793         struct ub_stats_info* s)
794 {
795         size_t msg, rrset, val, iter, respip;
796 #ifdef CLIENT_SUBNET
797         size_t subnet = 0;
798 #endif /* CLIENT_SUBNET */
799 #ifdef USE_IPSECMOD
800         size_t ipsecmod = 0;
801 #endif /* USE_IPSECMOD */
802 #ifdef USE_DNSCRYPT
803         size_t dnscrypt_shared_secret = 0;
804         size_t dnscrypt_nonce = 0;
805 #endif /* USE_DNSCRYPT */
806         msg = slabhash_get_mem(daemon->env->msg_cache);
807         rrset = slabhash_get_mem(&daemon->env->rrset_cache->table);
808         val = mod_get_mem(&worker->env, "validator");
809         iter = mod_get_mem(&worker->env, "iterator");
810         respip = mod_get_mem(&worker->env, "respip");
811 #ifdef CLIENT_SUBNET
812         subnet = mod_get_mem(&worker->env, "subnet");
813 #endif /* CLIENT_SUBNET */
814 #ifdef USE_IPSECMOD
815         ipsecmod = mod_get_mem(&worker->env, "ipsecmod");
816 #endif /* USE_IPSECMOD */
817 #ifdef USE_DNSCRYPT
818         if(daemon->dnscenv) {
819                 dnscrypt_shared_secret = slabhash_get_mem(
820                         daemon->dnscenv->shared_secrets_cache);
821                 dnscrypt_nonce = slabhash_get_mem(daemon->dnscenv->nonces_cache);
822         }
823 #endif /* USE_DNSCRYPT */
824
825         if(!print_longnum(ssl, "mem.cache.rrset"SQ, rrset))
826                 return 0;
827         if(!print_longnum(ssl, "mem.cache.message"SQ, msg))
828                 return 0;
829         if(!print_longnum(ssl, "mem.mod.iterator"SQ, iter))
830                 return 0;
831         if(!print_longnum(ssl, "mem.mod.validator"SQ, val))
832                 return 0;
833         if(!print_longnum(ssl, "mem.mod.respip"SQ, respip))
834                 return 0;
835 #ifdef CLIENT_SUBNET
836         if(!print_longnum(ssl, "mem.mod.subnet"SQ, subnet))
837                 return 0;
838 #endif /* CLIENT_SUBNET */
839 #ifdef USE_IPSECMOD
840         if(!print_longnum(ssl, "mem.mod.ipsecmod"SQ, ipsecmod))
841                 return 0;
842 #endif /* USE_IPSECMOD */
843 #ifdef USE_DNSCRYPT
844         if(!print_longnum(ssl, "mem.cache.dnscrypt_shared_secret"SQ,
845                         dnscrypt_shared_secret))
846                 return 0;
847         if(!print_longnum(ssl, "mem.cache.dnscrypt_nonce"SQ,
848                         dnscrypt_nonce))
849                 return 0;
850 #endif /* USE_DNSCRYPT */
851         if(!print_longnum(ssl, "mem.streamwait"SQ,
852                 (size_t)s->svr.mem_stream_wait))
853                 return 0;
854         return 1;
855 }
856
857 /** print uptime stats */
858 static int
859 print_uptime(RES* ssl, struct worker* worker, int reset)
860 {
861         struct timeval now = *worker->env.now_tv;
862         struct timeval up, dt;
863         timeval_subtract(&up, &now, &worker->daemon->time_boot);
864         timeval_subtract(&dt, &now, &worker->daemon->time_last_stat);
865         if(reset)
866                 worker->daemon->time_last_stat = now;
867         if(!ssl_printf(ssl, "time.now"SQ ARG_LL "d.%6.6d\n", 
868                 (long long)now.tv_sec, (unsigned)now.tv_usec)) return 0;
869         if(!ssl_printf(ssl, "time.up"SQ ARG_LL "d.%6.6d\n", 
870                 (long long)up.tv_sec, (unsigned)up.tv_usec)) return 0;
871         if(!ssl_printf(ssl, "time.elapsed"SQ ARG_LL "d.%6.6d\n", 
872                 (long long)dt.tv_sec, (unsigned)dt.tv_usec)) return 0;
873         return 1;
874 }
875
876 /** print extended histogram */
877 static int
878 print_hist(RES* ssl, struct ub_stats_info* s)
879 {
880         struct timehist* hist;
881         size_t i;
882         hist = timehist_setup();
883         if(!hist) {
884                 log_err("out of memory");
885                 return 0;
886         }
887         timehist_import(hist, s->svr.hist, NUM_BUCKETS_HIST);
888         for(i=0; i<hist->num; i++) {
889                 if(!ssl_printf(ssl, 
890                         "histogram.%6.6d.%6.6d.to.%6.6d.%6.6d=%lu\n",
891                         (int)hist->buckets[i].lower.tv_sec,
892                         (int)hist->buckets[i].lower.tv_usec,
893                         (int)hist->buckets[i].upper.tv_sec,
894                         (int)hist->buckets[i].upper.tv_usec,
895                         (unsigned long)hist->buckets[i].count)) {
896                         timehist_delete(hist);
897                         return 0;
898                 }
899         }
900         timehist_delete(hist);
901         return 1;
902 }
903
904 /** print extended stats */
905 static int
906 print_ext(RES* ssl, struct ub_stats_info* s)
907 {
908         int i;
909         char nm[16];
910         const sldns_rr_descriptor* desc;
911         const sldns_lookup_table* lt;
912         /* TYPE */
913         for(i=0; i<UB_STATS_QTYPE_NUM; i++) {
914                 if(inhibit_zero && s->svr.qtype[i] == 0)
915                         continue;
916                 desc = sldns_rr_descript((uint16_t)i);
917                 if(desc && desc->_name) {
918                         snprintf(nm, sizeof(nm), "%s", desc->_name);
919                 } else if (i == LDNS_RR_TYPE_IXFR) {
920                         snprintf(nm, sizeof(nm), "IXFR");
921                 } else if (i == LDNS_RR_TYPE_AXFR) {
922                         snprintf(nm, sizeof(nm), "AXFR");
923                 } else if (i == LDNS_RR_TYPE_MAILA) {
924                         snprintf(nm, sizeof(nm), "MAILA");
925                 } else if (i == LDNS_RR_TYPE_MAILB) {
926                         snprintf(nm, sizeof(nm), "MAILB");
927                 } else if (i == LDNS_RR_TYPE_ANY) {
928                         snprintf(nm, sizeof(nm), "ANY");
929                 } else {
930                         snprintf(nm, sizeof(nm), "TYPE%d", i);
931                 }
932                 if(!ssl_printf(ssl, "num.query.type.%s"SQ"%lu\n", 
933                         nm, (unsigned long)s->svr.qtype[i])) return 0;
934         }
935         if(!inhibit_zero || s->svr.qtype_big) {
936                 if(!ssl_printf(ssl, "num.query.type.other"SQ"%lu\n", 
937                         (unsigned long)s->svr.qtype_big)) return 0;
938         }
939         /* CLASS */
940         for(i=0; i<UB_STATS_QCLASS_NUM; i++) {
941                 if(inhibit_zero && s->svr.qclass[i] == 0)
942                         continue;
943                 lt = sldns_lookup_by_id(sldns_rr_classes, i);
944                 if(lt && lt->name) {
945                         snprintf(nm, sizeof(nm), "%s", lt->name);
946                 } else {
947                         snprintf(nm, sizeof(nm), "CLASS%d", i);
948                 }
949                 if(!ssl_printf(ssl, "num.query.class.%s"SQ"%lu\n", 
950                         nm, (unsigned long)s->svr.qclass[i])) return 0;
951         }
952         if(!inhibit_zero || s->svr.qclass_big) {
953                 if(!ssl_printf(ssl, "num.query.class.other"SQ"%lu\n", 
954                         (unsigned long)s->svr.qclass_big)) return 0;
955         }
956         /* OPCODE */
957         for(i=0; i<UB_STATS_OPCODE_NUM; i++) {
958                 if(inhibit_zero && s->svr.qopcode[i] == 0)
959                         continue;
960                 lt = sldns_lookup_by_id(sldns_opcodes, i);
961                 if(lt && lt->name) {
962                         snprintf(nm, sizeof(nm), "%s", lt->name);
963                 } else {
964                         snprintf(nm, sizeof(nm), "OPCODE%d", i);
965                 }
966                 if(!ssl_printf(ssl, "num.query.opcode.%s"SQ"%lu\n", 
967                         nm, (unsigned long)s->svr.qopcode[i])) return 0;
968         }
969         /* transport */
970         if(!ssl_printf(ssl, "num.query.tcp"SQ"%lu\n", 
971                 (unsigned long)s->svr.qtcp)) return 0;
972         if(!ssl_printf(ssl, "num.query.tcpout"SQ"%lu\n", 
973                 (unsigned long)s->svr.qtcp_outgoing)) return 0;
974         if(!ssl_printf(ssl, "num.query.tls"SQ"%lu\n", 
975                 (unsigned long)s->svr.qtls)) return 0;
976         if(!ssl_printf(ssl, "num.query.tls.resume"SQ"%lu\n", 
977                 (unsigned long)s->svr.qtls_resume)) return 0;
978         if(!ssl_printf(ssl, "num.query.ipv6"SQ"%lu\n", 
979                 (unsigned long)s->svr.qipv6)) return 0;
980         /* flags */
981         if(!ssl_printf(ssl, "num.query.flags.QR"SQ"%lu\n", 
982                 (unsigned long)s->svr.qbit_QR)) return 0;
983         if(!ssl_printf(ssl, "num.query.flags.AA"SQ"%lu\n", 
984                 (unsigned long)s->svr.qbit_AA)) return 0;
985         if(!ssl_printf(ssl, "num.query.flags.TC"SQ"%lu\n", 
986                 (unsigned long)s->svr.qbit_TC)) return 0;
987         if(!ssl_printf(ssl, "num.query.flags.RD"SQ"%lu\n", 
988                 (unsigned long)s->svr.qbit_RD)) return 0;
989         if(!ssl_printf(ssl, "num.query.flags.RA"SQ"%lu\n", 
990                 (unsigned long)s->svr.qbit_RA)) return 0;
991         if(!ssl_printf(ssl, "num.query.flags.Z"SQ"%lu\n", 
992                 (unsigned long)s->svr.qbit_Z)) return 0;
993         if(!ssl_printf(ssl, "num.query.flags.AD"SQ"%lu\n", 
994                 (unsigned long)s->svr.qbit_AD)) return 0;
995         if(!ssl_printf(ssl, "num.query.flags.CD"SQ"%lu\n", 
996                 (unsigned long)s->svr.qbit_CD)) return 0;
997         if(!ssl_printf(ssl, "num.query.edns.present"SQ"%lu\n", 
998                 (unsigned long)s->svr.qEDNS)) return 0;
999         if(!ssl_printf(ssl, "num.query.edns.DO"SQ"%lu\n", 
1000                 (unsigned long)s->svr.qEDNS_DO)) return 0;
1001
1002         /* RCODE */
1003         for(i=0; i<UB_STATS_RCODE_NUM; i++) {
1004                 /* Always include RCODEs 0-5 */
1005                 if(inhibit_zero && i > LDNS_RCODE_REFUSED && s->svr.ans_rcode[i] == 0)
1006                         continue;
1007                 lt = sldns_lookup_by_id(sldns_rcodes, i);
1008                 if(lt && lt->name) {
1009                         snprintf(nm, sizeof(nm), "%s", lt->name);
1010                 } else {
1011                         snprintf(nm, sizeof(nm), "RCODE%d", i);
1012                 }
1013                 if(!ssl_printf(ssl, "num.answer.rcode.%s"SQ"%lu\n", 
1014                         nm, (unsigned long)s->svr.ans_rcode[i])) return 0;
1015         }
1016         if(!inhibit_zero || s->svr.ans_rcode_nodata) {
1017                 if(!ssl_printf(ssl, "num.answer.rcode.nodata"SQ"%lu\n", 
1018                         (unsigned long)s->svr.ans_rcode_nodata)) return 0;
1019         }
1020         /* iteration */
1021         if(!ssl_printf(ssl, "num.query.ratelimited"SQ"%lu\n", 
1022                 (unsigned long)s->svr.queries_ratelimited)) return 0;
1023         /* validation */
1024         if(!ssl_printf(ssl, "num.answer.secure"SQ"%lu\n", 
1025                 (unsigned long)s->svr.ans_secure)) return 0;
1026         if(!ssl_printf(ssl, "num.answer.bogus"SQ"%lu\n", 
1027                 (unsigned long)s->svr.ans_bogus)) return 0;
1028         if(!ssl_printf(ssl, "num.rrset.bogus"SQ"%lu\n", 
1029                 (unsigned long)s->svr.rrset_bogus)) return 0;
1030         if(!ssl_printf(ssl, "num.query.aggressive.NOERROR"SQ"%lu\n", 
1031                 (unsigned long)s->svr.num_neg_cache_noerror)) return 0;
1032         if(!ssl_printf(ssl, "num.query.aggressive.NXDOMAIN"SQ"%lu\n", 
1033                 (unsigned long)s->svr.num_neg_cache_nxdomain)) return 0;
1034         /* threat detection */
1035         if(!ssl_printf(ssl, "unwanted.queries"SQ"%lu\n", 
1036                 (unsigned long)s->svr.unwanted_queries)) return 0;
1037         if(!ssl_printf(ssl, "unwanted.replies"SQ"%lu\n", 
1038                 (unsigned long)s->svr.unwanted_replies)) return 0;
1039         /* cache counts */
1040         if(!ssl_printf(ssl, "msg.cache.count"SQ"%u\n",
1041                 (unsigned)s->svr.msg_cache_count)) return 0;
1042         if(!ssl_printf(ssl, "rrset.cache.count"SQ"%u\n",
1043                 (unsigned)s->svr.rrset_cache_count)) return 0;
1044         if(!ssl_printf(ssl, "infra.cache.count"SQ"%u\n",
1045                 (unsigned)s->svr.infra_cache_count)) return 0;
1046         if(!ssl_printf(ssl, "key.cache.count"SQ"%u\n",
1047                 (unsigned)s->svr.key_cache_count)) return 0;
1048 #ifdef USE_DNSCRYPT
1049         if(!ssl_printf(ssl, "dnscrypt_shared_secret.cache.count"SQ"%u\n",
1050                 (unsigned)s->svr.shared_secret_cache_count)) return 0;
1051         if(!ssl_printf(ssl, "dnscrypt_nonce.cache.count"SQ"%u\n",
1052                 (unsigned)s->svr.nonce_cache_count)) return 0;
1053         if(!ssl_printf(ssl, "num.query.dnscrypt.shared_secret.cachemiss"SQ"%lu\n",
1054                 (unsigned long)s->svr.num_query_dnscrypt_secret_missed_cache)) return 0;
1055         if(!ssl_printf(ssl, "num.query.dnscrypt.replay"SQ"%lu\n",
1056                 (unsigned long)s->svr.num_query_dnscrypt_replay)) return 0;
1057 #endif /* USE_DNSCRYPT */
1058         if(!ssl_printf(ssl, "num.query.authzone.up"SQ"%lu\n",
1059                 (unsigned long)s->svr.num_query_authzone_up)) return 0;
1060         if(!ssl_printf(ssl, "num.query.authzone.down"SQ"%lu\n",
1061                 (unsigned long)s->svr.num_query_authzone_down)) return 0;
1062 #ifdef CLIENT_SUBNET
1063         if(!ssl_printf(ssl, "num.query.subnet"SQ"%lu\n",
1064                 (unsigned long)s->svr.num_query_subnet)) return 0;
1065         if(!ssl_printf(ssl, "num.query.subnet_cache"SQ"%lu\n",
1066                 (unsigned long)s->svr.num_query_subnet_cache)) return 0;
1067 #endif /* CLIENT_SUBNET */
1068         return 1;
1069 }
1070
1071 /** do the stats command */
1072 static void
1073 do_stats(RES* ssl, struct worker* worker, int reset)
1074 {
1075         struct daemon* daemon = worker->daemon;
1076         struct ub_stats_info total;
1077         struct ub_stats_info s;
1078         int i;
1079         memset(&total, 0, sizeof(total));
1080         log_assert(daemon->num > 0);
1081         /* gather all thread statistics in one place */
1082         for(i=0; i<daemon->num; i++) {
1083                 server_stats_obtain(worker, daemon->workers[i], &s, reset);
1084                 if(!print_thread_stats(ssl, i, &s))
1085                         return;
1086                 if(i == 0)
1087                         total = s;
1088                 else    server_stats_add(&total, &s);
1089         }
1090         /* print the thread statistics */
1091         total.mesh_time_median /= (double)daemon->num;
1092         if(!print_stats(ssl, "total", &total)) 
1093                 return;
1094         if(!print_uptime(ssl, worker, reset))
1095                 return;
1096         if(daemon->cfg->stat_extended) {
1097                 if(!print_mem(ssl, worker, daemon, &total))
1098                         return;
1099                 if(!print_hist(ssl, &total))
1100                         return;
1101                 if(!print_ext(ssl, &total))
1102                         return;
1103         }
1104 }
1105
1106 /** parse commandline argument domain name */
1107 static int
1108 parse_arg_name(RES* ssl, char* str, uint8_t** res, size_t* len, int* labs)
1109 {
1110         uint8_t nm[LDNS_MAX_DOMAINLEN+1];
1111         size_t nmlen = sizeof(nm);
1112         int status;
1113         *res = NULL;
1114         *len = 0;
1115         *labs = 0;
1116         status = sldns_str2wire_dname_buf(str, nm, &nmlen);
1117         if(status != 0) {
1118                 ssl_printf(ssl, "error cannot parse name %s at %d: %s\n", str,
1119                         LDNS_WIREPARSE_OFFSET(status),
1120                         sldns_get_errorstr_parse(status));
1121                 return 0;
1122         }
1123         *res = memdup(nm, nmlen);
1124         if(!*res) {
1125                 ssl_printf(ssl, "error out of memory\n");
1126                 return 0;
1127         }
1128         *labs = dname_count_size_labels(*res, len);
1129         return 1;
1130 }
1131
1132 /** find second argument, modifies string */
1133 static int
1134 find_arg2(RES* ssl, char* arg, char** arg2)
1135 {
1136         char* as = strchr(arg, ' ');
1137         char* at = strchr(arg, '\t');
1138         if(as && at) {
1139                 if(at < as)
1140                         as = at;
1141                 as[0]=0;
1142                 *arg2 = skipwhite(as+1);
1143         } else if(as) {
1144                 as[0]=0;
1145                 *arg2 = skipwhite(as+1);
1146         } else if(at) {
1147                 at[0]=0;
1148                 *arg2 = skipwhite(at+1);
1149         } else {
1150                 ssl_printf(ssl, "error could not find next argument "
1151                         "after %s\n", arg);
1152                 return 0;
1153         }
1154         return 1;
1155 }
1156
1157 /** Add a new zone */
1158 static int
1159 perform_zone_add(RES* ssl, struct local_zones* zones, char* arg)
1160 {
1161         uint8_t* nm;
1162         int nmlabs;
1163         size_t nmlen;
1164         char* arg2;
1165         enum localzone_type t;
1166         struct local_zone* z;
1167         if(!find_arg2(ssl, arg, &arg2))
1168                 return 0;
1169         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1170                 return 0;
1171         if(!local_zone_str2type(arg2, &t)) {
1172                 ssl_printf(ssl, "error not a zone type. %s\n", arg2);
1173                 free(nm);
1174                 return 0;
1175         }
1176         lock_rw_wrlock(&zones->lock);
1177         if((z=local_zones_find(zones, nm, nmlen, 
1178                 nmlabs, LDNS_RR_CLASS_IN))) {
1179                 /* already present in tree */
1180                 lock_rw_wrlock(&z->lock);
1181                 z->type = t; /* update type anyway */
1182                 lock_rw_unlock(&z->lock);
1183                 free(nm);
1184                 lock_rw_unlock(&zones->lock);
1185                 return 1;
1186         }
1187         if(!local_zones_add_zone(zones, nm, nmlen, 
1188                 nmlabs, LDNS_RR_CLASS_IN, t)) {
1189                 lock_rw_unlock(&zones->lock);
1190                 ssl_printf(ssl, "error out of memory\n");
1191                 return 0;
1192         }
1193         lock_rw_unlock(&zones->lock);
1194         return 1;
1195 }
1196
1197 /** Do the local_zone command */
1198 static void
1199 do_zone_add(RES* ssl, struct local_zones* zones, char* arg)
1200 {
1201         if(!perform_zone_add(ssl, zones, arg))
1202                 return;
1203         send_ok(ssl);
1204 }
1205
1206 /** Do the local_zones command */
1207 static void
1208 do_zones_add(RES* ssl, struct local_zones* zones)
1209 {
1210         char buf[2048];
1211         int num = 0;
1212         while(ssl_read_line(ssl, buf, sizeof(buf))) {
1213                 if(buf[0] == 0x04 && buf[1] == 0)
1214                         break; /* end of transmission */
1215                 if(!perform_zone_add(ssl, zones, buf)) {
1216                         if(!ssl_printf(ssl, "error for input line: %s\n", buf))
1217                                 return;
1218                 }
1219                 else
1220                         num++;
1221         }
1222         (void)ssl_printf(ssl, "added %d zones\n", num);
1223 }
1224
1225 /** Remove a zone */
1226 static int
1227 perform_zone_remove(RES* ssl, struct local_zones* zones, char* arg)
1228 {
1229         uint8_t* nm;
1230         int nmlabs;
1231         size_t nmlen;
1232         struct local_zone* z;
1233         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1234                 return 0;
1235         lock_rw_wrlock(&zones->lock);
1236         if((z=local_zones_find(zones, nm, nmlen, 
1237                 nmlabs, LDNS_RR_CLASS_IN))) {
1238                 /* present in tree */
1239                 local_zones_del_zone(zones, z);
1240         }
1241         lock_rw_unlock(&zones->lock);
1242         free(nm);
1243         return 1;
1244 }
1245
1246 /** Do the local_zone_remove command */
1247 static void
1248 do_zone_remove(RES* ssl, struct local_zones* zones, char* arg)
1249 {
1250         if(!perform_zone_remove(ssl, zones, arg))
1251                 return;
1252         send_ok(ssl);
1253 }
1254
1255 /** Do the local_zones_remove command */
1256 static void
1257 do_zones_remove(RES* ssl, struct local_zones* zones)
1258 {
1259         char buf[2048];
1260         int num = 0;
1261         while(ssl_read_line(ssl, buf, sizeof(buf))) {
1262                 if(buf[0] == 0x04 && buf[1] == 0)
1263                         break; /* end of transmission */
1264                 if(!perform_zone_remove(ssl, zones, buf)) {
1265                         if(!ssl_printf(ssl, "error for input line: %s\n", buf))
1266                                 return;
1267                 }
1268                 else
1269                         num++;
1270         }
1271         (void)ssl_printf(ssl, "removed %d zones\n", num);
1272 }
1273
1274 /** Add new RR data */
1275 static int
1276 perform_data_add(RES* ssl, struct local_zones* zones, char* arg)
1277 {
1278         if(!local_zones_add_RR(zones, arg)) {
1279                 ssl_printf(ssl,"error in syntax or out of memory, %s\n", arg);
1280                 return 0;
1281         }
1282         return 1;
1283 }
1284
1285 /** Do the local_data command */
1286 static void
1287 do_data_add(RES* ssl, struct local_zones* zones, char* arg)
1288 {
1289         if(!perform_data_add(ssl, zones, arg))
1290                 return;
1291         send_ok(ssl);
1292 }
1293
1294 /** Do the local_datas command */
1295 static void
1296 do_datas_add(RES* ssl, struct local_zones* zones)
1297 {
1298         char buf[2048];
1299         int num = 0;
1300         while(ssl_read_line(ssl, buf, sizeof(buf))) {
1301                 if(buf[0] == 0x04 && buf[1] == 0)
1302                         break; /* end of transmission */
1303                 if(!perform_data_add(ssl, zones, buf)) {
1304                         if(!ssl_printf(ssl, "error for input line: %s\n", buf))
1305                                 return;
1306                 }
1307                 else
1308                         num++;
1309         }
1310         (void)ssl_printf(ssl, "added %d datas\n", num);
1311 }
1312
1313 /** Remove RR data */
1314 static int
1315 perform_data_remove(RES* ssl, struct local_zones* zones, char* arg)
1316 {
1317         uint8_t* nm;
1318         int nmlabs;
1319         size_t nmlen;
1320         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1321                 return 0;
1322         local_zones_del_data(zones, nm,
1323                 nmlen, nmlabs, LDNS_RR_CLASS_IN);
1324         free(nm);
1325         return 1;
1326 }
1327
1328 /** Do the local_data_remove command */
1329 static void
1330 do_data_remove(RES* ssl, struct local_zones* zones, char* arg)
1331 {
1332         if(!perform_data_remove(ssl, zones, arg))
1333                 return;
1334         send_ok(ssl);
1335 }
1336
1337 /** Do the local_datas_remove command */
1338 static void
1339 do_datas_remove(RES* ssl, struct local_zones* zones)
1340 {
1341         char buf[2048];
1342         int num = 0;
1343         while(ssl_read_line(ssl, buf, sizeof(buf))) {
1344                 if(buf[0] == 0x04 && buf[1] == 0)
1345                         break; /* end of transmission */
1346                 if(!perform_data_remove(ssl, zones, buf)) {
1347                         if(!ssl_printf(ssl, "error for input line: %s\n", buf))
1348                                 return;
1349                 }
1350                 else
1351                         num++;
1352         }
1353         (void)ssl_printf(ssl, "removed %d datas\n", num);
1354 }
1355
1356 /** Add a new zone to view */
1357 static void
1358 do_view_zone_add(RES* ssl, struct worker* worker, char* arg)
1359 {
1360         char* arg2;
1361         struct view* v;
1362         if(!find_arg2(ssl, arg, &arg2))
1363                 return;
1364         v = views_find_view(worker->daemon->views,
1365                 arg, 1 /* get write lock*/);
1366         if(!v) {
1367                 ssl_printf(ssl,"no view with name: %s\n", arg);
1368                 return;
1369         }
1370         if(!v->local_zones) {
1371                 if(!(v->local_zones = local_zones_create())){
1372                         lock_rw_unlock(&v->lock);
1373                         ssl_printf(ssl,"error out of memory\n");
1374                         return;
1375                 }
1376                 if(!v->isfirst) {
1377                         /* Global local-zone is not used for this view,
1378                          * therefore add defaults to this view-specic
1379                          * local-zone. */
1380                         struct config_file lz_cfg;
1381                         memset(&lz_cfg, 0, sizeof(lz_cfg));
1382                         local_zone_enter_defaults(v->local_zones, &lz_cfg);
1383                 }
1384         }
1385         do_zone_add(ssl, v->local_zones, arg2);
1386         lock_rw_unlock(&v->lock);
1387 }
1388
1389 /** Remove a zone from view */
1390 static void
1391 do_view_zone_remove(RES* ssl, struct worker* worker, char* arg)
1392 {
1393         char* arg2;
1394         struct view* v;
1395         if(!find_arg2(ssl, arg, &arg2))
1396                 return;
1397         v = views_find_view(worker->daemon->views,
1398                 arg, 1 /* get write lock*/);
1399         if(!v) {
1400                 ssl_printf(ssl,"no view with name: %s\n", arg);
1401                 return;
1402         }
1403         if(!v->local_zones) {
1404                 lock_rw_unlock(&v->lock);
1405                 send_ok(ssl);
1406                 return;
1407         }
1408         do_zone_remove(ssl, v->local_zones, arg2);
1409         lock_rw_unlock(&v->lock);
1410 }
1411
1412 /** Add new RR data to view */
1413 static void
1414 do_view_data_add(RES* ssl, struct worker* worker, char* arg)
1415 {
1416         char* arg2;
1417         struct view* v;
1418         if(!find_arg2(ssl, arg, &arg2))
1419                 return;
1420         v = views_find_view(worker->daemon->views,
1421                 arg, 1 /* get write lock*/);
1422         if(!v) {
1423                 ssl_printf(ssl,"no view with name: %s\n", arg);
1424                 return;
1425         }
1426         if(!v->local_zones) {
1427                 if(!(v->local_zones = local_zones_create())){
1428                         lock_rw_unlock(&v->lock);
1429                         ssl_printf(ssl,"error out of memory\n");
1430                         return;
1431                 }
1432         }
1433         do_data_add(ssl, v->local_zones, arg2);
1434         lock_rw_unlock(&v->lock);
1435 }
1436
1437 /** Add new RR data from stdin to view */
1438 static void
1439 do_view_datas_add(RES* ssl, struct worker* worker, char* arg)
1440 {
1441         struct view* v;
1442         v = views_find_view(worker->daemon->views,
1443                 arg, 1 /* get write lock*/);
1444         if(!v) {
1445                 ssl_printf(ssl,"no view with name: %s\n", arg);
1446                 return;
1447         }
1448         if(!v->local_zones) {
1449                 if(!(v->local_zones = local_zones_create())){
1450                         lock_rw_unlock(&v->lock);
1451                         ssl_printf(ssl,"error out of memory\n");
1452                         return;
1453                 }
1454         }
1455         do_datas_add(ssl, v->local_zones);
1456         lock_rw_unlock(&v->lock);
1457 }
1458
1459 /** Remove RR data from view */
1460 static void
1461 do_view_data_remove(RES* ssl, struct worker* worker, char* arg)
1462 {
1463         char* arg2;
1464         struct view* v;
1465         if(!find_arg2(ssl, arg, &arg2))
1466                 return;
1467         v = views_find_view(worker->daemon->views,
1468                 arg, 1 /* get write lock*/);
1469         if(!v) {
1470                 ssl_printf(ssl,"no view with name: %s\n", arg);
1471                 return;
1472         }
1473         if(!v->local_zones) {
1474                 lock_rw_unlock(&v->lock);
1475                 send_ok(ssl);
1476                 return;
1477         }
1478         do_data_remove(ssl, v->local_zones, arg2);
1479         lock_rw_unlock(&v->lock);
1480 }
1481
1482 /** cache lookup of nameservers */
1483 static void
1484 do_lookup(RES* ssl, struct worker* worker, char* arg)
1485 {
1486         uint8_t* nm;
1487         int nmlabs;
1488         size_t nmlen;
1489         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1490                 return;
1491         (void)print_deleg_lookup(ssl, worker, nm, nmlen, nmlabs);
1492         free(nm);
1493 }
1494
1495 /** flush something from rrset and msg caches */
1496 static void
1497 do_cache_remove(struct worker* worker, uint8_t* nm, size_t nmlen,
1498         uint16_t t, uint16_t c)
1499 {
1500         hashvalue_type h;
1501         struct query_info k;
1502         rrset_cache_remove(worker->env.rrset_cache, nm, nmlen, t, c, 0);
1503         if(t == LDNS_RR_TYPE_SOA)
1504                 rrset_cache_remove(worker->env.rrset_cache, nm, nmlen, t, c,
1505                         PACKED_RRSET_SOA_NEG);
1506         k.qname = nm;
1507         k.qname_len = nmlen;
1508         k.qtype = t;
1509         k.qclass = c;
1510         k.local_alias = NULL;
1511         h = query_info_hash(&k, 0);
1512         slabhash_remove(worker->env.msg_cache, h, &k);
1513         if(t == LDNS_RR_TYPE_AAAA) {
1514                 /* for AAAA also flush dns64 bit_cd packet */
1515                 h = query_info_hash(&k, BIT_CD);
1516                 slabhash_remove(worker->env.msg_cache, h, &k);
1517         }
1518 }
1519
1520 /** flush a type */
1521 static void
1522 do_flush_type(RES* ssl, struct worker* worker, char* arg)
1523 {
1524         uint8_t* nm;
1525         int nmlabs;
1526         size_t nmlen;
1527         char* arg2;
1528         uint16_t t;
1529         if(!find_arg2(ssl, arg, &arg2))
1530                 return;
1531         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1532                 return;
1533         t = sldns_get_rr_type_by_name(arg2);
1534         do_cache_remove(worker, nm, nmlen, t, LDNS_RR_CLASS_IN);
1535         
1536         free(nm);
1537         send_ok(ssl);
1538 }
1539
1540 /** flush statistics */
1541 static void
1542 do_flush_stats(RES* ssl, struct worker* worker)
1543 {
1544         worker_stats_clear(worker);
1545         send_ok(ssl);
1546 }
1547
1548 /**
1549  * Local info for deletion functions
1550  */
1551 struct del_info {
1552         /** worker */
1553         struct worker* worker;
1554         /** name to delete */
1555         uint8_t* name;
1556         /** length */
1557         size_t len;
1558         /** labels */
1559         int labs;
1560         /** time to invalidate to */
1561         time_t expired;
1562         /** number of rrsets removed */
1563         size_t num_rrsets;
1564         /** number of msgs removed */
1565         size_t num_msgs;
1566         /** number of key entries removed */
1567         size_t num_keys;
1568         /** length of addr */
1569         socklen_t addrlen;
1570         /** socket address for host deletion */
1571         struct sockaddr_storage addr;
1572 };
1573
1574 /** callback to delete hosts in infra cache */
1575 static void
1576 infra_del_host(struct lruhash_entry* e, void* arg)
1577 {
1578         /* entry is locked */
1579         struct del_info* inf = (struct del_info*)arg;
1580         struct infra_key* k = (struct infra_key*)e->key;
1581         if(sockaddr_cmp(&inf->addr, inf->addrlen, &k->addr, k->addrlen) == 0) {
1582                 struct infra_data* d = (struct infra_data*)e->data;
1583                 d->probedelay = 0;
1584                 d->timeout_A = 0;
1585                 d->timeout_AAAA = 0;
1586                 d->timeout_other = 0;
1587                 rtt_init(&d->rtt);
1588                 if(d->ttl > inf->expired) {
1589                         d->ttl = inf->expired;
1590                         inf->num_keys++;
1591                 }
1592         }
1593 }
1594
1595 /** flush infra cache */
1596 static void
1597 do_flush_infra(RES* ssl, struct worker* worker, char* arg)
1598 {
1599         struct sockaddr_storage addr;
1600         socklen_t len;
1601         struct del_info inf;
1602         if(strcmp(arg, "all") == 0) {
1603                 slabhash_clear(worker->env.infra_cache->hosts);
1604                 send_ok(ssl);
1605                 return;
1606         }
1607         if(!ipstrtoaddr(arg, UNBOUND_DNS_PORT, &addr, &len)) {
1608                 (void)ssl_printf(ssl, "error parsing ip addr: '%s'\n", arg);
1609                 return;
1610         }
1611         /* delete all entries from cache */
1612         /* what we do is to set them all expired */
1613         inf.worker = worker;
1614         inf.name = 0;
1615         inf.len = 0;
1616         inf.labs = 0;
1617         inf.expired = *worker->env.now;
1618         inf.expired -= 3; /* handle 3 seconds skew between threads */
1619         inf.num_rrsets = 0;
1620         inf.num_msgs = 0;
1621         inf.num_keys = 0;
1622         inf.addrlen = len;
1623         memmove(&inf.addr, &addr, len);
1624         slabhash_traverse(worker->env.infra_cache->hosts, 1, &infra_del_host,
1625                 &inf);
1626         send_ok(ssl);
1627 }
1628
1629 /** flush requestlist */
1630 static void
1631 do_flush_requestlist(RES* ssl, struct worker* worker)
1632 {
1633         mesh_delete_all(worker->env.mesh);
1634         send_ok(ssl);
1635 }
1636
1637 /** callback to delete rrsets in a zone */
1638 static void
1639 zone_del_rrset(struct lruhash_entry* e, void* arg)
1640 {
1641         /* entry is locked */
1642         struct del_info* inf = (struct del_info*)arg;
1643         struct ub_packed_rrset_key* k = (struct ub_packed_rrset_key*)e->key;
1644         if(dname_subdomain_c(k->rk.dname, inf->name)) {
1645                 struct packed_rrset_data* d = 
1646                         (struct packed_rrset_data*)e->data;
1647                 if(d->ttl > inf->expired) {
1648                         d->ttl = inf->expired;
1649                         inf->num_rrsets++;
1650                 }
1651         }
1652 }
1653
1654 /** callback to delete messages in a zone */
1655 static void
1656 zone_del_msg(struct lruhash_entry* e, void* arg)
1657 {
1658         /* entry is locked */
1659         struct del_info* inf = (struct del_info*)arg;
1660         struct msgreply_entry* k = (struct msgreply_entry*)e->key;
1661         if(dname_subdomain_c(k->key.qname, inf->name)) {
1662                 struct reply_info* d = (struct reply_info*)e->data;
1663                 if(d->ttl > inf->expired) {
1664                         d->ttl = inf->expired;
1665                         d->prefetch_ttl = inf->expired;
1666                         d->serve_expired_ttl = inf->expired;
1667                         inf->num_msgs++;
1668                 }
1669         }
1670 }
1671
1672 /** callback to delete keys in zone */
1673 static void
1674 zone_del_kcache(struct lruhash_entry* e, void* arg)
1675 {
1676         /* entry is locked */
1677         struct del_info* inf = (struct del_info*)arg;
1678         struct key_entry_key* k = (struct key_entry_key*)e->key;
1679         if(dname_subdomain_c(k->name, inf->name)) {
1680                 struct key_entry_data* d = (struct key_entry_data*)e->data;
1681                 if(d->ttl > inf->expired) {
1682                         d->ttl = inf->expired;
1683                         inf->num_keys++;
1684                 }
1685         }
1686 }
1687
1688 /** remove all rrsets and keys from zone from cache */
1689 static void
1690 do_flush_zone(RES* ssl, struct worker* worker, char* arg)
1691 {
1692         uint8_t* nm;
1693         int nmlabs;
1694         size_t nmlen;
1695         struct del_info inf;
1696         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1697                 return;
1698         /* delete all RRs and key entries from zone */
1699         /* what we do is to set them all expired */
1700         inf.worker = worker;
1701         inf.name = nm;
1702         inf.len = nmlen;
1703         inf.labs = nmlabs;
1704         inf.expired = *worker->env.now;
1705         inf.expired -= 3; /* handle 3 seconds skew between threads */
1706         inf.num_rrsets = 0;
1707         inf.num_msgs = 0;
1708         inf.num_keys = 0;
1709         slabhash_traverse(&worker->env.rrset_cache->table, 1, 
1710                 &zone_del_rrset, &inf);
1711
1712         slabhash_traverse(worker->env.msg_cache, 1, &zone_del_msg, &inf);
1713
1714         /* and validator cache */
1715         if(worker->env.key_cache) {
1716                 slabhash_traverse(worker->env.key_cache->slab, 1, 
1717                         &zone_del_kcache, &inf);
1718         }
1719
1720         free(nm);
1721
1722         (void)ssl_printf(ssl, "ok removed %lu rrsets, %lu messages "
1723                 "and %lu key entries\n", (unsigned long)inf.num_rrsets, 
1724                 (unsigned long)inf.num_msgs, (unsigned long)inf.num_keys);
1725 }
1726
1727 /** callback to delete bogus rrsets */
1728 static void
1729 bogus_del_rrset(struct lruhash_entry* e, void* arg)
1730 {
1731         /* entry is locked */
1732         struct del_info* inf = (struct del_info*)arg;
1733         struct packed_rrset_data* d = (struct packed_rrset_data*)e->data;
1734         if(d->security == sec_status_bogus) {
1735                 d->ttl = inf->expired;
1736                 inf->num_rrsets++;
1737         }
1738 }
1739
1740 /** callback to delete bogus messages */
1741 static void
1742 bogus_del_msg(struct lruhash_entry* e, void* arg)
1743 {
1744         /* entry is locked */
1745         struct del_info* inf = (struct del_info*)arg;
1746         struct reply_info* d = (struct reply_info*)e->data;
1747         if(d->security == sec_status_bogus) {
1748                 d->ttl = inf->expired;
1749                 inf->num_msgs++;
1750         }
1751 }
1752
1753 /** callback to delete bogus keys */
1754 static void
1755 bogus_del_kcache(struct lruhash_entry* e, void* arg)
1756 {
1757         /* entry is locked */
1758         struct del_info* inf = (struct del_info*)arg;
1759         struct key_entry_data* d = (struct key_entry_data*)e->data;
1760         if(d->isbad) {
1761                 d->ttl = inf->expired;
1762                 inf->num_keys++;
1763         }
1764 }
1765
1766 /** remove all bogus rrsets, msgs and keys from cache */
1767 static void
1768 do_flush_bogus(RES* ssl, struct worker* worker)
1769 {
1770         struct del_info inf;
1771         /* what we do is to set them all expired */
1772         inf.worker = worker;
1773         inf.expired = *worker->env.now;
1774         inf.expired -= 3; /* handle 3 seconds skew between threads */
1775         inf.num_rrsets = 0;
1776         inf.num_msgs = 0;
1777         inf.num_keys = 0;
1778         slabhash_traverse(&worker->env.rrset_cache->table, 1, 
1779                 &bogus_del_rrset, &inf);
1780
1781         slabhash_traverse(worker->env.msg_cache, 1, &bogus_del_msg, &inf);
1782
1783         /* and validator cache */
1784         if(worker->env.key_cache) {
1785                 slabhash_traverse(worker->env.key_cache->slab, 1, 
1786                         &bogus_del_kcache, &inf);
1787         }
1788
1789         (void)ssl_printf(ssl, "ok removed %lu rrsets, %lu messages "
1790                 "and %lu key entries\n", (unsigned long)inf.num_rrsets, 
1791                 (unsigned long)inf.num_msgs, (unsigned long)inf.num_keys);
1792 }
1793
1794 /** callback to delete negative and servfail rrsets */
1795 static void
1796 negative_del_rrset(struct lruhash_entry* e, void* arg)
1797 {
1798         /* entry is locked */
1799         struct del_info* inf = (struct del_info*)arg;
1800         struct ub_packed_rrset_key* k = (struct ub_packed_rrset_key*)e->key;
1801         struct packed_rrset_data* d = (struct packed_rrset_data*)e->data;
1802         /* delete the parentside negative cache rrsets,
1803          * these are nameserver rrsets that failed lookup, rdata empty */
1804         if((k->rk.flags & PACKED_RRSET_PARENT_SIDE) && d->count == 1 &&
1805                 d->rrsig_count == 0 && d->rr_len[0] == 0) {
1806                 d->ttl = inf->expired;
1807                 inf->num_rrsets++;
1808         }
1809 }
1810
1811 /** callback to delete negative and servfail messages */
1812 static void
1813 negative_del_msg(struct lruhash_entry* e, void* arg)
1814 {
1815         /* entry is locked */
1816         struct del_info* inf = (struct del_info*)arg;
1817         struct reply_info* d = (struct reply_info*)e->data;
1818         /* rcode not NOERROR: NXDOMAIN, SERVFAIL, ..: an nxdomain or error
1819          * or NOERROR rcode with ANCOUNT==0: a NODATA answer */
1820         if(FLAGS_GET_RCODE(d->flags) != 0 || d->an_numrrsets == 0) {
1821                 d->ttl = inf->expired;
1822                 inf->num_msgs++;
1823         }
1824 }
1825
1826 /** callback to delete negative key entries */
1827 static void
1828 negative_del_kcache(struct lruhash_entry* e, void* arg)
1829 {
1830         /* entry is locked */
1831         struct del_info* inf = (struct del_info*)arg;
1832         struct key_entry_data* d = (struct key_entry_data*)e->data;
1833         /* could be bad because of lookup failure on the DS, DNSKEY, which
1834          * was nxdomain or servfail, and thus a result of negative lookups */
1835         if(d->isbad) {
1836                 d->ttl = inf->expired;
1837                 inf->num_keys++;
1838         }
1839 }
1840
1841 /** remove all negative(NODATA,NXDOMAIN), and servfail messages from cache */
1842 static void
1843 do_flush_negative(RES* ssl, struct worker* worker)
1844 {
1845         struct del_info inf;
1846         /* what we do is to set them all expired */
1847         inf.worker = worker;
1848         inf.expired = *worker->env.now;
1849         inf.expired -= 3; /* handle 3 seconds skew between threads */
1850         inf.num_rrsets = 0;
1851         inf.num_msgs = 0;
1852         inf.num_keys = 0;
1853         slabhash_traverse(&worker->env.rrset_cache->table, 1, 
1854                 &negative_del_rrset, &inf);
1855
1856         slabhash_traverse(worker->env.msg_cache, 1, &negative_del_msg, &inf);
1857
1858         /* and validator cache */
1859         if(worker->env.key_cache) {
1860                 slabhash_traverse(worker->env.key_cache->slab, 1, 
1861                         &negative_del_kcache, &inf);
1862         }
1863
1864         (void)ssl_printf(ssl, "ok removed %lu rrsets, %lu messages "
1865                 "and %lu key entries\n", (unsigned long)inf.num_rrsets, 
1866                 (unsigned long)inf.num_msgs, (unsigned long)inf.num_keys);
1867 }
1868
1869 /** remove name rrset from cache */
1870 static void
1871 do_flush_name(RES* ssl, struct worker* w, char* arg)
1872 {
1873         uint8_t* nm;
1874         int nmlabs;
1875         size_t nmlen;
1876         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1877                 return;
1878         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_A, LDNS_RR_CLASS_IN);
1879         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_AAAA, LDNS_RR_CLASS_IN);
1880         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_NS, LDNS_RR_CLASS_IN);
1881         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SOA, LDNS_RR_CLASS_IN);
1882         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_CNAME, LDNS_RR_CLASS_IN);
1883         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_DNAME, LDNS_RR_CLASS_IN);
1884         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_MX, LDNS_RR_CLASS_IN);
1885         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_PTR, LDNS_RR_CLASS_IN);
1886         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SRV, LDNS_RR_CLASS_IN);
1887         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_NAPTR, LDNS_RR_CLASS_IN);
1888         
1889         free(nm);
1890         send_ok(ssl);
1891 }
1892
1893 /** printout a delegation point info */
1894 static int
1895 ssl_print_name_dp(RES* ssl, const char* str, uint8_t* nm, uint16_t dclass,
1896         struct delegpt* dp)
1897 {
1898         char buf[257];
1899         struct delegpt_ns* ns;
1900         struct delegpt_addr* a;
1901         int f = 0;
1902         if(str) { /* print header for forward, stub */
1903                 char* c = sldns_wire2str_class(dclass);
1904                 dname_str(nm, buf);
1905                 if(!ssl_printf(ssl, "%s %s %s ", buf, (c?c:"CLASS??"), str)) {
1906                         free(c);
1907                         return 0;
1908                 }
1909                 free(c);
1910         }
1911         for(ns = dp->nslist; ns; ns = ns->next) {
1912                 dname_str(ns->name, buf);
1913                 if(!ssl_printf(ssl, "%s%s", (f?" ":""), buf))
1914                         return 0;
1915                 f = 1;
1916         }
1917         for(a = dp->target_list; a; a = a->next_target) {
1918                 addr_to_str(&a->addr, a->addrlen, buf, sizeof(buf));
1919                 if(!ssl_printf(ssl, "%s%s", (f?" ":""), buf))
1920                         return 0;
1921                 f = 1;
1922         }
1923         return ssl_printf(ssl, "\n");
1924 }
1925
1926
1927 /** print root forwards */
1928 static int
1929 print_root_fwds(RES* ssl, struct iter_forwards* fwds, uint8_t* root)
1930 {
1931         struct delegpt* dp;
1932         dp = forwards_lookup(fwds, root, LDNS_RR_CLASS_IN);
1933         if(!dp)
1934                 return ssl_printf(ssl, "off (using root hints)\n");
1935         /* if dp is returned it must be the root */
1936         log_assert(query_dname_compare(dp->name, root)==0);
1937         return ssl_print_name_dp(ssl, NULL, root, LDNS_RR_CLASS_IN, dp);
1938 }
1939
1940 /** parse args into delegpt */
1941 static struct delegpt*
1942 parse_delegpt(RES* ssl, char* args, uint8_t* nm, int allow_names)
1943 {
1944         /* parse args and add in */
1945         char* p = args;
1946         char* todo;
1947         struct delegpt* dp = delegpt_create_mlc(nm);
1948         struct sockaddr_storage addr;
1949         socklen_t addrlen;
1950         char* auth_name;
1951         if(!dp) {
1952                 (void)ssl_printf(ssl, "error out of memory\n");
1953                 return NULL;
1954         }
1955         while(p) {
1956                 todo = p;
1957                 p = strchr(p, ' '); /* find next spot, if any */
1958                 if(p) {
1959                         *p++ = 0;       /* end this spot */
1960                         p = skipwhite(p); /* position at next spot */
1961                 }
1962                 /* parse address */
1963                 if(!authextstrtoaddr(todo, &addr, &addrlen, &auth_name)) {
1964                         if(allow_names) {
1965                                 uint8_t* n = NULL;
1966                                 size_t ln;
1967                                 int lb;
1968                                 if(!parse_arg_name(ssl, todo, &n, &ln, &lb)) {
1969                                         (void)ssl_printf(ssl, "error cannot "
1970                                                 "parse IP address or name "
1971                                                 "'%s'\n", todo);
1972                                         delegpt_free_mlc(dp);
1973                                         return NULL;
1974                                 }
1975                                 if(!delegpt_add_ns_mlc(dp, n, 0)) {
1976                                         (void)ssl_printf(ssl, "error out of memory\n");
1977                                         free(n);
1978                                         delegpt_free_mlc(dp);
1979                                         return NULL;
1980                                 }
1981                                 free(n);
1982
1983                         } else {
1984                                 (void)ssl_printf(ssl, "error cannot parse"
1985                                         " IP address '%s'\n", todo);
1986                                 delegpt_free_mlc(dp);
1987                                 return NULL;
1988                         }
1989                 } else {
1990 #if ! defined(HAVE_SSL_SET1_HOST) && ! defined(HAVE_X509_VERIFY_PARAM_SET1_HOST)
1991                         if(auth_name)
1992                           log_err("no name verification functionality in "
1993                                 "ssl library, ignored name for %s", todo);
1994 #endif
1995                         /* add address */
1996                         if(!delegpt_add_addr_mlc(dp, &addr, addrlen, 0, 0,
1997                                 auth_name)) {
1998                                 (void)ssl_printf(ssl, "error out of memory\n");
1999                                 delegpt_free_mlc(dp);
2000                                 return NULL;
2001                         }
2002                 }
2003         }
2004         dp->has_parent_side_NS = 1;
2005         return dp;
2006 }
2007
2008 /** do the status command */
2009 static void
2010 do_forward(RES* ssl, struct worker* worker, char* args)
2011 {
2012         struct iter_forwards* fwd = worker->env.fwds;
2013         uint8_t* root = (uint8_t*)"\000";
2014         if(!fwd) {
2015                 (void)ssl_printf(ssl, "error: structure not allocated\n");
2016                 return;
2017         }
2018         if(args == NULL || args[0] == 0) {
2019                 (void)print_root_fwds(ssl, fwd, root);
2020                 return;
2021         }
2022         /* set root forwards for this thread. since we are in remote control
2023          * the actual mesh is not running, so we can freely edit it. */
2024         /* delete all the existing queries first */
2025         mesh_delete_all(worker->env.mesh);
2026         if(strcmp(args, "off") == 0) {
2027                 forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, root);
2028         } else {
2029                 struct delegpt* dp;
2030                 if(!(dp = parse_delegpt(ssl, args, root, 0)))
2031                         return;
2032                 if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp)) {
2033                         (void)ssl_printf(ssl, "error out of memory\n");
2034                         return;
2035                 }
2036         }
2037         send_ok(ssl);
2038 }
2039
2040 static int
2041 parse_fs_args(RES* ssl, char* args, uint8_t** nm, struct delegpt** dp,
2042         int* insecure, int* prime)
2043 {
2044         char* zonename;
2045         char* rest;
2046         size_t nmlen;
2047         int nmlabs;
2048         /* parse all -x args */
2049         while(args[0] == '+') {
2050                 if(!find_arg2(ssl, args, &rest))
2051                         return 0;
2052                 while(*(++args) != 0) {
2053                         if(*args == 'i' && insecure)
2054                                 *insecure = 1;
2055                         else if(*args == 'p' && prime)
2056                                 *prime = 1;
2057                         else {
2058                                 (void)ssl_printf(ssl, "error: unknown option %s\n", args);
2059                                 return 0;
2060                         }
2061                 }
2062                 args = rest;
2063         }
2064         /* parse name */
2065         if(dp) {
2066                 if(!find_arg2(ssl, args, &rest))
2067                         return 0;
2068                 zonename = args;
2069                 args = rest;
2070         } else  zonename = args;
2071         if(!parse_arg_name(ssl, zonename, nm, &nmlen, &nmlabs))
2072                 return 0;
2073
2074         /* parse dp */
2075         if(dp) {
2076                 if(!(*dp = parse_delegpt(ssl, args, *nm, 1))) {
2077                         free(*nm);
2078                         return 0;
2079                 }
2080         }
2081         return 1;
2082 }
2083
2084 /** do the forward_add command */
2085 static void
2086 do_forward_add(RES* ssl, struct worker* worker, char* args)
2087 {
2088         struct iter_forwards* fwd = worker->env.fwds;
2089         int insecure = 0;
2090         uint8_t* nm = NULL;
2091         struct delegpt* dp = NULL;
2092         if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, NULL))
2093                 return;
2094         if(insecure && worker->env.anchors) {
2095                 if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2096                         nm)) {
2097                         (void)ssl_printf(ssl, "error out of memory\n");
2098                         delegpt_free_mlc(dp);
2099                         free(nm);
2100                         return;
2101                 }
2102         }
2103         if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp)) {
2104                 (void)ssl_printf(ssl, "error out of memory\n");
2105                 free(nm);
2106                 return;
2107         }
2108         free(nm);
2109         send_ok(ssl);
2110 }
2111
2112 /** do the forward_remove command */
2113 static void
2114 do_forward_remove(RES* ssl, struct worker* worker, char* args)
2115 {
2116         struct iter_forwards* fwd = worker->env.fwds;
2117         int insecure = 0;
2118         uint8_t* nm = NULL;
2119         if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL))
2120                 return;
2121         if(insecure && worker->env.anchors)
2122                 anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2123                         nm);
2124         forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, nm);
2125         free(nm);
2126         send_ok(ssl);
2127 }
2128
2129 /** do the stub_add command */
2130 static void
2131 do_stub_add(RES* ssl, struct worker* worker, char* args)
2132 {
2133         struct iter_forwards* fwd = worker->env.fwds;
2134         int insecure = 0, prime = 0;
2135         uint8_t* nm = NULL;
2136         struct delegpt* dp = NULL;
2137         if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, &prime))
2138                 return;
2139         if(insecure && worker->env.anchors) {
2140                 if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2141                         nm)) {
2142                         (void)ssl_printf(ssl, "error out of memory\n");
2143                         delegpt_free_mlc(dp);
2144                         free(nm);
2145                         return;
2146                 }
2147         }
2148         if(!forwards_add_stub_hole(fwd, LDNS_RR_CLASS_IN, nm)) {
2149                 if(insecure && worker->env.anchors)
2150                         anchors_delete_insecure(worker->env.anchors,
2151                                 LDNS_RR_CLASS_IN, nm);
2152                 (void)ssl_printf(ssl, "error out of memory\n");
2153                 delegpt_free_mlc(dp);
2154                 free(nm);
2155                 return;
2156         }
2157         if(!hints_add_stub(worker->env.hints, LDNS_RR_CLASS_IN, dp, !prime)) {
2158                 (void)ssl_printf(ssl, "error out of memory\n");
2159                 forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm);
2160                 if(insecure && worker->env.anchors)
2161                         anchors_delete_insecure(worker->env.anchors,
2162                                 LDNS_RR_CLASS_IN, nm);
2163                 free(nm);
2164                 return;
2165         }
2166         free(nm);
2167         send_ok(ssl);
2168 }
2169
2170 /** do the stub_remove command */
2171 static void
2172 do_stub_remove(RES* ssl, struct worker* worker, char* args)
2173 {
2174         struct iter_forwards* fwd = worker->env.fwds;
2175         int insecure = 0;
2176         uint8_t* nm = NULL;
2177         if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL))
2178                 return;
2179         if(insecure && worker->env.anchors)
2180                 anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2181                         nm);
2182         forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm);
2183         hints_delete_stub(worker->env.hints, LDNS_RR_CLASS_IN, nm);
2184         free(nm);
2185         send_ok(ssl);
2186 }
2187
2188 /** do the insecure_add command */
2189 static void
2190 do_insecure_add(RES* ssl, struct worker* worker, char* arg)
2191 {
2192         size_t nmlen;
2193         int nmlabs;
2194         uint8_t* nm = NULL;
2195         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
2196                 return;
2197         if(worker->env.anchors) {
2198                 if(!anchors_add_insecure(worker->env.anchors,
2199                         LDNS_RR_CLASS_IN, nm)) {
2200                         (void)ssl_printf(ssl, "error out of memory\n");
2201                         free(nm);
2202                         return;
2203                 }
2204         }
2205         free(nm);
2206         send_ok(ssl);
2207 }
2208
2209 /** do the insecure_remove command */
2210 static void
2211 do_insecure_remove(RES* ssl, struct worker* worker, char* arg)
2212 {
2213         size_t nmlen;
2214         int nmlabs;
2215         uint8_t* nm = NULL;
2216         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
2217                 return;
2218         if(worker->env.anchors)
2219                 anchors_delete_insecure(worker->env.anchors,
2220                         LDNS_RR_CLASS_IN, nm);
2221         free(nm);
2222         send_ok(ssl);
2223 }
2224
2225 static void
2226 do_insecure_list(RES* ssl, struct worker* worker)
2227 {
2228         char buf[257];
2229         struct trust_anchor* a;
2230         if(worker->env.anchors) {
2231                 RBTREE_FOR(a, struct trust_anchor*, worker->env.anchors->tree) {
2232                         if(a->numDS == 0 && a->numDNSKEY == 0) {
2233                                 dname_str(a->name, buf);
2234                                 ssl_printf(ssl, "%s\n", buf);
2235                         }
2236                 }
2237         }
2238 }
2239
2240 /** do the status command */
2241 static void
2242 do_status(RES* ssl, struct worker* worker)
2243 {
2244         int i;
2245         time_t uptime;
2246         if(!ssl_printf(ssl, "version: %s\n", PACKAGE_VERSION))
2247                 return;
2248         if(!ssl_printf(ssl, "verbosity: %d\n", verbosity))
2249                 return;
2250         if(!ssl_printf(ssl, "threads: %d\n", worker->daemon->num))
2251                 return;
2252         if(!ssl_printf(ssl, "modules: %d [", worker->daemon->mods.num))
2253                 return;
2254         for(i=0; i<worker->daemon->mods.num; i++) {
2255                 if(!ssl_printf(ssl, " %s", worker->daemon->mods.mod[i]->name))
2256                         return;
2257         }
2258         if(!ssl_printf(ssl, " ]\n"))
2259                 return;
2260         uptime = (time_t)time(NULL) - (time_t)worker->daemon->time_boot.tv_sec;
2261         if(!ssl_printf(ssl, "uptime: " ARG_LL "d seconds\n", (long long)uptime))
2262                 return;
2263         if(!ssl_printf(ssl, "options:%s%s%s%s\n" , 
2264                 (worker->daemon->reuseport?" reuseport":""),
2265                 (worker->daemon->rc->accept_list?" control":""),
2266                 (worker->daemon->rc->accept_list && worker->daemon->rc->use_cert?"(ssl)":""),
2267                 (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)":"")
2268                 ))
2269                 return;
2270         if(!ssl_printf(ssl, "unbound (pid %d) is running...\n",
2271                 (int)getpid()))
2272                 return;
2273 }
2274
2275 /** get age for the mesh state */
2276 static void
2277 get_mesh_age(struct mesh_state* m, char* buf, size_t len, 
2278         struct module_env* env)
2279 {
2280         if(m->reply_list) {
2281                 struct timeval d;
2282                 struct mesh_reply* r = m->reply_list;
2283                 /* last reply is the oldest */
2284                 while(r && r->next)
2285                         r = r->next;
2286                 timeval_subtract(&d, env->now_tv, &r->start_time);
2287                 snprintf(buf, len, ARG_LL "d.%6.6d",
2288                         (long long)d.tv_sec, (int)d.tv_usec);
2289         } else {
2290                 snprintf(buf, len, "-");
2291         }
2292 }
2293
2294 /** get status of a mesh state */
2295 static void
2296 get_mesh_status(struct mesh_area* mesh, struct mesh_state* m, 
2297         char* buf, size_t len)
2298 {
2299         enum module_ext_state s = m->s.ext_state[m->s.curmod];
2300         const char *modname = mesh->mods.mod[m->s.curmod]->name;
2301         size_t l;
2302         if(strcmp(modname, "iterator") == 0 && s == module_wait_reply &&
2303                 m->s.minfo[m->s.curmod]) {
2304                 /* break into iterator to find out who its waiting for */
2305                 struct iter_qstate* qstate = (struct iter_qstate*)
2306                         m->s.minfo[m->s.curmod];
2307                 struct outbound_list* ol = &qstate->outlist;
2308                 struct outbound_entry* e;
2309                 snprintf(buf, len, "%s wait for", modname);
2310                 l = strlen(buf);
2311                 buf += l; len -= l;
2312                 if(ol->first == NULL)
2313                         snprintf(buf, len, " (empty_list)");
2314                 for(e = ol->first; e; e = e->next) {
2315                         snprintf(buf, len, " ");
2316                         l = strlen(buf);
2317                         buf += l; len -= l;
2318                         addr_to_str(&e->qsent->addr, e->qsent->addrlen, 
2319                                 buf, len);
2320                         l = strlen(buf);
2321                         buf += l; len -= l;
2322                 }
2323         } else if(s == module_wait_subquery) {
2324                 /* look in subs from mesh state to see what */
2325                 char nm[257];
2326                 struct mesh_state_ref* sub;
2327                 snprintf(buf, len, "%s wants", modname);
2328                 l = strlen(buf);
2329                 buf += l; len -= l;
2330                 if(m->sub_set.count == 0)
2331                         snprintf(buf, len, " (empty_list)");
2332                 RBTREE_FOR(sub, struct mesh_state_ref*, &m->sub_set) {
2333                         char* t = sldns_wire2str_type(sub->s->s.qinfo.qtype);
2334                         char* c = sldns_wire2str_class(sub->s->s.qinfo.qclass);
2335                         dname_str(sub->s->s.qinfo.qname, nm);
2336                         snprintf(buf, len, " %s %s %s", (t?t:"TYPE??"),
2337                                 (c?c:"CLASS??"), nm);
2338                         l = strlen(buf);
2339                         buf += l; len -= l;
2340                         free(t);
2341                         free(c);
2342                 }
2343         } else {
2344                 snprintf(buf, len, "%s is %s", modname, strextstate(s));
2345         }
2346 }
2347
2348 /** do the dump_requestlist command */
2349 static void
2350 do_dump_requestlist(RES* ssl, struct worker* worker)
2351 {
2352         struct mesh_area* mesh;
2353         struct mesh_state* m;
2354         int num = 0;
2355         char buf[257];
2356         char timebuf[32];
2357         char statbuf[10240];
2358         if(!ssl_printf(ssl, "thread #%d\n", worker->thread_num))
2359                 return;
2360         if(!ssl_printf(ssl, "#   type cl name    seconds    module status\n"))
2361                 return;
2362         /* show worker mesh contents */
2363         mesh = worker->env.mesh;
2364         if(!mesh) return;
2365         RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
2366                 char* t = sldns_wire2str_type(m->s.qinfo.qtype);
2367                 char* c = sldns_wire2str_class(m->s.qinfo.qclass);
2368                 dname_str(m->s.qinfo.qname, buf);
2369                 get_mesh_age(m, timebuf, sizeof(timebuf), &worker->env);
2370                 get_mesh_status(mesh, m, statbuf, sizeof(statbuf));
2371                 if(!ssl_printf(ssl, "%3d %4s %2s %s %s %s\n", 
2372                         num, (t?t:"TYPE??"), (c?c:"CLASS??"), buf, timebuf,
2373                         statbuf)) {
2374                         free(t);
2375                         free(c);
2376                         return;
2377                 }
2378                 num++;
2379                 free(t);
2380                 free(c);
2381         }
2382 }
2383
2384 /** structure for argument data for dump infra host */
2385 struct infra_arg {
2386         /** the infra cache */
2387         struct infra_cache* infra;
2388         /** the SSL connection */
2389         RES* ssl;
2390         /** the time now */
2391         time_t now;
2392         /** ssl failure? stop writing and skip the rest.  If the tcp
2393          * connection is broken, and writes fail, we then stop writing. */
2394         int ssl_failed;
2395 };
2396
2397 /** callback for every host element in the infra cache */
2398 static void
2399 dump_infra_host(struct lruhash_entry* e, void* arg)
2400 {
2401         struct infra_arg* a = (struct infra_arg*)arg;
2402         struct infra_key* k = (struct infra_key*)e->key;
2403         struct infra_data* d = (struct infra_data*)e->data;
2404         char ip_str[1024];
2405         char name[257];
2406         int port;
2407         if(a->ssl_failed)
2408                 return;
2409         addr_to_str(&k->addr, k->addrlen, ip_str, sizeof(ip_str));
2410         dname_str(k->zonename, name);
2411         port = (int)ntohs(((struct sockaddr_in*)&k->addr)->sin_port);
2412         if(port != UNBOUND_DNS_PORT) {
2413                 snprintf(ip_str+strlen(ip_str), sizeof(ip_str)-strlen(ip_str),
2414                         "@%d", port);
2415         }
2416         /* skip expired stuff (only backed off) */
2417         if(d->ttl < a->now) {
2418                 if(d->rtt.rto >= USEFUL_SERVER_TOP_TIMEOUT) {
2419                         if(!ssl_printf(a->ssl, "%s %s expired rto %d\n", ip_str,
2420                                 name, d->rtt.rto))  {
2421                                 a->ssl_failed = 1;
2422                                 return;
2423                         }
2424                 }
2425                 return;
2426         }
2427         if(!ssl_printf(a->ssl, "%s %s ttl %lu ping %d var %d rtt %d rto %d "
2428                 "tA %d tAAAA %d tother %d "
2429                 "ednsknown %d edns %d delay %d lame dnssec %d rec %d A %d "
2430                 "other %d\n", ip_str, name, (unsigned long)(d->ttl - a->now),
2431                 d->rtt.srtt, d->rtt.rttvar, rtt_notimeout(&d->rtt), d->rtt.rto,
2432                 d->timeout_A, d->timeout_AAAA, d->timeout_other,
2433                 (int)d->edns_lame_known, (int)d->edns_version,
2434                 (int)(a->now<d->probedelay?(d->probedelay - a->now):0),
2435                 (int)d->isdnsseclame, (int)d->rec_lame, (int)d->lame_type_A,
2436                 (int)d->lame_other)) {
2437                 a->ssl_failed = 1;
2438                 return;
2439         }
2440 }
2441
2442 /** do the dump_infra command */
2443 static void
2444 do_dump_infra(RES* ssl, struct worker* worker)
2445 {
2446         struct infra_arg arg;
2447         arg.infra = worker->env.infra_cache;
2448         arg.ssl = ssl;
2449         arg.now = *worker->env.now;
2450         arg.ssl_failed = 0;
2451         slabhash_traverse(arg.infra->hosts, 0, &dump_infra_host, (void*)&arg);
2452 }
2453
2454 /** do the log_reopen command */
2455 static void
2456 do_log_reopen(RES* ssl, struct worker* worker)
2457 {
2458         struct config_file* cfg = worker->env.cfg;
2459         send_ok(ssl);
2460         log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
2461 }
2462
2463 /** do the auth_zone_reload command */
2464 static void
2465 do_auth_zone_reload(RES* ssl, struct worker* worker, char* arg)
2466 {
2467         size_t nmlen;
2468         int nmlabs;
2469         uint8_t* nm = NULL;
2470         struct auth_zones* az = worker->env.auth_zones;
2471         struct auth_zone* z = NULL;
2472         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
2473                 return;
2474         if(az) {
2475                 lock_rw_rdlock(&az->lock);
2476                 z = auth_zone_find(az, nm, nmlen, LDNS_RR_CLASS_IN);
2477                 if(z) {
2478                         lock_rw_wrlock(&z->lock);
2479                 }
2480                 lock_rw_unlock(&az->lock);
2481         }
2482         free(nm);
2483         if(!z) {
2484                 (void)ssl_printf(ssl, "error no auth-zone %s\n", arg);
2485                 return;
2486         }
2487         if(!auth_zone_read_zonefile(z, worker->env.cfg)) {
2488                 lock_rw_unlock(&z->lock);
2489                 (void)ssl_printf(ssl, "error failed to read %s\n", arg);
2490                 return;
2491         }
2492         lock_rw_unlock(&z->lock);
2493         send_ok(ssl);
2494 }
2495
2496 /** do the auth_zone_transfer command */
2497 static void
2498 do_auth_zone_transfer(RES* ssl, struct worker* worker, char* arg)
2499 {
2500         size_t nmlen;
2501         int nmlabs;
2502         uint8_t* nm = NULL;
2503         struct auth_zones* az = worker->env.auth_zones;
2504         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
2505                 return;
2506         if(!az || !auth_zones_startprobesequence(az, &worker->env, nm, nmlen,
2507                 LDNS_RR_CLASS_IN)) {
2508                 (void)ssl_printf(ssl, "error zone xfr task not found %s\n", arg);
2509                 return;
2510         }
2511         send_ok(ssl);
2512 }
2513         
2514 /** do the set_option command */
2515 static void
2516 do_set_option(RES* ssl, struct worker* worker, char* arg)
2517 {
2518         char* arg2;
2519         if(!find_arg2(ssl, arg, &arg2))
2520                 return;
2521         if(!config_set_option(worker->env.cfg, arg, arg2)) {
2522                 (void)ssl_printf(ssl, "error setting option\n");
2523                 return;
2524         }
2525         /* effectuate some arguments */
2526         if(strcmp(arg, "val-override-date:") == 0) {
2527                 int m = modstack_find(&worker->env.mesh->mods, "validator");
2528                 struct val_env* val_env = NULL;
2529                 if(m != -1) val_env = (struct val_env*)worker->env.modinfo[m];
2530                 if(val_env)
2531                         val_env->date_override = worker->env.cfg->val_date_override;
2532         }
2533         send_ok(ssl);
2534 }
2535
2536 /* routine to printout option values over SSL */
2537 void remote_get_opt_ssl(char* line, void* arg)
2538 {
2539         RES* ssl = (RES*)arg;
2540         (void)ssl_printf(ssl, "%s\n", line);
2541 }
2542
2543 /** do the get_option command */
2544 static void
2545 do_get_option(RES* ssl, struct worker* worker, char* arg)
2546 {
2547         int r;
2548         r = config_get_option(worker->env.cfg, arg, remote_get_opt_ssl, ssl);
2549         if(!r) {
2550                 (void)ssl_printf(ssl, "error unknown option\n");
2551                 return;
2552         }
2553 }
2554
2555 /** do the list_forwards command */
2556 static void
2557 do_list_forwards(RES* ssl, struct worker* worker)
2558 {
2559         /* since its a per-worker structure no locks needed */
2560         struct iter_forwards* fwds = worker->env.fwds;
2561         struct iter_forward_zone* z;
2562         struct trust_anchor* a;
2563         int insecure;
2564         RBTREE_FOR(z, struct iter_forward_zone*, fwds->tree) {
2565                 if(!z->dp) continue; /* skip empty marker for stub */
2566
2567                 /* see if it is insecure */
2568                 insecure = 0;
2569                 if(worker->env.anchors &&
2570                         (a=anchor_find(worker->env.anchors, z->name,
2571                         z->namelabs, z->namelen,  z->dclass))) {
2572                         if(!a->keylist && !a->numDS && !a->numDNSKEY)
2573                                 insecure = 1;
2574                         lock_basic_unlock(&a->lock);
2575                 }
2576
2577                 if(!ssl_print_name_dp(ssl, (insecure?"forward +i":"forward"),
2578                         z->name, z->dclass, z->dp))
2579                         return;
2580         }
2581 }
2582
2583 /** do the list_stubs command */
2584 static void
2585 do_list_stubs(RES* ssl, struct worker* worker)
2586 {
2587         struct iter_hints_stub* z;
2588         struct trust_anchor* a;
2589         int insecure;
2590         char str[32];
2591         RBTREE_FOR(z, struct iter_hints_stub*, &worker->env.hints->tree) {
2592
2593                 /* see if it is insecure */
2594                 insecure = 0;
2595                 if(worker->env.anchors &&
2596                         (a=anchor_find(worker->env.anchors, z->node.name,
2597                         z->node.labs, z->node.len,  z->node.dclass))) {
2598                         if(!a->keylist && !a->numDS && !a->numDNSKEY)
2599                                 insecure = 1;
2600                         lock_basic_unlock(&a->lock);
2601                 }
2602
2603                 snprintf(str, sizeof(str), "stub %sprime%s",
2604                         (z->noprime?"no":""), (insecure?" +i":""));
2605                 if(!ssl_print_name_dp(ssl, str, z->node.name,
2606                         z->node.dclass, z->dp))
2607                         return;
2608         }
2609 }
2610
2611 /** do the list_auth_zones command */
2612 static void
2613 do_list_auth_zones(RES* ssl, struct auth_zones* az)
2614 {
2615         struct auth_zone* z;
2616         char buf[257], buf2[256];
2617         lock_rw_rdlock(&az->lock);
2618         RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
2619                 lock_rw_rdlock(&z->lock);
2620                 dname_str(z->name, buf);
2621                 if(z->zone_expired)
2622                         snprintf(buf2, sizeof(buf2), "expired");
2623                 else {
2624                         uint32_t serial = 0;
2625                         if(auth_zone_get_serial(z, &serial))
2626                                 snprintf(buf2, sizeof(buf2), "serial %u",
2627                                         (unsigned)serial);
2628                         else    snprintf(buf2, sizeof(buf2), "no serial");
2629                 }
2630                 if(!ssl_printf(ssl, "%s\t%s\n", buf, buf2)) {
2631                         /* failure to print */
2632                         lock_rw_unlock(&z->lock);
2633                         lock_rw_unlock(&az->lock);
2634                         return;
2635                 }
2636                 lock_rw_unlock(&z->lock);
2637         }
2638         lock_rw_unlock(&az->lock);
2639 }
2640
2641 /** do the list_local_zones command */
2642 static void
2643 do_list_local_zones(RES* ssl, struct local_zones* zones)
2644 {
2645         struct local_zone* z;
2646         char buf[257];
2647         lock_rw_rdlock(&zones->lock);
2648         RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
2649                 lock_rw_rdlock(&z->lock);
2650                 dname_str(z->name, buf);
2651                 if(!ssl_printf(ssl, "%s %s\n", buf, 
2652                         local_zone_type2str(z->type))) {
2653                         /* failure to print */
2654                         lock_rw_unlock(&z->lock);
2655                         lock_rw_unlock(&zones->lock);
2656                         return;
2657                 }
2658                 lock_rw_unlock(&z->lock);
2659         }
2660         lock_rw_unlock(&zones->lock);
2661 }
2662
2663 /** do the list_local_data command */
2664 static void
2665 do_list_local_data(RES* ssl, struct worker* worker, struct local_zones* zones)
2666 {
2667         struct local_zone* z;
2668         struct local_data* d;
2669         struct local_rrset* p;
2670         char* s = (char*)sldns_buffer_begin(worker->env.scratch_buffer);
2671         size_t slen = sldns_buffer_capacity(worker->env.scratch_buffer);
2672         lock_rw_rdlock(&zones->lock);
2673         RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
2674                 lock_rw_rdlock(&z->lock);
2675                 RBTREE_FOR(d, struct local_data*, &z->data) {
2676                         for(p = d->rrsets; p; p = p->next) {
2677                                 struct packed_rrset_data* d =
2678                                         (struct packed_rrset_data*)p->rrset->entry.data;
2679                                 size_t i;
2680                                 for(i=0; i<d->count + d->rrsig_count; i++) {
2681                                         if(!packed_rr_to_string(p->rrset, i,
2682                                                 0, s, slen)) {
2683                                                 if(!ssl_printf(ssl, "BADRR\n")) {
2684                                                         lock_rw_unlock(&z->lock);
2685                                                         lock_rw_unlock(&zones->lock);
2686                                                         return;
2687                                                 }
2688                                         }
2689                                         if(!ssl_printf(ssl, "%s\n", s)) {
2690                                                 lock_rw_unlock(&z->lock);
2691                                                 lock_rw_unlock(&zones->lock);
2692                                                 return;
2693                                         }
2694                                 }
2695                         }
2696                 }
2697                 lock_rw_unlock(&z->lock);
2698         }
2699         lock_rw_unlock(&zones->lock);
2700 }
2701
2702 /** do the view_list_local_zones command */
2703 static void
2704 do_view_list_local_zones(RES* ssl, struct worker* worker, char* arg)
2705 {
2706         struct view* v = views_find_view(worker->daemon->views,
2707                 arg, 0 /* get read lock*/);
2708         if(!v) {
2709                 ssl_printf(ssl,"no view with name: %s\n", arg);
2710                 return;
2711         }
2712         if(v->local_zones) {
2713                 do_list_local_zones(ssl, v->local_zones);
2714         }
2715         lock_rw_unlock(&v->lock);
2716 }
2717
2718 /** do the view_list_local_data command */
2719 static void
2720 do_view_list_local_data(RES* ssl, struct worker* worker, char* arg)
2721 {
2722         struct view* v = views_find_view(worker->daemon->views,
2723                 arg, 0 /* get read lock*/);
2724         if(!v) {
2725                 ssl_printf(ssl,"no view with name: %s\n", arg);
2726                 return;
2727         }
2728         if(v->local_zones) {
2729                 do_list_local_data(ssl, worker, v->local_zones);
2730         }
2731         lock_rw_unlock(&v->lock);
2732 }
2733
2734 /** struct for user arg ratelimit list */
2735 struct ratelimit_list_arg {
2736         /** the infra cache */
2737         struct infra_cache* infra;
2738         /** the SSL to print to */
2739         RES* ssl;
2740         /** all or only ratelimited */
2741         int all;
2742         /** current time */
2743         time_t now;
2744 };
2745
2746 #define ip_ratelimit_list_arg ratelimit_list_arg
2747
2748 /** list items in the ratelimit table */
2749 static void
2750 rate_list(struct lruhash_entry* e, void* arg)
2751 {
2752         struct ratelimit_list_arg* a = (struct ratelimit_list_arg*)arg;
2753         struct rate_key* k = (struct rate_key*)e->key;
2754         struct rate_data* d = (struct rate_data*)e->data;
2755         char buf[257];
2756         int lim = infra_find_ratelimit(a->infra, k->name, k->namelen);
2757         int max = infra_rate_max(d, a->now);
2758         if(a->all == 0) {
2759                 if(max < lim)
2760                         return;
2761         }
2762         dname_str(k->name, buf);
2763         ssl_printf(a->ssl, "%s %d limit %d\n", buf, max, lim);
2764 }
2765
2766 /** list items in the ip_ratelimit table */
2767 static void
2768 ip_rate_list(struct lruhash_entry* e, void* arg)
2769 {
2770         char ip[128];
2771         struct ip_ratelimit_list_arg* a = (struct ip_ratelimit_list_arg*)arg;
2772         struct ip_rate_key* k = (struct ip_rate_key*)e->key;
2773         struct ip_rate_data* d = (struct ip_rate_data*)e->data;
2774         int lim = infra_ip_ratelimit;
2775         int max = infra_rate_max(d, a->now);
2776         if(a->all == 0) {
2777                 if(max < lim)
2778                         return;
2779         }
2780         addr_to_str(&k->addr, k->addrlen, ip, sizeof(ip));
2781         ssl_printf(a->ssl, "%s %d limit %d\n", ip, max, lim);
2782 }
2783
2784 /** do the ratelimit_list command */
2785 static void
2786 do_ratelimit_list(RES* ssl, struct worker* worker, char* arg)
2787 {
2788         struct ratelimit_list_arg a;
2789         a.all = 0;
2790         a.infra = worker->env.infra_cache;
2791         a.now = *worker->env.now;
2792         a.ssl = ssl;
2793         arg = skipwhite(arg);
2794         if(strcmp(arg, "+a") == 0)
2795                 a.all = 1;
2796         if(a.infra->domain_rates==NULL ||
2797                 (a.all == 0 && infra_dp_ratelimit == 0))
2798                 return;
2799         slabhash_traverse(a.infra->domain_rates, 0, rate_list, &a);
2800 }
2801
2802 /** do the ip_ratelimit_list command */
2803 static void
2804 do_ip_ratelimit_list(RES* ssl, struct worker* worker, char* arg)
2805 {
2806         struct ip_ratelimit_list_arg a;
2807         a.all = 0;
2808         a.infra = worker->env.infra_cache;
2809         a.now = *worker->env.now;
2810         a.ssl = ssl;
2811         arg = skipwhite(arg);
2812         if(strcmp(arg, "+a") == 0)
2813                 a.all = 1;
2814         if(a.infra->client_ip_rates==NULL ||
2815                 (a.all == 0 && infra_ip_ratelimit == 0))
2816                 return;
2817         slabhash_traverse(a.infra->client_ip_rates, 0, ip_rate_list, &a);
2818 }
2819
2820 /** tell other processes to execute the command */
2821 static void
2822 distribute_cmd(struct daemon_remote* rc, RES* ssl, char* cmd)
2823 {
2824         int i;
2825         if(!cmd || !ssl) 
2826                 return;
2827         /* skip i=0 which is me */
2828         for(i=1; i<rc->worker->daemon->num; i++) {
2829                 worker_send_cmd(rc->worker->daemon->workers[i],
2830                         worker_cmd_remote);
2831                 if(!tube_write_msg(rc->worker->daemon->workers[i]->cmd,
2832                         (uint8_t*)cmd, strlen(cmd)+1, 0)) {
2833                         ssl_printf(ssl, "error could not distribute cmd\n");
2834                         return;
2835                 }
2836         }
2837 }
2838
2839 /** check for name with end-of-string, space or tab after it */
2840 static int
2841 cmdcmp(char* p, const char* cmd, size_t len)
2842 {
2843         return strncmp(p,cmd,len)==0 && (p[len]==0||p[len]==' '||p[len]=='\t');
2844 }
2845
2846 /** execute a remote control command */
2847 static void
2848 execute_cmd(struct daemon_remote* rc, RES* ssl, char* cmd, 
2849         struct worker* worker)
2850 {
2851         char* p = skipwhite(cmd);
2852         /* compare command */
2853         if(cmdcmp(p, "stop", 4)) {
2854                 do_stop(ssl, worker);
2855                 return;
2856         } else if(cmdcmp(p, "reload", 6)) {
2857                 do_reload(ssl, worker);
2858                 return;
2859         } else if(cmdcmp(p, "stats_noreset", 13)) {
2860                 do_stats(ssl, worker, 0);
2861                 return;
2862         } else if(cmdcmp(p, "stats", 5)) {
2863                 do_stats(ssl, worker, 1);
2864                 return;
2865         } else if(cmdcmp(p, "status", 6)) {
2866                 do_status(ssl, worker);
2867                 return;
2868         } else if(cmdcmp(p, "dump_cache", 10)) {
2869                 (void)dump_cache(ssl, worker);
2870                 return;
2871         } else if(cmdcmp(p, "load_cache", 10)) {
2872                 if(load_cache(ssl, worker)) send_ok(ssl);
2873                 return;
2874         } else if(cmdcmp(p, "list_forwards", 13)) {
2875                 do_list_forwards(ssl, worker);
2876                 return;
2877         } else if(cmdcmp(p, "list_stubs", 10)) {
2878                 do_list_stubs(ssl, worker);
2879                 return;
2880         } else if(cmdcmp(p, "list_insecure", 13)) {
2881                 do_insecure_list(ssl, worker);
2882                 return;
2883         } else if(cmdcmp(p, "list_local_zones", 16)) {
2884                 do_list_local_zones(ssl, worker->daemon->local_zones);
2885                 return;
2886         } else if(cmdcmp(p, "list_local_data", 15)) {
2887                 do_list_local_data(ssl, worker, worker->daemon->local_zones);
2888                 return;
2889         } else if(cmdcmp(p, "view_list_local_zones", 21)) {
2890                 do_view_list_local_zones(ssl, worker, skipwhite(p+21));
2891                 return;
2892         } else if(cmdcmp(p, "view_list_local_data", 20)) {
2893                 do_view_list_local_data(ssl, worker, skipwhite(p+20));
2894                 return;
2895         } else if(cmdcmp(p, "ratelimit_list", 14)) {
2896                 do_ratelimit_list(ssl, worker, p+14);
2897                 return;
2898         } else if(cmdcmp(p, "ip_ratelimit_list", 17)) {
2899                 do_ip_ratelimit_list(ssl, worker, p+17);
2900                 return;
2901         } else if(cmdcmp(p, "list_auth_zones", 15)) {
2902                 do_list_auth_zones(ssl, worker->env.auth_zones);
2903                 return;
2904         } else if(cmdcmp(p, "auth_zone_reload", 16)) {
2905                 do_auth_zone_reload(ssl, worker, skipwhite(p+16));
2906                 return;
2907         } else if(cmdcmp(p, "auth_zone_transfer", 18)) {
2908                 do_auth_zone_transfer(ssl, worker, skipwhite(p+18));
2909                 return;
2910         } else if(cmdcmp(p, "stub_add", 8)) {
2911                 /* must always distribute this cmd */
2912                 if(rc) distribute_cmd(rc, ssl, cmd);
2913                 do_stub_add(ssl, worker, skipwhite(p+8));
2914                 return;
2915         } else if(cmdcmp(p, "stub_remove", 11)) {
2916                 /* must always distribute this cmd */
2917                 if(rc) distribute_cmd(rc, ssl, cmd);
2918                 do_stub_remove(ssl, worker, skipwhite(p+11));
2919                 return;
2920         } else if(cmdcmp(p, "forward_add", 11)) {
2921                 /* must always distribute this cmd */
2922                 if(rc) distribute_cmd(rc, ssl, cmd);
2923                 do_forward_add(ssl, worker, skipwhite(p+11));
2924                 return;
2925         } else if(cmdcmp(p, "forward_remove", 14)) {
2926                 /* must always distribute this cmd */
2927                 if(rc) distribute_cmd(rc, ssl, cmd);
2928                 do_forward_remove(ssl, worker, skipwhite(p+14));
2929                 return;
2930         } else if(cmdcmp(p, "insecure_add", 12)) {
2931                 /* must always distribute this cmd */
2932                 if(rc) distribute_cmd(rc, ssl, cmd);
2933                 do_insecure_add(ssl, worker, skipwhite(p+12));
2934                 return;
2935         } else if(cmdcmp(p, "insecure_remove", 15)) {
2936                 /* must always distribute this cmd */
2937                 if(rc) distribute_cmd(rc, ssl, cmd);
2938                 do_insecure_remove(ssl, worker, skipwhite(p+15));
2939                 return;
2940         } else if(cmdcmp(p, "forward", 7)) {
2941                 /* must always distribute this cmd */
2942                 if(rc) distribute_cmd(rc, ssl, cmd);
2943                 do_forward(ssl, worker, skipwhite(p+7));
2944                 return;
2945         } else if(cmdcmp(p, "flush_stats", 11)) {
2946                 /* must always distribute this cmd */
2947                 if(rc) distribute_cmd(rc, ssl, cmd);
2948                 do_flush_stats(ssl, worker);
2949                 return;
2950         } else if(cmdcmp(p, "flush_requestlist", 17)) {
2951                 /* must always distribute this cmd */
2952                 if(rc) distribute_cmd(rc, ssl, cmd);
2953                 do_flush_requestlist(ssl, worker);
2954                 return;
2955         } else if(cmdcmp(p, "lookup", 6)) {
2956                 do_lookup(ssl, worker, skipwhite(p+6));
2957                 return;
2958         }
2959
2960 #ifdef THREADS_DISABLED
2961         /* other processes must execute the command as well */
2962         /* commands that should not be distributed, returned above. */
2963         if(rc) { /* only if this thread is the master (rc) thread */
2964                 /* done before the code below, which may split the string */
2965                 distribute_cmd(rc, ssl, cmd);
2966         }
2967 #endif
2968         if(cmdcmp(p, "verbosity", 9)) {
2969                 do_verbosity(ssl, skipwhite(p+9));
2970         } else if(cmdcmp(p, "local_zone_remove", 17)) {
2971                 do_zone_remove(ssl, worker->daemon->local_zones, skipwhite(p+17));
2972         } else if(cmdcmp(p, "local_zones_remove", 18)) {
2973                 do_zones_remove(ssl, worker->daemon->local_zones);
2974         } else if(cmdcmp(p, "local_zone", 10)) {
2975                 do_zone_add(ssl, worker->daemon->local_zones, skipwhite(p+10));
2976         } else if(cmdcmp(p, "local_zones", 11)) {
2977                 do_zones_add(ssl, worker->daemon->local_zones);
2978         } else if(cmdcmp(p, "local_data_remove", 17)) {
2979                 do_data_remove(ssl, worker->daemon->local_zones, skipwhite(p+17));
2980         } else if(cmdcmp(p, "local_datas_remove", 18)) {
2981                 do_datas_remove(ssl, worker->daemon->local_zones);
2982         } else if(cmdcmp(p, "local_data", 10)) {
2983                 do_data_add(ssl, worker->daemon->local_zones, skipwhite(p+10));
2984         } else if(cmdcmp(p, "local_datas", 11)) {
2985                 do_datas_add(ssl, worker->daemon->local_zones);
2986         } else if(cmdcmp(p, "view_local_zone_remove", 22)) {
2987                 do_view_zone_remove(ssl, worker, skipwhite(p+22));
2988         } else if(cmdcmp(p, "view_local_zone", 15)) {
2989                 do_view_zone_add(ssl, worker, skipwhite(p+15));
2990         } else if(cmdcmp(p, "view_local_data_remove", 22)) {
2991                 do_view_data_remove(ssl, worker, skipwhite(p+22));
2992         } else if(cmdcmp(p, "view_local_data", 15)) {
2993                 do_view_data_add(ssl, worker, skipwhite(p+15));
2994         } else if(cmdcmp(p, "view_local_datas", 16)) {
2995                 do_view_datas_add(ssl, worker, skipwhite(p+16));
2996         } else if(cmdcmp(p, "flush_zone", 10)) {
2997                 do_flush_zone(ssl, worker, skipwhite(p+10));
2998         } else if(cmdcmp(p, "flush_type", 10)) {
2999                 do_flush_type(ssl, worker, skipwhite(p+10));
3000         } else if(cmdcmp(p, "flush_infra", 11)) {
3001                 do_flush_infra(ssl, worker, skipwhite(p+11));
3002         } else if(cmdcmp(p, "flush", 5)) {
3003                 do_flush_name(ssl, worker, skipwhite(p+5));
3004         } else if(cmdcmp(p, "dump_requestlist", 16)) {
3005                 do_dump_requestlist(ssl, worker);
3006         } else if(cmdcmp(p, "dump_infra", 10)) {
3007                 do_dump_infra(ssl, worker);
3008         } else if(cmdcmp(p, "log_reopen", 10)) {
3009                 do_log_reopen(ssl, worker);
3010         } else if(cmdcmp(p, "set_option", 10)) {
3011                 do_set_option(ssl, worker, skipwhite(p+10));
3012         } else if(cmdcmp(p, "get_option", 10)) {
3013                 do_get_option(ssl, worker, skipwhite(p+10));
3014         } else if(cmdcmp(p, "flush_bogus", 11)) {
3015                 do_flush_bogus(ssl, worker);
3016         } else if(cmdcmp(p, "flush_negative", 14)) {
3017                 do_flush_negative(ssl, worker);
3018         } else {
3019                 (void)ssl_printf(ssl, "error unknown command '%s'\n", p);
3020         }
3021 }
3022
3023 void 
3024 daemon_remote_exec(struct worker* worker)
3025 {
3026         /* read the cmd string */
3027         uint8_t* msg = NULL;
3028         uint32_t len = 0;
3029         if(!tube_read_msg(worker->cmd, &msg, &len, 0)) {
3030                 log_err("daemon_remote_exec: tube_read_msg failed");
3031                 return;
3032         }
3033         verbose(VERB_ALGO, "remote exec distributed: %s", (char*)msg);
3034         execute_cmd(NULL, NULL, (char*)msg, worker);
3035         free(msg);
3036 }
3037
3038 /** handle remote control request */
3039 static void
3040 handle_req(struct daemon_remote* rc, struct rc_state* s, RES* res)
3041 {
3042         int r;
3043         char pre[10];
3044         char magic[7];
3045         char buf[1024];
3046 #ifdef USE_WINSOCK
3047         /* makes it possible to set the socket blocking again. */
3048         /* basically removes it from winsock_event ... */
3049         WSAEventSelect(s->c->fd, NULL, 0);
3050 #endif
3051         fd_set_block(s->c->fd);
3052
3053         /* try to read magic UBCT[version]_space_ string */
3054         if(res->ssl) {
3055                 ERR_clear_error();
3056                 if((r=SSL_read(res->ssl, magic, (int)sizeof(magic)-1)) <= 0) {
3057                         if(SSL_get_error(res->ssl, r) == SSL_ERROR_ZERO_RETURN)
3058                                 return;
3059                         log_crypto_err("could not SSL_read");
3060                         return;
3061                 }
3062         } else {
3063                 while(1) {
3064                         ssize_t rr = recv(res->fd, magic, sizeof(magic)-1, 0);
3065                         if(rr <= 0) {
3066                                 if(rr == 0) return;
3067                                 if(errno == EINTR || errno == EAGAIN)
3068                                         continue;
3069 #ifndef USE_WINSOCK
3070                                 log_err("could not recv: %s", strerror(errno));
3071 #else
3072                                 log_err("could not recv: %s", wsa_strerror(WSAGetLastError()));
3073 #endif
3074                                 return;
3075                         }
3076                         r = (int)rr;
3077                         break;
3078                 }
3079         }
3080         magic[6] = 0;
3081         if( r != 6 || strncmp(magic, "UBCT", 4) != 0) {
3082                 verbose(VERB_QUERY, "control connection has bad magic string");
3083                 /* probably wrong tool connected, ignore it completely */
3084                 return;
3085         }
3086
3087         /* read the command line */
3088         if(!ssl_read_line(res, buf, sizeof(buf))) {
3089                 return;
3090         }
3091         snprintf(pre, sizeof(pre), "UBCT%d ", UNBOUND_CONTROL_VERSION);
3092         if(strcmp(magic, pre) != 0) {
3093                 verbose(VERB_QUERY, "control connection had bad "
3094                         "version %s, cmd: %s", magic, buf);
3095                 ssl_printf(res, "error version mismatch\n");
3096                 return;
3097         }
3098         verbose(VERB_DETAIL, "control cmd: %s", buf);
3099
3100         /* figure out what to do */
3101         execute_cmd(rc, res, buf, rc->worker);
3102 }
3103
3104 /** handle SSL_do_handshake changes to the file descriptor to wait for later */
3105 static int
3106 remote_handshake_later(struct daemon_remote* rc, struct rc_state* s,
3107         struct comm_point* c, int r, int r2)
3108 {
3109         if(r2 == SSL_ERROR_WANT_READ) {
3110                 if(s->shake_state == rc_hs_read) {
3111                         /* try again later */
3112                         return 0;
3113                 }
3114                 s->shake_state = rc_hs_read;
3115                 comm_point_listen_for_rw(c, 1, 0);
3116                 return 0;
3117         } else if(r2 == SSL_ERROR_WANT_WRITE) {
3118                 if(s->shake_state == rc_hs_write) {
3119                         /* try again later */
3120                         return 0;
3121                 }
3122                 s->shake_state = rc_hs_write;
3123                 comm_point_listen_for_rw(c, 0, 1);
3124                 return 0;
3125         } else {
3126                 if(r == 0)
3127                         log_err("remote control connection closed prematurely");
3128                 log_addr(VERB_OPS, "failed connection from",
3129                         &s->c->repinfo.addr, s->c->repinfo.addrlen);
3130                 log_crypto_err("remote control failed ssl");
3131                 clean_point(rc, s);
3132         }
3133         return 0;
3134 }
3135
3136 int remote_control_callback(struct comm_point* c, void* arg, int err, 
3137         struct comm_reply* ATTR_UNUSED(rep))
3138 {
3139         RES res;
3140         struct rc_state* s = (struct rc_state*)arg;
3141         struct daemon_remote* rc = s->rc;
3142         int r;
3143         if(err != NETEVENT_NOERROR) {
3144                 if(err==NETEVENT_TIMEOUT) 
3145                         log_err("remote control timed out");
3146                 clean_point(rc, s);
3147                 return 0;
3148         }
3149         if(s->ssl) {
3150                 /* (continue to) setup the SSL connection */
3151                 ERR_clear_error();
3152                 r = SSL_do_handshake(s->ssl);
3153                 if(r != 1) {
3154                         int r2 = SSL_get_error(s->ssl, r);
3155                         return remote_handshake_later(rc, s, c, r, r2);
3156                 }
3157                 s->shake_state = rc_none;
3158         }
3159
3160         /* once handshake has completed, check authentication */
3161         if (!rc->use_cert) {
3162                 verbose(VERB_ALGO, "unauthenticated remote control connection");
3163         } else if(SSL_get_verify_result(s->ssl) == X509_V_OK) {
3164                 X509* x = SSL_get_peer_certificate(s->ssl);
3165                 if(!x) {
3166                         verbose(VERB_DETAIL, "remote control connection "
3167                                 "provided no client certificate");
3168                         clean_point(rc, s);
3169                         return 0;
3170                 }
3171                 verbose(VERB_ALGO, "remote control connection authenticated");
3172                 X509_free(x);
3173         } else {
3174                 verbose(VERB_DETAIL, "remote control connection failed to "
3175                         "authenticate with client certificate");
3176                 clean_point(rc, s);
3177                 return 0;
3178         }
3179
3180         /* if OK start to actually handle the request */
3181         res.ssl = s->ssl;
3182         res.fd = c->fd;
3183         handle_req(rc, s, &res);
3184
3185         verbose(VERB_ALGO, "remote control operation completed");
3186         clean_point(rc, s);
3187         return 0;
3188 }