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