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