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