]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/unbound/daemon/remote.c
openssh: cherry-pick OpenSSL 1.1.1 compatibility
[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.ipv6"SQ"%lu\n", 
970                 (unsigned long)s->svr.qipv6)) return 0;
971         /* flags */
972         if(!ssl_printf(ssl, "num.query.flags.QR"SQ"%lu\n", 
973                 (unsigned long)s->svr.qbit_QR)) return 0;
974         if(!ssl_printf(ssl, "num.query.flags.AA"SQ"%lu\n", 
975                 (unsigned long)s->svr.qbit_AA)) return 0;
976         if(!ssl_printf(ssl, "num.query.flags.TC"SQ"%lu\n", 
977                 (unsigned long)s->svr.qbit_TC)) return 0;
978         if(!ssl_printf(ssl, "num.query.flags.RD"SQ"%lu\n", 
979                 (unsigned long)s->svr.qbit_RD)) return 0;
980         if(!ssl_printf(ssl, "num.query.flags.RA"SQ"%lu\n", 
981                 (unsigned long)s->svr.qbit_RA)) return 0;
982         if(!ssl_printf(ssl, "num.query.flags.Z"SQ"%lu\n", 
983                 (unsigned long)s->svr.qbit_Z)) return 0;
984         if(!ssl_printf(ssl, "num.query.flags.AD"SQ"%lu\n", 
985                 (unsigned long)s->svr.qbit_AD)) return 0;
986         if(!ssl_printf(ssl, "num.query.flags.CD"SQ"%lu\n", 
987                 (unsigned long)s->svr.qbit_CD)) return 0;
988         if(!ssl_printf(ssl, "num.query.edns.present"SQ"%lu\n", 
989                 (unsigned long)s->svr.qEDNS)) return 0;
990         if(!ssl_printf(ssl, "num.query.edns.DO"SQ"%lu\n", 
991                 (unsigned long)s->svr.qEDNS_DO)) return 0;
992
993         /* RCODE */
994         for(i=0; i<UB_STATS_RCODE_NUM; i++) {
995                 /* Always include RCODEs 0-5 */
996                 if(inhibit_zero && i > LDNS_RCODE_REFUSED && s->svr.ans_rcode[i] == 0)
997                         continue;
998                 lt = sldns_lookup_by_id(sldns_rcodes, i);
999                 if(lt && lt->name) {
1000                         snprintf(nm, sizeof(nm), "%s", lt->name);
1001                 } else {
1002                         snprintf(nm, sizeof(nm), "RCODE%d", i);
1003                 }
1004                 if(!ssl_printf(ssl, "num.answer.rcode.%s"SQ"%lu\n", 
1005                         nm, (unsigned long)s->svr.ans_rcode[i])) return 0;
1006         }
1007         if(!inhibit_zero || s->svr.ans_rcode_nodata) {
1008                 if(!ssl_printf(ssl, "num.answer.rcode.nodata"SQ"%lu\n", 
1009                         (unsigned long)s->svr.ans_rcode_nodata)) return 0;
1010         }
1011         /* iteration */
1012         if(!ssl_printf(ssl, "num.query.ratelimited"SQ"%lu\n", 
1013                 (unsigned long)s->svr.queries_ratelimited)) return 0;
1014         /* validation */
1015         if(!ssl_printf(ssl, "num.answer.secure"SQ"%lu\n", 
1016                 (unsigned long)s->svr.ans_secure)) return 0;
1017         if(!ssl_printf(ssl, "num.answer.bogus"SQ"%lu\n", 
1018                 (unsigned long)s->svr.ans_bogus)) return 0;
1019         if(!ssl_printf(ssl, "num.rrset.bogus"SQ"%lu\n", 
1020                 (unsigned long)s->svr.rrset_bogus)) return 0;
1021         if(!ssl_printf(ssl, "num.query.aggressive.NOERROR"SQ"%lu\n", 
1022                 (unsigned long)s->svr.num_neg_cache_noerror)) return 0;
1023         if(!ssl_printf(ssl, "num.query.aggressive.NXDOMAIN"SQ"%lu\n", 
1024                 (unsigned long)s->svr.num_neg_cache_nxdomain)) return 0;
1025         /* threat detection */
1026         if(!ssl_printf(ssl, "unwanted.queries"SQ"%lu\n", 
1027                 (unsigned long)s->svr.unwanted_queries)) return 0;
1028         if(!ssl_printf(ssl, "unwanted.replies"SQ"%lu\n", 
1029                 (unsigned long)s->svr.unwanted_replies)) return 0;
1030         /* cache counts */
1031         if(!ssl_printf(ssl, "msg.cache.count"SQ"%u\n",
1032                 (unsigned)s->svr.msg_cache_count)) return 0;
1033         if(!ssl_printf(ssl, "rrset.cache.count"SQ"%u\n",
1034                 (unsigned)s->svr.rrset_cache_count)) return 0;
1035         if(!ssl_printf(ssl, "infra.cache.count"SQ"%u\n",
1036                 (unsigned)s->svr.infra_cache_count)) return 0;
1037         if(!ssl_printf(ssl, "key.cache.count"SQ"%u\n",
1038                 (unsigned)s->svr.key_cache_count)) return 0;
1039 #ifdef USE_DNSCRYPT
1040         if(!ssl_printf(ssl, "dnscrypt_shared_secret.cache.count"SQ"%u\n",
1041                 (unsigned)s->svr.shared_secret_cache_count)) return 0;
1042         if(!ssl_printf(ssl, "dnscrypt_nonce.cache.count"SQ"%u\n",
1043                 (unsigned)s->svr.nonce_cache_count)) return 0;
1044         if(!ssl_printf(ssl, "num.query.dnscrypt.shared_secret.cachemiss"SQ"%lu\n",
1045                 (unsigned long)s->svr.num_query_dnscrypt_secret_missed_cache)) return 0;
1046         if(!ssl_printf(ssl, "num.query.dnscrypt.replay"SQ"%lu\n",
1047                 (unsigned long)s->svr.num_query_dnscrypt_replay)) return 0;
1048 #endif /* USE_DNSCRYPT */
1049         if(!ssl_printf(ssl, "num.query.authzone.up"SQ"%lu\n",
1050                 (unsigned long)s->svr.num_query_authzone_up)) return 0;
1051         if(!ssl_printf(ssl, "num.query.authzone.down"SQ"%lu\n",
1052                 (unsigned long)s->svr.num_query_authzone_down)) return 0;
1053         return 1;
1054 }
1055
1056 /** do the stats command */
1057 static void
1058 do_stats(RES* ssl, struct daemon_remote* rc, int reset)
1059 {
1060         struct daemon* daemon = rc->worker->daemon;
1061         struct ub_stats_info total;
1062         struct ub_stats_info s;
1063         int i;
1064         log_assert(daemon->num > 0);
1065         /* gather all thread statistics in one place */
1066         for(i=0; i<daemon->num; i++) {
1067                 server_stats_obtain(rc->worker, daemon->workers[i], &s, reset);
1068                 if(!print_thread_stats(ssl, i, &s))
1069                         return;
1070                 if(i == 0)
1071                         total = s;
1072                 else    server_stats_add(&total, &s);
1073         }
1074         /* print the thread statistics */
1075         total.mesh_time_median /= (double)daemon->num;
1076         if(!print_stats(ssl, "total", &total)) 
1077                 return;
1078         if(!print_uptime(ssl, rc->worker, reset))
1079                 return;
1080         if(daemon->cfg->stat_extended) {
1081                 if(!print_mem(ssl, rc->worker, daemon)) 
1082                         return;
1083                 if(!print_hist(ssl, &total))
1084                         return;
1085                 if(!print_ext(ssl, &total))
1086                         return;
1087         }
1088 }
1089
1090 /** parse commandline argument domain name */
1091 static int
1092 parse_arg_name(RES* ssl, char* str, uint8_t** res, size_t* len, int* labs)
1093 {
1094         uint8_t nm[LDNS_MAX_DOMAINLEN+1];
1095         size_t nmlen = sizeof(nm);
1096         int status;
1097         *res = NULL;
1098         *len = 0;
1099         *labs = 0;
1100         status = sldns_str2wire_dname_buf(str, nm, &nmlen);
1101         if(status != 0) {
1102                 ssl_printf(ssl, "error cannot parse name %s at %d: %s\n", str,
1103                         LDNS_WIREPARSE_OFFSET(status),
1104                         sldns_get_errorstr_parse(status));
1105                 return 0;
1106         }
1107         *res = memdup(nm, nmlen);
1108         if(!*res) {
1109                 ssl_printf(ssl, "error out of memory\n");
1110                 return 0;
1111         }
1112         *labs = dname_count_size_labels(*res, len);
1113         return 1;
1114 }
1115
1116 /** find second argument, modifies string */
1117 static int
1118 find_arg2(RES* ssl, char* arg, char** arg2)
1119 {
1120         char* as = strchr(arg, ' ');
1121         char* at = strchr(arg, '\t');
1122         if(as && at) {
1123                 if(at < as)
1124                         as = at;
1125                 as[0]=0;
1126                 *arg2 = skipwhite(as+1);
1127         } else if(as) {
1128                 as[0]=0;
1129                 *arg2 = skipwhite(as+1);
1130         } else if(at) {
1131                 at[0]=0;
1132                 *arg2 = skipwhite(at+1);
1133         } else {
1134                 ssl_printf(ssl, "error could not find next argument "
1135                         "after %s\n", arg);
1136                 return 0;
1137         }
1138         return 1;
1139 }
1140
1141 /** Add a new zone */
1142 static int
1143 perform_zone_add(RES* ssl, struct local_zones* zones, char* arg)
1144 {
1145         uint8_t* nm;
1146         int nmlabs;
1147         size_t nmlen;
1148         char* arg2;
1149         enum localzone_type t;
1150         struct local_zone* z;
1151         if(!find_arg2(ssl, arg, &arg2))
1152                 return 0;
1153         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1154                 return 0;
1155         if(!local_zone_str2type(arg2, &t)) {
1156                 ssl_printf(ssl, "error not a zone type. %s\n", arg2);
1157                 free(nm);
1158                 return 0;
1159         }
1160         lock_rw_wrlock(&zones->lock);
1161         if((z=local_zones_find(zones, nm, nmlen, 
1162                 nmlabs, LDNS_RR_CLASS_IN))) {
1163                 /* already present in tree */
1164                 lock_rw_wrlock(&z->lock);
1165                 z->type = t; /* update type anyway */
1166                 lock_rw_unlock(&z->lock);
1167                 free(nm);
1168                 lock_rw_unlock(&zones->lock);
1169                 return 1;
1170         }
1171         if(!local_zones_add_zone(zones, nm, nmlen, 
1172                 nmlabs, LDNS_RR_CLASS_IN, t)) {
1173                 lock_rw_unlock(&zones->lock);
1174                 ssl_printf(ssl, "error out of memory\n");
1175                 return 0;
1176         }
1177         lock_rw_unlock(&zones->lock);
1178         return 1;
1179 }
1180
1181 /** Do the local_zone command */
1182 static void
1183 do_zone_add(RES* ssl, struct local_zones* zones, char* arg)
1184 {
1185         if(!perform_zone_add(ssl, zones, arg))
1186                 return;
1187         send_ok(ssl);
1188 }
1189
1190 /** Do the local_zones command */
1191 static void
1192 do_zones_add(RES* ssl, struct local_zones* zones)
1193 {
1194         char buf[2048];
1195         int num = 0;
1196         while(ssl_read_line(ssl, buf, sizeof(buf))) {
1197                 if(buf[0] == 0x04 && buf[1] == 0)
1198                         break; /* end of transmission */
1199                 if(!perform_zone_add(ssl, zones, buf)) {
1200                         if(!ssl_printf(ssl, "error for input line: %s\n", buf))
1201                                 return;
1202                 }
1203                 else
1204                         num++;
1205         }
1206         (void)ssl_printf(ssl, "added %d zones\n", num);
1207 }
1208
1209 /** Remove a zone */
1210 static int
1211 perform_zone_remove(RES* ssl, struct local_zones* zones, char* arg)
1212 {
1213         uint8_t* nm;
1214         int nmlabs;
1215         size_t nmlen;
1216         struct local_zone* z;
1217         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1218                 return 0;
1219         lock_rw_wrlock(&zones->lock);
1220         if((z=local_zones_find(zones, nm, nmlen, 
1221                 nmlabs, LDNS_RR_CLASS_IN))) {
1222                 /* present in tree */
1223                 local_zones_del_zone(zones, z);
1224         }
1225         lock_rw_unlock(&zones->lock);
1226         free(nm);
1227         return 1;
1228 }
1229
1230 /** Do the local_zone_remove command */
1231 static void
1232 do_zone_remove(RES* ssl, struct local_zones* zones, char* arg)
1233 {
1234         if(!perform_zone_remove(ssl, zones, arg))
1235                 return;
1236         send_ok(ssl);
1237 }
1238
1239 /** Do the local_zones_remove command */
1240 static void
1241 do_zones_remove(RES* ssl, struct local_zones* zones)
1242 {
1243         char buf[2048];
1244         int num = 0;
1245         while(ssl_read_line(ssl, buf, sizeof(buf))) {
1246                 if(buf[0] == 0x04 && buf[1] == 0)
1247                         break; /* end of transmission */
1248                 if(!perform_zone_remove(ssl, zones, buf)) {
1249                         if(!ssl_printf(ssl, "error for input line: %s\n", buf))
1250                                 return;
1251                 }
1252                 else
1253                         num++;
1254         }
1255         (void)ssl_printf(ssl, "removed %d zones\n", num);
1256 }
1257
1258 /** Add new RR data */
1259 static int
1260 perform_data_add(RES* ssl, struct local_zones* zones, char* arg)
1261 {
1262         if(!local_zones_add_RR(zones, arg)) {
1263                 ssl_printf(ssl,"error in syntax or out of memory, %s\n", arg);
1264                 return 0;
1265         }
1266         return 1;
1267 }
1268
1269 /** Do the local_data command */
1270 static void
1271 do_data_add(RES* ssl, struct local_zones* zones, char* arg)
1272 {
1273         if(!perform_data_add(ssl, zones, arg))
1274                 return;
1275         send_ok(ssl);
1276 }
1277
1278 /** Do the local_datas command */
1279 static void
1280 do_datas_add(RES* ssl, struct local_zones* zones)
1281 {
1282         char buf[2048];
1283         int num = 0;
1284         while(ssl_read_line(ssl, buf, sizeof(buf))) {
1285                 if(buf[0] == 0x04 && buf[1] == 0)
1286                         break; /* end of transmission */
1287                 if(!perform_data_add(ssl, zones, buf)) {
1288                         if(!ssl_printf(ssl, "error for input line: %s\n", buf))
1289                                 return;
1290                 }
1291                 else
1292                         num++;
1293         }
1294         (void)ssl_printf(ssl, "added %d datas\n", num);
1295 }
1296
1297 /** Remove RR data */
1298 static int
1299 perform_data_remove(RES* ssl, struct local_zones* zones, char* arg)
1300 {
1301         uint8_t* nm;
1302         int nmlabs;
1303         size_t nmlen;
1304         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1305                 return 0;
1306         local_zones_del_data(zones, nm,
1307                 nmlen, nmlabs, LDNS_RR_CLASS_IN);
1308         free(nm);
1309         return 1;
1310 }
1311
1312 /** Do the local_data_remove command */
1313 static void
1314 do_data_remove(RES* ssl, struct local_zones* zones, char* arg)
1315 {
1316         if(!perform_data_remove(ssl, zones, arg))
1317                 return;
1318         send_ok(ssl);
1319 }
1320
1321 /** Do the local_datas_remove command */
1322 static void
1323 do_datas_remove(RES* ssl, struct local_zones* zones)
1324 {
1325         char buf[2048];
1326         int num = 0;
1327         while(ssl_read_line(ssl, buf, sizeof(buf))) {
1328                 if(buf[0] == 0x04 && buf[1] == 0)
1329                         break; /* end of transmission */
1330                 if(!perform_data_remove(ssl, zones, buf)) {
1331                         if(!ssl_printf(ssl, "error for input line: %s\n", buf))
1332                                 return;
1333                 }
1334                 else
1335                         num++;
1336         }
1337         (void)ssl_printf(ssl, "removed %d datas\n", num);
1338 }
1339
1340 /** Add a new zone to view */
1341 static void
1342 do_view_zone_add(RES* ssl, struct worker* worker, char* arg)
1343 {
1344         char* arg2;
1345         struct view* v;
1346         if(!find_arg2(ssl, arg, &arg2))
1347                 return;
1348         v = views_find_view(worker->daemon->views,
1349                 arg, 1 /* get write lock*/);
1350         if(!v) {
1351                 ssl_printf(ssl,"no view with name: %s\n", arg);
1352                 return;
1353         }
1354         if(!v->local_zones) {
1355                 if(!(v->local_zones = local_zones_create())){
1356                         lock_rw_unlock(&v->lock);
1357                         ssl_printf(ssl,"error out of memory\n");
1358                         return;
1359                 }
1360                 if(!v->isfirst) {
1361                         /* Global local-zone is not used for this view,
1362                          * therefore add defaults to this view-specic
1363                          * local-zone. */
1364                         struct config_file lz_cfg;
1365                         memset(&lz_cfg, 0, sizeof(lz_cfg));
1366                         local_zone_enter_defaults(v->local_zones, &lz_cfg);
1367                 }
1368         }
1369         do_zone_add(ssl, v->local_zones, arg2);
1370         lock_rw_unlock(&v->lock);
1371 }
1372
1373 /** Remove a zone from view */
1374 static void
1375 do_view_zone_remove(RES* ssl, struct worker* worker, char* arg)
1376 {
1377         char* arg2;
1378         struct view* v;
1379         if(!find_arg2(ssl, arg, &arg2))
1380                 return;
1381         v = views_find_view(worker->daemon->views,
1382                 arg, 1 /* get write lock*/);
1383         if(!v) {
1384                 ssl_printf(ssl,"no view with name: %s\n", arg);
1385                 return;
1386         }
1387         if(!v->local_zones) {
1388                 lock_rw_unlock(&v->lock);
1389                 send_ok(ssl);
1390                 return;
1391         }
1392         do_zone_remove(ssl, v->local_zones, arg2);
1393         lock_rw_unlock(&v->lock);
1394 }
1395
1396 /** Add new RR data to view */
1397 static void
1398 do_view_data_add(RES* ssl, struct worker* worker, char* arg)
1399 {
1400         char* arg2;
1401         struct view* v;
1402         if(!find_arg2(ssl, arg, &arg2))
1403                 return;
1404         v = views_find_view(worker->daemon->views,
1405                 arg, 1 /* get write lock*/);
1406         if(!v) {
1407                 ssl_printf(ssl,"no view with name: %s\n", arg);
1408                 return;
1409         }
1410         if(!v->local_zones) {
1411                 if(!(v->local_zones = local_zones_create())){
1412                         lock_rw_unlock(&v->lock);
1413                         ssl_printf(ssl,"error out of memory\n");
1414                         return;
1415                 }
1416         }
1417         do_data_add(ssl, v->local_zones, arg2);
1418         lock_rw_unlock(&v->lock);
1419 }
1420
1421 /** Remove RR data from view */
1422 static void
1423 do_view_data_remove(RES* ssl, struct worker* worker, char* arg)
1424 {
1425         char* arg2;
1426         struct view* v;
1427         if(!find_arg2(ssl, arg, &arg2))
1428                 return;
1429         v = views_find_view(worker->daemon->views,
1430                 arg, 1 /* get write lock*/);
1431         if(!v) {
1432                 ssl_printf(ssl,"no view with name: %s\n", arg);
1433                 return;
1434         }
1435         if(!v->local_zones) {
1436                 lock_rw_unlock(&v->lock);
1437                 send_ok(ssl);
1438                 return;
1439         }
1440         do_data_remove(ssl, v->local_zones, arg2);
1441         lock_rw_unlock(&v->lock);
1442 }
1443
1444 /** cache lookup of nameservers */
1445 static void
1446 do_lookup(RES* ssl, struct worker* worker, char* arg)
1447 {
1448         uint8_t* nm;
1449         int nmlabs;
1450         size_t nmlen;
1451         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1452                 return;
1453         (void)print_deleg_lookup(ssl, worker, nm, nmlen, nmlabs);
1454         free(nm);
1455 }
1456
1457 /** flush something from rrset and msg caches */
1458 static void
1459 do_cache_remove(struct worker* worker, uint8_t* nm, size_t nmlen,
1460         uint16_t t, uint16_t c)
1461 {
1462         hashvalue_type h;
1463         struct query_info k;
1464         rrset_cache_remove(worker->env.rrset_cache, nm, nmlen, t, c, 0);
1465         if(t == LDNS_RR_TYPE_SOA)
1466                 rrset_cache_remove(worker->env.rrset_cache, nm, nmlen, t, c,
1467                         PACKED_RRSET_SOA_NEG);
1468         k.qname = nm;
1469         k.qname_len = nmlen;
1470         k.qtype = t;
1471         k.qclass = c;
1472         k.local_alias = NULL;
1473         h = query_info_hash(&k, 0);
1474         slabhash_remove(worker->env.msg_cache, h, &k);
1475         if(t == LDNS_RR_TYPE_AAAA) {
1476                 /* for AAAA also flush dns64 bit_cd packet */
1477                 h = query_info_hash(&k, BIT_CD);
1478                 slabhash_remove(worker->env.msg_cache, h, &k);
1479         }
1480 }
1481
1482 /** flush a type */
1483 static void
1484 do_flush_type(RES* ssl, struct worker* worker, char* arg)
1485 {
1486         uint8_t* nm;
1487         int nmlabs;
1488         size_t nmlen;
1489         char* arg2;
1490         uint16_t t;
1491         if(!find_arg2(ssl, arg, &arg2))
1492                 return;
1493         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1494                 return;
1495         t = sldns_get_rr_type_by_name(arg2);
1496         do_cache_remove(worker, nm, nmlen, t, LDNS_RR_CLASS_IN);
1497         
1498         free(nm);
1499         send_ok(ssl);
1500 }
1501
1502 /** flush statistics */
1503 static void
1504 do_flush_stats(RES* ssl, struct worker* worker)
1505 {
1506         worker_stats_clear(worker);
1507         send_ok(ssl);
1508 }
1509
1510 /**
1511  * Local info for deletion functions
1512  */
1513 struct del_info {
1514         /** worker */
1515         struct worker* worker;
1516         /** name to delete */
1517         uint8_t* name;
1518         /** length */
1519         size_t len;
1520         /** labels */
1521         int labs;
1522         /** time to invalidate to */
1523         time_t expired;
1524         /** number of rrsets removed */
1525         size_t num_rrsets;
1526         /** number of msgs removed */
1527         size_t num_msgs;
1528         /** number of key entries removed */
1529         size_t num_keys;
1530         /** length of addr */
1531         socklen_t addrlen;
1532         /** socket address for host deletion */
1533         struct sockaddr_storage addr;
1534 };
1535
1536 /** callback to delete hosts in infra cache */
1537 static void
1538 infra_del_host(struct lruhash_entry* e, void* arg)
1539 {
1540         /* entry is locked */
1541         struct del_info* inf = (struct del_info*)arg;
1542         struct infra_key* k = (struct infra_key*)e->key;
1543         if(sockaddr_cmp(&inf->addr, inf->addrlen, &k->addr, k->addrlen) == 0) {
1544                 struct infra_data* d = (struct infra_data*)e->data;
1545                 d->probedelay = 0;
1546                 d->timeout_A = 0;
1547                 d->timeout_AAAA = 0;
1548                 d->timeout_other = 0;
1549                 rtt_init(&d->rtt);
1550                 if(d->ttl > inf->expired) {
1551                         d->ttl = inf->expired;
1552                         inf->num_keys++;
1553                 }
1554         }
1555 }
1556
1557 /** flush infra cache */
1558 static void
1559 do_flush_infra(RES* ssl, struct worker* worker, char* arg)
1560 {
1561         struct sockaddr_storage addr;
1562         socklen_t len;
1563         struct del_info inf;
1564         if(strcmp(arg, "all") == 0) {
1565                 slabhash_clear(worker->env.infra_cache->hosts);
1566                 send_ok(ssl);
1567                 return;
1568         }
1569         if(!ipstrtoaddr(arg, UNBOUND_DNS_PORT, &addr, &len)) {
1570                 (void)ssl_printf(ssl, "error parsing ip addr: '%s'\n", arg);
1571                 return;
1572         }
1573         /* delete all entries from cache */
1574         /* what we do is to set them all expired */
1575         inf.worker = worker;
1576         inf.name = 0;
1577         inf.len = 0;
1578         inf.labs = 0;
1579         inf.expired = *worker->env.now;
1580         inf.expired -= 3; /* handle 3 seconds skew between threads */
1581         inf.num_rrsets = 0;
1582         inf.num_msgs = 0;
1583         inf.num_keys = 0;
1584         inf.addrlen = len;
1585         memmove(&inf.addr, &addr, len);
1586         slabhash_traverse(worker->env.infra_cache->hosts, 1, &infra_del_host,
1587                 &inf);
1588         send_ok(ssl);
1589 }
1590
1591 /** flush requestlist */
1592 static void
1593 do_flush_requestlist(RES* ssl, struct worker* worker)
1594 {
1595         mesh_delete_all(worker->env.mesh);
1596         send_ok(ssl);
1597 }
1598
1599 /** callback to delete rrsets in a zone */
1600 static void
1601 zone_del_rrset(struct lruhash_entry* e, void* arg)
1602 {
1603         /* entry is locked */
1604         struct del_info* inf = (struct del_info*)arg;
1605         struct ub_packed_rrset_key* k = (struct ub_packed_rrset_key*)e->key;
1606         if(dname_subdomain_c(k->rk.dname, inf->name)) {
1607                 struct packed_rrset_data* d = 
1608                         (struct packed_rrset_data*)e->data;
1609                 if(d->ttl > inf->expired) {
1610                         d->ttl = inf->expired;
1611                         inf->num_rrsets++;
1612                 }
1613         }
1614 }
1615
1616 /** callback to delete messages in a zone */
1617 static void
1618 zone_del_msg(struct lruhash_entry* e, void* arg)
1619 {
1620         /* entry is locked */
1621         struct del_info* inf = (struct del_info*)arg;
1622         struct msgreply_entry* k = (struct msgreply_entry*)e->key;
1623         if(dname_subdomain_c(k->key.qname, inf->name)) {
1624                 struct reply_info* d = (struct reply_info*)e->data;
1625                 if(d->ttl > inf->expired) {
1626                         d->ttl = inf->expired;
1627                         d->prefetch_ttl = inf->expired;
1628                         inf->num_msgs++;
1629                 }
1630         }
1631 }
1632
1633 /** callback to delete keys in zone */
1634 static void
1635 zone_del_kcache(struct lruhash_entry* e, void* arg)
1636 {
1637         /* entry is locked */
1638         struct del_info* inf = (struct del_info*)arg;
1639         struct key_entry_key* k = (struct key_entry_key*)e->key;
1640         if(dname_subdomain_c(k->name, inf->name)) {
1641                 struct key_entry_data* d = (struct key_entry_data*)e->data;
1642                 if(d->ttl > inf->expired) {
1643                         d->ttl = inf->expired;
1644                         inf->num_keys++;
1645                 }
1646         }
1647 }
1648
1649 /** remove all rrsets and keys from zone from cache */
1650 static void
1651 do_flush_zone(RES* ssl, struct worker* worker, char* arg)
1652 {
1653         uint8_t* nm;
1654         int nmlabs;
1655         size_t nmlen;
1656         struct del_info inf;
1657         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1658                 return;
1659         /* delete all RRs and key entries from zone */
1660         /* what we do is to set them all expired */
1661         inf.worker = worker;
1662         inf.name = nm;
1663         inf.len = nmlen;
1664         inf.labs = nmlabs;
1665         inf.expired = *worker->env.now;
1666         inf.expired -= 3; /* handle 3 seconds skew between threads */
1667         inf.num_rrsets = 0;
1668         inf.num_msgs = 0;
1669         inf.num_keys = 0;
1670         slabhash_traverse(&worker->env.rrset_cache->table, 1, 
1671                 &zone_del_rrset, &inf);
1672
1673         slabhash_traverse(worker->env.msg_cache, 1, &zone_del_msg, &inf);
1674
1675         /* and validator cache */
1676         if(worker->env.key_cache) {
1677                 slabhash_traverse(worker->env.key_cache->slab, 1, 
1678                         &zone_del_kcache, &inf);
1679         }
1680
1681         free(nm);
1682
1683         (void)ssl_printf(ssl, "ok removed %lu rrsets, %lu messages "
1684                 "and %lu key entries\n", (unsigned long)inf.num_rrsets, 
1685                 (unsigned long)inf.num_msgs, (unsigned long)inf.num_keys);
1686 }
1687
1688 /** callback to delete bogus rrsets */
1689 static void
1690 bogus_del_rrset(struct lruhash_entry* e, void* arg)
1691 {
1692         /* entry is locked */
1693         struct del_info* inf = (struct del_info*)arg;
1694         struct packed_rrset_data* d = (struct packed_rrset_data*)e->data;
1695         if(d->security == sec_status_bogus) {
1696                 d->ttl = inf->expired;
1697                 inf->num_rrsets++;
1698         }
1699 }
1700
1701 /** callback to delete bogus messages */
1702 static void
1703 bogus_del_msg(struct lruhash_entry* e, void* arg)
1704 {
1705         /* entry is locked */
1706         struct del_info* inf = (struct del_info*)arg;
1707         struct reply_info* d = (struct reply_info*)e->data;
1708         if(d->security == sec_status_bogus) {
1709                 d->ttl = inf->expired;
1710                 inf->num_msgs++;
1711         }
1712 }
1713
1714 /** callback to delete bogus keys */
1715 static void
1716 bogus_del_kcache(struct lruhash_entry* e, void* arg)
1717 {
1718         /* entry is locked */
1719         struct del_info* inf = (struct del_info*)arg;
1720         struct key_entry_data* d = (struct key_entry_data*)e->data;
1721         if(d->isbad) {
1722                 d->ttl = inf->expired;
1723                 inf->num_keys++;
1724         }
1725 }
1726
1727 /** remove all bogus rrsets, msgs and keys from cache */
1728 static void
1729 do_flush_bogus(RES* ssl, struct worker* worker)
1730 {
1731         struct del_info inf;
1732         /* what we do is to set them all expired */
1733         inf.worker = worker;
1734         inf.expired = *worker->env.now;
1735         inf.expired -= 3; /* handle 3 seconds skew between threads */
1736         inf.num_rrsets = 0;
1737         inf.num_msgs = 0;
1738         inf.num_keys = 0;
1739         slabhash_traverse(&worker->env.rrset_cache->table, 1, 
1740                 &bogus_del_rrset, &inf);
1741
1742         slabhash_traverse(worker->env.msg_cache, 1, &bogus_del_msg, &inf);
1743
1744         /* and validator cache */
1745         if(worker->env.key_cache) {
1746                 slabhash_traverse(worker->env.key_cache->slab, 1, 
1747                         &bogus_del_kcache, &inf);
1748         }
1749
1750         (void)ssl_printf(ssl, "ok removed %lu rrsets, %lu messages "
1751                 "and %lu key entries\n", (unsigned long)inf.num_rrsets, 
1752                 (unsigned long)inf.num_msgs, (unsigned long)inf.num_keys);
1753 }
1754
1755 /** callback to delete negative and servfail rrsets */
1756 static void
1757 negative_del_rrset(struct lruhash_entry* e, void* arg)
1758 {
1759         /* entry is locked */
1760         struct del_info* inf = (struct del_info*)arg;
1761         struct ub_packed_rrset_key* k = (struct ub_packed_rrset_key*)e->key;
1762         struct packed_rrset_data* d = (struct packed_rrset_data*)e->data;
1763         /* delete the parentside negative cache rrsets,
1764          * these are nameserver rrsets that failed lookup, rdata empty */
1765         if((k->rk.flags & PACKED_RRSET_PARENT_SIDE) && d->count == 1 &&
1766                 d->rrsig_count == 0 && d->rr_len[0] == 0) {
1767                 d->ttl = inf->expired;
1768                 inf->num_rrsets++;
1769         }
1770 }
1771
1772 /** callback to delete negative and servfail messages */
1773 static void
1774 negative_del_msg(struct lruhash_entry* e, void* arg)
1775 {
1776         /* entry is locked */
1777         struct del_info* inf = (struct del_info*)arg;
1778         struct reply_info* d = (struct reply_info*)e->data;
1779         /* rcode not NOERROR: NXDOMAIN, SERVFAIL, ..: an nxdomain or error
1780          * or NOERROR rcode with ANCOUNT==0: a NODATA answer */
1781         if(FLAGS_GET_RCODE(d->flags) != 0 || d->an_numrrsets == 0) {
1782                 d->ttl = inf->expired;
1783                 inf->num_msgs++;
1784         }
1785 }
1786
1787 /** callback to delete negative key entries */
1788 static void
1789 negative_del_kcache(struct lruhash_entry* e, void* arg)
1790 {
1791         /* entry is locked */
1792         struct del_info* inf = (struct del_info*)arg;
1793         struct key_entry_data* d = (struct key_entry_data*)e->data;
1794         /* could be bad because of lookup failure on the DS, DNSKEY, which
1795          * was nxdomain or servfail, and thus a result of negative lookups */
1796         if(d->isbad) {
1797                 d->ttl = inf->expired;
1798                 inf->num_keys++;
1799         }
1800 }
1801
1802 /** remove all negative(NODATA,NXDOMAIN), and servfail messages from cache */
1803 static void
1804 do_flush_negative(RES* ssl, struct worker* worker)
1805 {
1806         struct del_info inf;
1807         /* what we do is to set them all expired */
1808         inf.worker = worker;
1809         inf.expired = *worker->env.now;
1810         inf.expired -= 3; /* handle 3 seconds skew between threads */
1811         inf.num_rrsets = 0;
1812         inf.num_msgs = 0;
1813         inf.num_keys = 0;
1814         slabhash_traverse(&worker->env.rrset_cache->table, 1, 
1815                 &negative_del_rrset, &inf);
1816
1817         slabhash_traverse(worker->env.msg_cache, 1, &negative_del_msg, &inf);
1818
1819         /* and validator cache */
1820         if(worker->env.key_cache) {
1821                 slabhash_traverse(worker->env.key_cache->slab, 1, 
1822                         &negative_del_kcache, &inf);
1823         }
1824
1825         (void)ssl_printf(ssl, "ok removed %lu rrsets, %lu messages "
1826                 "and %lu key entries\n", (unsigned long)inf.num_rrsets, 
1827                 (unsigned long)inf.num_msgs, (unsigned long)inf.num_keys);
1828 }
1829
1830 /** remove name rrset from cache */
1831 static void
1832 do_flush_name(RES* ssl, struct worker* w, char* arg)
1833 {
1834         uint8_t* nm;
1835         int nmlabs;
1836         size_t nmlen;
1837         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
1838                 return;
1839         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_A, LDNS_RR_CLASS_IN);
1840         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_AAAA, LDNS_RR_CLASS_IN);
1841         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_NS, LDNS_RR_CLASS_IN);
1842         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SOA, LDNS_RR_CLASS_IN);
1843         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_CNAME, LDNS_RR_CLASS_IN);
1844         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_DNAME, LDNS_RR_CLASS_IN);
1845         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_MX, LDNS_RR_CLASS_IN);
1846         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_PTR, LDNS_RR_CLASS_IN);
1847         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SRV, LDNS_RR_CLASS_IN);
1848         do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_NAPTR, LDNS_RR_CLASS_IN);
1849         
1850         free(nm);
1851         send_ok(ssl);
1852 }
1853
1854 /** printout a delegation point info */
1855 static int
1856 ssl_print_name_dp(RES* ssl, const char* str, uint8_t* nm, uint16_t dclass,
1857         struct delegpt* dp)
1858 {
1859         char buf[257];
1860         struct delegpt_ns* ns;
1861         struct delegpt_addr* a;
1862         int f = 0;
1863         if(str) { /* print header for forward, stub */
1864                 char* c = sldns_wire2str_class(dclass);
1865                 dname_str(nm, buf);
1866                 if(!ssl_printf(ssl, "%s %s %s ", buf, (c?c:"CLASS??"), str)) {
1867                         free(c);
1868                         return 0;
1869                 }
1870                 free(c);
1871         }
1872         for(ns = dp->nslist; ns; ns = ns->next) {
1873                 dname_str(ns->name, buf);
1874                 if(!ssl_printf(ssl, "%s%s", (f?" ":""), buf))
1875                         return 0;
1876                 f = 1;
1877         }
1878         for(a = dp->target_list; a; a = a->next_target) {
1879                 addr_to_str(&a->addr, a->addrlen, buf, sizeof(buf));
1880                 if(!ssl_printf(ssl, "%s%s", (f?" ":""), buf))
1881                         return 0;
1882                 f = 1;
1883         }
1884         return ssl_printf(ssl, "\n");
1885 }
1886
1887
1888 /** print root forwards */
1889 static int
1890 print_root_fwds(RES* ssl, struct iter_forwards* fwds, uint8_t* root)
1891 {
1892         struct delegpt* dp;
1893         dp = forwards_lookup(fwds, root, LDNS_RR_CLASS_IN);
1894         if(!dp)
1895                 return ssl_printf(ssl, "off (using root hints)\n");
1896         /* if dp is returned it must be the root */
1897         log_assert(query_dname_compare(dp->name, root)==0);
1898         return ssl_print_name_dp(ssl, NULL, root, LDNS_RR_CLASS_IN, dp);
1899 }
1900
1901 /** parse args into delegpt */
1902 static struct delegpt*
1903 parse_delegpt(RES* ssl, char* args, uint8_t* nm, int allow_names)
1904 {
1905         /* parse args and add in */
1906         char* p = args;
1907         char* todo;
1908         struct delegpt* dp = delegpt_create_mlc(nm);
1909         struct sockaddr_storage addr;
1910         socklen_t addrlen;
1911         char* auth_name;
1912         if(!dp) {
1913                 (void)ssl_printf(ssl, "error out of memory\n");
1914                 return NULL;
1915         }
1916         while(p) {
1917                 todo = p;
1918                 p = strchr(p, ' '); /* find next spot, if any */
1919                 if(p) {
1920                         *p++ = 0;       /* end this spot */
1921                         p = skipwhite(p); /* position at next spot */
1922                 }
1923                 /* parse address */
1924                 if(!authextstrtoaddr(todo, &addr, &addrlen, &auth_name)) {
1925                         if(allow_names) {
1926                                 uint8_t* n = NULL;
1927                                 size_t ln;
1928                                 int lb;
1929                                 if(!parse_arg_name(ssl, todo, &n, &ln, &lb)) {
1930                                         (void)ssl_printf(ssl, "error cannot "
1931                                                 "parse IP address or name "
1932                                                 "'%s'\n", todo);
1933                                         delegpt_free_mlc(dp);
1934                                         return NULL;
1935                                 }
1936                                 if(!delegpt_add_ns_mlc(dp, n, 0)) {
1937                                         (void)ssl_printf(ssl, "error out of memory\n");
1938                                         free(n);
1939                                         delegpt_free_mlc(dp);
1940                                         return NULL;
1941                                 }
1942                                 free(n);
1943
1944                         } else {
1945                                 (void)ssl_printf(ssl, "error cannot parse"
1946                                         " IP address '%s'\n", todo);
1947                                 delegpt_free_mlc(dp);
1948                                 return NULL;
1949                         }
1950                 } else {
1951                         /* add address */
1952                         if(!delegpt_add_addr_mlc(dp, &addr, addrlen, 0, 0,
1953                                 auth_name)) {
1954                                 (void)ssl_printf(ssl, "error out of memory\n");
1955                                 delegpt_free_mlc(dp);
1956                                 return NULL;
1957                         }
1958                 }
1959         }
1960         dp->has_parent_side_NS = 1;
1961         return dp;
1962 }
1963
1964 /** do the status command */
1965 static void
1966 do_forward(RES* ssl, struct worker* worker, char* args)
1967 {
1968         struct iter_forwards* fwd = worker->env.fwds;
1969         uint8_t* root = (uint8_t*)"\000";
1970         if(!fwd) {
1971                 (void)ssl_printf(ssl, "error: structure not allocated\n");
1972                 return;
1973         }
1974         if(args == NULL || args[0] == 0) {
1975                 (void)print_root_fwds(ssl, fwd, root);
1976                 return;
1977         }
1978         /* set root forwards for this thread. since we are in remote control
1979          * the actual mesh is not running, so we can freely edit it. */
1980         /* delete all the existing queries first */
1981         mesh_delete_all(worker->env.mesh);
1982         if(strcmp(args, "off") == 0) {
1983                 forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, root);
1984         } else {
1985                 struct delegpt* dp;
1986                 if(!(dp = parse_delegpt(ssl, args, root, 0)))
1987                         return;
1988                 if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp)) {
1989                         (void)ssl_printf(ssl, "error out of memory\n");
1990                         return;
1991                 }
1992         }
1993         send_ok(ssl);
1994 }
1995
1996 static int
1997 parse_fs_args(RES* ssl, char* args, uint8_t** nm, struct delegpt** dp,
1998         int* insecure, int* prime)
1999 {
2000         char* zonename;
2001         char* rest;
2002         size_t nmlen;
2003         int nmlabs;
2004         /* parse all -x args */
2005         while(args[0] == '+') {
2006                 if(!find_arg2(ssl, args, &rest))
2007                         return 0;
2008                 while(*(++args) != 0) {
2009                         if(*args == 'i' && insecure)
2010                                 *insecure = 1;
2011                         else if(*args == 'p' && prime)
2012                                 *prime = 1;
2013                         else {
2014                                 (void)ssl_printf(ssl, "error: unknown option %s\n", args);
2015                                 return 0;
2016                         }
2017                 }
2018                 args = rest;
2019         }
2020         /* parse name */
2021         if(dp) {
2022                 if(!find_arg2(ssl, args, &rest))
2023                         return 0;
2024                 zonename = args;
2025                 args = rest;
2026         } else  zonename = args;
2027         if(!parse_arg_name(ssl, zonename, nm, &nmlen, &nmlabs))
2028                 return 0;
2029
2030         /* parse dp */
2031         if(dp) {
2032                 if(!(*dp = parse_delegpt(ssl, args, *nm, 1))) {
2033                         free(*nm);
2034                         return 0;
2035                 }
2036         }
2037         return 1;
2038 }
2039
2040 /** do the forward_add command */
2041 static void
2042 do_forward_add(RES* ssl, struct worker* worker, char* args)
2043 {
2044         struct iter_forwards* fwd = worker->env.fwds;
2045         int insecure = 0;
2046         uint8_t* nm = NULL;
2047         struct delegpt* dp = NULL;
2048         if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, NULL))
2049                 return;
2050         if(insecure && worker->env.anchors) {
2051                 if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2052                         nm)) {
2053                         (void)ssl_printf(ssl, "error out of memory\n");
2054                         delegpt_free_mlc(dp);
2055                         free(nm);
2056                         return;
2057                 }
2058         }
2059         if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp)) {
2060                 (void)ssl_printf(ssl, "error out of memory\n");
2061                 free(nm);
2062                 return;
2063         }
2064         free(nm);
2065         send_ok(ssl);
2066 }
2067
2068 /** do the forward_remove command */
2069 static void
2070 do_forward_remove(RES* ssl, struct worker* worker, char* args)
2071 {
2072         struct iter_forwards* fwd = worker->env.fwds;
2073         int insecure = 0;
2074         uint8_t* nm = NULL;
2075         if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL))
2076                 return;
2077         if(insecure && worker->env.anchors)
2078                 anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2079                         nm);
2080         forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, nm);
2081         free(nm);
2082         send_ok(ssl);
2083 }
2084
2085 /** do the stub_add command */
2086 static void
2087 do_stub_add(RES* ssl, struct worker* worker, char* args)
2088 {
2089         struct iter_forwards* fwd = worker->env.fwds;
2090         int insecure = 0, prime = 0;
2091         uint8_t* nm = NULL;
2092         struct delegpt* dp = NULL;
2093         if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, &prime))
2094                 return;
2095         if(insecure && worker->env.anchors) {
2096                 if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2097                         nm)) {
2098                         (void)ssl_printf(ssl, "error out of memory\n");
2099                         delegpt_free_mlc(dp);
2100                         free(nm);
2101                         return;
2102                 }
2103         }
2104         if(!forwards_add_stub_hole(fwd, LDNS_RR_CLASS_IN, nm)) {
2105                 if(insecure && worker->env.anchors)
2106                         anchors_delete_insecure(worker->env.anchors,
2107                                 LDNS_RR_CLASS_IN, nm);
2108                 (void)ssl_printf(ssl, "error out of memory\n");
2109                 delegpt_free_mlc(dp);
2110                 free(nm);
2111                 return;
2112         }
2113         if(!hints_add_stub(worker->env.hints, LDNS_RR_CLASS_IN, dp, !prime)) {
2114                 (void)ssl_printf(ssl, "error out of memory\n");
2115                 forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm);
2116                 if(insecure && worker->env.anchors)
2117                         anchors_delete_insecure(worker->env.anchors,
2118                                 LDNS_RR_CLASS_IN, nm);
2119                 free(nm);
2120                 return;
2121         }
2122         free(nm);
2123         send_ok(ssl);
2124 }
2125
2126 /** do the stub_remove command */
2127 static void
2128 do_stub_remove(RES* ssl, struct worker* worker, char* args)
2129 {
2130         struct iter_forwards* fwd = worker->env.fwds;
2131         int insecure = 0;
2132         uint8_t* nm = NULL;
2133         if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL))
2134                 return;
2135         if(insecure && worker->env.anchors)
2136                 anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN,
2137                         nm);
2138         forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm);
2139         hints_delete_stub(worker->env.hints, LDNS_RR_CLASS_IN, nm);
2140         free(nm);
2141         send_ok(ssl);
2142 }
2143
2144 /** do the insecure_add command */
2145 static void
2146 do_insecure_add(RES* ssl, struct worker* worker, char* arg)
2147 {
2148         size_t nmlen;
2149         int nmlabs;
2150         uint8_t* nm = NULL;
2151         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
2152                 return;
2153         if(worker->env.anchors) {
2154                 if(!anchors_add_insecure(worker->env.anchors,
2155                         LDNS_RR_CLASS_IN, nm)) {
2156                         (void)ssl_printf(ssl, "error out of memory\n");
2157                         free(nm);
2158                         return;
2159                 }
2160         }
2161         free(nm);
2162         send_ok(ssl);
2163 }
2164
2165 /** do the insecure_remove command */
2166 static void
2167 do_insecure_remove(RES* ssl, struct worker* worker, char* arg)
2168 {
2169         size_t nmlen;
2170         int nmlabs;
2171         uint8_t* nm = NULL;
2172         if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs))
2173                 return;
2174         if(worker->env.anchors)
2175                 anchors_delete_insecure(worker->env.anchors,
2176                         LDNS_RR_CLASS_IN, nm);
2177         free(nm);
2178         send_ok(ssl);
2179 }
2180
2181 static void
2182 do_insecure_list(RES* ssl, struct worker* worker)
2183 {
2184         char buf[257];
2185         struct trust_anchor* a;
2186         if(worker->env.anchors) {
2187                 RBTREE_FOR(a, struct trust_anchor*, worker->env.anchors->tree) {
2188                         if(a->numDS == 0 && a->numDNSKEY == 0) {
2189                                 dname_str(a->name, buf);
2190                                 ssl_printf(ssl, "%s\n", buf);
2191                         }
2192                 }
2193         }
2194 }
2195
2196 /** do the status command */
2197 static void
2198 do_status(RES* ssl, struct worker* worker)
2199 {
2200         int i;
2201         time_t uptime;
2202         if(!ssl_printf(ssl, "version: %s\n", PACKAGE_VERSION))
2203                 return;
2204         if(!ssl_printf(ssl, "verbosity: %d\n", verbosity))
2205                 return;
2206         if(!ssl_printf(ssl, "threads: %d\n", worker->daemon->num))
2207                 return;
2208         if(!ssl_printf(ssl, "modules: %d [", worker->daemon->mods.num))
2209                 return;
2210         for(i=0; i<worker->daemon->mods.num; i++) {
2211                 if(!ssl_printf(ssl, " %s", worker->daemon->mods.mod[i]->name))
2212                         return;
2213         }
2214         if(!ssl_printf(ssl, " ]\n"))
2215                 return;
2216         uptime = (time_t)time(NULL) - (time_t)worker->daemon->time_boot.tv_sec;
2217         if(!ssl_printf(ssl, "uptime: " ARG_LL "d seconds\n", (long long)uptime))
2218                 return;
2219         if(!ssl_printf(ssl, "options:%s%s%s%s\n" , 
2220                 (worker->daemon->reuseport?" reuseport":""),
2221                 (worker->daemon->rc->accept_list?" control":""),
2222                 (worker->daemon->rc->accept_list && worker->daemon->rc->use_cert?"(ssl)":""),
2223                 (worker->daemon->rc->accept_list && worker->daemon->cfg->control_ifs.first && worker->daemon->cfg->control_ifs.first->str && worker->daemon->cfg->control_ifs.first->str[0] == '/'?"(namedpipe)":"")
2224                 ))
2225                 return;
2226         if(!ssl_printf(ssl, "unbound (pid %d) is running...\n",
2227                 (int)getpid()))
2228                 return;
2229 }
2230
2231 /** get age for the mesh state */
2232 static void
2233 get_mesh_age(struct mesh_state* m, char* buf, size_t len, 
2234         struct module_env* env)
2235 {
2236         if(m->reply_list) {
2237                 struct timeval d;
2238                 struct mesh_reply* r = m->reply_list;
2239                 /* last reply is the oldest */
2240                 while(r && r->next)
2241                         r = r->next;
2242                 timeval_subtract(&d, env->now_tv, &r->start_time);
2243                 snprintf(buf, len, ARG_LL "d.%6.6d",
2244                         (long long)d.tv_sec, (int)d.tv_usec);
2245         } else {
2246                 snprintf(buf, len, "-");
2247         }
2248 }
2249
2250 /** get status of a mesh state */
2251 static void
2252 get_mesh_status(struct mesh_area* mesh, struct mesh_state* m, 
2253         char* buf, size_t len)
2254 {
2255         enum module_ext_state s = m->s.ext_state[m->s.curmod];
2256         const char *modname = mesh->mods.mod[m->s.curmod]->name;
2257         size_t l;
2258         if(strcmp(modname, "iterator") == 0 && s == module_wait_reply &&
2259                 m->s.minfo[m->s.curmod]) {
2260                 /* break into iterator to find out who its waiting for */
2261                 struct iter_qstate* qstate = (struct iter_qstate*)
2262                         m->s.minfo[m->s.curmod];
2263                 struct outbound_list* ol = &qstate->outlist;
2264                 struct outbound_entry* e;
2265                 snprintf(buf, len, "%s wait for", modname);
2266                 l = strlen(buf);
2267                 buf += l; len -= l;
2268                 if(ol->first == NULL)
2269                         snprintf(buf, len, " (empty_list)");
2270                 for(e = ol->first; e; e = e->next) {
2271                         snprintf(buf, len, " ");
2272                         l = strlen(buf);
2273                         buf += l; len -= l;
2274                         addr_to_str(&e->qsent->addr, e->qsent->addrlen, 
2275                                 buf, len);
2276                         l = strlen(buf);
2277                         buf += l; len -= l;
2278                 }
2279         } else if(s == module_wait_subquery) {
2280                 /* look in subs from mesh state to see what */
2281                 char nm[257];
2282                 struct mesh_state_ref* sub;
2283                 snprintf(buf, len, "%s wants", modname);
2284                 l = strlen(buf);
2285                 buf += l; len -= l;
2286                 if(m->sub_set.count == 0)
2287                         snprintf(buf, len, " (empty_list)");
2288                 RBTREE_FOR(sub, struct mesh_state_ref*, &m->sub_set) {
2289                         char* t = sldns_wire2str_type(sub->s->s.qinfo.qtype);
2290                         char* c = sldns_wire2str_class(sub->s->s.qinfo.qclass);
2291                         dname_str(sub->s->s.qinfo.qname, nm);
2292                         snprintf(buf, len, " %s %s %s", (t?t:"TYPE??"),
2293                                 (c?c:"CLASS??"), nm);
2294                         l = strlen(buf);
2295                         buf += l; len -= l;
2296                         free(t);
2297                         free(c);
2298                 }
2299         } else {
2300                 snprintf(buf, len, "%s is %s", modname, strextstate(s));
2301         }
2302 }
2303
2304 /** do the dump_requestlist command */
2305 static void
2306 do_dump_requestlist(RES* ssl, struct worker* worker)
2307 {
2308         struct mesh_area* mesh;
2309         struct mesh_state* m;
2310         int num = 0;
2311         char buf[257];
2312         char timebuf[32];
2313         char statbuf[10240];
2314         if(!ssl_printf(ssl, "thread #%d\n", worker->thread_num))
2315                 return;
2316         if(!ssl_printf(ssl, "#   type cl name    seconds    module status\n"))
2317                 return;
2318         /* show worker mesh contents */
2319         mesh = worker->env.mesh;
2320         if(!mesh) return;
2321         RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
2322                 char* t = sldns_wire2str_type(m->s.qinfo.qtype);
2323                 char* c = sldns_wire2str_class(m->s.qinfo.qclass);
2324                 dname_str(m->s.qinfo.qname, buf);
2325                 get_mesh_age(m, timebuf, sizeof(timebuf), &worker->env);
2326                 get_mesh_status(mesh, m, statbuf, sizeof(statbuf));
2327                 if(!ssl_printf(ssl, "%3d %4s %2s %s %s %s\n", 
2328                         num, (t?t:"TYPE??"), (c?c:"CLASS??"), buf, timebuf,
2329                         statbuf)) {
2330                         free(t);
2331                         free(c);
2332                         return;
2333                 }
2334                 num++;
2335                 free(t);
2336                 free(c);
2337         }
2338 }
2339
2340 /** structure for argument data for dump infra host */
2341 struct infra_arg {
2342         /** the infra cache */
2343         struct infra_cache* infra;
2344         /** the SSL connection */
2345         RES* ssl;
2346         /** the time now */
2347         time_t now;
2348         /** ssl failure? stop writing and skip the rest.  If the tcp
2349          * connection is broken, and writes fail, we then stop writing. */
2350         int ssl_failed;
2351 };
2352
2353 /** callback for every host element in the infra cache */
2354 static void
2355 dump_infra_host(struct lruhash_entry* e, void* arg)
2356 {
2357         struct infra_arg* a = (struct infra_arg*)arg;
2358         struct infra_key* k = (struct infra_key*)e->key;
2359         struct infra_data* d = (struct infra_data*)e->data;
2360         char ip_str[1024];
2361         char name[257];
2362         int port;
2363         if(a->ssl_failed)
2364                 return;
2365         addr_to_str(&k->addr, k->addrlen, ip_str, sizeof(ip_str));
2366         dname_str(k->zonename, name);
2367         port = (int)ntohs(((struct sockaddr_in*)&k->addr)->sin_port);
2368         if(port != UNBOUND_DNS_PORT) {
2369                 snprintf(ip_str+strlen(ip_str), sizeof(ip_str)-strlen(ip_str),
2370                         "@%d", port);
2371         }
2372         /* skip expired stuff (only backed off) */
2373         if(d->ttl < a->now) {
2374                 if(d->rtt.rto >= USEFUL_SERVER_TOP_TIMEOUT) {
2375                         if(!ssl_printf(a->ssl, "%s %s expired rto %d\n", ip_str,
2376                                 name, d->rtt.rto))  {
2377                                 a->ssl_failed = 1;
2378                                 return;
2379                         }
2380                 }
2381                 return;
2382         }
2383         if(!ssl_printf(a->ssl, "%s %s ttl %lu ping %d var %d rtt %d rto %d "
2384                 "tA %d tAAAA %d tother %d "
2385                 "ednsknown %d edns %d delay %d lame dnssec %d rec %d A %d "
2386                 "other %d\n", ip_str, name, (unsigned long)(d->ttl - a->now),
2387                 d->rtt.srtt, d->rtt.rttvar, rtt_notimeout(&d->rtt), d->rtt.rto,
2388                 d->timeout_A, d->timeout_AAAA, d->timeout_other,
2389                 (int)d->edns_lame_known, (int)d->edns_version,
2390                 (int)(a->now<d->probedelay?(d->probedelay - a->now):0),
2391                 (int)d->isdnsseclame, (int)d->rec_lame, (int)d->lame_type_A,
2392                 (int)d->lame_other)) {
2393                 a->ssl_failed = 1;
2394                 return;
2395         }
2396 }
2397
2398 /** do the dump_infra command */
2399 static void
2400 do_dump_infra(RES* ssl, struct worker* worker)
2401 {
2402         struct infra_arg arg;
2403         arg.infra = worker->env.infra_cache;
2404         arg.ssl = ssl;
2405         arg.now = *worker->env.now;
2406         arg.ssl_failed = 0;
2407         slabhash_traverse(arg.infra->hosts, 0, &dump_infra_host, (void*)&arg);
2408 }
2409
2410 /** do the log_reopen command */
2411 static void
2412 do_log_reopen(RES* ssl, struct worker* worker)
2413 {
2414         struct config_file* cfg = worker->env.cfg;
2415         send_ok(ssl);
2416         log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
2417 }
2418
2419 /** do the set_option command */
2420 static void
2421 do_set_option(RES* ssl, struct worker* worker, char* arg)
2422 {
2423         char* arg2;
2424         if(!find_arg2(ssl, arg, &arg2))
2425                 return;
2426         if(!config_set_option(worker->env.cfg, arg, arg2)) {
2427                 (void)ssl_printf(ssl, "error setting option\n");
2428                 return;
2429         }
2430         /* effectuate some arguments */
2431         if(strcmp(arg, "val-override-date:") == 0) {
2432                 int m = modstack_find(&worker->env.mesh->mods, "validator");
2433                 struct val_env* val_env = NULL;
2434                 if(m != -1) val_env = (struct val_env*)worker->env.modinfo[m];
2435                 if(val_env)
2436                         val_env->date_override = worker->env.cfg->val_date_override;
2437         }
2438         send_ok(ssl);
2439 }
2440
2441 /* routine to printout option values over SSL */
2442 void remote_get_opt_ssl(char* line, void* arg)
2443 {
2444         RES* ssl = (RES*)arg;
2445         (void)ssl_printf(ssl, "%s\n", line);
2446 }
2447
2448 /** do the get_option command */
2449 static void
2450 do_get_option(RES* ssl, struct worker* worker, char* arg)
2451 {
2452         int r;
2453         r = config_get_option(worker->env.cfg, arg, remote_get_opt_ssl, ssl);
2454         if(!r) {
2455                 (void)ssl_printf(ssl, "error unknown option\n");
2456                 return;
2457         }
2458 }
2459
2460 /** do the list_forwards command */
2461 static void
2462 do_list_forwards(RES* ssl, struct worker* worker)
2463 {
2464         /* since its a per-worker structure no locks needed */
2465         struct iter_forwards* fwds = worker->env.fwds;
2466         struct iter_forward_zone* z;
2467         struct trust_anchor* a;
2468         int insecure;
2469         RBTREE_FOR(z, struct iter_forward_zone*, fwds->tree) {
2470                 if(!z->dp) continue; /* skip empty marker for stub */
2471
2472                 /* see if it is insecure */
2473                 insecure = 0;
2474                 if(worker->env.anchors &&
2475                         (a=anchor_find(worker->env.anchors, z->name,
2476                         z->namelabs, z->namelen,  z->dclass))) {
2477                         if(!a->keylist && !a->numDS && !a->numDNSKEY)
2478                                 insecure = 1;
2479                         lock_basic_unlock(&a->lock);
2480                 }
2481
2482                 if(!ssl_print_name_dp(ssl, (insecure?"forward +i":"forward"),
2483                         z->name, z->dclass, z->dp))
2484                         return;
2485         }
2486 }
2487
2488 /** do the list_stubs command */
2489 static void
2490 do_list_stubs(RES* ssl, struct worker* worker)
2491 {
2492         struct iter_hints_stub* z;
2493         struct trust_anchor* a;
2494         int insecure;
2495         char str[32];
2496         RBTREE_FOR(z, struct iter_hints_stub*, &worker->env.hints->tree) {
2497
2498                 /* see if it is insecure */
2499                 insecure = 0;
2500                 if(worker->env.anchors &&
2501                         (a=anchor_find(worker->env.anchors, z->node.name,
2502                         z->node.labs, z->node.len,  z->node.dclass))) {
2503                         if(!a->keylist && !a->numDS && !a->numDNSKEY)
2504                                 insecure = 1;
2505                         lock_basic_unlock(&a->lock);
2506                 }
2507
2508                 snprintf(str, sizeof(str), "stub %sprime%s",
2509                         (z->noprime?"no":""), (insecure?" +i":""));
2510                 if(!ssl_print_name_dp(ssl, str, z->node.name,
2511                         z->node.dclass, z->dp))
2512                         return;
2513         }
2514 }
2515
2516 /** do the list_auth_zones command */
2517 static void
2518 do_list_auth_zones(RES* ssl, struct auth_zones* az)
2519 {
2520         struct auth_zone* z;
2521         char buf[257], buf2[256];
2522         lock_rw_rdlock(&az->lock);
2523         RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
2524                 lock_rw_rdlock(&z->lock);
2525                 dname_str(z->name, buf);
2526                 if(z->zone_expired)
2527                         snprintf(buf2, sizeof(buf2), "expired");
2528                 else {
2529                         uint32_t serial = 0;
2530                         if(auth_zone_get_serial(z, &serial))
2531                                 snprintf(buf2, sizeof(buf2), "serial %u",
2532                                         (unsigned)serial);
2533                         else    snprintf(buf2, sizeof(buf2), "no serial");
2534                 }
2535                 if(!ssl_printf(ssl, "%s\t%s\n", buf, buf2)) {
2536                         /* failure to print */
2537                         lock_rw_unlock(&z->lock);
2538                         lock_rw_unlock(&az->lock);
2539                         return;
2540                 }
2541                 lock_rw_unlock(&z->lock);
2542         }
2543         lock_rw_unlock(&az->lock);
2544 }
2545
2546 /** do the list_local_zones command */
2547 static void
2548 do_list_local_zones(RES* ssl, struct local_zones* zones)
2549 {
2550         struct local_zone* z;
2551         char buf[257];
2552         lock_rw_rdlock(&zones->lock);
2553         RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
2554                 lock_rw_rdlock(&z->lock);
2555                 dname_str(z->name, buf);
2556                 if(!ssl_printf(ssl, "%s %s\n", buf, 
2557                         local_zone_type2str(z->type))) {
2558                         /* failure to print */
2559                         lock_rw_unlock(&z->lock);
2560                         lock_rw_unlock(&zones->lock);
2561                         return;
2562                 }
2563                 lock_rw_unlock(&z->lock);
2564         }
2565         lock_rw_unlock(&zones->lock);
2566 }
2567
2568 /** do the list_local_data command */
2569 static void
2570 do_list_local_data(RES* ssl, struct worker* worker, struct local_zones* zones)
2571 {
2572         struct local_zone* z;
2573         struct local_data* d;
2574         struct local_rrset* p;
2575         char* s = (char*)sldns_buffer_begin(worker->env.scratch_buffer);
2576         size_t slen = sldns_buffer_capacity(worker->env.scratch_buffer);
2577         lock_rw_rdlock(&zones->lock);
2578         RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
2579                 lock_rw_rdlock(&z->lock);
2580                 RBTREE_FOR(d, struct local_data*, &z->data) {
2581                         for(p = d->rrsets; p; p = p->next) {
2582                                 struct packed_rrset_data* d =
2583                                         (struct packed_rrset_data*)p->rrset->entry.data;
2584                                 size_t i;
2585                                 for(i=0; i<d->count + d->rrsig_count; i++) {
2586                                         if(!packed_rr_to_string(p->rrset, i,
2587                                                 0, s, slen)) {
2588                                                 if(!ssl_printf(ssl, "BADRR\n")) {
2589                                                         lock_rw_unlock(&z->lock);
2590                                                         lock_rw_unlock(&zones->lock);
2591                                                         return;
2592                                                 }
2593                                         }
2594                                         if(!ssl_printf(ssl, "%s\n", s)) {
2595                                                 lock_rw_unlock(&z->lock);
2596                                                 lock_rw_unlock(&zones->lock);
2597                                                 return;
2598                                         }
2599                                 }
2600                         }
2601                 }
2602                 lock_rw_unlock(&z->lock);
2603         }
2604         lock_rw_unlock(&zones->lock);
2605 }
2606
2607 /** do the view_list_local_zones command */
2608 static void
2609 do_view_list_local_zones(RES* ssl, struct worker* worker, char* arg)
2610 {
2611         struct view* v = views_find_view(worker->daemon->views,
2612                 arg, 0 /* get read lock*/);
2613         if(!v) {
2614                 ssl_printf(ssl,"no view with name: %s\n", arg);
2615                 return;
2616         }
2617         if(v->local_zones) {
2618                 do_list_local_zones(ssl, v->local_zones);
2619         }
2620         lock_rw_unlock(&v->lock);
2621 }
2622
2623 /** do the view_list_local_data command */
2624 static void
2625 do_view_list_local_data(RES* ssl, struct worker* worker, char* arg)
2626 {
2627         struct view* v = views_find_view(worker->daemon->views,
2628                 arg, 0 /* get read lock*/);
2629         if(!v) {
2630                 ssl_printf(ssl,"no view with name: %s\n", arg);
2631                 return;
2632         }
2633         if(v->local_zones) {
2634                 do_list_local_data(ssl, worker, v->local_zones);
2635         }
2636         lock_rw_unlock(&v->lock);
2637 }
2638
2639 /** struct for user arg ratelimit list */
2640 struct ratelimit_list_arg {
2641         /** the infra cache */
2642         struct infra_cache* infra;
2643         /** the SSL to print to */
2644         RES* ssl;
2645         /** all or only ratelimited */
2646         int all;
2647         /** current time */
2648         time_t now;
2649 };
2650
2651 #define ip_ratelimit_list_arg ratelimit_list_arg
2652
2653 /** list items in the ratelimit table */
2654 static void
2655 rate_list(struct lruhash_entry* e, void* arg)
2656 {
2657         struct ratelimit_list_arg* a = (struct ratelimit_list_arg*)arg;
2658         struct rate_key* k = (struct rate_key*)e->key;
2659         struct rate_data* d = (struct rate_data*)e->data;
2660         char buf[257];
2661         int lim = infra_find_ratelimit(a->infra, k->name, k->namelen);
2662         int max = infra_rate_max(d, a->now);
2663         if(a->all == 0) {
2664                 if(max < lim)
2665                         return;
2666         }
2667         dname_str(k->name, buf);
2668         ssl_printf(a->ssl, "%s %d limit %d\n", buf, max, lim);
2669 }
2670
2671 /** list items in the ip_ratelimit table */
2672 static void
2673 ip_rate_list(struct lruhash_entry* e, void* arg)
2674 {
2675         char ip[128];
2676         struct ip_ratelimit_list_arg* a = (struct ip_ratelimit_list_arg*)arg;
2677         struct ip_rate_key* k = (struct ip_rate_key*)e->key;
2678         struct ip_rate_data* d = (struct ip_rate_data*)e->data;
2679         int lim = infra_ip_ratelimit;
2680         int max = infra_rate_max(d, a->now);
2681         if(a->all == 0) {
2682                 if(max < lim)
2683                         return;
2684         }
2685         addr_to_str(&k->addr, k->addrlen, ip, sizeof(ip));
2686         ssl_printf(a->ssl, "%s %d limit %d\n", ip, max, lim);
2687 }
2688
2689 /** do the ratelimit_list command */
2690 static void
2691 do_ratelimit_list(RES* ssl, struct worker* worker, char* arg)
2692 {
2693         struct ratelimit_list_arg a;
2694         a.all = 0;
2695         a.infra = worker->env.infra_cache;
2696         a.now = *worker->env.now;
2697         a.ssl = ssl;
2698         arg = skipwhite(arg);
2699         if(strcmp(arg, "+a") == 0)
2700                 a.all = 1;
2701         if(a.infra->domain_rates==NULL ||
2702                 (a.all == 0 && infra_dp_ratelimit == 0))
2703                 return;
2704         slabhash_traverse(a.infra->domain_rates, 0, rate_list, &a);
2705 }
2706
2707 /** do the ip_ratelimit_list command */
2708 static void
2709 do_ip_ratelimit_list(RES* ssl, struct worker* worker, char* arg)
2710 {
2711         struct ip_ratelimit_list_arg a;
2712         a.all = 0;
2713         a.infra = worker->env.infra_cache;
2714         a.now = *worker->env.now;
2715         a.ssl = ssl;
2716         arg = skipwhite(arg);
2717         if(strcmp(arg, "+a") == 0)
2718                 a.all = 1;
2719         if(a.infra->client_ip_rates==NULL ||
2720                 (a.all == 0 && infra_ip_ratelimit == 0))
2721                 return;
2722         slabhash_traverse(a.infra->client_ip_rates, 0, ip_rate_list, &a);
2723 }
2724
2725 /** tell other processes to execute the command */
2726 static void
2727 distribute_cmd(struct daemon_remote* rc, RES* ssl, char* cmd)
2728 {
2729         int i;
2730         if(!cmd || !ssl) 
2731                 return;
2732         /* skip i=0 which is me */
2733         for(i=1; i<rc->worker->daemon->num; i++) {
2734                 worker_send_cmd(rc->worker->daemon->workers[i],
2735                         worker_cmd_remote);
2736                 if(!tube_write_msg(rc->worker->daemon->workers[i]->cmd,
2737                         (uint8_t*)cmd, strlen(cmd)+1, 0)) {
2738                         ssl_printf(ssl, "error could not distribute cmd\n");
2739                         return;
2740                 }
2741         }
2742 }
2743
2744 /** check for name with end-of-string, space or tab after it */
2745 static int
2746 cmdcmp(char* p, const char* cmd, size_t len)
2747 {
2748         return strncmp(p,cmd,len)==0 && (p[len]==0||p[len]==' '||p[len]=='\t');
2749 }
2750
2751 /** execute a remote control command */
2752 static void
2753 execute_cmd(struct daemon_remote* rc, RES* ssl, char* cmd, 
2754         struct worker* worker)
2755 {
2756         char* p = skipwhite(cmd);
2757         /* compare command */
2758         if(cmdcmp(p, "stop", 4)) {
2759                 do_stop(ssl, rc);
2760                 return;
2761         } else if(cmdcmp(p, "reload", 6)) {
2762                 do_reload(ssl, rc);
2763                 return;
2764         } else if(cmdcmp(p, "stats_noreset", 13)) {
2765                 do_stats(ssl, rc, 0);
2766                 return;
2767         } else if(cmdcmp(p, "stats", 5)) {
2768                 do_stats(ssl, rc, 1);
2769                 return;
2770         } else if(cmdcmp(p, "status", 6)) {
2771                 do_status(ssl, worker);
2772                 return;
2773         } else if(cmdcmp(p, "dump_cache", 10)) {
2774                 (void)dump_cache(ssl, worker);
2775                 return;
2776         } else if(cmdcmp(p, "load_cache", 10)) {
2777                 if(load_cache(ssl, worker)) send_ok(ssl);
2778                 return;
2779         } else if(cmdcmp(p, "list_forwards", 13)) {
2780                 do_list_forwards(ssl, worker);
2781                 return;
2782         } else if(cmdcmp(p, "list_stubs", 10)) {
2783                 do_list_stubs(ssl, worker);
2784                 return;
2785         } else if(cmdcmp(p, "list_insecure", 13)) {
2786                 do_insecure_list(ssl, worker);
2787                 return;
2788         } else if(cmdcmp(p, "list_local_zones", 16)) {
2789                 do_list_local_zones(ssl, worker->daemon->local_zones);
2790                 return;
2791         } else if(cmdcmp(p, "list_local_data", 15)) {
2792                 do_list_local_data(ssl, worker, worker->daemon->local_zones);
2793                 return;
2794         } else if(cmdcmp(p, "view_list_local_zones", 21)) {
2795                 do_view_list_local_zones(ssl, worker, skipwhite(p+21));
2796                 return;
2797         } else if(cmdcmp(p, "view_list_local_data", 20)) {
2798                 do_view_list_local_data(ssl, worker, skipwhite(p+20));
2799                 return;
2800         } else if(cmdcmp(p, "ratelimit_list", 14)) {
2801                 do_ratelimit_list(ssl, worker, p+14);
2802                 return;
2803         } else if(cmdcmp(p, "ip_ratelimit_list", 17)) {
2804                 do_ip_ratelimit_list(ssl, worker, p+17);
2805                 return;
2806         } else if(cmdcmp(p, "list_auth_zones", 15)) {
2807                 do_list_auth_zones(ssl, worker->env.auth_zones);
2808                 return;
2809         } else if(cmdcmp(p, "stub_add", 8)) {
2810                 /* must always distribute this cmd */
2811                 if(rc) distribute_cmd(rc, ssl, cmd);
2812                 do_stub_add(ssl, worker, skipwhite(p+8));
2813                 return;
2814         } else if(cmdcmp(p, "stub_remove", 11)) {
2815                 /* must always distribute this cmd */
2816                 if(rc) distribute_cmd(rc, ssl, cmd);
2817                 do_stub_remove(ssl, worker, skipwhite(p+11));
2818                 return;
2819         } else if(cmdcmp(p, "forward_add", 11)) {
2820                 /* must always distribute this cmd */
2821                 if(rc) distribute_cmd(rc, ssl, cmd);
2822                 do_forward_add(ssl, worker, skipwhite(p+11));
2823                 return;
2824         } else if(cmdcmp(p, "forward_remove", 14)) {
2825                 /* must always distribute this cmd */
2826                 if(rc) distribute_cmd(rc, ssl, cmd);
2827                 do_forward_remove(ssl, worker, skipwhite(p+14));
2828                 return;
2829         } else if(cmdcmp(p, "insecure_add", 12)) {
2830                 /* must always distribute this cmd */
2831                 if(rc) distribute_cmd(rc, ssl, cmd);
2832                 do_insecure_add(ssl, worker, skipwhite(p+12));
2833                 return;
2834         } else if(cmdcmp(p, "insecure_remove", 15)) {
2835                 /* must always distribute this cmd */
2836                 if(rc) distribute_cmd(rc, ssl, cmd);
2837                 do_insecure_remove(ssl, worker, skipwhite(p+15));
2838                 return;
2839         } else if(cmdcmp(p, "forward", 7)) {
2840                 /* must always distribute this cmd */
2841                 if(rc) distribute_cmd(rc, ssl, cmd);
2842                 do_forward(ssl, worker, skipwhite(p+7));
2843                 return;
2844         } else if(cmdcmp(p, "flush_stats", 11)) {
2845                 /* must always distribute this cmd */
2846                 if(rc) distribute_cmd(rc, ssl, cmd);
2847                 do_flush_stats(ssl, worker);
2848                 return;
2849         } else if(cmdcmp(p, "flush_requestlist", 17)) {
2850                 /* must always distribute this cmd */
2851                 if(rc) distribute_cmd(rc, ssl, cmd);
2852                 do_flush_requestlist(ssl, worker);
2853                 return;
2854         } else if(cmdcmp(p, "lookup", 6)) {
2855                 do_lookup(ssl, worker, skipwhite(p+6));
2856                 return;
2857         }
2858
2859 #ifdef THREADS_DISABLED
2860         /* other processes must execute the command as well */
2861         /* commands that should not be distributed, returned above. */
2862         if(rc) { /* only if this thread is the master (rc) thread */
2863                 /* done before the code below, which may split the string */
2864                 distribute_cmd(rc, ssl, cmd);
2865         }
2866 #endif
2867         if(cmdcmp(p, "verbosity", 9)) {
2868                 do_verbosity(ssl, skipwhite(p+9));
2869         } else if(cmdcmp(p, "local_zone_remove", 17)) {
2870                 do_zone_remove(ssl, worker->daemon->local_zones, skipwhite(p+17));
2871         } else if(cmdcmp(p, "local_zones_remove", 18)) {
2872                 do_zones_remove(ssl, worker->daemon->local_zones);
2873         } else if(cmdcmp(p, "local_zone", 10)) {
2874                 do_zone_add(ssl, worker->daemon->local_zones, skipwhite(p+10));
2875         } else if(cmdcmp(p, "local_zones", 11)) {
2876                 do_zones_add(ssl, worker->daemon->local_zones);
2877         } else if(cmdcmp(p, "local_data_remove", 17)) {
2878                 do_data_remove(ssl, worker->daemon->local_zones, skipwhite(p+17));
2879         } else if(cmdcmp(p, "local_datas_remove", 18)) {
2880                 do_datas_remove(ssl, worker->daemon->local_zones);
2881         } else if(cmdcmp(p, "local_data", 10)) {
2882                 do_data_add(ssl, worker->daemon->local_zones, skipwhite(p+10));
2883         } else if(cmdcmp(p, "local_datas", 11)) {
2884                 do_datas_add(ssl, worker->daemon->local_zones);
2885         } else if(cmdcmp(p, "view_local_zone_remove", 22)) {
2886                 do_view_zone_remove(ssl, worker, skipwhite(p+22));
2887         } else if(cmdcmp(p, "view_local_zone", 15)) {
2888                 do_view_zone_add(ssl, worker, skipwhite(p+15));
2889         } else if(cmdcmp(p, "view_local_data_remove", 22)) {
2890                 do_view_data_remove(ssl, worker, skipwhite(p+22));
2891         } else if(cmdcmp(p, "view_local_data", 15)) {
2892                 do_view_data_add(ssl, worker, skipwhite(p+15));
2893         } else if(cmdcmp(p, "flush_zone", 10)) {
2894                 do_flush_zone(ssl, worker, skipwhite(p+10));
2895         } else if(cmdcmp(p, "flush_type", 10)) {
2896                 do_flush_type(ssl, worker, skipwhite(p+10));
2897         } else if(cmdcmp(p, "flush_infra", 11)) {
2898                 do_flush_infra(ssl, worker, skipwhite(p+11));
2899         } else if(cmdcmp(p, "flush", 5)) {
2900                 do_flush_name(ssl, worker, skipwhite(p+5));
2901         } else if(cmdcmp(p, "dump_requestlist", 16)) {
2902                 do_dump_requestlist(ssl, worker);
2903         } else if(cmdcmp(p, "dump_infra", 10)) {
2904                 do_dump_infra(ssl, worker);
2905         } else if(cmdcmp(p, "log_reopen", 10)) {
2906                 do_log_reopen(ssl, worker);
2907         } else if(cmdcmp(p, "set_option", 10)) {
2908                 do_set_option(ssl, worker, skipwhite(p+10));
2909         } else if(cmdcmp(p, "get_option", 10)) {
2910                 do_get_option(ssl, worker, skipwhite(p+10));
2911         } else if(cmdcmp(p, "flush_bogus", 11)) {
2912                 do_flush_bogus(ssl, worker);
2913         } else if(cmdcmp(p, "flush_negative", 14)) {
2914                 do_flush_negative(ssl, worker);
2915         } else {
2916                 (void)ssl_printf(ssl, "error unknown command '%s'\n", p);
2917         }
2918 }
2919
2920 void 
2921 daemon_remote_exec(struct worker* worker)
2922 {
2923         /* read the cmd string */
2924         uint8_t* msg = NULL;
2925         uint32_t len = 0;
2926         if(!tube_read_msg(worker->cmd, &msg, &len, 0)) {
2927                 log_err("daemon_remote_exec: tube_read_msg failed");
2928                 return;
2929         }
2930         verbose(VERB_ALGO, "remote exec distributed: %s", (char*)msg);
2931         execute_cmd(NULL, NULL, (char*)msg, worker);
2932         free(msg);
2933 }
2934
2935 /** handle remote control request */
2936 static void
2937 handle_req(struct daemon_remote* rc, struct rc_state* s, RES* res)
2938 {
2939         int r;
2940         char pre[10];
2941         char magic[7];
2942         char buf[1024];
2943 #ifdef USE_WINSOCK
2944         /* makes it possible to set the socket blocking again. */
2945         /* basically removes it from winsock_event ... */
2946         WSAEventSelect(s->c->fd, NULL, 0);
2947 #endif
2948         fd_set_block(s->c->fd);
2949
2950         /* try to read magic UBCT[version]_space_ string */
2951         if(res->ssl) {
2952                 ERR_clear_error();
2953                 if((r=SSL_read(res->ssl, magic, (int)sizeof(magic)-1)) <= 0) {
2954                         if(SSL_get_error(res->ssl, r) == SSL_ERROR_ZERO_RETURN)
2955                                 return;
2956                         log_crypto_err("could not SSL_read");
2957                         return;
2958                 }
2959         } else {
2960                 while(1) {
2961                         ssize_t rr = recv(res->fd, magic, sizeof(magic)-1, 0);
2962                         if(rr <= 0) {
2963                                 if(rr == 0) return;
2964                                 if(errno == EINTR || errno == EAGAIN)
2965                                         continue;
2966 #ifndef USE_WINSOCK
2967                                 log_err("could not recv: %s", strerror(errno));
2968 #else
2969                                 log_err("could not recv: %s", wsa_strerror(WSAGetLastError()));
2970 #endif
2971                                 return;
2972                         }
2973                         r = (int)rr;
2974                         break;
2975                 }
2976         }
2977         magic[6] = 0;
2978         if( r != 6 || strncmp(magic, "UBCT", 4) != 0) {
2979                 verbose(VERB_QUERY, "control connection has bad magic string");
2980                 /* probably wrong tool connected, ignore it completely */
2981                 return;
2982         }
2983
2984         /* read the command line */
2985         if(!ssl_read_line(res, buf, sizeof(buf))) {
2986                 return;
2987         }
2988         snprintf(pre, sizeof(pre), "UBCT%d ", UNBOUND_CONTROL_VERSION);
2989         if(strcmp(magic, pre) != 0) {
2990                 verbose(VERB_QUERY, "control connection had bad "
2991                         "version %s, cmd: %s", magic, buf);
2992                 ssl_printf(res, "error version mismatch\n");
2993                 return;
2994         }
2995         verbose(VERB_DETAIL, "control cmd: %s", buf);
2996
2997         /* figure out what to do */
2998         execute_cmd(rc, res, buf, rc->worker);
2999 }
3000
3001 /** handle SSL_do_handshake changes to the file descriptor to wait for later */
3002 static int
3003 remote_handshake_later(struct daemon_remote* rc, struct rc_state* s,
3004         struct comm_point* c, int r, int r2)
3005 {
3006         if(r2 == SSL_ERROR_WANT_READ) {
3007                 if(s->shake_state == rc_hs_read) {
3008                         /* try again later */
3009                         return 0;
3010                 }
3011                 s->shake_state = rc_hs_read;
3012                 comm_point_listen_for_rw(c, 1, 0);
3013                 return 0;
3014         } else if(r2 == SSL_ERROR_WANT_WRITE) {
3015                 if(s->shake_state == rc_hs_write) {
3016                         /* try again later */
3017                         return 0;
3018                 }
3019                 s->shake_state = rc_hs_write;
3020                 comm_point_listen_for_rw(c, 0, 1);
3021                 return 0;
3022         } else {
3023                 if(r == 0)
3024                         log_err("remote control connection closed prematurely");
3025                 log_addr(1, "failed connection from",
3026                         &s->c->repinfo.addr, s->c->repinfo.addrlen);
3027                 log_crypto_err("remote control failed ssl");
3028                 clean_point(rc, s);
3029         }
3030         return 0;
3031 }
3032
3033 int remote_control_callback(struct comm_point* c, void* arg, int err, 
3034         struct comm_reply* ATTR_UNUSED(rep))
3035 {
3036         RES res;
3037         struct rc_state* s = (struct rc_state*)arg;
3038         struct daemon_remote* rc = s->rc;
3039         int r;
3040         if(err != NETEVENT_NOERROR) {
3041                 if(err==NETEVENT_TIMEOUT) 
3042                         log_err("remote control timed out");
3043                 clean_point(rc, s);
3044                 return 0;
3045         }
3046         if(s->ssl) {
3047                 /* (continue to) setup the SSL connection */
3048                 ERR_clear_error();
3049                 r = SSL_do_handshake(s->ssl);
3050                 if(r != 1) {
3051                         int r2 = SSL_get_error(s->ssl, r);
3052                         return remote_handshake_later(rc, s, c, r, r2);
3053                 }
3054                 s->shake_state = rc_none;
3055         }
3056
3057         /* once handshake has completed, check authentication */
3058         if (!rc->use_cert) {
3059                 verbose(VERB_ALGO, "unauthenticated remote control connection");
3060         } else if(SSL_get_verify_result(s->ssl) == X509_V_OK) {
3061                 X509* x = SSL_get_peer_certificate(s->ssl);
3062                 if(!x) {
3063                         verbose(VERB_DETAIL, "remote control connection "
3064                                 "provided no client certificate");
3065                         clean_point(rc, s);
3066                         return 0;
3067                 }
3068                 verbose(VERB_ALGO, "remote control connection authenticated");
3069                 X509_free(x);
3070         } else {
3071                 verbose(VERB_DETAIL, "remote control connection failed to "
3072                         "authenticate with client certificate");
3073                 clean_point(rc, s);
3074                 return 0;
3075         }
3076
3077         /* if OK start to actually handle the request */
3078         res.ssl = s->ssl;
3079         res.fd = c->fd;
3080         handle_req(rc, s, &res);
3081
3082         verbose(VERB_ALGO, "remote control operation completed");
3083         clean_point(rc, s);
3084         return 0;
3085 }