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