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