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