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