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