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