1 /* 2 * daemon/remote.c - remote control for the unbound daemon. 3 * 4 * Copyright (c) 2008, NLnet Labs. All rights reserved. 5 * 6 * This software is open source. 7 * 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the following conditions 10 * are met: 11 * 12 * Redistributions of source code must retain the above copyright notice, 13 * this list of conditions and the following disclaimer. 14 * 15 * Redistributions in binary form must reproduce the above copyright notice, 16 * this list of conditions and the following disclaimer in the documentation 17 * and/or other materials provided with the distribution. 18 * 19 * Neither the name of the NLNET LABS nor the names of its contributors may 20 * be used to endorse or promote products derived from this software without 21 * specific prior written permission. 22 * 23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 24 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 25 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 26 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 27 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 28 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 29 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 30 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 31 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 32 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 33 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 */ 35 36 /** 37 * \file 38 * 39 * This file contains the remote control functionality for the daemon. 40 * The remote control can be performed using either the commandline 41 * unbound-control tool, or a TLS capable web browser. 42 * The channel is secured using TLSv1, and certificates. 43 * Both the server and the client(control tool) have their own keys. 44 */ 45 #include "config.h" 46 #ifdef HAVE_OPENSSL_ERR_H 47 #include <openssl/err.h> 48 #endif 49 #ifdef HAVE_OPENSSL_DH_H 50 #include <openssl/dh.h> 51 #endif 52 #ifdef HAVE_OPENSSL_BN_H 53 #include <openssl/bn.h> 54 #endif 55 #ifdef HAVE_STDATOMIC_H 56 #include <stdatomic.h> 57 #endif 58 59 #include <ctype.h> 60 #include "daemon/remote.h" 61 #include "daemon/worker.h" 62 #include "daemon/daemon.h" 63 #include "daemon/stats.h" 64 #include "daemon/cachedump.h" 65 #include "util/log.h" 66 #include "util/config_file.h" 67 #include "util/net_help.h" 68 #include "util/module.h" 69 #include "util/ub_event.h" 70 #include "services/listen_dnsport.h" 71 #include "services/cache/rrset.h" 72 #include "services/cache/infra.h" 73 #include "services/mesh.h" 74 #include "services/localzone.h" 75 #include "services/authzone.h" 76 #include "services/rpz.h" 77 #include "util/storage/slabhash.h" 78 #include "util/fptr_wlist.h" 79 #include "util/data/dname.h" 80 #include "validator/validator.h" 81 #include "validator/val_kcache.h" 82 #include "validator/val_kentry.h" 83 #include "validator/val_anchor.h" 84 #include "validator/val_neg.h" 85 #include "iterator/iterator.h" 86 #include "iterator/iter_fwd.h" 87 #include "iterator/iter_hints.h" 88 #include "iterator/iter_delegpt.h" 89 #include "iterator/iter_utils.h" 90 #include "iterator/iter_donotq.h" 91 #include "iterator/iter_priv.h" 92 #include "services/outbound_list.h" 93 #include "services/outside_network.h" 94 #include "sldns/str2wire.h" 95 #include "sldns/parseutil.h" 96 #include "sldns/wire2str.h" 97 #include "sldns/sbuffer.h" 98 #include "util/timeval_func.h" 99 #include "util/tcp_conn_limit.h" 100 #include "util/edns.h" 101 #ifdef USE_CACHEDB 102 #include "cachedb/cachedb.h" 103 #endif 104 #ifdef CLIENT_SUBNET 105 #include "edns-subnet/subnetmod.h" 106 #include "edns-subnet/addrtree.h" 107 #endif 108 109 #ifdef HAVE_SYS_TYPES_H 110 # include <sys/types.h> 111 #endif 112 #ifdef HAVE_SYS_STAT_H 113 #include <sys/stat.h> 114 #endif 115 #ifdef HAVE_NETDB_H 116 #include <netdb.h> 117 #endif 118 #ifdef HAVE_POLL_H 119 #include <poll.h> 120 #endif 121 122 /* just for portability */ 123 #ifdef SQ 124 #undef SQ 125 #endif 126 127 /** what to put on statistics lines between var and value, ": " or "=" */ 128 #define SQ "=" 129 130 /** Acceptable lengths of str lines */ 131 #define MAX_CMD_STRLINE 1024 132 #define MAX_STDIN_STRLINE 2048 133 /** What number of loop iterations is too much for ipc retries */ 134 #define IPC_LOOP_MAX 200 135 /** Timeout in msec for ipc socket poll. */ 136 #define IPC_NOTIFICATION_WAIT 200 137 138 static void fr_printq_delete(struct fast_reload_printq* printq); 139 static void fr_main_perform_printout(struct fast_reload_thread* fr); 140 static int fr_printq_empty(struct fast_reload_printq* printq); 141 static void fr_printq_list_insert(struct fast_reload_printq* printq, 142 struct daemon* daemon); 143 static void fr_printq_remove(struct fast_reload_printq* printq); 144 static void fr_check_cmd_from_thread(struct fast_reload_thread* fr); 145 146 static int 147 remote_setup_ctx(struct daemon_remote* rc, struct config_file* cfg) 148 { 149 char* s_cert; 150 char* s_key; 151 rc->ctx = SSL_CTX_new(SSLv23_server_method()); 152 if(!rc->ctx) { 153 log_crypto_err("could not SSL_CTX_new"); 154 return 0; 155 } 156 if(!listen_sslctx_setup(rc->ctx, cfg->tls_protocols)) { 157 return 0; 158 } 159 160 s_cert = fname_after_chroot(cfg->server_cert_file, cfg, 1); 161 s_key = fname_after_chroot(cfg->server_key_file, cfg, 1); 162 if(!s_cert || !s_key) { 163 log_err("out of memory in remote control fname"); 164 goto setup_error; 165 } 166 verbose(VERB_ALGO, "setup SSL certificates"); 167 if (!SSL_CTX_use_certificate_chain_file(rc->ctx,s_cert)) { 168 log_err("Error for server-cert-file: %s", s_cert); 169 log_crypto_err("Error in SSL_CTX use_certificate_chain_file"); 170 goto setup_error; 171 } 172 if(!SSL_CTX_use_PrivateKey_file(rc->ctx,s_key,SSL_FILETYPE_PEM)) { 173 log_err("Error for server-key-file: %s", s_key); 174 log_crypto_err("Error in SSL_CTX use_PrivateKey_file"); 175 goto setup_error; 176 } 177 if(!SSL_CTX_check_private_key(rc->ctx)) { 178 log_err("Error for server-key-file: %s", s_key); 179 log_crypto_err("Error in SSL_CTX check_private_key"); 180 goto setup_error; 181 } 182 listen_sslctx_setup_2(rc->ctx); 183 if(!SSL_CTX_load_verify_locations(rc->ctx, s_cert, NULL)) { 184 log_crypto_err("Error setting up SSL_CTX verify locations"); 185 setup_error: 186 free(s_cert); 187 free(s_key); 188 return 0; 189 } 190 SSL_CTX_set_client_CA_list(rc->ctx, SSL_load_client_CA_file(s_cert)); 191 SSL_CTX_set_verify(rc->ctx, SSL_VERIFY_PEER, NULL); 192 free(s_cert); 193 free(s_key); 194 return 1; 195 } 196 197 struct daemon_remote* 198 daemon_remote_create(struct config_file* cfg) 199 { 200 struct daemon_remote* rc = (struct daemon_remote*)calloc(1, 201 sizeof(*rc)); 202 if(!rc) { 203 log_err("out of memory in daemon_remote_create"); 204 return NULL; 205 } 206 rc->max_active = 10; 207 208 if(!cfg->remote_control_enable) { 209 rc->ctx = NULL; 210 return rc; 211 } 212 if(options_remote_is_address(cfg) && cfg->control_use_cert) { 213 if(!remote_setup_ctx(rc, cfg)) { 214 daemon_remote_delete(rc); 215 return NULL; 216 } 217 rc->use_cert = 1; 218 } else { 219 struct config_strlist* p; 220 rc->ctx = NULL; 221 rc->use_cert = 0; 222 if(!options_remote_is_address(cfg)) 223 for(p = cfg->control_ifs.first; p; p = p->next) { 224 if(p->str && p->str[0] != '/') 225 log_warn("control-interface %s is not using TLS, but plain transfer, because first control-interface in config file is a local socket (starts with a /).", p->str); 226 } 227 } 228 return rc; 229 } 230 231 void daemon_remote_clear(struct daemon_remote* rc) 232 { 233 struct rc_state* p, *np; 234 if(!rc) return; 235 /* but do not close the ports */ 236 listen_list_delete(rc->accept_list); 237 rc->accept_list = NULL; 238 /* do close these sockets */ 239 p = rc->busy_list; 240 while(p) { 241 np = p->next; 242 if(p->ssl) 243 SSL_free(p->ssl); 244 comm_point_delete(p->c); 245 free(p); 246 p = np; 247 } 248 rc->busy_list = NULL; 249 rc->active = 0; 250 rc->worker = NULL; 251 } 252 253 void daemon_remote_delete(struct daemon_remote* rc) 254 { 255 if(!rc) return; 256 daemon_remote_clear(rc); 257 if(rc->ctx) { 258 SSL_CTX_free(rc->ctx); 259 } 260 free(rc); 261 } 262 263 /** 264 * Add and open a new control port 265 * @param ip: ip str 266 * @param nr: port nr 267 * @param list: list head 268 * @param noproto_is_err: if lack of protocol support is an error. 269 * @param cfg: config with username for chown of unix-sockets. 270 * @return false on failure. 271 */ 272 static int 273 add_open(const char* ip, int nr, struct listen_port** list, int noproto_is_err, 274 struct config_file* cfg) 275 { 276 struct addrinfo hints; 277 struct addrinfo* res; 278 struct listen_port* n; 279 int noproto = 0; 280 int fd, r; 281 char port[15]; 282 snprintf(port, sizeof(port), "%d", nr); 283 port[sizeof(port)-1]=0; 284 memset(&hints, 0, sizeof(hints)); 285 log_assert(ip); 286 287 if(ip[0] == '/') { 288 /* This looks like a local socket */ 289 fd = create_local_accept_sock(ip, &noproto, cfg->use_systemd); 290 /* 291 * Change socket ownership and permissions so users other 292 * than root can access it provided they are in the same 293 * group as the user we run as. 294 */ 295 if(fd != -1) { 296 #ifdef HAVE_CHOWN 297 chmod(ip, (mode_t)(S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)); 298 if (cfg->username && cfg->username[0] && 299 cfg_uid != (uid_t)-1) { 300 if(chown(ip, cfg_uid, cfg_gid) == -1) 301 verbose(VERB_QUERY, "cannot chown %u.%u %s: %s", 302 (unsigned)cfg_uid, (unsigned)cfg_gid, 303 ip, strerror(errno)); 304 } 305 #else 306 (void)cfg; 307 #endif 308 } 309 } else { 310 char* s = strchr(ip, '@'); 311 char newif[128]; 312 if(s) { 313 /* override port with ifspec@port */ 314 int portnr; 315 if((size_t)(s-ip) >= sizeof(newif)) { 316 log_err("ifname too long: %s", ip); 317 return -1; 318 } 319 portnr = atoi(s+1); 320 if(portnr < 0 || 0 == portnr || portnr > 65535) { 321 log_err("invalid portnumber in control-interface: %s", ip); 322 return -1; 323 } 324 (void)strlcpy(newif, ip, sizeof(newif)); 325 newif[s-ip] = 0; 326 ip = newif; 327 snprintf(port, sizeof(port), "%d", portnr); 328 port[sizeof(port)-1]=0; 329 } 330 hints.ai_socktype = SOCK_STREAM; 331 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST; 332 if((r = getaddrinfo(ip, port, &hints, &res)) != 0 || !res) { 333 #ifdef USE_WINSOCK 334 if(!noproto_is_err && r == EAI_NONAME) { 335 /* tried to lookup the address as name */ 336 return 1; /* return success, but do nothing */ 337 } 338 #endif /* USE_WINSOCK */ 339 log_err("control interface %s:%s getaddrinfo: %s %s", 340 ip?ip:"default", port, gai_strerror(r), 341 #ifdef EAI_SYSTEM 342 r==EAI_SYSTEM?(char*)strerror(errno):"" 343 #else 344 "" 345 #endif 346 ); 347 return 0; 348 } 349 350 /* open fd */ 351 fd = create_tcp_accept_sock(res, 1, &noproto, 0, 352 cfg->ip_transparent, 0, 0, cfg->ip_freebind, 353 cfg->use_systemd, cfg->ip_dscp, "unbound-control"); 354 freeaddrinfo(res); 355 } 356 357 if(fd == -1 && noproto) { 358 if(!noproto_is_err) 359 return 1; /* return success, but do nothing */ 360 log_err("cannot open control interface %s %d : " 361 "protocol not supported", ip, nr); 362 return 0; 363 } 364 if(fd == -1) { 365 log_err("cannot open control interface %s %d", ip, nr); 366 return 0; 367 } 368 369 /* alloc */ 370 n = (struct listen_port*)calloc(1, sizeof(*n)); 371 if(!n) { 372 sock_close(fd); 373 log_err("out of memory"); 374 return 0; 375 } 376 n->next = *list; 377 *list = n; 378 n->fd = fd; 379 return 1; 380 } 381 382 struct listen_port* daemon_remote_open_ports(struct config_file* cfg) 383 { 384 struct listen_port* l = NULL; 385 log_assert(cfg->remote_control_enable && cfg->control_port); 386 if(cfg->control_ifs.first) { 387 char** rcif = NULL; 388 int i, num_rcif = 0; 389 if(!resolve_interface_names(NULL, 0, cfg->control_ifs.first, 390 &rcif, &num_rcif)) { 391 return NULL; 392 } 393 for(i=0; i<num_rcif; i++) { 394 if(!add_open(rcif[i], cfg->control_port, &l, 1, cfg)) { 395 listening_ports_free(l); 396 config_del_strarray(rcif, num_rcif); 397 return NULL; 398 } 399 } 400 config_del_strarray(rcif, num_rcif); 401 } else { 402 /* defaults */ 403 if(cfg->do_ip6 && 404 !add_open("::1", cfg->control_port, &l, 0, cfg)) { 405 listening_ports_free(l); 406 return NULL; 407 } 408 if(cfg->do_ip4 && 409 !add_open("127.0.0.1", cfg->control_port, &l, 1, cfg)) { 410 listening_ports_free(l); 411 return NULL; 412 } 413 } 414 return l; 415 } 416 417 /** open accept commpoint */ 418 static int 419 accept_open(struct daemon_remote* rc, int fd) 420 { 421 struct listen_list* n = (struct listen_list*)malloc(sizeof(*n)); 422 if(!n) { 423 log_err("out of memory"); 424 return 0; 425 } 426 n->next = rc->accept_list; 427 rc->accept_list = n; 428 /* open commpt */ 429 n->com = comm_point_create_raw(rc->worker->base, fd, 0, 430 &remote_accept_callback, rc); 431 if(!n->com) 432 return 0; 433 /* keep this port open, its fd is kept in the rc portlist */ 434 n->com->do_not_close = 1; 435 return 1; 436 } 437 438 int daemon_remote_open_accept(struct daemon_remote* rc, 439 struct listen_port* ports, struct worker* worker) 440 { 441 struct listen_port* p; 442 rc->worker = worker; 443 for(p = ports; p; p = p->next) { 444 if(!accept_open(rc, p->fd)) { 445 log_err("could not create accept comm point"); 446 return 0; 447 } 448 } 449 return 1; 450 } 451 452 void daemon_remote_stop_accept(struct daemon_remote* rc) 453 { 454 struct listen_list* p; 455 for(p=rc->accept_list; p; p=p->next) { 456 comm_point_stop_listening(p->com); 457 } 458 } 459 460 void daemon_remote_start_accept(struct daemon_remote* rc) 461 { 462 struct listen_list* p; 463 for(p=rc->accept_list; p; p=p->next) { 464 comm_point_start_listening(p->com, -1, -1); 465 } 466 } 467 468 int remote_accept_callback(struct comm_point* c, void* arg, int err, 469 struct comm_reply* ATTR_UNUSED(rep)) 470 { 471 struct daemon_remote* rc = (struct daemon_remote*)arg; 472 struct sockaddr_storage addr; 473 socklen_t addrlen; 474 int newfd; 475 struct rc_state* n; 476 if(err != NETEVENT_NOERROR) { 477 log_err("error %d on remote_accept_callback", err); 478 return 0; 479 } 480 /* perform the accept */ 481 newfd = comm_point_perform_accept(c, &addr, &addrlen); 482 if(newfd == -1) 483 return 0; 484 /* create new commpoint unless we are servicing already */ 485 if(rc->active >= rc->max_active) { 486 log_warn("drop incoming remote control: too many connections"); 487 close_exit: 488 sock_close(newfd); 489 return 0; 490 } 491 492 /* setup commpoint to service the remote control command */ 493 n = (struct rc_state*)calloc(1, sizeof(*n)); 494 if(!n) { 495 log_err("out of memory"); 496 goto close_exit; 497 } 498 n->fd = newfd; 499 /* start in reading state */ 500 n->c = comm_point_create_raw(rc->worker->base, newfd, 0, 501 &remote_control_callback, n); 502 if(!n->c) { 503 log_err("out of memory"); 504 free(n); 505 goto close_exit; 506 } 507 log_addr(VERB_QUERY, "new control connection from", &addr, addrlen); 508 n->c->do_not_close = 0; 509 comm_point_stop_listening(n->c); 510 comm_point_start_listening(n->c, -1, REMOTE_CONTROL_TCP_TIMEOUT); 511 memcpy(&n->c->repinfo.remote_addr, &addr, addrlen); 512 n->c->repinfo.remote_addrlen = addrlen; 513 if(rc->use_cert) { 514 n->shake_state = rc_hs_read; 515 n->ssl = SSL_new(rc->ctx); 516 if(!n->ssl) { 517 log_crypto_err("could not SSL_new"); 518 comm_point_delete(n->c); 519 free(n); 520 goto close_exit; 521 } 522 SSL_set_accept_state(n->ssl); 523 (void)SSL_set_mode(n->ssl, (long)SSL_MODE_AUTO_RETRY); 524 if(!SSL_set_fd(n->ssl, newfd)) { 525 log_crypto_err("could not SSL_set_fd"); 526 SSL_free(n->ssl); 527 comm_point_delete(n->c); 528 free(n); 529 goto close_exit; 530 } 531 } else { 532 n->ssl = NULL; 533 } 534 535 n->rc = rc; 536 n->next = rc->busy_list; 537 rc->busy_list = n; 538 rc->active ++; 539 540 /* perform the first nonblocking read already, for windows, 541 * so it can return wouldblock. could be faster too. */ 542 (void)remote_control_callback(n->c, n, NETEVENT_NOERROR, NULL); 543 return 0; 544 } 545 546 /** delete from list */ 547 static void 548 state_list_remove_elem(struct rc_state** list, struct comm_point* c) 549 { 550 while(*list) { 551 if( (*list)->c == c) { 552 *list = (*list)->next; 553 return; 554 } 555 list = &(*list)->next; 556 } 557 } 558 559 /** decrease active count and remove commpoint from busy list */ 560 static void 561 clean_point(struct daemon_remote* rc, struct rc_state* s) 562 { 563 if(!s->rc) { 564 /* the state has been picked up and moved away */ 565 free(s); 566 return; 567 } 568 state_list_remove_elem(&rc->busy_list, s->c); 569 rc->active --; 570 if(s->ssl) { 571 SSL_shutdown(s->ssl); 572 SSL_free(s->ssl); 573 } 574 comm_point_delete(s->c); 575 free(s); 576 } 577 578 int 579 ssl_print_text(RES* res, const char* text) 580 { 581 int r; 582 if(!res) 583 return 0; 584 if(res->ssl) { 585 ERR_clear_error(); 586 if((r=SSL_write(res->ssl, text, (int)strlen(text))) <= 0) { 587 int r2; 588 if((r2=SSL_get_error(res->ssl, r)) == SSL_ERROR_ZERO_RETURN) { 589 verbose(VERB_QUERY, "warning, in SSL_write, peer " 590 "closed connection"); 591 return 0; 592 } 593 log_crypto_err_io("could not SSL_write", r2); 594 return 0; 595 } 596 } else { 597 size_t at = 0; 598 while(at < strlen(text)) { 599 ssize_t r = send(res->fd, text+at, strlen(text)-at, 0); 600 if(r == -1) { 601 if(errno == EAGAIN || errno == EINTR) 602 continue; 603 log_err("could not send: %s", 604 sock_strerror(errno)); 605 return 0; 606 } 607 at += r; 608 } 609 } 610 return 1; 611 } 612 613 /** print text over the ssl connection */ 614 static int 615 ssl_print_vmsg(RES* ssl, const char* format, va_list args) 616 { 617 char msg[65535]; 618 vsnprintf(msg, sizeof(msg), format, args); 619 return ssl_print_text(ssl, msg); 620 } 621 622 /** printf style printing to the ssl connection */ 623 int ssl_printf(RES* ssl, const char* format, ...) 624 { 625 va_list args; 626 int ret; 627 va_start(args, format); 628 ret = ssl_print_vmsg(ssl, format, args); 629 va_end(args); 630 return ret; 631 } 632 633 int 634 ssl_read_line(RES* res, char* buf, size_t max) 635 { 636 int r; 637 size_t len = 0; 638 if(!res) 639 return 0; 640 while(len < max) { 641 if(res->ssl) { 642 ERR_clear_error(); 643 if((r=SSL_read(res->ssl, buf+len, 1)) <= 0) { 644 int r2; 645 if((r2=SSL_get_error(res->ssl, r)) == SSL_ERROR_ZERO_RETURN) { 646 buf[len] = 0; 647 return 1; 648 } 649 log_crypto_err_io("could not SSL_read", r2); 650 return 0; 651 } 652 } else { 653 while(1) { 654 ssize_t rr = recv(res->fd, buf+len, 1, 0); 655 if(rr <= 0) { 656 if(rr == 0) { 657 buf[len] = 0; 658 return 1; 659 } 660 if(errno == EINTR || errno == EAGAIN) 661 continue; 662 if(rr < 0) log_err("could not recv: %s", 663 sock_strerror(errno)); 664 return 0; 665 } 666 break; 667 } 668 } 669 if(buf[len] == '\n') { 670 /* return string without \n */ 671 buf[len] = 0; 672 return 1; 673 } 674 len++; 675 } 676 buf[max-1] = 0; 677 log_err("control line too long (%d): %s", (int)max, buf); 678 return 0; 679 } 680 681 /** skip whitespace, return new pointer into string */ 682 static char* 683 skipwhite(char* str) 684 { 685 /* EOS \0 is not a space */ 686 while( isspace((unsigned char)*str) ) 687 str++; 688 return str; 689 } 690 691 /** send the OK to the control client */ 692 static void send_ok(RES* ssl) 693 { 694 (void)ssl_printf(ssl, "ok\n"); 695 } 696 697 /** tell other processes to execute the command */ 698 static void 699 distribute_cmd(struct daemon_remote* rc, RES* ssl, char* cmd) 700 { 701 int i; 702 if(!cmd || !ssl) 703 return; 704 /* skip i=0 which is me */ 705 for(i=1; i<rc->worker->daemon->num; i++) { 706 worker_send_cmd(rc->worker->daemon->workers[i], 707 worker_cmd_remote); 708 if(!tube_write_msg(rc->worker->daemon->workers[i]->cmd, 709 (uint8_t*)cmd, strlen(cmd)+1, 0)) { 710 (void)ssl_printf(ssl, "error could not distribute cmd\n"); 711 return; 712 } 713 } 714 } 715 716 /** do the stop command */ 717 static void 718 do_stop(RES* ssl, struct worker* worker) 719 { 720 worker->need_to_exit = 1; 721 comm_base_exit(worker->base); 722 send_ok(ssl); 723 } 724 725 /** do the reload command */ 726 static void 727 do_reload(RES* ssl, struct worker* worker, int reuse_cache) 728 { 729 worker->reuse_cache = reuse_cache; 730 worker->need_to_exit = 0; 731 comm_base_exit(worker->base); 732 send_ok(ssl); 733 } 734 735 #ifndef THREADS_DISABLED 736 /** parse fast reload command options. */ 737 static int 738 fr_parse_options(RES* ssl, char* arg, int* fr_verb, int* fr_nopause, 739 int* fr_drop_mesh) 740 { 741 char* argp = arg; 742 while(*argp=='+') { 743 argp++; 744 while(*argp!=0 && *argp!=' ' && *argp!='\t') { 745 if(*argp == 'v') { 746 (*fr_verb)++; 747 } else if(*argp == 'p') { 748 (*fr_nopause) = 1; 749 } else if(*argp == 'd') { 750 (*fr_drop_mesh) = 1; 751 } else { 752 if(!ssl_printf(ssl, 753 "error: unknown option '+%c'\n", 754 *argp)) 755 return 0; 756 return 0; 757 } 758 argp++; 759 } 760 argp = skipwhite(argp); 761 } 762 if(*argp!=0) { 763 if(!ssl_printf(ssl, "error: unknown option '%s'\n", argp)) 764 return 0; 765 return 0; 766 } 767 return 1; 768 } 769 #endif /* !THREADS_DISABLED */ 770 771 /** do the fast_reload command */ 772 static void 773 do_fast_reload(RES* ssl, struct worker* worker, struct rc_state* s, char* arg) 774 { 775 #ifdef THREADS_DISABLED 776 if(!ssl_printf(ssl, "error: no threads for fast_reload, compiled without threads.\n")) 777 return; 778 (void)worker; 779 (void)s; 780 (void)arg; 781 #else 782 int fr_verb = 0, fr_nopause = 0, fr_drop_mesh = 0; 783 if(!fr_parse_options(ssl, arg, &fr_verb, &fr_nopause, &fr_drop_mesh)) 784 return; 785 if(fr_verb >= 1) { 786 if(!ssl_printf(ssl, "start fast_reload\n")) 787 return; 788 } 789 fast_reload_thread_start(ssl, worker, s, fr_verb, fr_nopause, 790 fr_drop_mesh); 791 #endif 792 } 793 794 /** do the verbosity command */ 795 static void 796 do_verbosity(RES* ssl, char* str) 797 { 798 int val = atoi(str); 799 if(val == 0 && strcmp(str, "0") != 0) { 800 ssl_printf(ssl, "error in verbosity number syntax: %s\n", str); 801 return; 802 } 803 verbosity = val; 804 send_ok(ssl); 805 } 806 807 /** print stats from statinfo */ 808 static int 809 print_stats(RES* ssl, const char* nm, struct ub_stats_info* s) 810 { 811 struct timeval sumwait, avg; 812 if(!ssl_printf(ssl, "%s.num.queries"SQ"%lu\n", nm, 813 (unsigned long)s->svr.num_queries)) return 0; 814 if(!ssl_printf(ssl, "%s.num.queries_ip_ratelimited"SQ"%lu\n", nm, 815 (unsigned long)s->svr.num_queries_ip_ratelimited)) return 0; 816 if(!ssl_printf(ssl, "%s.num.queries_cookie_valid"SQ"%lu\n", nm, 817 (unsigned long)s->svr.num_queries_cookie_valid)) return 0; 818 if(!ssl_printf(ssl, "%s.num.queries_cookie_client"SQ"%lu\n", nm, 819 (unsigned long)s->svr.num_queries_cookie_client)) return 0; 820 if(!ssl_printf(ssl, "%s.num.queries_cookie_invalid"SQ"%lu\n", nm, 821 (unsigned long)s->svr.num_queries_cookie_invalid)) return 0; 822 if(!ssl_printf(ssl, "%s.num.queries_discard_timeout"SQ"%lu\n", nm, 823 (unsigned long)s->svr.num_queries_discard_timeout)) return 0; 824 if(!ssl_printf(ssl, "%s.num.queries_replyaddr_limit"SQ"%lu\n", nm, 825 (unsigned long)s->svr.num_queries_replyaddr_limit)) return 0; 826 if(!ssl_printf(ssl, "%s.num.queries_wait_limit"SQ"%lu\n", nm, 827 (unsigned long)s->svr.num_queries_wait_limit)) return 0; 828 if(!ssl_printf(ssl, "%s.num.cachehits"SQ"%lu\n", nm, 829 (unsigned long)(s->svr.num_queries 830 - s->svr.num_queries_missed_cache))) return 0; 831 if(!ssl_printf(ssl, "%s.num.cachemiss"SQ"%lu\n", nm, 832 (unsigned long)s->svr.num_queries_missed_cache)) return 0; 833 if(!ssl_printf(ssl, "%s.num.prefetch"SQ"%lu\n", nm, 834 (unsigned long)s->svr.num_queries_prefetch)) return 0; 835 if(!ssl_printf(ssl, "%s.num.queries_timed_out"SQ"%lu\n", nm, 836 (unsigned long)s->svr.num_queries_timed_out)) return 0; 837 if(!ssl_printf(ssl, "%s.query.queue_time_us.max"SQ"%lu\n", nm, 838 (unsigned long)s->svr.max_query_time_us)) return 0; 839 if(!ssl_printf(ssl, "%s.num.expired"SQ"%lu\n", nm, 840 (unsigned long)s->svr.ans_expired)) return 0; 841 if(!ssl_printf(ssl, "%s.num.recursivereplies"SQ"%lu\n", nm, 842 (unsigned long)s->mesh_replies_sent)) return 0; 843 #ifdef USE_DNSCRYPT 844 if(!ssl_printf(ssl, "%s.num.dnscrypt.crypted"SQ"%lu\n", nm, 845 (unsigned long)s->svr.num_query_dnscrypt_crypted)) return 0; 846 if(!ssl_printf(ssl, "%s.num.dnscrypt.cert"SQ"%lu\n", nm, 847 (unsigned long)s->svr.num_query_dnscrypt_cert)) return 0; 848 if(!ssl_printf(ssl, "%s.num.dnscrypt.cleartext"SQ"%lu\n", nm, 849 (unsigned long)s->svr.num_query_dnscrypt_cleartext)) return 0; 850 if(!ssl_printf(ssl, "%s.num.dnscrypt.malformed"SQ"%lu\n", nm, 851 (unsigned long)s->svr.num_query_dnscrypt_crypted_malformed)) return 0; 852 #endif 853 if(!ssl_printf(ssl, "%s.num.dns_error_reports"SQ"%lu\n", nm, 854 (unsigned long)s->svr.num_dns_error_reports)) return 0; 855 if(!ssl_printf(ssl, "%s.requestlist.avg"SQ"%g\n", nm, 856 (s->svr.num_queries_missed_cache+s->svr.num_queries_prefetch)? 857 (double)s->svr.sum_query_list_size/ 858 (double)(s->svr.num_queries_missed_cache+ 859 s->svr.num_queries_prefetch) : 0.0)) return 0; 860 if(!ssl_printf(ssl, "%s.requestlist.max"SQ"%lu\n", nm, 861 (unsigned long)s->svr.max_query_list_size)) return 0; 862 if(!ssl_printf(ssl, "%s.requestlist.overwritten"SQ"%lu\n", nm, 863 (unsigned long)s->mesh_jostled)) return 0; 864 if(!ssl_printf(ssl, "%s.requestlist.exceeded"SQ"%lu\n", nm, 865 (unsigned long)s->mesh_dropped)) return 0; 866 if(!ssl_printf(ssl, "%s.requestlist.current.all"SQ"%lu\n", nm, 867 (unsigned long)s->mesh_num_states)) return 0; 868 if(!ssl_printf(ssl, "%s.requestlist.current.user"SQ"%lu\n", nm, 869 (unsigned long)s->mesh_num_reply_states)) return 0; 870 if(!ssl_printf(ssl, "%s.requestlist.current.replies"SQ"%lu\n", nm, 871 (unsigned long)s->mesh_num_reply_addrs)) return 0; 872 #ifndef S_SPLINT_S 873 sumwait.tv_sec = s->mesh_replies_sum_wait_sec; 874 sumwait.tv_usec = s->mesh_replies_sum_wait_usec; 875 #endif 876 timeval_divide(&avg, &sumwait, s->mesh_replies_sent); 877 if(!ssl_printf(ssl, "%s.recursion.time.avg"SQ ARG_LL "d.%6.6d\n", nm, 878 (long long)avg.tv_sec, (int)avg.tv_usec)) return 0; 879 if(!ssl_printf(ssl, "%s.recursion.time.median"SQ"%g\n", nm, 880 s->mesh_time_median)) return 0; 881 if(!ssl_printf(ssl, "%s.tcpusage"SQ"%lu\n", nm, 882 (unsigned long)s->svr.tcp_accept_usage)) return 0; 883 return 1; 884 } 885 886 /** print stats for one thread */ 887 static int 888 print_thread_stats(RES* ssl, int i, struct ub_stats_info* s) 889 { 890 char nm[32]; 891 snprintf(nm, sizeof(nm), "thread%d", i); 892 nm[sizeof(nm)-1]=0; 893 return print_stats(ssl, nm, s); 894 } 895 896 /** print long number */ 897 static int 898 print_longnum(RES* ssl, const char* desc, size_t x) 899 { 900 if(x > 1024*1024*1024) { 901 /* more than a Gb */ 902 size_t front = x / (size_t)1000000; 903 size_t back = x % (size_t)1000000; 904 return ssl_printf(ssl, "%s%u%6.6u\n", desc, 905 (unsigned)front, (unsigned)back); 906 } else { 907 return ssl_printf(ssl, "%s%lu\n", desc, (unsigned long)x); 908 } 909 } 910 911 /** print mem stats */ 912 static int 913 print_mem(RES* ssl, struct worker* worker, struct daemon* daemon, 914 struct ub_stats_info* s) 915 { 916 size_t msg, rrset, val, iter, respip; 917 #ifdef CLIENT_SUBNET 918 size_t subnet = 0; 919 #endif /* CLIENT_SUBNET */ 920 #ifdef USE_IPSECMOD 921 size_t ipsecmod = 0; 922 #endif /* USE_IPSECMOD */ 923 #ifdef USE_DNSCRYPT 924 size_t dnscrypt_shared_secret = 0; 925 size_t dnscrypt_nonce = 0; 926 #endif /* USE_DNSCRYPT */ 927 #ifdef WITH_DYNLIBMODULE 928 size_t dynlib = 0; 929 #endif /* WITH_DYNLIBMODULE */ 930 msg = slabhash_get_mem(daemon->env->msg_cache); 931 rrset = slabhash_get_mem(&daemon->env->rrset_cache->table); 932 val = mod_get_mem(&worker->env, "validator"); 933 iter = mod_get_mem(&worker->env, "iterator"); 934 respip = mod_get_mem(&worker->env, "respip"); 935 #ifdef CLIENT_SUBNET 936 subnet = mod_get_mem(&worker->env, "subnetcache"); 937 #endif /* CLIENT_SUBNET */ 938 #ifdef USE_IPSECMOD 939 ipsecmod = mod_get_mem(&worker->env, "ipsecmod"); 940 #endif /* USE_IPSECMOD */ 941 #ifdef USE_DNSCRYPT 942 if(daemon->dnscenv) { 943 dnscrypt_shared_secret = slabhash_get_mem( 944 daemon->dnscenv->shared_secrets_cache); 945 dnscrypt_nonce = slabhash_get_mem(daemon->dnscenv->nonces_cache); 946 } 947 #endif /* USE_DNSCRYPT */ 948 #ifdef WITH_DYNLIBMODULE 949 dynlib = mod_get_mem(&worker->env, "dynlib"); 950 #endif /* WITH_DYNLIBMODULE */ 951 952 if(!print_longnum(ssl, "mem.cache.rrset"SQ, rrset)) 953 return 0; 954 if(!print_longnum(ssl, "mem.cache.message"SQ, msg)) 955 return 0; 956 if(!print_longnum(ssl, "mem.mod.iterator"SQ, iter)) 957 return 0; 958 if(!print_longnum(ssl, "mem.mod.validator"SQ, val)) 959 return 0; 960 if(!print_longnum(ssl, "mem.mod.respip"SQ, respip)) 961 return 0; 962 #ifdef CLIENT_SUBNET 963 if(!print_longnum(ssl, "mem.mod.subnet"SQ, subnet)) 964 return 0; 965 #endif /* CLIENT_SUBNET */ 966 #ifdef USE_IPSECMOD 967 if(!print_longnum(ssl, "mem.mod.ipsecmod"SQ, ipsecmod)) 968 return 0; 969 #endif /* USE_IPSECMOD */ 970 #ifdef USE_DNSCRYPT 971 if(!print_longnum(ssl, "mem.cache.dnscrypt_shared_secret"SQ, 972 dnscrypt_shared_secret)) 973 return 0; 974 if(!print_longnum(ssl, "mem.cache.dnscrypt_nonce"SQ, 975 dnscrypt_nonce)) 976 return 0; 977 #endif /* USE_DNSCRYPT */ 978 #ifdef WITH_DYNLIBMODULE 979 if(!print_longnum(ssl, "mem.mod.dynlibmod"SQ, dynlib)) 980 return 0; 981 #endif /* WITH_DYNLIBMODULE */ 982 if(!print_longnum(ssl, "mem.streamwait"SQ, 983 (size_t)s->svr.mem_stream_wait)) 984 return 0; 985 if(!print_longnum(ssl, "mem.http.query_buffer"SQ, 986 (size_t)s->svr.mem_http2_query_buffer)) 987 return 0; 988 if(!print_longnum(ssl, "mem.http.response_buffer"SQ, 989 (size_t)s->svr.mem_http2_response_buffer)) 990 return 0; 991 #ifdef HAVE_NGTCP2 992 if(!print_longnum(ssl, "mem.quic"SQ, (size_t)s->svr.mem_quic)) 993 return 0; 994 #endif /* HAVE_NGTCP2 */ 995 return 1; 996 } 997 998 /** print uptime stats */ 999 static int 1000 print_uptime(RES* ssl, struct worker* worker, int reset) 1001 { 1002 struct timeval now = *worker->env.now_tv; 1003 struct timeval up, dt; 1004 timeval_subtract(&up, &now, &worker->daemon->time_boot); 1005 timeval_subtract(&dt, &now, &worker->daemon->time_last_stat); 1006 if(reset) 1007 worker->daemon->time_last_stat = now; 1008 if(!ssl_printf(ssl, "time.now"SQ ARG_LL "d.%6.6d\n", 1009 (long long)now.tv_sec, (unsigned)now.tv_usec)) return 0; 1010 if(!ssl_printf(ssl, "time.up"SQ ARG_LL "d.%6.6d\n", 1011 (long long)up.tv_sec, (unsigned)up.tv_usec)) return 0; 1012 if(!ssl_printf(ssl, "time.elapsed"SQ ARG_LL "d.%6.6d\n", 1013 (long long)dt.tv_sec, (unsigned)dt.tv_usec)) return 0; 1014 return 1; 1015 } 1016 1017 /** print extended histogram */ 1018 static int 1019 print_hist(RES* ssl, struct ub_stats_info* s) 1020 { 1021 struct timehist* hist; 1022 size_t i; 1023 hist = timehist_setup(); 1024 if(!hist) { 1025 log_err("out of memory"); 1026 return 0; 1027 } 1028 timehist_import(hist, s->svr.hist, NUM_BUCKETS_HIST); 1029 for(i=0; i<hist->num; i++) { 1030 if(!ssl_printf(ssl, 1031 "histogram.%6.6d.%6.6d.to.%6.6d.%6.6d=%lu\n", 1032 (int)hist->buckets[i].lower.tv_sec, 1033 (int)hist->buckets[i].lower.tv_usec, 1034 (int)hist->buckets[i].upper.tv_sec, 1035 (int)hist->buckets[i].upper.tv_usec, 1036 (unsigned long)hist->buckets[i].count)) { 1037 timehist_delete(hist); 1038 return 0; 1039 } 1040 } 1041 timehist_delete(hist); 1042 return 1; 1043 } 1044 1045 /** print extended stats */ 1046 static int 1047 print_ext(RES* ssl, struct ub_stats_info* s, int inhibit_zero) 1048 { 1049 int i; 1050 char nm[32]; 1051 const sldns_rr_descriptor* desc; 1052 const sldns_lookup_table* lt; 1053 /* TYPE */ 1054 for(i=0; i<UB_STATS_QTYPE_NUM; i++) { 1055 if(inhibit_zero && s->svr.qtype[i] == 0) 1056 continue; 1057 desc = sldns_rr_descript((uint16_t)i); 1058 if(desc && desc->_name) { 1059 snprintf(nm, sizeof(nm), "%s", desc->_name); 1060 } else if (i == LDNS_RR_TYPE_IXFR) { 1061 snprintf(nm, sizeof(nm), "IXFR"); 1062 } else if (i == LDNS_RR_TYPE_AXFR) { 1063 snprintf(nm, sizeof(nm), "AXFR"); 1064 } else if (i == LDNS_RR_TYPE_MAILA) { 1065 snprintf(nm, sizeof(nm), "MAILA"); 1066 } else if (i == LDNS_RR_TYPE_MAILB) { 1067 snprintf(nm, sizeof(nm), "MAILB"); 1068 } else if (i == LDNS_RR_TYPE_ANY) { 1069 snprintf(nm, sizeof(nm), "ANY"); 1070 } else { 1071 snprintf(nm, sizeof(nm), "TYPE%d", i); 1072 } 1073 if(!ssl_printf(ssl, "num.query.type.%s"SQ"%lu\n", 1074 nm, (unsigned long)s->svr.qtype[i])) return 0; 1075 } 1076 if(!inhibit_zero || s->svr.qtype_big) { 1077 if(!ssl_printf(ssl, "num.query.type.other"SQ"%lu\n", 1078 (unsigned long)s->svr.qtype_big)) return 0; 1079 } 1080 /* CLASS */ 1081 for(i=0; i<UB_STATS_QCLASS_NUM; i++) { 1082 if(inhibit_zero && s->svr.qclass[i] == 0) 1083 continue; 1084 lt = sldns_lookup_by_id(sldns_rr_classes, i); 1085 if(lt && lt->name) { 1086 snprintf(nm, sizeof(nm), "%s", lt->name); 1087 } else { 1088 snprintf(nm, sizeof(nm), "CLASS%d", i); 1089 } 1090 if(!ssl_printf(ssl, "num.query.class.%s"SQ"%lu\n", 1091 nm, (unsigned long)s->svr.qclass[i])) return 0; 1092 } 1093 if(!inhibit_zero || s->svr.qclass_big) { 1094 if(!ssl_printf(ssl, "num.query.class.other"SQ"%lu\n", 1095 (unsigned long)s->svr.qclass_big)) return 0; 1096 } 1097 /* OPCODE */ 1098 for(i=0; i<UB_STATS_OPCODE_NUM; i++) { 1099 if(inhibit_zero && s->svr.qopcode[i] == 0) 1100 continue; 1101 lt = sldns_lookup_by_id(sldns_opcodes, i); 1102 if(lt && lt->name) { 1103 snprintf(nm, sizeof(nm), "%s", lt->name); 1104 } else { 1105 snprintf(nm, sizeof(nm), "OPCODE%d", i); 1106 } 1107 if(!ssl_printf(ssl, "num.query.opcode.%s"SQ"%lu\n", 1108 nm, (unsigned long)s->svr.qopcode[i])) return 0; 1109 } 1110 /* transport */ 1111 if(!ssl_printf(ssl, "num.query.tcp"SQ"%lu\n", 1112 (unsigned long)s->svr.qtcp)) return 0; 1113 if(!ssl_printf(ssl, "num.query.tcpout"SQ"%lu\n", 1114 (unsigned long)s->svr.qtcp_outgoing)) return 0; 1115 if(!ssl_printf(ssl, "num.query.udpout"SQ"%lu\n", 1116 (unsigned long)s->svr.qudp_outgoing)) return 0; 1117 if(!ssl_printf(ssl, "num.query.tls"SQ"%lu\n", 1118 (unsigned long)s->svr.qtls)) return 0; 1119 if(!ssl_printf(ssl, "num.query.tls.resume"SQ"%lu\n", 1120 (unsigned long)s->svr.qtls_resume)) return 0; 1121 if(!ssl_printf(ssl, "num.query.ipv6"SQ"%lu\n", 1122 (unsigned long)s->svr.qipv6)) return 0; 1123 if(!ssl_printf(ssl, "num.query.https"SQ"%lu\n", 1124 (unsigned long)s->svr.qhttps)) return 0; 1125 #ifdef HAVE_NGTCP2 1126 if(!ssl_printf(ssl, "num.query.quic"SQ"%lu\n", 1127 (unsigned long)s->svr.qquic)) return 0; 1128 #endif /* HAVE_NGTCP2 */ 1129 /* flags */ 1130 if(!ssl_printf(ssl, "num.query.flags.QR"SQ"%lu\n", 1131 (unsigned long)s->svr.qbit_QR)) return 0; 1132 if(!ssl_printf(ssl, "num.query.flags.AA"SQ"%lu\n", 1133 (unsigned long)s->svr.qbit_AA)) return 0; 1134 if(!ssl_printf(ssl, "num.query.flags.TC"SQ"%lu\n", 1135 (unsigned long)s->svr.qbit_TC)) return 0; 1136 if(!ssl_printf(ssl, "num.query.flags.RD"SQ"%lu\n", 1137 (unsigned long)s->svr.qbit_RD)) return 0; 1138 if(!ssl_printf(ssl, "num.query.flags.RA"SQ"%lu\n", 1139 (unsigned long)s->svr.qbit_RA)) return 0; 1140 if(!ssl_printf(ssl, "num.query.flags.Z"SQ"%lu\n", 1141 (unsigned long)s->svr.qbit_Z)) return 0; 1142 if(!ssl_printf(ssl, "num.query.flags.AD"SQ"%lu\n", 1143 (unsigned long)s->svr.qbit_AD)) return 0; 1144 if(!ssl_printf(ssl, "num.query.flags.CD"SQ"%lu\n", 1145 (unsigned long)s->svr.qbit_CD)) return 0; 1146 if(!ssl_printf(ssl, "num.query.edns.present"SQ"%lu\n", 1147 (unsigned long)s->svr.qEDNS)) return 0; 1148 if(!ssl_printf(ssl, "num.query.edns.DO"SQ"%lu\n", 1149 (unsigned long)s->svr.qEDNS_DO)) return 0; 1150 1151 /* RCODE */ 1152 for(i=0; i<UB_STATS_RCODE_NUM; i++) { 1153 /* Always include RCODEs 0-5 */ 1154 if(inhibit_zero && i > LDNS_RCODE_REFUSED && s->svr.ans_rcode[i] == 0) 1155 continue; 1156 lt = sldns_lookup_by_id(sldns_rcodes, i); 1157 if(lt && lt->name) { 1158 snprintf(nm, sizeof(nm), "%s", lt->name); 1159 } else { 1160 snprintf(nm, sizeof(nm), "RCODE%d", i); 1161 } 1162 if(!ssl_printf(ssl, "num.answer.rcode.%s"SQ"%lu\n", 1163 nm, (unsigned long)s->svr.ans_rcode[i])) return 0; 1164 } 1165 if(!inhibit_zero || s->svr.ans_rcode_nodata) { 1166 if(!ssl_printf(ssl, "num.answer.rcode.nodata"SQ"%lu\n", 1167 (unsigned long)s->svr.ans_rcode_nodata)) return 0; 1168 } 1169 /* iteration */ 1170 if(!ssl_printf(ssl, "num.query.ratelimited"SQ"%lu\n", 1171 (unsigned long)s->svr.queries_ratelimited)) return 0; 1172 /* validation */ 1173 if(!ssl_printf(ssl, "num.answer.secure"SQ"%lu\n", 1174 (unsigned long)s->svr.ans_secure)) return 0; 1175 if(!ssl_printf(ssl, "num.answer.bogus"SQ"%lu\n", 1176 (unsigned long)s->svr.ans_bogus)) return 0; 1177 if(!ssl_printf(ssl, "num.rrset.bogus"SQ"%lu\n", 1178 (unsigned long)s->svr.rrset_bogus)) return 0; 1179 if(!ssl_printf(ssl, "num.valops"SQ"%lu\n", 1180 (unsigned long)s->svr.val_ops)) return 0; 1181 if(!ssl_printf(ssl, "num.query.aggressive.NOERROR"SQ"%lu\n", 1182 (unsigned long)s->svr.num_neg_cache_noerror)) return 0; 1183 if(!ssl_printf(ssl, "num.query.aggressive.NXDOMAIN"SQ"%lu\n", 1184 (unsigned long)s->svr.num_neg_cache_nxdomain)) return 0; 1185 /* threat detection */ 1186 if(!ssl_printf(ssl, "unwanted.queries"SQ"%lu\n", 1187 (unsigned long)s->svr.unwanted_queries)) return 0; 1188 if(!ssl_printf(ssl, "unwanted.replies"SQ"%lu\n", 1189 (unsigned long)s->svr.unwanted_replies)) return 0; 1190 /* cache counts */ 1191 if(!ssl_printf(ssl, "msg.cache.count"SQ"%u\n", 1192 (unsigned)s->svr.msg_cache_count)) return 0; 1193 if(!ssl_printf(ssl, "rrset.cache.count"SQ"%u\n", 1194 (unsigned)s->svr.rrset_cache_count)) return 0; 1195 if(!ssl_printf(ssl, "infra.cache.count"SQ"%u\n", 1196 (unsigned)s->svr.infra_cache_count)) return 0; 1197 if(!ssl_printf(ssl, "key.cache.count"SQ"%u\n", 1198 (unsigned)s->svr.key_cache_count)) return 0; 1199 /* max collisions */ 1200 if(!ssl_printf(ssl, "msg.cache.max_collisions"SQ"%u\n", 1201 (unsigned)s->svr.msg_cache_max_collisions)) return 0; 1202 if(!ssl_printf(ssl, "rrset.cache.max_collisions"SQ"%u\n", 1203 (unsigned)s->svr.rrset_cache_max_collisions)) return 0; 1204 /* applied RPZ actions */ 1205 for(i=0; i<UB_STATS_RPZ_ACTION_NUM; i++) { 1206 if(i == RPZ_NO_OVERRIDE_ACTION) 1207 continue; 1208 if(inhibit_zero && s->svr.rpz_action[i] == 0) 1209 continue; 1210 if(!ssl_printf(ssl, "num.rpz.action.%s"SQ"%lu\n", 1211 rpz_action_to_string(i), 1212 (unsigned long)s->svr.rpz_action[i])) return 0; 1213 } 1214 #ifdef USE_DNSCRYPT 1215 if(!ssl_printf(ssl, "dnscrypt_shared_secret.cache.count"SQ"%u\n", 1216 (unsigned)s->svr.shared_secret_cache_count)) return 0; 1217 if(!ssl_printf(ssl, "dnscrypt_nonce.cache.count"SQ"%u\n", 1218 (unsigned)s->svr.nonce_cache_count)) return 0; 1219 if(!ssl_printf(ssl, "num.query.dnscrypt.shared_secret.cachemiss"SQ"%lu\n", 1220 (unsigned long)s->svr.num_query_dnscrypt_secret_missed_cache)) return 0; 1221 if(!ssl_printf(ssl, "num.query.dnscrypt.replay"SQ"%lu\n", 1222 (unsigned long)s->svr.num_query_dnscrypt_replay)) return 0; 1223 #endif /* USE_DNSCRYPT */ 1224 if(!ssl_printf(ssl, "num.query.authzone.up"SQ"%lu\n", 1225 (unsigned long)s->svr.num_query_authzone_up)) return 0; 1226 if(!ssl_printf(ssl, "num.query.authzone.down"SQ"%lu\n", 1227 (unsigned long)s->svr.num_query_authzone_down)) return 0; 1228 #ifdef CLIENT_SUBNET 1229 if(!ssl_printf(ssl, "num.query.subnet"SQ"%lu\n", 1230 (unsigned long)s->svr.num_query_subnet)) return 0; 1231 if(!ssl_printf(ssl, "num.query.subnet_cache"SQ"%lu\n", 1232 (unsigned long)s->svr.num_query_subnet_cache)) return 0; 1233 #endif /* CLIENT_SUBNET */ 1234 #ifdef USE_CACHEDB 1235 if(!ssl_printf(ssl, "num.query.cachedb"SQ"%lu\n", 1236 (unsigned long)s->svr.num_query_cachedb)) return 0; 1237 #endif /* USE_CACHEDB */ 1238 return 1; 1239 } 1240 1241 /** do the stats command */ 1242 static void 1243 do_stats(RES* ssl, struct worker* worker, int reset) 1244 { 1245 struct daemon* daemon = worker->daemon; 1246 struct ub_stats_info total; 1247 struct ub_stats_info s; 1248 int i; 1249 memset(&total, 0, sizeof(total)); 1250 log_assert(daemon->num > 0); 1251 /* gather all thread statistics in one place */ 1252 for(i=0; i<daemon->num; i++) { 1253 server_stats_obtain(worker, daemon->workers[i], &s, reset); 1254 if(!print_thread_stats(ssl, i, &s)) 1255 return; 1256 if(i == 0) 1257 total = s; 1258 else server_stats_add(&total, &s); 1259 } 1260 /* print the thread statistics */ 1261 total.mesh_time_median /= (double)daemon->num; 1262 if(!print_stats(ssl, "total", &total)) 1263 return; 1264 if(!print_uptime(ssl, worker, reset)) 1265 return; 1266 if(daemon->cfg->stat_extended) { 1267 if(!print_mem(ssl, worker, daemon, &total)) 1268 return; 1269 if(!print_hist(ssl, &total)) 1270 return; 1271 if(!print_ext(ssl, &total, daemon->cfg->stat_inhibit_zero)) 1272 return; 1273 } 1274 } 1275 1276 /** parse commandline argument domain name */ 1277 static int 1278 parse_arg_name(RES* ssl, char* str, uint8_t** res, size_t* len, int* labs) 1279 { 1280 uint8_t nm[LDNS_MAX_DOMAINLEN+1]; 1281 size_t nmlen = sizeof(nm); 1282 int status; 1283 *res = NULL; 1284 *len = 0; 1285 *labs = 0; 1286 if(str[0] == '\0') { 1287 ssl_printf(ssl, "error: this option requires a domain name\n"); 1288 return 0; 1289 } 1290 status = sldns_str2wire_dname_buf(str, nm, &nmlen); 1291 if(status != 0) { 1292 ssl_printf(ssl, "error cannot parse name %s at %d: %s\n", str, 1293 LDNS_WIREPARSE_OFFSET(status), 1294 sldns_get_errorstr_parse(status)); 1295 return 0; 1296 } 1297 *res = memdup(nm, nmlen); 1298 if(!*res) { 1299 ssl_printf(ssl, "error out of memory\n"); 1300 return 0; 1301 } 1302 *labs = dname_count_size_labels(*res, len); 1303 return 1; 1304 } 1305 1306 /** find second argument, modifies string */ 1307 static int 1308 find_arg2(RES* ssl, char* arg, char** arg2) 1309 { 1310 char* as = strchr(arg, ' '); 1311 char* at = strchr(arg, '\t'); 1312 if(as && at) { 1313 if(at < as) 1314 as = at; 1315 as[0]=0; 1316 *arg2 = skipwhite(as+1); 1317 } else if(as) { 1318 as[0]=0; 1319 *arg2 = skipwhite(as+1); 1320 } else if(at) { 1321 at[0]=0; 1322 *arg2 = skipwhite(at+1); 1323 } else { 1324 ssl_printf(ssl, "error could not find next argument " 1325 "after %s\n", arg); 1326 return 0; 1327 } 1328 return 1; 1329 } 1330 1331 /** Add a new zone */ 1332 static int 1333 perform_zone_add(RES* ssl, struct local_zones* zones, char* arg) 1334 { 1335 uint8_t* nm; 1336 int nmlabs; 1337 size_t nmlen; 1338 char* arg2; 1339 enum localzone_type t; 1340 struct local_zone* z; 1341 if(!find_arg2(ssl, arg, &arg2)) 1342 return 0; 1343 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs)) 1344 return 0; 1345 if(!local_zone_str2type(arg2, &t)) { 1346 ssl_printf(ssl, "error not a zone type. %s\n", arg2); 1347 free(nm); 1348 return 0; 1349 } 1350 lock_rw_wrlock(&zones->lock); 1351 if((z=local_zones_find(zones, nm, nmlen, 1352 nmlabs, LDNS_RR_CLASS_IN))) { 1353 /* already present in tree */ 1354 lock_rw_wrlock(&z->lock); 1355 z->type = t; /* update type anyway */ 1356 lock_rw_unlock(&z->lock); 1357 free(nm); 1358 lock_rw_unlock(&zones->lock); 1359 return 1; 1360 } 1361 if(!local_zones_add_zone(zones, nm, nmlen, 1362 nmlabs, LDNS_RR_CLASS_IN, t)) { 1363 lock_rw_unlock(&zones->lock); 1364 ssl_printf(ssl, "error out of memory\n"); 1365 return 0; 1366 } 1367 lock_rw_unlock(&zones->lock); 1368 return 1; 1369 } 1370 1371 /** Do the local_zone command */ 1372 static void 1373 do_zone_add(RES* ssl, struct local_zones* zones, char* arg) 1374 { 1375 if(!perform_zone_add(ssl, zones, arg)) 1376 return; 1377 send_ok(ssl); 1378 } 1379 1380 /** Do the local_zones command */ 1381 static void 1382 do_zones_add(struct daemon_remote* rc, RES* ssl, struct worker* worker) 1383 { 1384 char buf[MAX_CMD_STRLINE + MAX_STDIN_STRLINE] = "local_zone "; 1385 int num = 0; 1386 size_t cmd_len = strlen(buf); 1387 while(ssl_read_line(ssl, buf+cmd_len, MAX_STDIN_STRLINE)) { 1388 if(buf[0+cmd_len] == 0 || 1389 (buf[0+cmd_len] == 0x04 && buf[1+cmd_len] == 0)) 1390 break; /* zero byte line or end of transmission */ 1391 #ifdef THREADS_DISABLED 1392 /* distribute single item command */ 1393 if(rc) distribute_cmd(rc, ssl, buf); 1394 #else 1395 (void)rc; /* unused */ 1396 #endif 1397 if(!perform_zone_add(ssl, worker->daemon->local_zones, 1398 buf+cmd_len)) { 1399 if(!ssl_printf(ssl, "error for input line: %s\n", 1400 buf+cmd_len)) 1401 return; 1402 } 1403 else num++; 1404 } 1405 (void)ssl_printf(ssl, "added %d zones\n", num); 1406 } 1407 1408 /** Remove a zone */ 1409 static int 1410 perform_zone_remove(RES* ssl, struct local_zones* zones, char* arg) 1411 { 1412 uint8_t* nm; 1413 int nmlabs; 1414 size_t nmlen; 1415 struct local_zone* z; 1416 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs)) 1417 return 0; 1418 lock_rw_wrlock(&zones->lock); 1419 if((z=local_zones_find(zones, nm, nmlen, 1420 nmlabs, LDNS_RR_CLASS_IN))) { 1421 /* present in tree */ 1422 local_zones_del_zone(zones, z); 1423 } 1424 lock_rw_unlock(&zones->lock); 1425 free(nm); 1426 return 1; 1427 } 1428 1429 /** Do the local_zone_remove command */ 1430 static void 1431 do_zone_remove(RES* ssl, struct local_zones* zones, char* arg) 1432 { 1433 if(!perform_zone_remove(ssl, zones, arg)) 1434 return; 1435 send_ok(ssl); 1436 } 1437 1438 /** Do the local_zones_remove command */ 1439 static void 1440 do_zones_remove(struct daemon_remote* rc, RES* ssl, struct worker* worker) 1441 { 1442 char buf[MAX_CMD_STRLINE + MAX_STDIN_STRLINE] = "local_zone_remove "; 1443 int num = 0; 1444 size_t cmd_len = strlen(buf); 1445 while(ssl_read_line(ssl, buf+cmd_len, MAX_STDIN_STRLINE)) { 1446 if(buf[0+cmd_len] == 0 || 1447 (buf[0+cmd_len] == 0x04 && buf[1+cmd_len] == 0)) 1448 break; /* zero byte line or end of transmission */ 1449 #ifdef THREADS_DISABLED 1450 /* distribute single item command */ 1451 if(rc) distribute_cmd(rc, ssl, buf); 1452 #else 1453 (void)rc; /* unused */ 1454 #endif 1455 if(!perform_zone_remove(ssl, worker->daemon->local_zones, 1456 buf+cmd_len)) { 1457 if(!ssl_printf(ssl, "error for input line: %s\n", 1458 buf+cmd_len)) 1459 return; 1460 } 1461 else num++; 1462 } 1463 (void)ssl_printf(ssl, "removed %d zones\n", num); 1464 } 1465 1466 /** check syntax of newly added RR */ 1467 static int 1468 check_RR_syntax(RES* ssl, char* str, int line) 1469 { 1470 uint8_t rr[LDNS_RR_BUF_SIZE]; 1471 size_t len = sizeof(rr), dname_len = 0; 1472 int s = sldns_str2wire_rr_buf(str, rr, &len, &dname_len, 3600, 1473 NULL, 0, NULL, 0); 1474 if(s != 0) { 1475 char linestr[32]; 1476 if(line == 0) 1477 linestr[0]=0; 1478 else snprintf(linestr, sizeof(linestr), "line %d ", line); 1479 if(!ssl_printf(ssl, "error parsing local-data at %sposition %d '%s': %s\n", 1480 linestr, LDNS_WIREPARSE_OFFSET(s), str, 1481 sldns_get_errorstr_parse(s))) 1482 return 0; 1483 return 0; 1484 } 1485 return 1; 1486 } 1487 1488 /** Add new RR data */ 1489 static int 1490 perform_data_add(RES* ssl, struct local_zones* zones, char* arg, int line) 1491 { 1492 if(!check_RR_syntax(ssl, arg, line)) { 1493 return 0; 1494 } 1495 if(!local_zones_add_RR(zones, arg)) { 1496 ssl_printf(ssl,"error in syntax or out of memory, %s\n", arg); 1497 return 0; 1498 } 1499 return 1; 1500 } 1501 1502 /** Do the local_data command */ 1503 static void 1504 do_data_add(RES* ssl, struct local_zones* zones, char* arg) 1505 { 1506 if(!perform_data_add(ssl, zones, arg, 0)) 1507 return; 1508 send_ok(ssl); 1509 } 1510 1511 /** Do the local_datas command */ 1512 static void 1513 do_datas_add(struct daemon_remote* rc, RES* ssl, struct worker* worker) 1514 { 1515 char buf[MAX_CMD_STRLINE + MAX_STDIN_STRLINE] = "local_data "; 1516 int num = 0, line = 0; 1517 size_t cmd_len = strlen(buf); 1518 while(ssl_read_line(ssl, buf+cmd_len, MAX_STDIN_STRLINE)) { 1519 if(buf[0+cmd_len] == 0 || 1520 (buf[0+cmd_len] == 0x04 && buf[1+cmd_len] == 0)) 1521 break; /* zero byte line or end of transmission */ 1522 #ifdef THREADS_DISABLED 1523 /* distribute single item command */ 1524 if(rc) distribute_cmd(rc, ssl, buf); 1525 #else 1526 (void)rc; /* unused */ 1527 #endif 1528 line++; 1529 if(perform_data_add(ssl, worker->daemon->local_zones, 1530 buf+cmd_len, line)) 1531 num++; 1532 } 1533 (void)ssl_printf(ssl, "added %d datas\n", num); 1534 } 1535 1536 /** Remove RR data */ 1537 static int 1538 perform_data_remove(RES* ssl, struct local_zones* zones, char* arg) 1539 { 1540 uint8_t* nm; 1541 int nmlabs; 1542 size_t nmlen; 1543 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs)) 1544 return 0; 1545 local_zones_del_data(zones, nm, 1546 nmlen, nmlabs, LDNS_RR_CLASS_IN); 1547 free(nm); 1548 return 1; 1549 } 1550 1551 /** Do the local_data_remove command */ 1552 static void 1553 do_data_remove(RES* ssl, struct local_zones* zones, char* arg) 1554 { 1555 if(!perform_data_remove(ssl, zones, arg)) 1556 return; 1557 send_ok(ssl); 1558 } 1559 1560 /** Do the local_datas_remove command */ 1561 static void 1562 do_datas_remove(struct daemon_remote* rc, RES* ssl, struct worker* worker) 1563 { 1564 char buf[MAX_CMD_STRLINE + MAX_STDIN_STRLINE] = "local_data_remove "; 1565 int num = 0; 1566 size_t cmd_len = strlen(buf); 1567 while(ssl_read_line(ssl, buf+cmd_len, MAX_STDIN_STRLINE)) { 1568 if(buf[0+cmd_len] == 0 || 1569 (buf[0+cmd_len] == 0x04 && buf[1+cmd_len] == 0)) 1570 break; /* zero byte line or end of transmission */ 1571 #ifdef THREADS_DISABLED 1572 /* distribute single item command */ 1573 if(rc) distribute_cmd(rc, ssl, buf); 1574 #else 1575 (void)rc; /* unused */ 1576 #endif 1577 if(!perform_data_remove(ssl, worker->daemon->local_zones, 1578 buf+cmd_len)) { 1579 if(!ssl_printf(ssl, "error for input line: %s\n", 1580 buf+cmd_len)) 1581 return; 1582 } 1583 else num++; 1584 } 1585 (void)ssl_printf(ssl, "removed %d datas\n", num); 1586 } 1587 1588 /** Add a new zone to view */ 1589 static void 1590 do_view_zone_add(RES* ssl, struct worker* worker, char* arg) 1591 { 1592 char* arg2; 1593 struct view* v; 1594 if(!find_arg2(ssl, arg, &arg2)) 1595 return; 1596 v = views_find_view(worker->env.views, arg, 1 /* get write lock*/); 1597 if(!v) { 1598 ssl_printf(ssl,"no view with name: %s\n", arg); 1599 return; 1600 } 1601 if(!v->local_zones) { 1602 if(!(v->local_zones = local_zones_create())){ 1603 lock_rw_unlock(&v->lock); 1604 ssl_printf(ssl,"error out of memory\n"); 1605 return; 1606 } 1607 if(!v->isfirst) { 1608 /* Global local-zone is not used for this view, 1609 * therefore add defaults to this view-specific 1610 * local-zone. */ 1611 struct config_file lz_cfg; 1612 memset(&lz_cfg, 0, sizeof(lz_cfg)); 1613 local_zone_enter_defaults(v->local_zones, &lz_cfg); 1614 } 1615 } 1616 do_zone_add(ssl, v->local_zones, arg2); 1617 lock_rw_unlock(&v->lock); 1618 } 1619 1620 /** Remove a zone from view */ 1621 static void 1622 do_view_zone_remove(RES* ssl, struct worker* worker, char* arg) 1623 { 1624 char* arg2; 1625 struct view* v; 1626 if(!find_arg2(ssl, arg, &arg2)) 1627 return; 1628 v = views_find_view(worker->env.views, arg, 1 /* get write lock*/); 1629 if(!v) { 1630 ssl_printf(ssl,"no view with name: %s\n", arg); 1631 return; 1632 } 1633 if(!v->local_zones) { 1634 lock_rw_unlock(&v->lock); 1635 send_ok(ssl); 1636 return; 1637 } 1638 do_zone_remove(ssl, v->local_zones, arg2); 1639 lock_rw_unlock(&v->lock); 1640 } 1641 1642 /** Add new RR data to view */ 1643 static void 1644 do_view_data_add(RES* ssl, struct worker* worker, char* arg) 1645 { 1646 char* arg2; 1647 struct view* v; 1648 if(!find_arg2(ssl, arg, &arg2)) 1649 return; 1650 v = views_find_view(worker->env.views, arg, 1 /* get write lock*/); 1651 if(!v) { 1652 ssl_printf(ssl,"no view with name: %s\n", arg); 1653 return; 1654 } 1655 if(!v->local_zones) { 1656 if(!(v->local_zones = local_zones_create())){ 1657 lock_rw_unlock(&v->lock); 1658 ssl_printf(ssl,"error out of memory\n"); 1659 return; 1660 } 1661 } 1662 do_data_add(ssl, v->local_zones, arg2); 1663 lock_rw_unlock(&v->lock); 1664 } 1665 1666 /** Add new RR data from stdin to view */ 1667 static void 1668 do_view_datas_add(struct daemon_remote* rc, RES* ssl, struct worker* worker, 1669 char* arg) 1670 { 1671 struct view* v; 1672 char buf[MAX_CMD_STRLINE + MAX_STDIN_STRLINE] = "view_local_data "; 1673 size_t cmd_len; 1674 int num = 0, line = 0; 1675 v = views_find_view(worker->env.views, arg, 1 /* get write lock*/); 1676 if(!v) { 1677 ssl_printf(ssl,"no view with name: %s\n", arg); 1678 return; 1679 } 1680 if(!v->local_zones) { 1681 if(!(v->local_zones = local_zones_create())){ 1682 lock_rw_unlock(&v->lock); 1683 ssl_printf(ssl,"error out of memory\n"); 1684 return; 1685 } 1686 } 1687 /* put the view name in the command buf */ 1688 (void)snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%s ", arg); 1689 cmd_len = strlen(buf); 1690 while(ssl_read_line(ssl, buf+cmd_len, MAX_STDIN_STRLINE)) { 1691 if(buf[0+cmd_len] == 0 || 1692 (buf[0+cmd_len] == 0x04 && buf[1+cmd_len] == 0)) 1693 break; /* zero byte line or end of transmission */ 1694 #ifdef THREADS_DISABLED 1695 /* distribute single item command */ 1696 if(rc) distribute_cmd(rc, ssl, buf); 1697 #else 1698 (void)rc; /* unused */ 1699 #endif 1700 line++; 1701 if(perform_data_add(ssl, v->local_zones, buf+cmd_len, line)) 1702 num++; 1703 } 1704 lock_rw_unlock(&v->lock); 1705 (void)ssl_printf(ssl, "added %d datas\n", num); 1706 } 1707 1708 /** Remove RR data from view */ 1709 static void 1710 do_view_data_remove(RES* ssl, struct worker* worker, char* arg) 1711 { 1712 char* arg2; 1713 struct view* v; 1714 if(!find_arg2(ssl, arg, &arg2)) 1715 return; 1716 v = views_find_view(worker->env.views, arg, 1 /* get write lock*/); 1717 if(!v) { 1718 ssl_printf(ssl,"no view with name: %s\n", arg); 1719 return; 1720 } 1721 if(!v->local_zones) { 1722 lock_rw_unlock(&v->lock); 1723 send_ok(ssl); 1724 return; 1725 } 1726 do_data_remove(ssl, v->local_zones, arg2); 1727 lock_rw_unlock(&v->lock); 1728 } 1729 1730 /** Remove RR data from stdin from view */ 1731 static void 1732 do_view_datas_remove(struct daemon_remote* rc, RES* ssl, struct worker* worker, 1733 char* arg) 1734 { 1735 struct view* v; 1736 char buf[MAX_CMD_STRLINE + MAX_STDIN_STRLINE] = "view_local_data_remove "; 1737 int num = 0; 1738 size_t cmd_len; 1739 v = views_find_view(worker->env.views, arg, 1 /* get write lock*/); 1740 if(!v) { 1741 ssl_printf(ssl,"no view with name: %s\n", arg); 1742 return; 1743 } 1744 if(!v->local_zones){ 1745 lock_rw_unlock(&v->lock); 1746 ssl_printf(ssl, "removed 0 datas\n"); 1747 return; 1748 } 1749 /* put the view name in the command buf */ 1750 (void)snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%s ", arg); 1751 cmd_len = strlen(buf); 1752 while(ssl_read_line(ssl, buf+cmd_len, MAX_STDIN_STRLINE)) { 1753 if(buf[0+cmd_len] == 0 || 1754 (buf[0+cmd_len] == 0x04 && buf[1+cmd_len] == 0)) 1755 break; /* zero byte line or end of transmission */ 1756 #ifdef THREADS_DISABLED 1757 /* distribute single item command */ 1758 if(rc) distribute_cmd(rc, ssl, buf); 1759 #else 1760 (void)rc; /* unused */ 1761 #endif 1762 if(!perform_data_remove(ssl, v->local_zones, buf+cmd_len)) { 1763 if(!ssl_printf(ssl, "error for input line: %s\n", 1764 buf+cmd_len)) 1765 return; 1766 } 1767 else num++; 1768 } 1769 lock_rw_unlock(&v->lock); 1770 (void)ssl_printf(ssl, "removed %d datas\n", num); 1771 } 1772 1773 /** information for the domain search */ 1774 struct cache_lookup_info { 1775 /** The connection to print on. */ 1776 RES* ssl; 1777 /** The worker. */ 1778 struct worker* worker; 1779 /** The domain, in wireformat. */ 1780 uint8_t* nm; 1781 /** The length of nm. */ 1782 size_t nmlen; 1783 }; 1784 1785 #ifdef CLIENT_SUBNET 1786 static void addrtree_traverse_visit_node(struct addrnode* n, addrkey_t* addr, 1787 size_t addr_size, int is_ipv6, time_t now, struct query_info* q, 1788 void (*func)(struct query_info*, struct reply_info*, addrkey_t*, 1789 size_t, int, addrlen_t, int, time_t, void*), void* arg); 1790 1791 /** Lookup in subnet addrtree */ 1792 static void 1793 cache_lookup_subnet_addrnode(struct query_info* q, struct reply_info* d, 1794 addrkey_t* addr, size_t addr_size, int is_ipv6, addrlen_t scope, 1795 int only_match_scope_zero, time_t ttl, void* arg) 1796 { 1797 size_t i; 1798 char s[65535], tp[32], cl[32], rc[32], fg[32], astr[64]; 1799 struct cache_lookup_info* inf = (struct cache_lookup_info*)arg; 1800 if(is_ipv6) { 1801 if(addr_size < 16 || inet_ntop(AF_INET6, addr, astr, 1802 sizeof(astr)) == NULL) 1803 snprintf(astr, sizeof(astr), "(inet6ntoperror)"); 1804 } else { 1805 if(addr_size < 4 || inet_ntop(AF_INET, addr, astr, 1806 sizeof(astr)) == NULL) 1807 snprintf(astr, sizeof(astr), "(inetntoperror)"); 1808 } 1809 sldns_wire2str_dname_buf(q->qname, q->qname_len, s, sizeof(s)); 1810 sldns_wire2str_type_buf(q->qtype, tp, sizeof(tp)); 1811 sldns_wire2str_class_buf(q->qclass, cl, sizeof(cl)); 1812 sldns_wire2str_rcode_buf(FLAGS_GET_RCODE(d->flags), 1813 rc, sizeof(rc)); 1814 snprintf(fg, sizeof(fg), "%s%s%s%s%s%s%s%s", 1815 ((d->flags&BIT_QR)?" QR":""), 1816 ((d->flags&BIT_AA)?" AA":""), 1817 ((d->flags&BIT_TC)?" TC":""), 1818 ((d->flags&BIT_RD)?" RD":""), 1819 ((d->flags&BIT_RA)?" RA":""), 1820 ((d->flags&BIT_Z)?" Z":""), 1821 ((d->flags&BIT_AD)?" AD":""), 1822 ((d->flags&BIT_CD)?" CD":"")); 1823 if(!rrset_array_lock(d->ref, d->rrset_count, 1824 *inf->worker->env.now)) { 1825 /* rrsets have timed out or do not exist */ 1826 return; 1827 } 1828 if(!ssl_printf(inf->ssl, "subnet %s/%d%s %s %s %s " ARG_LL "d\n", astr, 1829 (int)scope, (only_match_scope_zero?" scope_zero":""), 1830 s, cl, tp, (long long)(ttl-*inf->worker->env.now))) { 1831 rrset_array_unlock(d->ref, d->rrset_count); 1832 return; 1833 } 1834 ssl_printf(inf->ssl, 1835 "subnet msg %s %s %s%s %s %d %d " ARG_LL "d %d %u %u %u %d %s\n", 1836 s, cl, tp, fg, rc, 1837 (int)d->flags, (int)d->qdcount, 1838 (long long)(d->ttl-*inf->worker->env.now), 1839 (int)d->security, 1840 (unsigned)d->an_numrrsets, 1841 (unsigned)d->ns_numrrsets, 1842 (unsigned)d->ar_numrrsets, 1843 (int)d->reason_bogus, 1844 d->reason_bogus_str?d->reason_bogus_str:""); 1845 for(i=0; i<d->rrset_count; i++) { 1846 struct ub_packed_rrset_key* rk = d->rrsets[i]; 1847 struct packed_rrset_data* rd = (struct packed_rrset_data*)rk->entry.data; 1848 size_t j; 1849 for(j=0; j<rd->count + rd->rrsig_count; j++) { 1850 if(!packed_rr_to_string(rk, j, 1851 *inf->worker->env.now, s, sizeof(s))) { 1852 ssl_printf(inf->ssl, "BADRR\n"); 1853 } else { 1854 ssl_printf(inf->ssl, "%s", s); 1855 } 1856 } 1857 } 1858 rrset_array_unlock(d->ref, d->rrset_count); 1859 ssl_printf(inf->ssl, "\n"); 1860 } 1861 1862 /** Visit an edge in subnet addrtree traverse */ 1863 static void 1864 addrtree_traverse_visit_edge(struct addredge* edge, addrkey_t* addr, 1865 size_t addr_size, int is_ipv6, time_t now, struct query_info* q, 1866 void (*func)(struct query_info*, struct reply_info*, addrkey_t*, 1867 size_t, int, addrlen_t, int, time_t, void*), void* arg) 1868 { 1869 size_t n; 1870 addrlen_t addrlen; 1871 if(!edge || !edge->node) 1872 return; 1873 addrlen = edge->len; 1874 /* ceil() */ 1875 n = (size_t)((addrlen / KEYWIDTH) + ((addrlen % KEYWIDTH != 0)?1:0)); 1876 if(n > addr_size) 1877 n = addr_size; 1878 memset(addr, 0, addr_size); 1879 memcpy(addr, edge->str, n); 1880 addrtree_traverse_visit_node(edge->node, addr, addr_size, is_ipv6, 1881 now, q, func, arg); 1882 } 1883 1884 /** Visit a node in subnet addrtree traverse */ 1885 static void 1886 addrtree_traverse_visit_node(struct addrnode* n, addrkey_t* addr, 1887 size_t addr_size, int is_ipv6, time_t now, struct query_info* q, 1888 void (*func)(struct query_info*, struct reply_info*, addrkey_t*, 1889 size_t, int, addrlen_t, int, time_t, void*), void* arg) 1890 { 1891 /* If this node has data, and not expired. */ 1892 if(n->elem && n->ttl >= now) { 1893 func(q, (struct reply_info*)n->elem, addr, addr_size, is_ipv6, 1894 n->scope, n->only_match_scope_zero, n->ttl, arg); 1895 } 1896 /* Traverse edges. */ 1897 addrtree_traverse_visit_edge(n->edge[0], addr, addr_size, is_ipv6, 1898 now, q, func, arg); 1899 addrtree_traverse_visit_edge(n->edge[1], addr, addr_size, is_ipv6, 1900 now, q, func, arg); 1901 } 1902 1903 /** Traverse subnet addrtree */ 1904 static void 1905 addrtree_traverse(struct addrtree* tree, int is_ipv6, time_t now, 1906 struct query_info* q, 1907 void (*func)(struct query_info*, struct reply_info*, addrkey_t*, 1908 size_t, int, addrlen_t, int, time_t, void*), void* arg) 1909 { 1910 uint8_t addr[16]; /* Large enough for IPv4 and IPv6. */ 1911 memset(addr, 0, sizeof(addr)); 1912 addrtree_traverse_visit_node(tree->root, (addrkey_t*)addr, 1913 sizeof(addr), is_ipv6, now, q, func, arg); 1914 } 1915 1916 /** Lookup cache_lookup for subnet content. */ 1917 static void 1918 cache_lookup_subnet_msg(struct lruhash_entry* e, void* arg) 1919 { 1920 struct cache_lookup_info* inf = (struct cache_lookup_info*)arg; 1921 struct msgreply_entry *k = (struct msgreply_entry*)e->key; 1922 struct subnet_msg_cache_data* d = 1923 (struct subnet_msg_cache_data*)e->data; 1924 if(!dname_subdomain_c(k->key.qname, inf->nm)) 1925 return; 1926 1927 if(d->tree4) { 1928 addrtree_traverse(d->tree4, 0, *inf->worker->env.now, &k->key, 1929 &cache_lookup_subnet_addrnode, inf); 1930 } 1931 if(d->tree6) { 1932 addrtree_traverse(d->tree6, 1, *inf->worker->env.now, &k->key, 1933 &cache_lookup_subnet_addrnode, inf); 1934 } 1935 } 1936 #endif /* CLIENT_SUBNET */ 1937 1938 static void 1939 cache_lookup_rrset(struct lruhash_entry* e, void* arg) 1940 { 1941 struct cache_lookup_info* inf = (struct cache_lookup_info*)arg; 1942 struct ub_packed_rrset_key* k = (struct ub_packed_rrset_key*)e->key; 1943 struct packed_rrset_data* d = (struct packed_rrset_data*)e->data; 1944 if(*inf->worker->env.now < d->ttl && 1945 k->id != 0 && /* not deleted */ 1946 dname_subdomain_c(k->rk.dname, inf->nm)) { 1947 size_t i; 1948 for(i=0; i<d->count + d->rrsig_count; i++) { 1949 char s[65535]; 1950 if(!packed_rr_to_string(k, i, *inf->worker->env.now, 1951 s, sizeof(s))) { 1952 ssl_printf(inf->ssl, "BADRR\n"); 1953 return; 1954 } 1955 ssl_printf(inf->ssl, "%s", s); 1956 } 1957 ssl_printf(inf->ssl, "\n"); 1958 } 1959 } 1960 1961 static void 1962 cache_lookup_msg(struct lruhash_entry* e, void* arg) 1963 { 1964 struct cache_lookup_info* inf = (struct cache_lookup_info*)arg; 1965 struct msgreply_entry* k = (struct msgreply_entry*)e->key; 1966 struct reply_info* d = (struct reply_info*)e->data; 1967 if(*inf->worker->env.now < d->ttl && 1968 dname_subdomain_c(k->key.qname, inf->nm)) { 1969 size_t i; 1970 char s[65535], tp[32], cl[32], rc[32], fg[32]; 1971 sldns_wire2str_dname_buf(k->key.qname, k->key.qname_len, 1972 s, sizeof(s)); 1973 sldns_wire2str_type_buf(k->key.qtype, tp, sizeof(tp)); 1974 sldns_wire2str_class_buf(k->key.qclass, cl, sizeof(cl)); 1975 sldns_wire2str_rcode_buf(FLAGS_GET_RCODE(d->flags), 1976 rc, sizeof(rc)); 1977 snprintf(fg, sizeof(fg), "%s%s%s%s%s%s%s%s", 1978 ((d->flags&BIT_QR)?" QR":""), 1979 ((d->flags&BIT_AA)?" AA":""), 1980 ((d->flags&BIT_TC)?" TC":""), 1981 ((d->flags&BIT_RD)?" RD":""), 1982 ((d->flags&BIT_RA)?" RA":""), 1983 ((d->flags&BIT_Z)?" Z":""), 1984 ((d->flags&BIT_AD)?" AD":""), 1985 ((d->flags&BIT_CD)?" CD":"")); 1986 if(!rrset_array_lock(d->ref, d->rrset_count, 1987 *inf->worker->env.now)) { 1988 /* rrsets have timed out or do not exist */ 1989 return; 1990 } 1991 ssl_printf(inf->ssl, 1992 "msg %s %s %s%s %s %d %d " ARG_LL "d %d %u %u %u %d %s\n", 1993 s, cl, tp, fg, rc, 1994 (int)d->flags, (int)d->qdcount, 1995 (long long)(d->ttl-*inf->worker->env.now), 1996 (int)d->security, 1997 (unsigned)d->an_numrrsets, 1998 (unsigned)d->ns_numrrsets, 1999 (unsigned)d->ar_numrrsets, 2000 (int)d->reason_bogus, 2001 d->reason_bogus_str?d->reason_bogus_str:""); 2002 for(i=0; i<d->rrset_count; i++) { 2003 struct ub_packed_rrset_key* rk = d->rrsets[i]; 2004 struct packed_rrset_data* rd = (struct packed_rrset_data*)rk->entry.data; 2005 size_t j; 2006 for(j=0; j<rd->count + rd->rrsig_count; j++) { 2007 if(!packed_rr_to_string(rk, j, 2008 *inf->worker->env.now, s, sizeof(s))) { 2009 rrset_array_unlock(d->ref, d->rrset_count); 2010 ssl_printf(inf->ssl, "BADRR\n"); 2011 return; 2012 } 2013 ssl_printf(inf->ssl, "%s", s); 2014 } 2015 } 2016 rrset_array_unlock(d->ref, d->rrset_count); 2017 ssl_printf(inf->ssl, "\n"); 2018 } 2019 } 2020 2021 /** perform cache search for domain */ 2022 static void 2023 do_cache_lookup_domain(RES* ssl, struct worker* worker, uint8_t* nm, 2024 size_t nmlen) 2025 { 2026 #ifdef CLIENT_SUBNET 2027 int m; 2028 struct subnet_env* sn_env = NULL; 2029 #endif /* CLIENT_SUBNET */ 2030 struct cache_lookup_info inf; 2031 inf.ssl = ssl; 2032 inf.worker = worker; 2033 inf.nm = nm; 2034 inf.nmlen = nmlen; 2035 2036 #ifdef CLIENT_SUBNET 2037 m = modstack_find(worker->env.modstack, "subnetcache"); 2038 if(m != -1) sn_env = (struct subnet_env*)worker->env.modinfo[m]; 2039 if(sn_env) { 2040 lock_rw_rdlock(&sn_env->biglock); 2041 slabhash_traverse(sn_env->subnet_msg_cache, 0, 2042 &cache_lookup_subnet_msg, &inf); 2043 lock_rw_unlock(&sn_env->biglock); 2044 } 2045 #endif /* CLIENT_SUBNET */ 2046 2047 slabhash_traverse(&worker->env.rrset_cache->table, 0, 2048 &cache_lookup_rrset, &inf); 2049 slabhash_traverse(worker->env.msg_cache, 0, &cache_lookup_msg, &inf); 2050 } 2051 2052 /** cache lookup of domain */ 2053 static void 2054 do_cache_lookup(RES* ssl, struct worker* worker, char* arg) 2055 { 2056 uint8_t nm[LDNS_MAX_DOMAINLEN+1]; 2057 size_t nmlen; 2058 int status; 2059 char* s = arg, *next = NULL; 2060 int allow_long = 0; 2061 2062 if(arg[0] == '+' && arg[1] == 't' && (arg[2]==' ' || arg[2]=='\t')) { 2063 allow_long = 1; 2064 s = arg+2; 2065 } 2066 2067 /* Find the commandline arguments of domains. */ 2068 while(s && *s != 0) { 2069 s = skipwhite(s); 2070 if(*s == 0) 2071 break; 2072 if(strchr(s, ' ') || strchr(s, '\t')) { 2073 char* sp = strchr(s, ' '); 2074 if(strchr(s, '\t') != 0 && strchr(s, '\t') < sp) 2075 sp = strchr(s, '\t'); 2076 *sp = 0; 2077 next = sp+1; 2078 } else { 2079 next = NULL; 2080 } 2081 2082 nmlen = sizeof(nm); 2083 status = sldns_str2wire_dname_buf(s, nm, &nmlen); 2084 if(status != 0) { 2085 ssl_printf(ssl, "error cannot parse name %s at %d: %s\n", s, 2086 LDNS_WIREPARSE_OFFSET(status), 2087 sldns_get_errorstr_parse(status)); 2088 return; 2089 } 2090 if(!allow_long && dname_count_labels(nm) < 3) { 2091 ssl_printf(ssl, "error name too short: '%s'. Need example.com. or longer, short names take very long, use +t to allow them.\n", s); 2092 return; 2093 } 2094 2095 do_cache_lookup_domain(ssl, worker, nm, nmlen); 2096 2097 s = next; 2098 } 2099 } 2100 2101 /** cache lookup of nameservers */ 2102 static void 2103 do_lookup(RES* ssl, struct worker* worker, char* arg) 2104 { 2105 uint8_t* nm; 2106 int nmlabs; 2107 size_t nmlen; 2108 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs)) 2109 return; 2110 (void)print_deleg_lookup(ssl, worker, nm, nmlen, nmlabs); 2111 free(nm); 2112 } 2113 2114 /** flush something from rrset and msg caches */ 2115 static void 2116 do_cache_remove(struct worker* worker, uint8_t* nm, size_t nmlen, 2117 uint16_t t, uint16_t c, int remcachedb) 2118 { 2119 hashvalue_type h; 2120 struct query_info k; 2121 rrset_cache_remove(worker->env.rrset_cache, nm, nmlen, t, c, 0); 2122 if(t == LDNS_RR_TYPE_SOA) 2123 rrset_cache_remove(worker->env.rrset_cache, nm, nmlen, t, c, 2124 PACKED_RRSET_SOA_NEG); 2125 k.qname = nm; 2126 k.qname_len = nmlen; 2127 k.qtype = t; 2128 k.qclass = c; 2129 k.local_alias = NULL; 2130 h = query_info_hash(&k, 0); 2131 slabhash_remove(worker->env.msg_cache, h, &k); 2132 if(t == LDNS_RR_TYPE_AAAA) { 2133 /* for AAAA also flush dns64 bit_cd packet */ 2134 h = query_info_hash(&k, BIT_CD); 2135 slabhash_remove(worker->env.msg_cache, h, &k); 2136 } 2137 #ifdef USE_CACHEDB 2138 if(remcachedb && worker->env.cachedb_enabled) 2139 cachedb_msg_remove_qinfo(&worker->env, &k); 2140 #else 2141 (void)remcachedb; 2142 #endif 2143 } 2144 2145 /** parse '+c' option, modifies string to return remainder. */ 2146 static int 2147 parse_remcachedb(RES* ssl, char** arg, int* pc) 2148 { 2149 *arg = skipwhite(*arg); 2150 if((*arg)[0] == '+' && (*arg)[1] == 'c') { 2151 char* arg2; 2152 *pc = 1; 2153 if(!find_arg2(ssl, *arg, &arg2)) 2154 return 0; 2155 *arg = arg2; 2156 return 1; 2157 } 2158 /* The option was not found, no problem */ 2159 return 1; 2160 } 2161 2162 /** flush a type */ 2163 static void 2164 do_flush_type(RES* ssl, struct worker* worker, char* arg) 2165 { 2166 uint8_t* nm; 2167 int nmlabs; 2168 size_t nmlen; 2169 char* arg2; 2170 uint16_t t; 2171 int pc = 0; /* '+c' option */ 2172 if(!parse_remcachedb(ssl, &arg, &pc)) 2173 return; 2174 if(!find_arg2(ssl, arg, &arg2)) 2175 return; 2176 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs)) 2177 return; 2178 t = sldns_get_rr_type_by_name(arg2); 2179 if(t == 0 && strcmp(arg2, "TYPE0") != 0) { 2180 (void)ssl_printf(ssl, "error parsing RRset type: '%s'\n", arg2); 2181 free(nm); 2182 return; 2183 } 2184 do_cache_remove(worker, nm, nmlen, t, LDNS_RR_CLASS_IN, pc); 2185 2186 free(nm); 2187 send_ok(ssl); 2188 } 2189 2190 /** flush statistics */ 2191 static void 2192 do_flush_stats(RES* ssl, struct worker* worker) 2193 { 2194 worker_stats_clear(worker); 2195 send_ok(ssl); 2196 } 2197 2198 /** 2199 * Local info for deletion functions 2200 */ 2201 struct del_info { 2202 /** worker */ 2203 struct worker* worker; 2204 /** name to delete */ 2205 uint8_t* name; 2206 /** length */ 2207 size_t len; 2208 /** labels */ 2209 int labs; 2210 /** time to invalidate to */ 2211 time_t expired; 2212 /** number of rrsets removed */ 2213 size_t num_rrsets; 2214 /** number of msgs removed */ 2215 size_t num_msgs; 2216 /** number of key entries removed */ 2217 size_t num_keys; 2218 /** length of addr */ 2219 socklen_t addrlen; 2220 /** socket address for host deletion */ 2221 struct sockaddr_storage addr; 2222 /** if cachedb information should be flushed too */ 2223 int remcachedb; 2224 }; 2225 2226 /** callback to delete hosts in infra cache */ 2227 static void 2228 infra_del_host(struct lruhash_entry* e, void* arg) 2229 { 2230 /* entry is locked */ 2231 struct del_info* inf = (struct del_info*)arg; 2232 struct infra_key* k = (struct infra_key*)e->key; 2233 if(sockaddr_cmp(&inf->addr, inf->addrlen, &k->addr, k->addrlen) == 0) { 2234 struct infra_data* d = (struct infra_data*)e->data; 2235 d->probedelay = 0; 2236 d->timeout_A = 0; 2237 d->timeout_AAAA = 0; 2238 d->timeout_other = 0; 2239 rtt_init(&d->rtt); 2240 if(d->ttl > inf->expired) { 2241 d->ttl = inf->expired; 2242 inf->num_keys++; 2243 } 2244 } 2245 } 2246 2247 /** flush infra cache */ 2248 static void 2249 do_flush_infra(RES* ssl, struct worker* worker, char* arg) 2250 { 2251 struct sockaddr_storage addr; 2252 socklen_t len; 2253 struct del_info inf; 2254 if(strcmp(arg, "all") == 0) { 2255 slabhash_clear(worker->env.infra_cache->hosts); 2256 send_ok(ssl); 2257 return; 2258 } 2259 if(!ipstrtoaddr(arg, UNBOUND_DNS_PORT, &addr, &len)) { 2260 (void)ssl_printf(ssl, "error parsing ip addr: '%s'\n", arg); 2261 return; 2262 } 2263 /* delete all entries from cache */ 2264 /* what we do is to set them all expired */ 2265 inf.worker = worker; 2266 inf.name = 0; 2267 inf.len = 0; 2268 inf.labs = 0; 2269 inf.expired = *worker->env.now; 2270 inf.expired -= 3; /* handle 3 seconds skew between threads */ 2271 inf.num_rrsets = 0; 2272 inf.num_msgs = 0; 2273 inf.num_keys = 0; 2274 inf.addrlen = len; 2275 inf.remcachedb = 0; 2276 memmove(&inf.addr, &addr, len); 2277 slabhash_traverse(worker->env.infra_cache->hosts, 1, &infra_del_host, 2278 &inf); 2279 send_ok(ssl); 2280 } 2281 2282 /** flush requestlist */ 2283 static void 2284 do_flush_requestlist(RES* ssl, struct worker* worker) 2285 { 2286 mesh_delete_all(worker->env.mesh); 2287 send_ok(ssl); 2288 } 2289 2290 /** callback to delete rrsets in a zone */ 2291 static void 2292 zone_del_rrset(struct lruhash_entry* e, void* arg) 2293 { 2294 /* entry is locked */ 2295 struct del_info* inf = (struct del_info*)arg; 2296 struct ub_packed_rrset_key* k = (struct ub_packed_rrset_key*)e->key; 2297 if(dname_subdomain_c(k->rk.dname, inf->name)) { 2298 struct packed_rrset_data* d = 2299 (struct packed_rrset_data*)e->data; 2300 if(d->ttl > inf->expired) { 2301 d->ttl = inf->expired; 2302 inf->num_rrsets++; 2303 } 2304 } 2305 } 2306 2307 /** callback to delete messages in a zone */ 2308 static void 2309 zone_del_msg(struct lruhash_entry* e, void* arg) 2310 { 2311 /* entry is locked */ 2312 struct del_info* inf = (struct del_info*)arg; 2313 struct msgreply_entry* k = (struct msgreply_entry*)e->key; 2314 if(dname_subdomain_c(k->key.qname, inf->name)) { 2315 struct reply_info* d = (struct reply_info*)e->data; 2316 if(d->ttl > inf->expired) { 2317 d->ttl = inf->expired; 2318 d->prefetch_ttl = inf->expired; 2319 d->serve_expired_ttl = inf->expired; 2320 inf->num_msgs++; 2321 } 2322 #ifdef USE_CACHEDB 2323 if(inf->remcachedb && inf->worker->env.cachedb_enabled) 2324 cachedb_msg_remove_qinfo(&inf->worker->env, &k->key); 2325 #endif 2326 } 2327 } 2328 2329 /** callback to delete keys in zone */ 2330 static void 2331 zone_del_kcache(struct lruhash_entry* e, void* arg) 2332 { 2333 /* entry is locked */ 2334 struct del_info* inf = (struct del_info*)arg; 2335 struct key_entry_key* k = (struct key_entry_key*)e->key; 2336 if(dname_subdomain_c(k->name, inf->name)) { 2337 struct key_entry_data* d = (struct key_entry_data*)e->data; 2338 if(d->ttl > inf->expired) { 2339 d->ttl = inf->expired; 2340 inf->num_keys++; 2341 } 2342 } 2343 } 2344 2345 /** remove all rrsets and keys from zone from cache */ 2346 static void 2347 do_flush_zone(RES* ssl, struct worker* worker, char* arg) 2348 { 2349 uint8_t* nm; 2350 int nmlabs; 2351 size_t nmlen; 2352 struct del_info inf; 2353 int pc = 0; /* '+c' option */ 2354 if(!parse_remcachedb(ssl, &arg, &pc)) 2355 return; 2356 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs)) 2357 return; 2358 /* delete all RRs and key entries from zone */ 2359 /* what we do is to set them all expired */ 2360 inf.worker = worker; 2361 inf.name = nm; 2362 inf.len = nmlen; 2363 inf.labs = nmlabs; 2364 inf.expired = *worker->env.now; 2365 inf.expired -= 3; /* handle 3 seconds skew between threads */ 2366 inf.num_rrsets = 0; 2367 inf.num_msgs = 0; 2368 inf.num_keys = 0; 2369 inf.remcachedb = pc; 2370 slabhash_traverse(&worker->env.rrset_cache->table, 1, 2371 &zone_del_rrset, &inf); 2372 2373 slabhash_traverse(worker->env.msg_cache, 1, &zone_del_msg, &inf); 2374 2375 /* and validator cache */ 2376 if(worker->env.key_cache) { 2377 slabhash_traverse(worker->env.key_cache->slab, 1, 2378 &zone_del_kcache, &inf); 2379 } 2380 2381 free(nm); 2382 2383 (void)ssl_printf(ssl, "ok removed %lu rrsets, %lu messages " 2384 "and %lu key entries\n", (unsigned long)inf.num_rrsets, 2385 (unsigned long)inf.num_msgs, (unsigned long)inf.num_keys); 2386 } 2387 2388 /** callback to delete bogus rrsets */ 2389 static void 2390 bogus_del_rrset(struct lruhash_entry* e, void* arg) 2391 { 2392 /* entry is locked */ 2393 struct del_info* inf = (struct del_info*)arg; 2394 struct packed_rrset_data* d = (struct packed_rrset_data*)e->data; 2395 if(d->security == sec_status_bogus && d->ttl > inf->expired) { 2396 d->ttl = inf->expired; 2397 inf->num_rrsets++; 2398 } 2399 } 2400 2401 /** callback to delete bogus messages */ 2402 static void 2403 bogus_del_msg(struct lruhash_entry* e, void* arg) 2404 { 2405 /* entry is locked */ 2406 struct del_info* inf = (struct del_info*)arg; 2407 struct reply_info* d = (struct reply_info*)e->data; 2408 if(d->security == sec_status_bogus && d->ttl > inf->expired) { 2409 d->ttl = inf->expired; 2410 d->prefetch_ttl = inf->expired; 2411 d->serve_expired_ttl = inf->expired; 2412 inf->num_msgs++; 2413 #ifdef USE_CACHEDB 2414 if(inf->remcachedb && inf->worker->env.cachedb_enabled) 2415 cachedb_msg_remove_qinfo(&inf->worker->env, 2416 &((struct msgreply_entry*)e->key)->key); 2417 #endif 2418 } 2419 } 2420 2421 /** callback to delete bogus keys */ 2422 static void 2423 bogus_del_kcache(struct lruhash_entry* e, void* arg) 2424 { 2425 /* entry is locked */ 2426 struct del_info* inf = (struct del_info*)arg; 2427 struct key_entry_data* d = (struct key_entry_data*)e->data; 2428 if(d->isbad && d->ttl > inf->expired) { 2429 d->ttl = inf->expired; 2430 inf->num_keys++; 2431 } 2432 } 2433 2434 /** remove all bogus rrsets, msgs and keys from cache */ 2435 static void 2436 do_flush_bogus(RES* ssl, struct worker* worker, char* arg) 2437 { 2438 struct del_info inf; 2439 int pc = 0; /* '+c' option */ 2440 if(!parse_remcachedb(ssl, &arg, &pc)) 2441 return; 2442 /* what we do is to set them all expired */ 2443 inf.worker = worker; 2444 inf.expired = *worker->env.now; 2445 inf.expired -= 3; /* handle 3 seconds skew between threads */ 2446 inf.num_rrsets = 0; 2447 inf.num_msgs = 0; 2448 inf.num_keys = 0; 2449 inf.remcachedb = pc; 2450 slabhash_traverse(&worker->env.rrset_cache->table, 1, 2451 &bogus_del_rrset, &inf); 2452 2453 slabhash_traverse(worker->env.msg_cache, 1, &bogus_del_msg, &inf); 2454 2455 /* and validator cache */ 2456 if(worker->env.key_cache) { 2457 slabhash_traverse(worker->env.key_cache->slab, 1, 2458 &bogus_del_kcache, &inf); 2459 } 2460 2461 (void)ssl_printf(ssl, "ok removed %lu rrsets, %lu messages " 2462 "and %lu key entries\n", (unsigned long)inf.num_rrsets, 2463 (unsigned long)inf.num_msgs, (unsigned long)inf.num_keys); 2464 } 2465 2466 /** callback to delete negative and servfail rrsets */ 2467 static void 2468 negative_del_rrset(struct lruhash_entry* e, void* arg) 2469 { 2470 /* entry is locked */ 2471 struct del_info* inf = (struct del_info*)arg; 2472 struct ub_packed_rrset_key* k = (struct ub_packed_rrset_key*)e->key; 2473 struct packed_rrset_data* d = (struct packed_rrset_data*)e->data; 2474 /* delete the parentside negative cache rrsets, 2475 * these are nameserver rrsets that failed lookup, rdata empty */ 2476 if((k->rk.flags & PACKED_RRSET_PARENT_SIDE) && d->count == 1 && 2477 d->rrsig_count == 0 && d->rr_len[0] == 0 && 2478 d->ttl > inf->expired) { 2479 d->ttl = inf->expired; 2480 inf->num_rrsets++; 2481 } 2482 } 2483 2484 /** callback to delete negative and servfail messages */ 2485 static void 2486 negative_del_msg(struct lruhash_entry* e, void* arg) 2487 { 2488 /* entry is locked */ 2489 struct del_info* inf = (struct del_info*)arg; 2490 struct reply_info* d = (struct reply_info*)e->data; 2491 /* rcode not NOERROR: NXDOMAIN, SERVFAIL, ..: an nxdomain or error 2492 * or NOERROR rcode with ANCOUNT==0: a NODATA answer */ 2493 if((FLAGS_GET_RCODE(d->flags) != 0 || d->an_numrrsets == 0) && 2494 d->ttl > inf->expired) { 2495 d->ttl = inf->expired; 2496 d->prefetch_ttl = inf->expired; 2497 d->serve_expired_ttl = inf->expired; 2498 inf->num_msgs++; 2499 #ifdef USE_CACHEDB 2500 if(inf->remcachedb && inf->worker->env.cachedb_enabled) 2501 cachedb_msg_remove_qinfo(&inf->worker->env, 2502 &((struct msgreply_entry*)e->key)->key); 2503 #endif 2504 } 2505 } 2506 2507 /** callback to delete negative key entries */ 2508 static void 2509 negative_del_kcache(struct lruhash_entry* e, void* arg) 2510 { 2511 /* entry is locked */ 2512 struct del_info* inf = (struct del_info*)arg; 2513 struct key_entry_data* d = (struct key_entry_data*)e->data; 2514 /* could be bad because of lookup failure on the DS, DNSKEY, which 2515 * was nxdomain or servfail, and thus a result of negative lookups */ 2516 if(d->isbad && d->ttl > inf->expired) { 2517 d->ttl = inf->expired; 2518 inf->num_keys++; 2519 } 2520 } 2521 2522 /** remove all negative(NODATA,NXDOMAIN), and servfail messages from cache */ 2523 static void 2524 do_flush_negative(RES* ssl, struct worker* worker, char* arg) 2525 { 2526 struct del_info inf; 2527 int pc = 0; /* '+c' option */ 2528 if(!parse_remcachedb(ssl, &arg, &pc)) 2529 return; 2530 /* what we do is to set them all expired */ 2531 inf.worker = worker; 2532 inf.expired = *worker->env.now; 2533 inf.expired -= 3; /* handle 3 seconds skew between threads */ 2534 inf.num_rrsets = 0; 2535 inf.num_msgs = 0; 2536 inf.num_keys = 0; 2537 inf.remcachedb = pc; 2538 slabhash_traverse(&worker->env.rrset_cache->table, 1, 2539 &negative_del_rrset, &inf); 2540 2541 slabhash_traverse(worker->env.msg_cache, 1, &negative_del_msg, &inf); 2542 2543 /* and validator cache */ 2544 if(worker->env.key_cache) { 2545 slabhash_traverse(worker->env.key_cache->slab, 1, 2546 &negative_del_kcache, &inf); 2547 } 2548 2549 (void)ssl_printf(ssl, "ok removed %lu rrsets, %lu messages " 2550 "and %lu key entries\n", (unsigned long)inf.num_rrsets, 2551 (unsigned long)inf.num_msgs, (unsigned long)inf.num_keys); 2552 } 2553 2554 /** remove name rrset from cache */ 2555 static void 2556 do_flush_name(RES* ssl, struct worker* w, char* arg) 2557 { 2558 uint8_t* nm; 2559 int nmlabs; 2560 size_t nmlen; 2561 int pc = 0; /* '+c' option */ 2562 if(!parse_remcachedb(ssl, &arg, &pc)) 2563 return; 2564 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs)) 2565 return; 2566 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_A, LDNS_RR_CLASS_IN, pc); 2567 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_AAAA, LDNS_RR_CLASS_IN, pc); 2568 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_NS, LDNS_RR_CLASS_IN, pc); 2569 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SOA, LDNS_RR_CLASS_IN, pc); 2570 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_CNAME, LDNS_RR_CLASS_IN, pc); 2571 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_DNAME, LDNS_RR_CLASS_IN, pc); 2572 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_MX, LDNS_RR_CLASS_IN, pc); 2573 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_PTR, LDNS_RR_CLASS_IN, pc); 2574 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SRV, LDNS_RR_CLASS_IN, pc); 2575 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_NAPTR, LDNS_RR_CLASS_IN, pc); 2576 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_SVCB, LDNS_RR_CLASS_IN, pc); 2577 do_cache_remove(w, nm, nmlen, LDNS_RR_TYPE_HTTPS, LDNS_RR_CLASS_IN, pc); 2578 2579 free(nm); 2580 send_ok(ssl); 2581 } 2582 2583 /** printout a delegation point info */ 2584 static int 2585 ssl_print_name_dp(RES* ssl, const char* str, uint8_t* nm, uint16_t dclass, 2586 struct delegpt* dp) 2587 { 2588 char buf[LDNS_MAX_DOMAINLEN]; 2589 struct delegpt_ns* ns; 2590 struct delegpt_addr* a; 2591 int f = 0; 2592 if(str) { /* print header for forward, stub */ 2593 char* c = sldns_wire2str_class(dclass); 2594 dname_str(nm, buf); 2595 if(!ssl_printf(ssl, "%s %s %s ", buf, (c?c:"CLASS??"), str)) { 2596 free(c); 2597 return 0; 2598 } 2599 free(c); 2600 } 2601 for(ns = dp->nslist; ns; ns = ns->next) { 2602 dname_str(ns->name, buf); 2603 if(!ssl_printf(ssl, "%s%s", (f?" ":""), buf)) 2604 return 0; 2605 f = 1; 2606 } 2607 for(a = dp->target_list; a; a = a->next_target) { 2608 addr_to_str(&a->addr, a->addrlen, buf, sizeof(buf)); 2609 if(!ssl_printf(ssl, "%s%s", (f?" ":""), buf)) 2610 return 0; 2611 f = 1; 2612 } 2613 return ssl_printf(ssl, "\n"); 2614 } 2615 2616 2617 /** print root forwards */ 2618 static int 2619 print_root_fwds(RES* ssl, struct iter_forwards* fwds, uint8_t* root) 2620 { 2621 struct delegpt* dp; 2622 int nolock = 0; 2623 dp = forwards_lookup(fwds, root, LDNS_RR_CLASS_IN, nolock); 2624 if(!dp) { 2625 return ssl_printf(ssl, "off (using root hints)\n"); 2626 } 2627 /* if dp is returned it must be the root */ 2628 log_assert(query_dname_compare(dp->name, root)==0); 2629 if(!ssl_print_name_dp(ssl, NULL, root, LDNS_RR_CLASS_IN, dp)) { 2630 lock_rw_unlock(&fwds->lock); 2631 return 0; 2632 } 2633 lock_rw_unlock(&fwds->lock); 2634 return 1; 2635 } 2636 2637 /** parse args into delegpt */ 2638 static struct delegpt* 2639 parse_delegpt(RES* ssl, char* args, uint8_t* nm) 2640 { 2641 /* parse args and add in */ 2642 char* p = args; 2643 char* todo; 2644 struct delegpt* dp = delegpt_create_mlc(nm); 2645 struct sockaddr_storage addr; 2646 socklen_t addrlen; 2647 char* auth_name; 2648 if(!dp) { 2649 (void)ssl_printf(ssl, "error out of memory\n"); 2650 return NULL; 2651 } 2652 while(p) { 2653 todo = p; 2654 p = strchr(p, ' '); /* find next spot, if any */ 2655 if(p) { 2656 *p++ = 0; /* end this spot */ 2657 p = skipwhite(p); /* position at next spot */ 2658 } 2659 /* parse address */ 2660 if(!authextstrtoaddr(todo, &addr, &addrlen, &auth_name)) { 2661 uint8_t* dname= NULL; 2662 int port; 2663 dname = authextstrtodname(todo, &port, &auth_name); 2664 if(!dname) { 2665 (void)ssl_printf(ssl, "error cannot parse" 2666 " '%s'\n", todo); 2667 delegpt_free_mlc(dp); 2668 return NULL; 2669 } 2670 #if ! defined(HAVE_SSL_SET1_HOST) && ! defined(HAVE_X509_VERIFY_PARAM_SET1_HOST) 2671 if(auth_name) 2672 log_err("no name verification functionality in " 2673 "ssl library, ignored name for %s", todo); 2674 #endif 2675 if(!delegpt_add_ns_mlc(dp, dname, 0, auth_name, port)) { 2676 (void)ssl_printf(ssl, "error out of memory\n"); 2677 free(dname); 2678 delegpt_free_mlc(dp); 2679 return NULL; 2680 } 2681 } else { 2682 #if ! defined(HAVE_SSL_SET1_HOST) && ! defined(HAVE_X509_VERIFY_PARAM_SET1_HOST) 2683 if(auth_name) 2684 log_err("no name verification functionality in " 2685 "ssl library, ignored name for %s", todo); 2686 #endif 2687 /* add address */ 2688 if(!delegpt_add_addr_mlc(dp, &addr, addrlen, 0, 0, 2689 auth_name, -1)) { 2690 (void)ssl_printf(ssl, "error out of memory\n"); 2691 delegpt_free_mlc(dp); 2692 return NULL; 2693 } 2694 } 2695 } 2696 dp->has_parent_side_NS = 1; 2697 return dp; 2698 } 2699 2700 /** do the forward command */ 2701 static void 2702 do_forward(RES* ssl, struct worker* worker, char* args) 2703 { 2704 struct iter_forwards* fwd = worker->env.fwds; 2705 uint8_t* root = (uint8_t*)"\000"; 2706 int nolock = 0; 2707 if(!fwd) { 2708 (void)ssl_printf(ssl, "error: structure not allocated\n"); 2709 return; 2710 } 2711 if(args == NULL || args[0] == 0) { 2712 (void)print_root_fwds(ssl, fwd, root); 2713 return; 2714 } 2715 /* set root forwards for this thread. since we are in remote control 2716 * the actual mesh is not running, so we can freely edit it. */ 2717 /* delete all the existing queries first */ 2718 mesh_delete_all(worker->env.mesh); 2719 if(strcmp(args, "off") == 0) { 2720 forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, root, nolock); 2721 } else { 2722 struct delegpt* dp; 2723 if(!(dp = parse_delegpt(ssl, args, root))) 2724 return; 2725 if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp, nolock)) { 2726 (void)ssl_printf(ssl, "error out of memory\n"); 2727 return; 2728 } 2729 } 2730 send_ok(ssl); 2731 } 2732 2733 static int 2734 parse_fs_args(RES* ssl, char* args, uint8_t** nm, struct delegpt** dp, 2735 int* insecure, int* prime, int* tls) 2736 { 2737 char* zonename; 2738 char* rest; 2739 size_t nmlen; 2740 int nmlabs; 2741 /* parse all -x args */ 2742 while(args[0] == '+') { 2743 if(!find_arg2(ssl, args, &rest)) 2744 return 0; 2745 while(*(++args) != 0) { 2746 if(*args == 'i' && insecure) 2747 *insecure = 1; 2748 else if(*args == 'p' && prime) 2749 *prime = 1; 2750 else if(*args == 't' && tls) 2751 *tls = 1; 2752 else { 2753 (void)ssl_printf(ssl, "error: unknown option %s\n", args); 2754 return 0; 2755 } 2756 } 2757 args = rest; 2758 } 2759 /* parse name */ 2760 if(dp) { 2761 if(!find_arg2(ssl, args, &rest)) 2762 return 0; 2763 zonename = args; 2764 args = rest; 2765 } else zonename = args; 2766 if(!parse_arg_name(ssl, zonename, nm, &nmlen, &nmlabs)) 2767 return 0; 2768 2769 /* parse dp */ 2770 if(dp) { 2771 if(!(*dp = parse_delegpt(ssl, args, *nm))) { 2772 free(*nm); 2773 return 0; 2774 } 2775 } 2776 return 1; 2777 } 2778 2779 /** do the forward_add command */ 2780 static void 2781 do_forward_add(RES* ssl, struct worker* worker, char* args) 2782 { 2783 struct iter_forwards* fwd = worker->env.fwds; 2784 int insecure = 0, tls = 0; 2785 uint8_t* nm = NULL; 2786 struct delegpt* dp = NULL; 2787 int nolock = 1; 2788 if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, NULL, &tls)) 2789 return; 2790 if(tls) 2791 dp->ssl_upstream = 1; 2792 /* prelock forwarders for atomic operation with anchors */ 2793 lock_rw_wrlock(&fwd->lock); 2794 if(insecure && worker->env.anchors) { 2795 if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN, 2796 nm)) { 2797 lock_rw_unlock(&fwd->lock); 2798 (void)ssl_printf(ssl, "error out of memory\n"); 2799 delegpt_free_mlc(dp); 2800 free(nm); 2801 return; 2802 } 2803 } 2804 if(!forwards_add_zone(fwd, LDNS_RR_CLASS_IN, dp, nolock)) { 2805 lock_rw_unlock(&fwd->lock); 2806 (void)ssl_printf(ssl, "error out of memory\n"); 2807 free(nm); 2808 return; 2809 } 2810 lock_rw_unlock(&fwd->lock); 2811 free(nm); 2812 send_ok(ssl); 2813 } 2814 2815 /** do the forward_remove command */ 2816 static void 2817 do_forward_remove(RES* ssl, struct worker* worker, char* args) 2818 { 2819 struct iter_forwards* fwd = worker->env.fwds; 2820 int insecure = 0; 2821 uint8_t* nm = NULL; 2822 int nolock = 1; 2823 if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL, NULL)) 2824 return; 2825 /* prelock forwarders for atomic operation with anchors */ 2826 lock_rw_wrlock(&fwd->lock); 2827 if(insecure && worker->env.anchors) 2828 anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN, 2829 nm); 2830 forwards_delete_zone(fwd, LDNS_RR_CLASS_IN, nm, nolock); 2831 lock_rw_unlock(&fwd->lock); 2832 free(nm); 2833 send_ok(ssl); 2834 } 2835 2836 /** do the stub_add command */ 2837 static void 2838 do_stub_add(RES* ssl, struct worker* worker, char* args) 2839 { 2840 struct iter_forwards* fwd = worker->env.fwds; 2841 int insecure = 0, prime = 0, tls = 0; 2842 uint8_t* nm = NULL; 2843 struct delegpt* dp = NULL; 2844 int nolock = 1; 2845 if(!parse_fs_args(ssl, args, &nm, &dp, &insecure, &prime, &tls)) 2846 return; 2847 if(tls) 2848 dp->ssl_upstream = 1; 2849 /* prelock forwarders and hints for atomic operation with anchors */ 2850 lock_rw_wrlock(&fwd->lock); 2851 lock_rw_wrlock(&worker->env.hints->lock); 2852 if(insecure && worker->env.anchors) { 2853 if(!anchors_add_insecure(worker->env.anchors, LDNS_RR_CLASS_IN, 2854 nm)) { 2855 lock_rw_unlock(&fwd->lock); 2856 lock_rw_unlock(&worker->env.hints->lock); 2857 (void)ssl_printf(ssl, "error out of memory\n"); 2858 delegpt_free_mlc(dp); 2859 free(nm); 2860 return; 2861 } 2862 } 2863 if(!forwards_add_stub_hole(fwd, LDNS_RR_CLASS_IN, nm, nolock)) { 2864 if(insecure && worker->env.anchors) 2865 anchors_delete_insecure(worker->env.anchors, 2866 LDNS_RR_CLASS_IN, nm); 2867 lock_rw_unlock(&fwd->lock); 2868 lock_rw_unlock(&worker->env.hints->lock); 2869 (void)ssl_printf(ssl, "error out of memory\n"); 2870 delegpt_free_mlc(dp); 2871 free(nm); 2872 return; 2873 } 2874 if(!hints_add_stub(worker->env.hints, LDNS_RR_CLASS_IN, dp, !prime, 2875 nolock)) { 2876 (void)ssl_printf(ssl, "error out of memory\n"); 2877 forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm, nolock); 2878 if(insecure && worker->env.anchors) 2879 anchors_delete_insecure(worker->env.anchors, 2880 LDNS_RR_CLASS_IN, nm); 2881 lock_rw_unlock(&fwd->lock); 2882 lock_rw_unlock(&worker->env.hints->lock); 2883 free(nm); 2884 return; 2885 } 2886 lock_rw_unlock(&fwd->lock); 2887 lock_rw_unlock(&worker->env.hints->lock); 2888 free(nm); 2889 send_ok(ssl); 2890 } 2891 2892 /** do the stub_remove command */ 2893 static void 2894 do_stub_remove(RES* ssl, struct worker* worker, char* args) 2895 { 2896 struct iter_forwards* fwd = worker->env.fwds; 2897 int insecure = 0; 2898 uint8_t* nm = NULL; 2899 int nolock = 1; 2900 if(!parse_fs_args(ssl, args, &nm, NULL, &insecure, NULL, NULL)) 2901 return; 2902 /* prelock forwarders and hints for atomic operation with anchors */ 2903 lock_rw_wrlock(&fwd->lock); 2904 lock_rw_wrlock(&worker->env.hints->lock); 2905 if(insecure && worker->env.anchors) 2906 anchors_delete_insecure(worker->env.anchors, LDNS_RR_CLASS_IN, 2907 nm); 2908 forwards_delete_stub_hole(fwd, LDNS_RR_CLASS_IN, nm, nolock); 2909 hints_delete_stub(worker->env.hints, LDNS_RR_CLASS_IN, nm, nolock); 2910 lock_rw_unlock(&fwd->lock); 2911 lock_rw_unlock(&worker->env.hints->lock); 2912 free(nm); 2913 send_ok(ssl); 2914 } 2915 2916 /** do the insecure_add command */ 2917 static void 2918 do_insecure_add(RES* ssl, struct worker* worker, char* arg) 2919 { 2920 size_t nmlen; 2921 int nmlabs; 2922 uint8_t* nm = NULL; 2923 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs)) 2924 return; 2925 if(worker->env.anchors) { 2926 if(!anchors_add_insecure(worker->env.anchors, 2927 LDNS_RR_CLASS_IN, nm)) { 2928 (void)ssl_printf(ssl, "error out of memory\n"); 2929 free(nm); 2930 return; 2931 } 2932 } 2933 free(nm); 2934 send_ok(ssl); 2935 } 2936 2937 /** do the insecure_remove command */ 2938 static void 2939 do_insecure_remove(RES* ssl, struct worker* worker, char* arg) 2940 { 2941 size_t nmlen; 2942 int nmlabs; 2943 uint8_t* nm = NULL; 2944 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs)) 2945 return; 2946 if(worker->env.anchors) 2947 anchors_delete_insecure(worker->env.anchors, 2948 LDNS_RR_CLASS_IN, nm); 2949 free(nm); 2950 send_ok(ssl); 2951 } 2952 2953 static void 2954 do_insecure_list(RES* ssl, struct worker* worker) 2955 { 2956 char buf[LDNS_MAX_DOMAINLEN]; 2957 struct trust_anchor* a; 2958 if(worker->env.anchors) { 2959 RBTREE_FOR(a, struct trust_anchor*, worker->env.anchors->tree) { 2960 if(a->numDS == 0 && a->numDNSKEY == 0) { 2961 dname_str(a->name, buf); 2962 ssl_printf(ssl, "%s\n", buf); 2963 } 2964 } 2965 } 2966 } 2967 2968 /** do the status command */ 2969 static void 2970 do_status(RES* ssl, struct worker* worker) 2971 { 2972 int i; 2973 time_t uptime; 2974 if(!ssl_printf(ssl, "version: %s\n", PACKAGE_VERSION)) 2975 return; 2976 if(!ssl_printf(ssl, "verbosity: %d\n", verbosity)) 2977 return; 2978 if(!ssl_printf(ssl, "threads: %d\n", worker->daemon->num)) 2979 return; 2980 if(!ssl_printf(ssl, "modules: %d [", worker->daemon->mods.num)) 2981 return; 2982 for(i=0; i<worker->daemon->mods.num; i++) { 2983 if(!ssl_printf(ssl, " %s", worker->daemon->mods.mod[i]->name)) 2984 return; 2985 } 2986 if(!ssl_printf(ssl, " ]\n")) 2987 return; 2988 uptime = (time_t)time(NULL) - (time_t)worker->daemon->time_boot.tv_sec; 2989 if(!ssl_printf(ssl, "uptime: " ARG_LL "d seconds\n", (long long)uptime)) 2990 return; 2991 if(!ssl_printf(ssl, "options:%s%s%s%s\n" , 2992 (worker->daemon->reuseport?" reuseport":""), 2993 (worker->daemon->rc->accept_list?" control":""), 2994 (worker->daemon->rc->accept_list && worker->daemon->rc->use_cert?"(ssl)":""), 2995 (worker->daemon->rc->accept_list && worker->daemon->cfg->control_ifs.first && worker->daemon->cfg->control_ifs.first->str && worker->daemon->cfg->control_ifs.first->str[0] == '/'?"(namedpipe)":"") 2996 )) 2997 return; 2998 if(!ssl_printf(ssl, "unbound (pid %d) is running...\n", 2999 (int)getpid())) 3000 return; 3001 } 3002 3003 /** get age for the mesh state */ 3004 static void 3005 get_mesh_age(struct mesh_state* m, char* buf, size_t len, 3006 struct module_env* env) 3007 { 3008 if(m->reply_list) { 3009 struct timeval d; 3010 struct mesh_reply* r = m->reply_list; 3011 /* last reply is the oldest */ 3012 while(r && r->next) 3013 r = r->next; 3014 timeval_subtract(&d, env->now_tv, &r->start_time); 3015 snprintf(buf, len, ARG_LL "d.%6.6d", 3016 (long long)d.tv_sec, (int)d.tv_usec); 3017 } else { 3018 snprintf(buf, len, "-"); 3019 } 3020 } 3021 3022 /** get status of a mesh state */ 3023 static void 3024 get_mesh_status(struct mesh_area* mesh, struct mesh_state* m, 3025 char* buf, size_t len) 3026 { 3027 enum module_ext_state s = m->s.ext_state[m->s.curmod]; 3028 const char *modname = mesh->mods.mod[m->s.curmod]->name; 3029 size_t l; 3030 if(strcmp(modname, "iterator") == 0 && s == module_wait_reply && 3031 m->s.minfo[m->s.curmod]) { 3032 /* break into iterator to find out who its waiting for */ 3033 struct iter_qstate* qstate = (struct iter_qstate*) 3034 m->s.minfo[m->s.curmod]; 3035 struct outbound_list* ol = &qstate->outlist; 3036 struct outbound_entry* e; 3037 snprintf(buf, len, "%s wait for", modname); 3038 l = strlen(buf); 3039 buf += l; len -= l; 3040 if(ol->first == NULL) 3041 snprintf(buf, len, " (empty_list)"); 3042 for(e = ol->first; e; e = e->next) { 3043 snprintf(buf, len, " "); 3044 l = strlen(buf); 3045 buf += l; len -= l; 3046 addr_to_str(&e->qsent->addr, e->qsent->addrlen, 3047 buf, len); 3048 l = strlen(buf); 3049 buf += l; len -= l; 3050 } 3051 } else if(s == module_wait_subquery) { 3052 /* look in subs from mesh state to see what */ 3053 char nm[LDNS_MAX_DOMAINLEN]; 3054 struct mesh_state_ref* sub; 3055 snprintf(buf, len, "%s wants", modname); 3056 l = strlen(buf); 3057 buf += l; len -= l; 3058 if(m->sub_set.count == 0) 3059 snprintf(buf, len, " (empty_list)"); 3060 RBTREE_FOR(sub, struct mesh_state_ref*, &m->sub_set) { 3061 char* t = sldns_wire2str_type(sub->s->s.qinfo.qtype); 3062 char* c = sldns_wire2str_class(sub->s->s.qinfo.qclass); 3063 dname_str(sub->s->s.qinfo.qname, nm); 3064 snprintf(buf, len, " %s %s %s", (t?t:"TYPE??"), 3065 (c?c:"CLASS??"), nm); 3066 l = strlen(buf); 3067 buf += l; len -= l; 3068 free(t); 3069 free(c); 3070 } 3071 } else { 3072 snprintf(buf, len, "%s is %s", modname, strextstate(s)); 3073 } 3074 } 3075 3076 /** do the dump_requestlist command */ 3077 static void 3078 do_dump_requestlist(RES* ssl, struct worker* worker) 3079 { 3080 struct mesh_area* mesh; 3081 struct mesh_state* m; 3082 int num = 0; 3083 char buf[LDNS_MAX_DOMAINLEN]; 3084 char timebuf[32]; 3085 char statbuf[10240]; 3086 if(!ssl_printf(ssl, "thread #%d\n", worker->thread_num)) 3087 return; 3088 if(!ssl_printf(ssl, "# type cl name seconds module status\n")) 3089 return; 3090 /* show worker mesh contents */ 3091 mesh = worker->env.mesh; 3092 if(!mesh) return; 3093 RBTREE_FOR(m, struct mesh_state*, &mesh->all) { 3094 char* t = sldns_wire2str_type(m->s.qinfo.qtype); 3095 char* c = sldns_wire2str_class(m->s.qinfo.qclass); 3096 dname_str(m->s.qinfo.qname, buf); 3097 get_mesh_age(m, timebuf, sizeof(timebuf), &worker->env); 3098 get_mesh_status(mesh, m, statbuf, sizeof(statbuf)); 3099 if(!ssl_printf(ssl, "%3d %4s %2s %s %s %s\n", 3100 num, (t?t:"TYPE??"), (c?c:"CLASS??"), buf, timebuf, 3101 statbuf)) { 3102 free(t); 3103 free(c); 3104 return; 3105 } 3106 num++; 3107 free(t); 3108 free(c); 3109 } 3110 } 3111 3112 /** structure for argument data for dump infra host */ 3113 struct infra_arg { 3114 /** the infra cache */ 3115 struct infra_cache* infra; 3116 /** the SSL connection */ 3117 RES* ssl; 3118 /** the time now */ 3119 time_t now; 3120 /** ssl failure? stop writing and skip the rest. If the tcp 3121 * connection is broken, and writes fail, we then stop writing. */ 3122 int ssl_failed; 3123 }; 3124 3125 /** callback for every host element in the infra cache */ 3126 static void 3127 dump_infra_host(struct lruhash_entry* e, void* arg) 3128 { 3129 struct infra_arg* a = (struct infra_arg*)arg; 3130 struct infra_key* k = (struct infra_key*)e->key; 3131 struct infra_data* d = (struct infra_data*)e->data; 3132 char ip_str[1024]; 3133 char name[LDNS_MAX_DOMAINLEN]; 3134 int port; 3135 if(a->ssl_failed) 3136 return; 3137 addr_to_str(&k->addr, k->addrlen, ip_str, sizeof(ip_str)); 3138 dname_str(k->zonename, name); 3139 port = (int)ntohs(((struct sockaddr_in*)&k->addr)->sin_port); 3140 if(port != UNBOUND_DNS_PORT) { 3141 snprintf(ip_str+strlen(ip_str), sizeof(ip_str)-strlen(ip_str), 3142 "@%d", port); 3143 } 3144 /* skip expired stuff (only backed off) */ 3145 if(d->ttl < a->now) { 3146 if(d->rtt.rto >= USEFUL_SERVER_TOP_TIMEOUT) { 3147 if(!ssl_printf(a->ssl, "%s %s expired rto %d\n", ip_str, 3148 name, d->rtt.rto)) { 3149 a->ssl_failed = 1; 3150 return; 3151 } 3152 } 3153 return; 3154 } 3155 if(!ssl_printf(a->ssl, "%s %s ttl %lu ping %d var %d rtt %d rto %d " 3156 "tA %d tAAAA %d tother %d " 3157 "ednsknown %d edns %d delay %d lame dnssec %d rec %d A %d " 3158 "other %d\n", ip_str, name, (unsigned long)(d->ttl - a->now), 3159 d->rtt.srtt, d->rtt.rttvar, rtt_notimeout(&d->rtt), d->rtt.rto, 3160 d->timeout_A, d->timeout_AAAA, d->timeout_other, 3161 (int)d->edns_lame_known, (int)d->edns_version, 3162 (int)(a->now<d->probedelay?(d->probedelay - a->now):0), 3163 (int)d->isdnsseclame, (int)d->rec_lame, (int)d->lame_type_A, 3164 (int)d->lame_other)) { 3165 a->ssl_failed = 1; 3166 return; 3167 } 3168 } 3169 3170 /** do the dump_infra command */ 3171 static void 3172 do_dump_infra(RES* ssl, struct worker* worker) 3173 { 3174 struct infra_arg arg; 3175 arg.infra = worker->env.infra_cache; 3176 arg.ssl = ssl; 3177 arg.now = *worker->env.now; 3178 arg.ssl_failed = 0; 3179 slabhash_traverse(arg.infra->hosts, 0, &dump_infra_host, (void*)&arg); 3180 } 3181 3182 /** do the log_reopen command */ 3183 static void 3184 do_log_reopen(RES* ssl, struct worker* worker) 3185 { 3186 struct config_file* cfg = worker->env.cfg; 3187 send_ok(ssl); 3188 log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir); 3189 } 3190 3191 /** do the auth_zone_reload command */ 3192 static void 3193 do_auth_zone_reload(RES* ssl, struct worker* worker, char* arg) 3194 { 3195 size_t nmlen; 3196 int nmlabs; 3197 uint8_t* nm = NULL; 3198 struct auth_zones* az = worker->env.auth_zones; 3199 struct auth_zone* z = NULL; 3200 struct auth_xfer* xfr = NULL; 3201 char* reason = NULL; 3202 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs)) 3203 return; 3204 if(az) { 3205 lock_rw_rdlock(&az->lock); 3206 z = auth_zone_find(az, nm, nmlen, LDNS_RR_CLASS_IN); 3207 if(z) { 3208 lock_rw_wrlock(&z->lock); 3209 } 3210 xfr = auth_xfer_find(az, nm, nmlen, LDNS_RR_CLASS_IN); 3211 if(xfr) { 3212 lock_basic_lock(&xfr->lock); 3213 } 3214 lock_rw_unlock(&az->lock); 3215 } 3216 free(nm); 3217 if(!z) { 3218 if(xfr) { 3219 lock_basic_unlock(&xfr->lock); 3220 } 3221 (void)ssl_printf(ssl, "error no auth-zone %s\n", arg); 3222 return; 3223 } 3224 if(!auth_zone_read_zonefile(z, worker->env.cfg)) { 3225 lock_rw_unlock(&z->lock); 3226 if(xfr) { 3227 lock_basic_unlock(&xfr->lock); 3228 } 3229 (void)ssl_printf(ssl, "error failed to read %s\n", arg); 3230 return; 3231 } 3232 3233 z->zone_expired = 0; 3234 if(xfr) { 3235 xfr->zone_expired = 0; 3236 if(!xfr_find_soa(z, xfr)) { 3237 if(z->data.count == 0) { 3238 lock_rw_unlock(&z->lock); 3239 lock_basic_unlock(&xfr->lock); 3240 (void)ssl_printf(ssl, "zone %s has no contents\n", arg); 3241 return; 3242 } 3243 lock_rw_unlock(&z->lock); 3244 lock_basic_unlock(&xfr->lock); 3245 (void)ssl_printf(ssl, "error: no SOA in zone after read %s\n", arg); 3246 return; 3247 } 3248 if(xfr->have_zone) { 3249 xfr->lease_time = *worker->env.now; 3250 xfr->soa_zone_acquired = *worker->env.now; 3251 } 3252 lock_basic_unlock(&xfr->lock); 3253 } 3254 z->soa_zone_acquired = *worker->env.now; 3255 3256 auth_zone_verify_zonemd(z, &worker->env, &worker->env.mesh->mods, 3257 &reason, 0, 0); 3258 if(reason && z->zone_expired) { 3259 lock_rw_unlock(&z->lock); 3260 (void)ssl_printf(ssl, "error zonemd for %s failed: %s\n", 3261 arg, reason); 3262 free(reason); 3263 return; 3264 } else if(reason && strcmp(reason, "ZONEMD verification successful") 3265 ==0) { 3266 (void)ssl_printf(ssl, "%s: %s\n", arg, reason); 3267 } 3268 lock_rw_unlock(&z->lock); 3269 free(reason); 3270 send_ok(ssl); 3271 } 3272 3273 /** do the auth_zone_transfer command */ 3274 static void 3275 do_auth_zone_transfer(RES* ssl, struct worker* worker, char* arg) 3276 { 3277 size_t nmlen; 3278 int nmlabs; 3279 uint8_t* nm = NULL; 3280 struct auth_zones* az = worker->env.auth_zones; 3281 if(!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs)) 3282 return; 3283 if(!az || !auth_zones_startprobesequence(az, &worker->env, nm, nmlen, 3284 LDNS_RR_CLASS_IN)) { 3285 (void)ssl_printf(ssl, "error zone xfr task not found %s\n", arg); 3286 free(nm); 3287 return; 3288 } 3289 free(nm); 3290 send_ok(ssl); 3291 } 3292 3293 /** do the set_option command */ 3294 static void 3295 do_set_option(RES* ssl, struct worker* worker, char* arg) 3296 { 3297 char* arg2; 3298 if(!find_arg2(ssl, arg, &arg2)) 3299 return; 3300 if(!config_set_option(worker->env.cfg, arg, arg2)) { 3301 (void)ssl_printf(ssl, "error setting option\n"); 3302 return; 3303 } 3304 /* effectuate some arguments */ 3305 if(strcmp(arg, "val-override-date:") == 0) { 3306 int m = modstack_find(&worker->env.mesh->mods, "validator"); 3307 struct val_env* val_env = NULL; 3308 if(m != -1) val_env = (struct val_env*)worker->env.modinfo[m]; 3309 if(val_env) 3310 val_env->date_override = worker->env.cfg->val_date_override; 3311 } 3312 send_ok(ssl); 3313 } 3314 3315 /* routine to printout option values over SSL */ 3316 void remote_get_opt_ssl(char* line, void* arg) 3317 { 3318 RES* ssl = (RES*)arg; 3319 (void)ssl_printf(ssl, "%s\n", line); 3320 } 3321 3322 /** do the get_option command */ 3323 static void 3324 do_get_option(RES* ssl, struct worker* worker, char* arg) 3325 { 3326 int r; 3327 r = config_get_option(worker->env.cfg, arg, remote_get_opt_ssl, ssl); 3328 if(!r) { 3329 (void)ssl_printf(ssl, "error unknown option\n"); 3330 return; 3331 } 3332 } 3333 3334 /** do the list_forwards command */ 3335 static void 3336 do_list_forwards(RES* ssl, struct worker* worker) 3337 { 3338 /* since its a per-worker structure no locks needed */ 3339 struct iter_forwards* fwds = worker->env.fwds; 3340 struct iter_forward_zone* z; 3341 struct trust_anchor* a; 3342 int insecure; 3343 lock_rw_rdlock(&fwds->lock); 3344 RBTREE_FOR(z, struct iter_forward_zone*, fwds->tree) { 3345 if(!z->dp) continue; /* skip empty marker for stub */ 3346 3347 /* see if it is insecure */ 3348 insecure = 0; 3349 if(worker->env.anchors && 3350 (a=anchor_find(worker->env.anchors, z->name, 3351 z->namelabs, z->namelen, z->dclass))) { 3352 if(!a->keylist && !a->numDS && !a->numDNSKEY) 3353 insecure = 1; 3354 lock_basic_unlock(&a->lock); 3355 } 3356 3357 if(!ssl_print_name_dp(ssl, (insecure?"forward +i":"forward"), 3358 z->name, z->dclass, z->dp)) { 3359 lock_rw_unlock(&fwds->lock); 3360 return; 3361 } 3362 } 3363 lock_rw_unlock(&fwds->lock); 3364 } 3365 3366 /** do the list_stubs command */ 3367 static void 3368 do_list_stubs(RES* ssl, struct worker* worker) 3369 { 3370 struct iter_hints_stub* z; 3371 struct trust_anchor* a; 3372 int insecure; 3373 char str[32]; 3374 lock_rw_rdlock(&worker->env.hints->lock); 3375 RBTREE_FOR(z, struct iter_hints_stub*, &worker->env.hints->tree) { 3376 3377 /* see if it is insecure */ 3378 insecure = 0; 3379 if(worker->env.anchors && 3380 (a=anchor_find(worker->env.anchors, z->node.name, 3381 z->node.labs, z->node.len, z->node.dclass))) { 3382 if(!a->keylist && !a->numDS && !a->numDNSKEY) 3383 insecure = 1; 3384 lock_basic_unlock(&a->lock); 3385 } 3386 3387 snprintf(str, sizeof(str), "stub %sprime%s", 3388 (z->noprime?"no":""), (insecure?" +i":"")); 3389 if(!ssl_print_name_dp(ssl, str, z->node.name, 3390 z->node.dclass, z->dp)) { 3391 lock_rw_unlock(&worker->env.hints->lock); 3392 return; 3393 } 3394 } 3395 lock_rw_unlock(&worker->env.hints->lock); 3396 } 3397 3398 /** do the list_auth_zones command */ 3399 static void 3400 do_list_auth_zones(RES* ssl, struct auth_zones* az) 3401 { 3402 struct auth_zone* z; 3403 char buf[LDNS_MAX_DOMAINLEN], buf2[256], buf3[256]; 3404 lock_rw_rdlock(&az->lock); 3405 RBTREE_FOR(z, struct auth_zone*, &az->ztree) { 3406 lock_rw_rdlock(&z->lock); 3407 dname_str(z->name, buf); 3408 if(z->zone_expired) 3409 snprintf(buf2, sizeof(buf2), "expired"); 3410 else { 3411 uint32_t serial = 0; 3412 if(auth_zone_get_serial(z, &serial)) { 3413 snprintf(buf2, sizeof(buf2), "serial %u", 3414 (unsigned)serial); 3415 if(z->soa_zone_acquired != 0) { 3416 #if defined(HAVE_STRFTIME) && defined(HAVE_LOCALTIME_R) 3417 char tmbuf[32]; 3418 struct tm tm; 3419 struct tm *tm_p; 3420 tm_p = localtime_r( 3421 &z->soa_zone_acquired, &tm); 3422 if(!strftime(tmbuf, sizeof(tmbuf), "%Y-%m-%dT%H:%M:%S", tm_p)) 3423 snprintf(tmbuf, sizeof(tmbuf), "strftime-err-%u", (unsigned)z->soa_zone_acquired); 3424 snprintf(buf3, sizeof(buf3), 3425 "\t since %u %s", 3426 (unsigned)z->soa_zone_acquired, 3427 tmbuf); 3428 #else 3429 snprintf(buf3, sizeof(buf3), 3430 "\t since %u", 3431 (unsigned)z->soa_zone_acquired); 3432 #endif 3433 } else { 3434 buf3[0]=0; 3435 } 3436 } else { 3437 snprintf(buf2, sizeof(buf2), "no serial"); 3438 buf3[0]=0; 3439 } 3440 } 3441 lock_rw_unlock(&z->lock); 3442 if(!ssl_printf(ssl, "%s\t%s%s\n", buf, buf2, buf3)) { 3443 /* failure to print */ 3444 lock_rw_unlock(&az->lock); 3445 return; 3446 } 3447 } 3448 lock_rw_unlock(&az->lock); 3449 } 3450 3451 /** do the list_local_zones command */ 3452 static void 3453 do_list_local_zones(RES* ssl, struct local_zones* zones) 3454 { 3455 struct local_zone* z; 3456 char buf[LDNS_MAX_DOMAINLEN]; 3457 lock_rw_rdlock(&zones->lock); 3458 RBTREE_FOR(z, struct local_zone*, &zones->ztree) { 3459 lock_rw_rdlock(&z->lock); 3460 dname_str(z->name, buf); 3461 if(!ssl_printf(ssl, "%s %s\n", buf, 3462 local_zone_type2str(z->type))) { 3463 /* failure to print */ 3464 lock_rw_unlock(&z->lock); 3465 lock_rw_unlock(&zones->lock); 3466 return; 3467 } 3468 lock_rw_unlock(&z->lock); 3469 } 3470 lock_rw_unlock(&zones->lock); 3471 } 3472 3473 /** do the list_local_data command */ 3474 static void 3475 do_list_local_data(RES* ssl, struct worker* worker, struct local_zones* zones) 3476 { 3477 struct local_zone* z; 3478 struct local_data* d; 3479 struct local_rrset* p; 3480 char* s = (char*)sldns_buffer_begin(worker->env.scratch_buffer); 3481 size_t slen = sldns_buffer_capacity(worker->env.scratch_buffer); 3482 lock_rw_rdlock(&zones->lock); 3483 RBTREE_FOR(z, struct local_zone*, &zones->ztree) { 3484 lock_rw_rdlock(&z->lock); 3485 RBTREE_FOR(d, struct local_data*, &z->data) { 3486 for(p = d->rrsets; p; p = p->next) { 3487 struct packed_rrset_data* d = 3488 (struct packed_rrset_data*)p->rrset->entry.data; 3489 size_t i; 3490 for(i=0; i<d->count + d->rrsig_count; i++) { 3491 if(!packed_rr_to_string(p->rrset, i, 3492 0, s, slen)) { 3493 if(!ssl_printf(ssl, "BADRR\n")) { 3494 lock_rw_unlock(&z->lock); 3495 lock_rw_unlock(&zones->lock); 3496 return; 3497 } 3498 } 3499 if(!ssl_printf(ssl, "%s\n", s)) { 3500 lock_rw_unlock(&z->lock); 3501 lock_rw_unlock(&zones->lock); 3502 return; 3503 } 3504 } 3505 } 3506 } 3507 lock_rw_unlock(&z->lock); 3508 } 3509 lock_rw_unlock(&zones->lock); 3510 } 3511 3512 /** do the view_list_local_zones command */ 3513 static void 3514 do_view_list_local_zones(RES* ssl, struct worker* worker, char* arg) 3515 { 3516 struct view* v = views_find_view(worker->env.views, 3517 arg, 0 /* get read lock*/); 3518 if(!v) { 3519 ssl_printf(ssl,"no view with name: %s\n", arg); 3520 return; 3521 } 3522 if(v->local_zones) { 3523 do_list_local_zones(ssl, v->local_zones); 3524 } 3525 lock_rw_unlock(&v->lock); 3526 } 3527 3528 /** do the view_list_local_data command */ 3529 static void 3530 do_view_list_local_data(RES* ssl, struct worker* worker, char* arg) 3531 { 3532 struct view* v = views_find_view(worker->env.views, 3533 arg, 0 /* get read lock*/); 3534 if(!v) { 3535 ssl_printf(ssl,"no view with name: %s\n", arg); 3536 return; 3537 } 3538 if(v->local_zones) { 3539 do_list_local_data(ssl, worker, v->local_zones); 3540 } 3541 lock_rw_unlock(&v->lock); 3542 } 3543 3544 /** struct for user arg ratelimit list */ 3545 struct ratelimit_list_arg { 3546 /** the infra cache */ 3547 struct infra_cache* infra; 3548 /** the SSL to print to */ 3549 RES* ssl; 3550 /** all or only ratelimited */ 3551 int all; 3552 /** current time */ 3553 time_t now; 3554 /** if backoff is enabled */ 3555 int backoff; 3556 }; 3557 3558 #define ip_ratelimit_list_arg ratelimit_list_arg 3559 3560 /** list items in the ratelimit table */ 3561 static void 3562 rate_list(struct lruhash_entry* e, void* arg) 3563 { 3564 struct ratelimit_list_arg* a = (struct ratelimit_list_arg*)arg; 3565 struct rate_key* k = (struct rate_key*)e->key; 3566 struct rate_data* d = (struct rate_data*)e->data; 3567 char buf[LDNS_MAX_DOMAINLEN]; 3568 int lim = infra_find_ratelimit(a->infra, k->name, k->namelen); 3569 int max = infra_rate_max(d, a->now, a->backoff); 3570 if(a->all == 0) { 3571 if(max < lim) 3572 return; 3573 } 3574 dname_str(k->name, buf); 3575 ssl_printf(a->ssl, "%s %d limit %d\n", buf, max, lim); 3576 } 3577 3578 /** list items in the ip_ratelimit table */ 3579 static void 3580 ip_rate_list(struct lruhash_entry* e, void* arg) 3581 { 3582 char ip[128]; 3583 struct ip_ratelimit_list_arg* a = (struct ip_ratelimit_list_arg*)arg; 3584 struct ip_rate_key* k = (struct ip_rate_key*)e->key; 3585 struct ip_rate_data* d = (struct ip_rate_data*)e->data; 3586 int lim = infra_ip_ratelimit; 3587 int max = infra_rate_max(d, a->now, a->backoff); 3588 if(a->all == 0) { 3589 if(max < lim) 3590 return; 3591 } 3592 addr_to_str(&k->addr, k->addrlen, ip, sizeof(ip)); 3593 ssl_printf(a->ssl, "%s %d limit %d\n", ip, max, lim); 3594 } 3595 3596 /** do the ratelimit_list command */ 3597 static void 3598 do_ratelimit_list(RES* ssl, struct worker* worker, char* arg) 3599 { 3600 struct ratelimit_list_arg a; 3601 a.all = 0; 3602 a.infra = worker->env.infra_cache; 3603 a.now = *worker->env.now; 3604 a.ssl = ssl; 3605 a.backoff = worker->env.cfg->ratelimit_backoff; 3606 arg = skipwhite(arg); 3607 if(strcmp(arg, "+a") == 0) 3608 a.all = 1; 3609 if(a.infra->domain_rates==NULL || 3610 (a.all == 0 && infra_dp_ratelimit == 0)) 3611 return; 3612 slabhash_traverse(a.infra->domain_rates, 0, rate_list, &a); 3613 } 3614 3615 /** do the ip_ratelimit_list command */ 3616 static void 3617 do_ip_ratelimit_list(RES* ssl, struct worker* worker, char* arg) 3618 { 3619 struct ip_ratelimit_list_arg a; 3620 a.all = 0; 3621 a.infra = worker->env.infra_cache; 3622 a.now = *worker->env.now; 3623 a.ssl = ssl; 3624 a.backoff = worker->env.cfg->ip_ratelimit_backoff; 3625 arg = skipwhite(arg); 3626 if(strcmp(arg, "+a") == 0) 3627 a.all = 1; 3628 if(a.infra->client_ip_rates==NULL || 3629 (a.all == 0 && infra_ip_ratelimit == 0)) 3630 return; 3631 slabhash_traverse(a.infra->client_ip_rates, 0, ip_rate_list, &a); 3632 } 3633 3634 /** do the rpz_enable/disable command */ 3635 static void 3636 do_rpz_enable_disable(RES* ssl, struct worker* worker, char* arg, int enable) { 3637 size_t nmlen; 3638 int nmlabs; 3639 uint8_t *nm = NULL; 3640 struct auth_zones *az = worker->env.auth_zones; 3641 struct auth_zone *z = NULL; 3642 if (!parse_arg_name(ssl, arg, &nm, &nmlen, &nmlabs)) 3643 return; 3644 if (az) { 3645 lock_rw_rdlock(&az->lock); 3646 z = auth_zone_find(az, nm, nmlen, LDNS_RR_CLASS_IN); 3647 if (z) { 3648 lock_rw_wrlock(&z->lock); 3649 } 3650 lock_rw_unlock(&az->lock); 3651 } 3652 free(nm); 3653 if (!z) { 3654 (void) ssl_printf(ssl, "error no auth-zone %s\n", arg); 3655 return; 3656 } 3657 if (!z->rpz) { 3658 (void) ssl_printf(ssl, "error auth-zone %s not RPZ\n", arg); 3659 lock_rw_unlock(&z->lock); 3660 return; 3661 } 3662 if (enable) { 3663 rpz_enable(z->rpz); 3664 } else { 3665 rpz_disable(z->rpz); 3666 } 3667 lock_rw_unlock(&z->lock); 3668 send_ok(ssl); 3669 } 3670 3671 /** do the rpz_enable command */ 3672 static void 3673 do_rpz_enable(RES* ssl, struct worker* worker, char* arg) 3674 { 3675 do_rpz_enable_disable(ssl, worker, arg, 1); 3676 } 3677 3678 /** do the rpz_disable command */ 3679 static void 3680 do_rpz_disable(RES* ssl, struct worker* worker, char* arg) 3681 { 3682 do_rpz_enable_disable(ssl, worker, arg, 0); 3683 } 3684 3685 /** Write the cookie secrets to file, returns `0` on failure. 3686 * Caller has to hold the lock. */ 3687 static int 3688 cookie_secret_file_dump(RES* ssl, struct worker* worker) { 3689 char const* secret_file = worker->env.cfg->cookie_secret_file; 3690 struct cookie_secrets* cookie_secrets = worker->daemon->cookie_secrets; 3691 char secret_hex[UNBOUND_COOKIE_SECRET_SIZE * 2 + 1]; 3692 FILE* f; 3693 size_t i; 3694 if(secret_file == NULL || secret_file[0]==0) { 3695 (void)ssl_printf(ssl, "error: no cookie secret file configured\n"); 3696 return 0; 3697 } 3698 log_assert( secret_file != NULL ); 3699 3700 /* open write only and truncate */ 3701 if((f = fopen(secret_file, "w")) == NULL ) { 3702 (void)ssl_printf(ssl, "unable to open cookie secret file %s: %s", 3703 secret_file, strerror(errno)); 3704 return 0; 3705 } 3706 if(cookie_secrets == NULL) { 3707 /* nothing to write */ 3708 fclose(f); 3709 return 1; 3710 } 3711 3712 for(i = 0; i < cookie_secrets->cookie_count; i++) { 3713 struct cookie_secret const* cs = &cookie_secrets-> 3714 cookie_secrets[i]; 3715 ssize_t const len = hex_ntop(cs->cookie_secret, 3716 UNBOUND_COOKIE_SECRET_SIZE, secret_hex, 3717 sizeof(secret_hex)); 3718 (void)len; /* silence unused variable warning with -DNDEBUG */ 3719 log_assert( len == UNBOUND_COOKIE_SECRET_SIZE * 2 ); 3720 secret_hex[UNBOUND_COOKIE_SECRET_SIZE * 2] = '\0'; 3721 fprintf(f, "%s\n", secret_hex); 3722 } 3723 explicit_bzero(secret_hex, sizeof(secret_hex)); 3724 fclose(f); 3725 return 1; 3726 } 3727 3728 /** Activate cookie secret */ 3729 static void 3730 do_activate_cookie_secret(RES* ssl, struct worker* worker) { 3731 char const* secret_file = worker->env.cfg->cookie_secret_file; 3732 struct cookie_secrets* cookie_secrets = worker->daemon->cookie_secrets; 3733 3734 if(secret_file == NULL || secret_file[0] == 0) { 3735 (void)ssl_printf(ssl, "error: no cookie secret file configured\n"); 3736 return; 3737 } 3738 if(cookie_secrets == NULL) { 3739 (void)ssl_printf(ssl, "error: there are no cookie_secrets."); 3740 return; 3741 } 3742 lock_basic_lock(&cookie_secrets->lock); 3743 3744 if(cookie_secrets->cookie_count <= 1 ) { 3745 lock_basic_unlock(&cookie_secrets->lock); 3746 (void)ssl_printf(ssl, "error: no staging cookie secret to activate\n"); 3747 return; 3748 } 3749 /* Only the worker 0 writes to file, the others update state. */ 3750 if(worker->thread_num == 0 && !cookie_secret_file_dump(ssl, worker)) { 3751 lock_basic_unlock(&cookie_secrets->lock); 3752 (void)ssl_printf(ssl, "error: writing to cookie secret file: \"%s\"\n", 3753 secret_file); 3754 return; 3755 } 3756 activate_cookie_secret(cookie_secrets); 3757 if(worker->thread_num == 0) 3758 (void)cookie_secret_file_dump(ssl, worker); 3759 lock_basic_unlock(&cookie_secrets->lock); 3760 send_ok(ssl); 3761 } 3762 3763 /** Drop cookie secret */ 3764 static void 3765 do_drop_cookie_secret(RES* ssl, struct worker* worker) { 3766 char const* secret_file = worker->env.cfg->cookie_secret_file; 3767 struct cookie_secrets* cookie_secrets = worker->daemon->cookie_secrets; 3768 3769 if(secret_file == NULL || secret_file[0] == 0) { 3770 (void)ssl_printf(ssl, "error: no cookie secret file configured\n"); 3771 return; 3772 } 3773 if(cookie_secrets == NULL) { 3774 (void)ssl_printf(ssl, "error: there are no cookie_secrets."); 3775 return; 3776 } 3777 lock_basic_lock(&cookie_secrets->lock); 3778 3779 if(cookie_secrets->cookie_count <= 1 ) { 3780 lock_basic_unlock(&cookie_secrets->lock); 3781 (void)ssl_printf(ssl, "error: can not drop the currently active cookie secret\n"); 3782 return; 3783 } 3784 /* Only the worker 0 writes to file, the others update state. */ 3785 if(worker->thread_num == 0 && !cookie_secret_file_dump(ssl, worker)) { 3786 lock_basic_unlock(&cookie_secrets->lock); 3787 (void)ssl_printf(ssl, "error: writing to cookie secret file: \"%s\"\n", 3788 secret_file); 3789 return; 3790 } 3791 drop_cookie_secret(cookie_secrets); 3792 if(worker->thread_num == 0) 3793 (void)cookie_secret_file_dump(ssl, worker); 3794 lock_basic_unlock(&cookie_secrets->lock); 3795 send_ok(ssl); 3796 } 3797 3798 /** Add cookie secret */ 3799 static void 3800 do_add_cookie_secret(RES* ssl, struct worker* worker, char* arg) { 3801 uint8_t secret[UNBOUND_COOKIE_SECRET_SIZE]; 3802 char const* secret_file = worker->env.cfg->cookie_secret_file; 3803 struct cookie_secrets* cookie_secrets = worker->daemon->cookie_secrets; 3804 3805 if(secret_file == NULL || secret_file[0] == 0) { 3806 (void)ssl_printf(ssl, "error: no cookie secret file configured\n"); 3807 return; 3808 } 3809 if(cookie_secrets == NULL) { 3810 worker->daemon->cookie_secrets = cookie_secrets_create(); 3811 if(!worker->daemon->cookie_secrets) { 3812 (void)ssl_printf(ssl, "error: out of memory"); 3813 return; 3814 } 3815 cookie_secrets = worker->daemon->cookie_secrets; 3816 } 3817 lock_basic_lock(&cookie_secrets->lock); 3818 3819 if(*arg == '\0') { 3820 lock_basic_unlock(&cookie_secrets->lock); 3821 (void)ssl_printf(ssl, "error: missing argument (cookie_secret)\n"); 3822 return; 3823 } 3824 if(strlen(arg) != 32) { 3825 lock_basic_unlock(&cookie_secrets->lock); 3826 explicit_bzero(arg, strlen(arg)); 3827 (void)ssl_printf(ssl, "invalid cookie secret: invalid argument length\n"); 3828 (void)ssl_printf(ssl, "please provide a 128bit hex encoded secret\n"); 3829 return; 3830 } 3831 if(hex_pton(arg, secret, UNBOUND_COOKIE_SECRET_SIZE) != 3832 UNBOUND_COOKIE_SECRET_SIZE ) { 3833 lock_basic_unlock(&cookie_secrets->lock); 3834 explicit_bzero(secret, UNBOUND_COOKIE_SECRET_SIZE); 3835 explicit_bzero(arg, strlen(arg)); 3836 (void)ssl_printf(ssl, "invalid cookie secret: parse error\n"); 3837 (void)ssl_printf(ssl, "please provide a 128bit hex encoded secret\n"); 3838 return; 3839 } 3840 /* Only the worker 0 writes to file, the others update state. */ 3841 if(worker->thread_num == 0 && !cookie_secret_file_dump(ssl, worker)) { 3842 lock_basic_unlock(&cookie_secrets->lock); 3843 explicit_bzero(secret, UNBOUND_COOKIE_SECRET_SIZE); 3844 explicit_bzero(arg, strlen(arg)); 3845 (void)ssl_printf(ssl, "error: writing to cookie secret file: \"%s\"\n", 3846 secret_file); 3847 return; 3848 } 3849 add_cookie_secret(cookie_secrets, secret, UNBOUND_COOKIE_SECRET_SIZE); 3850 explicit_bzero(secret, UNBOUND_COOKIE_SECRET_SIZE); 3851 if(worker->thread_num == 0) 3852 (void)cookie_secret_file_dump(ssl, worker); 3853 lock_basic_unlock(&cookie_secrets->lock); 3854 explicit_bzero(arg, strlen(arg)); 3855 send_ok(ssl); 3856 } 3857 3858 /** Print cookie secrets */ 3859 static void 3860 do_print_cookie_secrets(RES* ssl, struct worker* worker) { 3861 struct cookie_secrets* cookie_secrets = worker->daemon->cookie_secrets; 3862 char secret_hex[UNBOUND_COOKIE_SECRET_SIZE * 2 + 1]; 3863 int i; 3864 3865 if(!cookie_secrets) 3866 return; /* Output is empty. */ 3867 lock_basic_lock(&cookie_secrets->lock); 3868 for(i = 0; (size_t)i < cookie_secrets->cookie_count; i++) { 3869 struct cookie_secret const* cs = &cookie_secrets-> 3870 cookie_secrets[i]; 3871 ssize_t const len = hex_ntop(cs->cookie_secret, 3872 UNBOUND_COOKIE_SECRET_SIZE, secret_hex, 3873 sizeof(secret_hex)); 3874 (void)len; /* silence unused variable warning with -DNDEBUG */ 3875 log_assert( len == UNBOUND_COOKIE_SECRET_SIZE * 2 ); 3876 secret_hex[UNBOUND_COOKIE_SECRET_SIZE * 2] = '\0'; 3877 if (i == 0) 3878 (void)ssl_printf(ssl, "active : %s\n", secret_hex); 3879 else if (cookie_secrets->cookie_count == 2) 3880 (void)ssl_printf(ssl, "staging: %s\n", secret_hex); 3881 else 3882 (void)ssl_printf(ssl, "staging[%d]: %s\n", i, 3883 secret_hex); 3884 } 3885 lock_basic_unlock(&cookie_secrets->lock); 3886 explicit_bzero(secret_hex, sizeof(secret_hex)); 3887 } 3888 3889 /** check that there is no argument after a command that takes no arguments. */ 3890 static int 3891 cmd_no_args(RES* ssl, char* cmd, char* p) 3892 { 3893 if(p && *p != 0) { 3894 /* cmd contains the command that is called at the start, 3895 * with space or tab after it. */ 3896 char* c = cmd; 3897 if(strchr(c, ' ') && strchr(c, '\t')) { 3898 if(strchr(c, ' ') < strchr(c, '\t')) 3899 *strchr(c, ' ')=0; 3900 else *strchr(c, '\t')=0; 3901 } else if(strchr(c, ' ')) { 3902 *strchr(c, ' ')=0; 3903 } else if(strchr(c, '\t')) { 3904 *strchr(c, '\t')=0; 3905 } 3906 (void)ssl_printf(ssl, "error command %s takes no arguments," 3907 " have '%s'\n", c, p); 3908 return 1; 3909 } 3910 return 0; 3911 } 3912 3913 /** check for name with end-of-string, space or tab after it */ 3914 static int 3915 cmdcmp(char* p, const char* cmd, size_t len) 3916 { 3917 return strncmp(p,cmd,len)==0 && (p[len]==0||p[len]==' '||p[len]=='\t'); 3918 } 3919 3920 /** execute a remote control command */ 3921 static void 3922 execute_cmd(struct daemon_remote* rc, struct rc_state* s, RES* ssl, char* cmd, 3923 struct worker* worker) 3924 { 3925 char* p = skipwhite(cmd); 3926 /* compare command */ 3927 if(cmdcmp(p, "stop", 4)) { 3928 if(cmd_no_args(ssl, p, skipwhite(p+4))) 3929 return; 3930 do_stop(ssl, worker); 3931 return; 3932 } else if(cmdcmp(p, "reload_keep_cache", 17)) { 3933 if(cmd_no_args(ssl, p, skipwhite(p+17))) 3934 return; 3935 do_reload(ssl, worker, 1); 3936 return; 3937 } else if(cmdcmp(p, "reload", 6)) { 3938 if(cmd_no_args(ssl, p, skipwhite(p+6))) 3939 return; 3940 do_reload(ssl, worker, 0); 3941 return; 3942 } else if(cmdcmp(p, "fast_reload", 11)) { 3943 do_fast_reload(ssl, worker, s, skipwhite(p+11)); 3944 return; 3945 } else if(cmdcmp(p, "stats_noreset", 13)) { 3946 if(cmd_no_args(ssl, p, skipwhite(p+13))) 3947 return; 3948 do_stats(ssl, worker, 0); 3949 return; 3950 } else if(cmdcmp(p, "stats", 5)) { 3951 if(cmd_no_args(ssl, p, skipwhite(p+5))) 3952 return; 3953 do_stats(ssl, worker, 1); 3954 return; 3955 } else if(cmdcmp(p, "status", 6)) { 3956 if(cmd_no_args(ssl, p, skipwhite(p+6))) 3957 return; 3958 do_status(ssl, worker); 3959 return; 3960 } else if(cmdcmp(p, "dump_cache", 10)) { 3961 if(cmd_no_args(ssl, p, skipwhite(p+10))) 3962 return; 3963 #ifdef THREADS_DISABLED 3964 if(worker->daemon->num > 1) { 3965 (void)ssl_printf(ssl, "dump_cache/load_cache is not " 3966 "supported in multi-process operation\n"); 3967 return; 3968 } 3969 #endif 3970 (void)dump_cache(ssl, worker); 3971 return; 3972 } else if(cmdcmp(p, "load_cache", 10)) { 3973 if(cmd_no_args(ssl, p, skipwhite(p+10))) 3974 return; 3975 #ifdef THREADS_DISABLED 3976 if(worker->daemon->num > 1) { 3977 /* The warning can't be printed when stdin is sending 3978 * data; just return */ 3979 return; 3980 } 3981 #endif 3982 if(load_cache(ssl, worker)) send_ok(ssl); 3983 return; 3984 } else if(cmdcmp(p, "list_forwards", 13)) { 3985 if(cmd_no_args(ssl, p, skipwhite(p+13))) 3986 return; 3987 do_list_forwards(ssl, worker); 3988 return; 3989 } else if(cmdcmp(p, "list_stubs", 10)) { 3990 if(cmd_no_args(ssl, p, skipwhite(p+10))) 3991 return; 3992 do_list_stubs(ssl, worker); 3993 return; 3994 } else if(cmdcmp(p, "list_insecure", 13)) { 3995 if(cmd_no_args(ssl, p, skipwhite(p+13))) 3996 return; 3997 do_insecure_list(ssl, worker); 3998 return; 3999 } else if(cmdcmp(p, "list_local_zones", 16)) { 4000 if(cmd_no_args(ssl, p, skipwhite(p+16))) 4001 return; 4002 do_list_local_zones(ssl, worker->daemon->local_zones); 4003 return; 4004 } else if(cmdcmp(p, "list_local_data", 15)) { 4005 if(cmd_no_args(ssl, p, skipwhite(p+15))) 4006 return; 4007 do_list_local_data(ssl, worker, worker->daemon->local_zones); 4008 return; 4009 } else if(cmdcmp(p, "view_list_local_zones", 21)) { 4010 do_view_list_local_zones(ssl, worker, skipwhite(p+21)); 4011 return; 4012 } else if(cmdcmp(p, "view_list_local_data", 20)) { 4013 do_view_list_local_data(ssl, worker, skipwhite(p+20)); 4014 return; 4015 } else if(cmdcmp(p, "ratelimit_list", 14)) { 4016 do_ratelimit_list(ssl, worker, p+14); 4017 return; 4018 } else if(cmdcmp(p, "ip_ratelimit_list", 17)) { 4019 do_ip_ratelimit_list(ssl, worker, p+17); 4020 return; 4021 } else if(cmdcmp(p, "list_auth_zones", 15)) { 4022 if(cmd_no_args(ssl, p, skipwhite(p+15))) 4023 return; 4024 do_list_auth_zones(ssl, worker->env.auth_zones); 4025 return; 4026 } else if(cmdcmp(p, "auth_zone_reload", 16)) { 4027 do_auth_zone_reload(ssl, worker, skipwhite(p+16)); 4028 return; 4029 } else if(cmdcmp(p, "auth_zone_transfer", 18)) { 4030 do_auth_zone_transfer(ssl, worker, skipwhite(p+18)); 4031 return; 4032 } else if(cmdcmp(p, "insecure_add", 12)) { 4033 /* must always distribute this cmd */ 4034 if(rc) distribute_cmd(rc, ssl, cmd); 4035 do_insecure_add(ssl, worker, skipwhite(p+12)); 4036 return; 4037 } else if(cmdcmp(p, "insecure_remove", 15)) { 4038 /* must always distribute this cmd */ 4039 if(rc) distribute_cmd(rc, ssl, cmd); 4040 do_insecure_remove(ssl, worker, skipwhite(p+15)); 4041 return; 4042 } else if(cmdcmp(p, "flush_stats", 11)) { 4043 /* must always distribute this cmd */ 4044 if(cmd_no_args(ssl, p, skipwhite(p+11))) 4045 return; 4046 if(rc) distribute_cmd(rc, ssl, cmd); 4047 do_flush_stats(ssl, worker); 4048 return; 4049 } else if(cmdcmp(p, "flush_requestlist", 17)) { 4050 /* must always distribute this cmd */ 4051 if(cmd_no_args(ssl, p, skipwhite(p+17))) 4052 return; 4053 if(rc) distribute_cmd(rc, ssl, cmd); 4054 do_flush_requestlist(ssl, worker); 4055 return; 4056 } else if(cmdcmp(p, "cache_lookup", 12)) { 4057 do_cache_lookup(ssl, worker, skipwhite(p+12)); 4058 return; 4059 } else if(cmdcmp(p, "lookup", 6)) { 4060 do_lookup(ssl, worker, skipwhite(p+6)); 4061 return; 4062 /* The following are commands that read stdin. 4063 * Each line needs to be distributed if THREADS_DISABLED. 4064 */ 4065 } else if(cmdcmp(p, "local_zones_remove", 18)) { 4066 if(cmd_no_args(ssl, p, skipwhite(p+18))) 4067 return; 4068 do_zones_remove(rc, ssl, worker); 4069 return; 4070 } else if(cmdcmp(p, "local_zones", 11)) { 4071 if(cmd_no_args(ssl, p, skipwhite(p+11))) 4072 return; 4073 do_zones_add(rc, ssl, worker); 4074 return; 4075 } else if(cmdcmp(p, "local_datas_remove", 18)) { 4076 if(cmd_no_args(ssl, p, skipwhite(p+18))) 4077 return; 4078 do_datas_remove(rc, ssl, worker); 4079 return; 4080 } else if(cmdcmp(p, "local_datas", 11)) { 4081 if(cmd_no_args(ssl, p, skipwhite(p+11))) 4082 return; 4083 do_datas_add(rc, ssl, worker); 4084 return; 4085 } else if(cmdcmp(p, "view_local_datas_remove", 23)){ 4086 do_view_datas_remove(rc, ssl, worker, skipwhite(p+23)); 4087 return; 4088 } else if(cmdcmp(p, "view_local_datas", 16)) { 4089 do_view_datas_add(rc, ssl, worker, skipwhite(p+16)); 4090 return; 4091 } else if(cmdcmp(p, "print_cookie_secrets", 20)) { 4092 if(cmd_no_args(ssl, p, skipwhite(p+20))) 4093 return; 4094 do_print_cookie_secrets(ssl, worker); 4095 return; 4096 } 4097 4098 #ifdef THREADS_DISABLED 4099 /* other processes must execute the command as well */ 4100 /* commands that should not be distributed, returned above. */ 4101 if(rc) { /* only if this thread is the master (rc) thread */ 4102 /* done before the code below, which may split the string */ 4103 distribute_cmd(rc, ssl, cmd); 4104 } 4105 #endif 4106 if(cmdcmp(p, "verbosity", 9)) { 4107 do_verbosity(ssl, skipwhite(p+9)); 4108 } else if(cmdcmp(p, "local_zone_remove", 17)) { 4109 do_zone_remove(ssl, worker->daemon->local_zones, skipwhite(p+17)); 4110 } else if(cmdcmp(p, "local_zone", 10)) { 4111 do_zone_add(ssl, worker->daemon->local_zones, skipwhite(p+10)); 4112 } else if(cmdcmp(p, "local_data_remove", 17)) { 4113 do_data_remove(ssl, worker->daemon->local_zones, skipwhite(p+17)); 4114 } else if(cmdcmp(p, "local_data", 10)) { 4115 do_data_add(ssl, worker->daemon->local_zones, skipwhite(p+10)); 4116 } else if(cmdcmp(p, "forward_add", 11)) { 4117 do_forward_add(ssl, worker, skipwhite(p+11)); 4118 } else if(cmdcmp(p, "forward_remove", 14)) { 4119 do_forward_remove(ssl, worker, skipwhite(p+14)); 4120 } else if(cmdcmp(p, "forward", 7)) { 4121 do_forward(ssl, worker, skipwhite(p+7)); 4122 } else if(cmdcmp(p, "stub_add", 8)) { 4123 do_stub_add(ssl, worker, skipwhite(p+8)); 4124 } else if(cmdcmp(p, "stub_remove", 11)) { 4125 do_stub_remove(ssl, worker, skipwhite(p+11)); 4126 } else if(cmdcmp(p, "view_local_zone_remove", 22)) { 4127 do_view_zone_remove(ssl, worker, skipwhite(p+22)); 4128 } else if(cmdcmp(p, "view_local_zone", 15)) { 4129 do_view_zone_add(ssl, worker, skipwhite(p+15)); 4130 } else if(cmdcmp(p, "view_local_data_remove", 22)) { 4131 do_view_data_remove(ssl, worker, skipwhite(p+22)); 4132 } else if(cmdcmp(p, "view_local_data", 15)) { 4133 do_view_data_add(ssl, worker, skipwhite(p+15)); 4134 } else if(cmdcmp(p, "flush_zone", 10)) { 4135 do_flush_zone(ssl, worker, skipwhite(p+10)); 4136 } else if(cmdcmp(p, "flush_type", 10)) { 4137 do_flush_type(ssl, worker, skipwhite(p+10)); 4138 } else if(cmdcmp(p, "flush_infra", 11)) { 4139 do_flush_infra(ssl, worker, skipwhite(p+11)); 4140 } else if(cmdcmp(p, "flush", 5)) { 4141 do_flush_name(ssl, worker, skipwhite(p+5)); 4142 } else if(cmdcmp(p, "dump_requestlist", 16)) { 4143 if(cmd_no_args(ssl, p, skipwhite(p+16))) 4144 return; 4145 do_dump_requestlist(ssl, worker); 4146 } else if(cmdcmp(p, "dump_infra", 10)) { 4147 if(cmd_no_args(ssl, p, skipwhite(p+10))) 4148 return; 4149 do_dump_infra(ssl, worker); 4150 } else if(cmdcmp(p, "log_reopen", 10)) { 4151 if(cmd_no_args(ssl, p, skipwhite(p+10))) 4152 return; 4153 do_log_reopen(ssl, worker); 4154 } else if(cmdcmp(p, "set_option", 10)) { 4155 do_set_option(ssl, worker, skipwhite(p+10)); 4156 } else if(cmdcmp(p, "get_option", 10)) { 4157 do_get_option(ssl, worker, skipwhite(p+10)); 4158 } else if(cmdcmp(p, "flush_bogus", 11)) { 4159 do_flush_bogus(ssl, worker, skipwhite(p+11)); 4160 } else if(cmdcmp(p, "flush_negative", 14)) { 4161 do_flush_negative(ssl, worker, skipwhite(p+14)); 4162 } else if(cmdcmp(p, "rpz_enable", 10)) { 4163 do_rpz_enable(ssl, worker, skipwhite(p+10)); 4164 } else if(cmdcmp(p, "rpz_disable", 11)) { 4165 do_rpz_disable(ssl, worker, skipwhite(p+11)); 4166 } else if(cmdcmp(p, "add_cookie_secret", 17)) { 4167 do_add_cookie_secret(ssl, worker, skipwhite(p+17)); 4168 } else if(cmdcmp(p, "drop_cookie_secret", 18)) { 4169 if(cmd_no_args(ssl, p, skipwhite(p+18))) 4170 return; 4171 do_drop_cookie_secret(ssl, worker); 4172 } else if(cmdcmp(p, "activate_cookie_secret", 22)) { 4173 if(cmd_no_args(ssl, p, skipwhite(p+22))) 4174 return; 4175 do_activate_cookie_secret(ssl, worker); 4176 } else { 4177 (void)ssl_printf(ssl, "error unknown command '%s'\n", p); 4178 } 4179 } 4180 4181 void 4182 daemon_remote_exec(struct worker* worker) 4183 { 4184 /* read the cmd string */ 4185 uint8_t* msg = NULL; 4186 uint32_t len = 0; 4187 if(!tube_read_msg(worker->cmd, &msg, &len, 0)) { 4188 log_err("daemon_remote_exec: tube_read_msg failed"); 4189 return; 4190 } 4191 verbose(VERB_ALGO, "remote exec distributed: %s", (char*)msg); 4192 execute_cmd(NULL, NULL, NULL, (char*)msg, worker); 4193 free(msg); 4194 } 4195 4196 /** handle remote control request */ 4197 static void 4198 handle_req(struct daemon_remote* rc, struct rc_state* s, RES* res) 4199 { 4200 int r; 4201 char pre[10]; 4202 char magic[7]; 4203 char buf[MAX_CMD_STRLINE]; 4204 #ifdef USE_WINSOCK 4205 /* makes it possible to set the socket blocking again. */ 4206 /* basically removes it from winsock_event ... */ 4207 WSAEventSelect(s->c->fd, NULL, 0); 4208 #endif 4209 fd_set_block(s->c->fd); 4210 4211 /* try to read magic UBCT[version]_space_ string */ 4212 if(res->ssl) { 4213 ERR_clear_error(); 4214 if((r=SSL_read(res->ssl, magic, (int)sizeof(magic)-1)) <= 0) { 4215 int r2; 4216 if((r2=SSL_get_error(res->ssl, r)) == SSL_ERROR_ZERO_RETURN) 4217 return; 4218 log_crypto_err_io("could not SSL_read", r2); 4219 return; 4220 } 4221 } else { 4222 while(1) { 4223 ssize_t rr = recv(res->fd, magic, sizeof(magic)-1, 0); 4224 if(rr <= 0) { 4225 if(rr == 0) return; 4226 if(errno == EINTR || errno == EAGAIN) 4227 continue; 4228 log_err("could not recv: %s", sock_strerror(errno)); 4229 return; 4230 } 4231 r = (int)rr; 4232 break; 4233 } 4234 } 4235 magic[6] = 0; 4236 if( r != 6 || strncmp(magic, "UBCT", 4) != 0) { 4237 verbose(VERB_QUERY, "control connection has bad magic string"); 4238 /* probably wrong tool connected, ignore it completely */ 4239 return; 4240 } 4241 4242 /* read the command line */ 4243 if(!ssl_read_line(res, buf, sizeof(buf))) { 4244 return; 4245 } 4246 snprintf(pre, sizeof(pre), "UBCT%d ", UNBOUND_CONTROL_VERSION); 4247 if(strcmp(magic, pre) != 0) { 4248 verbose(VERB_QUERY, "control connection had bad " 4249 "version %s, cmd: %s", magic, buf); 4250 ssl_printf(res, "error version mismatch\n"); 4251 return; 4252 } 4253 verbose(VERB_DETAIL, "control cmd: %s", buf); 4254 4255 /* figure out what to do */ 4256 execute_cmd(rc, s, res, buf, rc->worker); 4257 } 4258 4259 /** handle SSL_do_handshake changes to the file descriptor to wait for later */ 4260 static int 4261 remote_handshake_later(struct daemon_remote* rc, struct rc_state* s, 4262 struct comm_point* c, int r, int r2) 4263 { 4264 if(r2 == SSL_ERROR_WANT_READ) { 4265 if(s->shake_state == rc_hs_read) { 4266 /* try again later */ 4267 return 0; 4268 } 4269 s->shake_state = rc_hs_read; 4270 comm_point_listen_for_rw(c, 1, 0); 4271 return 0; 4272 } else if(r2 == SSL_ERROR_WANT_WRITE) { 4273 if(s->shake_state == rc_hs_write) { 4274 /* try again later */ 4275 return 0; 4276 } 4277 s->shake_state = rc_hs_write; 4278 comm_point_listen_for_rw(c, 0, 1); 4279 return 0; 4280 } else { 4281 if(r == 0) 4282 log_err("remote control connection closed prematurely"); 4283 log_addr(VERB_OPS, "failed connection from", 4284 &s->c->repinfo.remote_addr, s->c->repinfo.remote_addrlen); 4285 log_crypto_err_io("remote control failed ssl", r2); 4286 clean_point(rc, s); 4287 } 4288 return 0; 4289 } 4290 4291 int remote_control_callback(struct comm_point* c, void* arg, int err, 4292 struct comm_reply* ATTR_UNUSED(rep)) 4293 { 4294 RES res; 4295 struct rc_state* s = (struct rc_state*)arg; 4296 struct daemon_remote* rc = s->rc; 4297 int r; 4298 if(err != NETEVENT_NOERROR) { 4299 if(err==NETEVENT_TIMEOUT) 4300 log_err("remote control timed out"); 4301 clean_point(rc, s); 4302 return 0; 4303 } 4304 if(s->ssl) { 4305 /* (continue to) setup the SSL connection */ 4306 ERR_clear_error(); 4307 r = SSL_do_handshake(s->ssl); 4308 if(r != 1) { 4309 int r2 = SSL_get_error(s->ssl, r); 4310 return remote_handshake_later(rc, s, c, r, r2); 4311 } 4312 s->shake_state = rc_none; 4313 } 4314 4315 /* once handshake has completed, check authentication */ 4316 if (!rc->use_cert) { 4317 verbose(VERB_ALGO, "unauthenticated remote control connection"); 4318 } else if(SSL_get_verify_result(s->ssl) == X509_V_OK) { 4319 #ifdef HAVE_SSL_GET1_PEER_CERTIFICATE 4320 X509* x = SSL_get1_peer_certificate(s->ssl); 4321 #else 4322 X509* x = SSL_get_peer_certificate(s->ssl); 4323 #endif 4324 if(!x) { 4325 verbose(VERB_DETAIL, "remote control connection " 4326 "provided no client certificate"); 4327 clean_point(rc, s); 4328 return 0; 4329 } 4330 verbose(VERB_ALGO, "remote control connection authenticated"); 4331 X509_free(x); 4332 } else { 4333 verbose(VERB_DETAIL, "remote control connection failed to " 4334 "authenticate with client certificate"); 4335 clean_point(rc, s); 4336 return 0; 4337 } 4338 4339 /* if OK start to actually handle the request */ 4340 res.ssl = s->ssl; 4341 res.fd = c->fd; 4342 handle_req(rc, s, &res); 4343 4344 verbose(VERB_ALGO, "remote control operation completed"); 4345 clean_point(rc, s); 4346 return 0; 4347 } 4348 4349 /** 4350 * This routine polls a socket for readiness. 4351 * @param fd: file descriptor, -1 uses no fd for a timer only. 4352 * @param timeout: time in msec to wait. 0 means nonblocking test, 4353 * -1 waits blocking for events. 4354 * @param pollin: check for input event. 4355 * @param pollout: check for output event. 4356 * @param event: output variable, set to true if the event happens. 4357 * It is false if there was an error or timeout. 4358 * @return false is system call failure, also logged. 4359 */ 4360 static int 4361 sock_poll_timeout(int fd, int timeout, int pollin, int pollout, int* event) 4362 { 4363 int loopcount = 0; 4364 /* Loop if the system call returns an errno to do so, like EINTR. */ 4365 log_assert(pollin || pollout); 4366 while(1) { 4367 struct pollfd p, *fds; 4368 int nfds, ret; 4369 if(++loopcount > IPC_LOOP_MAX) { 4370 log_err("sock_poll_timeout: loop"); 4371 if(event) 4372 *event = 0; 4373 return 0; 4374 } 4375 if(fd == -1) { 4376 fds = NULL; 4377 nfds = 0; 4378 } else { 4379 fds = &p; 4380 nfds = 1; 4381 memset(&p, 0, sizeof(p)); 4382 p.fd = fd; 4383 #ifndef USE_WINSOCK 4384 p.events = POLLERR 4385 | POLLHUP 4386 ; 4387 #endif 4388 if(pollin) 4389 p.events |= POLLIN; 4390 if(pollout) 4391 p.events |= POLLOUT; 4392 } 4393 #ifndef USE_WINSOCK 4394 ret = poll(fds, nfds, timeout); 4395 #else 4396 if(fds == NULL) { 4397 Sleep(timeout); 4398 ret = 0; 4399 } else { 4400 ret = WSAPoll(fds, nfds, timeout); 4401 } 4402 #endif 4403 if(ret == -1) { 4404 #ifndef USE_WINSOCK 4405 if( 4406 errno == EINTR || errno == EAGAIN 4407 # ifdef EWOULDBLOCK 4408 || errno == EWOULDBLOCK 4409 # endif 4410 ) continue; /* Try again. */ 4411 #endif 4412 /* For WSAPoll we only get errors here: 4413 * o WSAENETDOWN 4414 * o WSAEFAULT 4415 * o WSAEINVAL 4416 * o WSAENOBUFS 4417 */ 4418 log_err("poll: %s", sock_strerror(errno)); 4419 if(event) 4420 *event = 0; 4421 return 0; 4422 } else if(ret == 0) { 4423 /* Timeout */ 4424 if(event) 4425 *event = 0; 4426 return 1; 4427 } 4428 break; 4429 } 4430 if(event) 4431 *event = 1; 4432 return 1; 4433 } 4434 4435 /** fast reload convert fast reload notification status to string */ 4436 static const char* 4437 fr_notification_to_string(enum fast_reload_notification status) 4438 { 4439 switch(status) { 4440 case fast_reload_notification_none: 4441 return "none"; 4442 case fast_reload_notification_done: 4443 return "done"; 4444 case fast_reload_notification_done_error: 4445 return "done_error"; 4446 case fast_reload_notification_exit: 4447 return "exit"; 4448 case fast_reload_notification_exited: 4449 return "exited"; 4450 case fast_reload_notification_printout: 4451 return "printout"; 4452 case fast_reload_notification_reload_stop: 4453 return "reload_stop"; 4454 case fast_reload_notification_reload_ack: 4455 return "reload_ack"; 4456 case fast_reload_notification_reload_nopause_poll: 4457 return "reload_nopause_poll"; 4458 case fast_reload_notification_reload_start: 4459 return "reload_start"; 4460 default: 4461 break; 4462 } 4463 return "unknown"; 4464 } 4465 4466 #ifndef THREADS_DISABLED 4467 /** fast reload, poll for notification incoming. True if quit */ 4468 static int 4469 fr_poll_for_quit(struct fast_reload_thread* fr) 4470 { 4471 int inevent, loopexit = 0, bcount = 0; 4472 uint32_t cmd; 4473 ssize_t ret; 4474 4475 if(fr->need_to_quit) 4476 return 1; 4477 /* Is there data? */ 4478 if(!sock_poll_timeout(fr->commpair[1], 0, 1, 0, &inevent)) { 4479 log_err("fr_poll_for_quit: poll failed"); 4480 return 0; 4481 } 4482 if(!inevent) 4483 return 0; 4484 4485 /* Read the data */ 4486 while(1) { 4487 if(++loopexit > IPC_LOOP_MAX) { 4488 log_err("fr_poll_for_quit: recv loops %s", 4489 sock_strerror(errno)); 4490 return 0; 4491 } 4492 ret = recv(fr->commpair[1], ((char*)&cmd)+bcount, 4493 sizeof(cmd)-bcount, 0); 4494 if(ret == -1) { 4495 if( 4496 #ifndef USE_WINSOCK 4497 errno == EINTR || errno == EAGAIN 4498 # ifdef EWOULDBLOCK 4499 || errno == EWOULDBLOCK 4500 # endif 4501 #else 4502 WSAGetLastError() == WSAEINTR || 4503 WSAGetLastError() == WSAEINPROGRESS || 4504 WSAGetLastError() == WSAEWOULDBLOCK 4505 #endif 4506 ) 4507 continue; /* Try again. */ 4508 log_err("fr_poll_for_quit: recv: %s", 4509 sock_strerror(errno)); 4510 return 0; 4511 } else if(ret+(ssize_t)bcount != sizeof(cmd)) { 4512 bcount += ret; 4513 if((size_t)bcount < sizeof(cmd)) 4514 continue; 4515 } 4516 break; 4517 } 4518 if(cmd == fast_reload_notification_exit) { 4519 fr->need_to_quit = 1; 4520 verbose(VERB_ALGO, "fast reload: exit notification received"); 4521 return 1; 4522 } 4523 log_err("fr_poll_for_quit: unknown notification status received: %d %s", 4524 cmd, fr_notification_to_string(cmd)); 4525 return 0; 4526 } 4527 4528 /** fast reload thread. Send notification from the fast reload thread */ 4529 static void 4530 fr_send_notification(struct fast_reload_thread* fr, 4531 enum fast_reload_notification status) 4532 { 4533 int outevent, loopexit = 0, bcount = 0; 4534 uint32_t cmd; 4535 ssize_t ret; 4536 verbose(VERB_ALGO, "fast reload: send notification %s", 4537 fr_notification_to_string(status)); 4538 /* Make a blocking attempt to send. But meanwhile stay responsive, 4539 * once in a while for quit commands. In case the server has to quit. */ 4540 /* see if there is incoming quit signals */ 4541 if(fr_poll_for_quit(fr)) 4542 return; 4543 cmd = status; 4544 while(1) { 4545 if(++loopexit > IPC_LOOP_MAX) { 4546 log_err("fast reload: could not send notification"); 4547 return; 4548 } 4549 /* wait for socket to become writable */ 4550 if(!sock_poll_timeout(fr->commpair[1], IPC_NOTIFICATION_WAIT, 4551 0, 1, &outevent)) { 4552 log_err("fast reload: poll failed"); 4553 return; 4554 } 4555 if(fr_poll_for_quit(fr)) 4556 return; 4557 if(!outevent) 4558 continue; 4559 ret = send(fr->commpair[1], ((char*)&cmd)+bcount, 4560 sizeof(cmd)-bcount, 0); 4561 if(ret == -1) { 4562 if( 4563 #ifndef USE_WINSOCK 4564 errno == EINTR || errno == EAGAIN 4565 # ifdef EWOULDBLOCK 4566 || errno == EWOULDBLOCK 4567 # endif 4568 #else 4569 WSAGetLastError() == WSAEINTR || 4570 WSAGetLastError() == WSAEINPROGRESS || 4571 WSAGetLastError() == WSAEWOULDBLOCK 4572 #endif 4573 ) 4574 continue; /* Try again. */ 4575 log_err("fast reload send notification: send: %s", 4576 sock_strerror(errno)); 4577 return; 4578 } else if(ret+(ssize_t)bcount != sizeof(cmd)) { 4579 bcount += ret; 4580 if((size_t)bcount < sizeof(cmd)) 4581 continue; 4582 } 4583 break; 4584 } 4585 } 4586 4587 /** fast reload thread queue up text string for output */ 4588 static int 4589 fr_output_text(struct fast_reload_thread* fr, const char* msg) 4590 { 4591 char* item = strdup(msg); 4592 if(!item) { 4593 log_err("fast reload output text: strdup out of memory"); 4594 return 0; 4595 } 4596 lock_basic_lock(&fr->fr_output_lock); 4597 if(!cfg_strlist_append(fr->fr_output, item)) { 4598 lock_basic_unlock(&fr->fr_output_lock); 4599 /* The item is freed by cfg_strlist_append on failure. */ 4600 log_err("fast reload output text: append out of memory"); 4601 return 0; 4602 } 4603 lock_basic_unlock(&fr->fr_output_lock); 4604 return 1; 4605 } 4606 4607 /** fast reload thread output vmsg function */ 4608 static int 4609 fr_output_vmsg(struct fast_reload_thread* fr, const char* format, va_list args) 4610 { 4611 char msg[1024]; 4612 vsnprintf(msg, sizeof(msg), format, args); 4613 return fr_output_text(fr, msg); 4614 } 4615 4616 /** fast reload thread printout function, with printf arguments */ 4617 static int fr_output_printf(struct fast_reload_thread* fr, 4618 const char* format, ...) ATTR_FORMAT(printf, 2, 3); 4619 4620 /** fast reload thread printout function, prints to list and signals 4621 * the remote control thread to move that to get written to the socket 4622 * of the remote control connection. */ 4623 static int 4624 fr_output_printf(struct fast_reload_thread* fr, const char* format, ...) 4625 { 4626 va_list args; 4627 int ret; 4628 va_start(args, format); 4629 ret = fr_output_vmsg(fr, format, args); 4630 va_end(args); 4631 return ret; 4632 } 4633 4634 /** fast reload thread, init time counters */ 4635 static void 4636 fr_init_time(struct timeval* time_start, struct timeval* time_read, 4637 struct timeval* time_construct, struct timeval* time_reload, 4638 struct timeval* time_end) 4639 { 4640 memset(time_start, 0, sizeof(*time_start)); 4641 memset(time_read, 0, sizeof(*time_read)); 4642 memset(time_construct, 0, sizeof(*time_construct)); 4643 memset(time_reload, 0, sizeof(*time_reload)); 4644 memset(time_end, 0, sizeof(*time_end)); 4645 if(gettimeofday(time_start, NULL) < 0) 4646 log_err("gettimeofday: %s", strerror(errno)); 4647 } 4648 4649 /** 4650 * Structure with constructed elements for use during fast reload. 4651 * At the start it contains the tree items for the new config. 4652 * After the tree items are swapped into the server, the old elements 4653 * are kept in here. They can then be deleted. 4654 */ 4655 struct fast_reload_construct { 4656 /** ssl context for listening to dnstcp over ssl */ 4657 void* listen_dot_sslctx; 4658 /** ssl context for connecting to dnstcp over ssl */ 4659 void* connect_dot_sslctx; 4660 /** ssl context for listening to DoH */ 4661 void* listen_doh_sslctx; 4662 /** ssl context for listening to quic */ 4663 void* listen_quic_sslctx; 4664 /** the file name that the ssl context is made with, private key. */ 4665 char* ssl_service_key; 4666 /** the file name that the ssl context is made with, certificate. */ 4667 char* ssl_service_pem; 4668 /** modification time for ssl_service_key, in sec and ns. Like 4669 * in a struct timespec, but without that for portability. */ 4670 time_t mtime_ssl_service_key; 4671 long mtime_ns_ssl_service_key; 4672 /** modification time for ssl_service_pem, in sec and ns. Like 4673 * in a struct timespec, but without that for portability. */ 4674 time_t mtime_ssl_service_pem; 4675 long mtime_ns_ssl_service_pem; 4676 /** construct for views */ 4677 struct views* views; 4678 /** construct for auth zones */ 4679 struct auth_zones* auth_zones; 4680 /** construct for forwards */ 4681 struct iter_forwards* fwds; 4682 /** construct for stubs */ 4683 struct iter_hints* hints; 4684 /** construct for respip_set */ 4685 struct respip_set* respip_set; 4686 /** construct for access control */ 4687 struct acl_list* acl; 4688 /** construct for access control interface */ 4689 struct acl_list* acl_interface; 4690 /** construct for tcp connection limit */ 4691 struct tcl_list* tcl; 4692 /** construct for local zones */ 4693 struct local_zones* local_zones; 4694 /** if there is response ip configuration in use */ 4695 int use_response_ip; 4696 /** if there is an rpz zone */ 4697 int use_rpz; 4698 /** construct for edns strings */ 4699 struct edns_strings* edns_strings; 4700 /** construct for trust anchors */ 4701 struct val_anchors* anchors; 4702 /** construct for nsec3 key size */ 4703 size_t* nsec3_keysize; 4704 /** construct for nsec3 max iter */ 4705 size_t* nsec3_maxiter; 4706 /** construct for nsec3 keyiter count */ 4707 int nsec3_keyiter_count; 4708 /** construct for target fetch policy */ 4709 int* target_fetch_policy; 4710 /** construct for max dependency depth */ 4711 int max_dependency_depth; 4712 /** construct for donotquery addresses */ 4713 struct iter_donotq* donotq; 4714 /** construct for private addresses and domains */ 4715 struct iter_priv* priv; 4716 /** construct whitelist for capsforid names */ 4717 struct rbtree_type* caps_white; 4718 /** construct for nat64 */ 4719 struct iter_nat64 nat64; 4720 /** construct for wait_limits_netblock */ 4721 struct rbtree_type wait_limits_netblock; 4722 /** construct for wait_limits_cookie_netblock */ 4723 struct rbtree_type wait_limits_cookie_netblock; 4724 /** construct for domain limits */ 4725 struct rbtree_type domain_limits; 4726 /** storage for the old configuration elements. The outer struct 4727 * is allocated with malloc here, the items are from config. */ 4728 struct config_file* oldcfg; 4729 }; 4730 4731 /** fast reload thread, read config */ 4732 static int 4733 fr_read_config(struct fast_reload_thread* fr, struct config_file** newcfg) 4734 { 4735 /* Create new config structure. */ 4736 *newcfg = config_create(); 4737 if(!*newcfg) { 4738 if(!fr_output_printf(fr, "config_create failed: out of memory\n")) 4739 return 0; 4740 fr_send_notification(fr, fast_reload_notification_printout); 4741 return 0; 4742 } 4743 if(fr_poll_for_quit(fr)) 4744 return 1; 4745 4746 /* Read new config from file */ 4747 if(!config_read(*newcfg, fr->worker->daemon->cfgfile, 4748 fr->worker->daemon->chroot)) { 4749 config_delete(*newcfg); 4750 if(!fr_output_printf(fr, "config_read %s%s%s%s failed: %s\n", 4751 (fr->worker->daemon->chroot?"<chroot:":""), 4752 (fr->worker->daemon->chroot?fr->worker->daemon->chroot:""), 4753 (fr->worker->daemon->chroot?"> ":""), 4754 fr->worker->daemon->cfgfile, strerror(errno))) 4755 return 0; 4756 fr_send_notification(fr, fast_reload_notification_printout); 4757 return 0; 4758 } 4759 if(fr_poll_for_quit(fr)) 4760 return 1; 4761 if(fr->fr_verb >= 1) { 4762 if(!fr_output_printf(fr, "done read config file %s%s%s%s\n", 4763 (fr->worker->daemon->chroot?"<chroot:":""), 4764 (fr->worker->daemon->chroot?fr->worker->daemon->chroot:""), 4765 (fr->worker->daemon->chroot?"> ":""), 4766 fr->worker->daemon->cfgfile)) 4767 return 0; 4768 fr_send_notification(fr, fast_reload_notification_printout); 4769 } 4770 4771 return 1; 4772 } 4773 4774 /** Check if two taglists are equal. */ 4775 static int 4776 taglist_equal(char** tagname_a, int num_tags_a, char** tagname_b, 4777 int num_tags_b) 4778 { 4779 int i; 4780 if(num_tags_a != num_tags_b) 4781 return 0; 4782 for(i=0; i<num_tags_a; i++) { 4783 if(strcmp(tagname_a[i], tagname_b[i]) != 0) 4784 return 0; 4785 } 4786 return 1; 4787 } 4788 4789 /** Check the change from a to b is only new entries at the end. */ 4790 static int 4791 taglist_change_at_end(char** tagname_a, int num_tags_a, char** tagname_b, 4792 int num_tags_b) 4793 { 4794 if(num_tags_a < 0 || num_tags_b < 0) 4795 return 0; 4796 if(num_tags_a >= num_tags_b) 4797 return 0; 4798 /* So, b is longer than a. Check if the initial start of the two 4799 * taglists is the same. */ 4800 if(!taglist_equal(tagname_a, num_tags_a, tagname_b, num_tags_a)) 4801 return 0; 4802 return 1; 4803 } 4804 4805 /** fast reload thread, check tag defines. */ 4806 static int 4807 fr_check_tag_defines(struct fast_reload_thread* fr, struct config_file* newcfg) 4808 { 4809 /* The tags are kept in a bitlist for items. Some of them are stored 4810 * in query info. If the tags change, then the old values are 4811 * inaccurate. The solution is to then flush the query list. 4812 * Unless the change only involves adding new tags at the end, that 4813 * needs no changes. */ 4814 if(!taglist_equal(fr->worker->daemon->cfg->tagname, 4815 fr->worker->daemon->cfg->num_tags, newcfg->tagname, 4816 newcfg->num_tags) && 4817 !taglist_change_at_end(fr->worker->daemon->cfg->tagname, 4818 fr->worker->daemon->cfg->num_tags, newcfg->tagname, 4819 newcfg->num_tags)) { 4820 /* The tags have changed too much, the define-tag config. */ 4821 if(fr->fr_drop_mesh) 4822 return 1; /* already dropping queries */ 4823 fr->fr_drop_mesh = 1; 4824 fr->worker->daemon->fast_reload_drop_mesh = fr->fr_drop_mesh; 4825 if(!fr_output_printf(fr, "tags have changed, with " 4826 "'define-tag', and the queries have to be dropped " 4827 "for consistency, setting '+d'\n")) 4828 return 0; 4829 fr_send_notification(fr, fast_reload_notification_printout); 4830 } 4831 return 1; 4832 } 4833 4834 /** fast reload thread, add incompatible option to the explanatory string */ 4835 static void 4836 fr_add_incompatible_option(const char* desc, char* str, size_t len) 4837 { 4838 size_t slen = strlen(str); 4839 size_t desclen = strlen(desc); 4840 if(slen == 0) { 4841 snprintf(str, len, "%s", desc); 4842 return; 4843 } 4844 if(len - slen < desclen+2) 4845 return; /* It does not fit */ 4846 snprintf(str+slen, len-slen, " %s", desc); 4847 } 4848 4849 /** fast reload thread, check if config item has changed; thus incompatible */ 4850 #define FR_CHECK_CHANGED_CFG(desc, var, str) \ 4851 do { \ 4852 if(cfg->var != newcfg->var) { \ 4853 fr_add_incompatible_option(desc, str, sizeof(str)); \ 4854 } \ 4855 } while(0); 4856 4857 /** fast reload thread, check if config string has changed, checks NULLs. */ 4858 #define FR_CHECK_CHANGED_CFG_STR(desc, var, str) \ 4859 do { \ 4860 if((!cfg->var && newcfg->var) || \ 4861 (cfg->var && !newcfg->var) || \ 4862 (cfg->var && newcfg->var \ 4863 && strcmp(cfg->var, newcfg->var) != 0)) { \ 4864 fr_add_incompatible_option(desc, str, sizeof(str)); \ 4865 } \ 4866 } while(0); 4867 4868 /** fast reload thread, check if config strlist has changed. */ 4869 #define FR_CHECK_CHANGED_CFG_STRLIST(desc, var, str) do { \ 4870 fr_check_changed_cfg_strlist(cfg->var, newcfg->var, desc, str, \ 4871 sizeof(str)); \ 4872 } while(0); 4873 static void 4874 fr_check_changed_cfg_strlist(struct config_strlist* cmp1, 4875 struct config_strlist* cmp2, const char* desc, char* str, size_t len) 4876 { 4877 struct config_strlist* p1 = cmp1, *p2 = cmp2; 4878 while(p1 && p2) { 4879 if((!p1->str && p2->str) || 4880 (p1->str && !p2->str) || 4881 (p1->str && p2->str && strcmp(p1->str, p2->str) != 0)) { 4882 /* The strlist is different. */ 4883 fr_add_incompatible_option(desc, str, len); 4884 return; 4885 } 4886 p1 = p1->next; 4887 p2 = p2->next; 4888 } 4889 if((!p1 && p2) || (p1 && !p2)) { 4890 fr_add_incompatible_option(desc, str, len); 4891 } 4892 } 4893 4894 /** fast reload thread, check if config str2list has changed. */ 4895 #define FR_CHECK_CHANGED_CFG_STR2LIST(desc, var, buff) do { \ 4896 fr_check_changed_cfg_str2list(cfg->var, newcfg->var, desc, buff,\ 4897 sizeof(buff)); \ 4898 } while(0); 4899 static void 4900 fr_check_changed_cfg_str2list(struct config_str2list* cmp1, 4901 struct config_str2list* cmp2, const char* desc, char* str, size_t len) 4902 { 4903 struct config_str2list* p1 = cmp1, *p2 = cmp2; 4904 while(p1 && p2) { 4905 if((!p1->str && p2->str) || 4906 (p1->str && !p2->str) || 4907 (p1->str && p2->str && strcmp(p1->str, p2->str) != 0)) { 4908 /* The str2list is different. */ 4909 fr_add_incompatible_option(desc, str, len); 4910 return; 4911 } 4912 if((!p1->str2 && p2->str2) || 4913 (p1->str2 && !p2->str2) || 4914 (p1->str2 && p2->str2 && 4915 strcmp(p1->str2, p2->str2) != 0)) { 4916 /* The str2list is different. */ 4917 fr_add_incompatible_option(desc, str, len); 4918 return; 4919 } 4920 p1 = p1->next; 4921 p2 = p2->next; 4922 } 4923 if((!p1 && p2) || (p1 && !p2)) { 4924 fr_add_incompatible_option(desc, str, len); 4925 } 4926 } 4927 4928 /** fast reload thread, check compatible config items */ 4929 static int 4930 fr_check_compat_cfg(struct fast_reload_thread* fr, struct config_file* newcfg) 4931 { 4932 int i; 4933 char changed_str[1024]; 4934 struct config_file* cfg = fr->worker->env.cfg; 4935 changed_str[0]=0; 4936 4937 /* Find incompatible options, and if so, print an error. */ 4938 FR_CHECK_CHANGED_CFG("num-threads", num_threads, changed_str); 4939 FR_CHECK_CHANGED_CFG("do-ip4", do_ip4, changed_str); 4940 FR_CHECK_CHANGED_CFG("do-ip6", do_ip6, changed_str); 4941 FR_CHECK_CHANGED_CFG("do-udp", do_udp, changed_str); 4942 FR_CHECK_CHANGED_CFG("do-tcp", do_tcp, changed_str); 4943 FR_CHECK_CHANGED_CFG("port", port, changed_str); 4944 /* But cfg->outgoing_num_ports has been changed at startup, 4945 * possibly to reduce it, so do not check it here. */ 4946 FR_CHECK_CHANGED_CFG("outgoing-num-tcp", outgoing_num_tcp, changed_str); 4947 FR_CHECK_CHANGED_CFG("incoming-num-tcp", incoming_num_tcp, changed_str); 4948 FR_CHECK_CHANGED_CFG("outgoing-interface", num_out_ifs, changed_str); 4949 if(cfg->num_out_ifs == newcfg->num_out_ifs) { 4950 for(i=0; i<cfg->num_out_ifs; i++) 4951 FR_CHECK_CHANGED_CFG_STR("outgoing-interface", 4952 out_ifs[i], changed_str); 4953 } 4954 FR_CHECK_CHANGED_CFG("interface", num_ifs, changed_str); 4955 if(cfg->num_ifs == newcfg->num_ifs) { 4956 for(i=0; i<cfg->num_ifs; i++) 4957 FR_CHECK_CHANGED_CFG_STR("interface", 4958 ifs[i], changed_str); 4959 } 4960 FR_CHECK_CHANGED_CFG("interface-automatic", if_automatic, changed_str); 4961 FR_CHECK_CHANGED_CFG("so-rcvbuf", so_rcvbuf, changed_str); 4962 FR_CHECK_CHANGED_CFG("so-sndbuf", so_sndbuf, changed_str); 4963 FR_CHECK_CHANGED_CFG("so-reuseport", so_reuseport, changed_str); 4964 FR_CHECK_CHANGED_CFG("ip-transparent", ip_transparent, changed_str); 4965 FR_CHECK_CHANGED_CFG("ip-freebind", ip_freebind, changed_str); 4966 FR_CHECK_CHANGED_CFG("udp-connect", udp_connect, changed_str); 4967 FR_CHECK_CHANGED_CFG("msg-buffer-size", msg_buffer_size, changed_str); 4968 FR_CHECK_CHANGED_CFG("edns-tcp-keepalive", do_tcp_keepalive, changed_str); 4969 FR_CHECK_CHANGED_CFG("edns-tcp-keepalive-timeout", tcp_keepalive_timeout, changed_str); 4970 FR_CHECK_CHANGED_CFG("tcp-idle-timeout", tcp_idle_timeout, changed_str); 4971 /* Not changed, only if DoH is used, it is then stored in commpoints, 4972 * as well as used from cfg. */ 4973 FR_CHECK_CHANGED_CFG("harden-large-queries", harden_large_queries, changed_str); 4974 FR_CHECK_CHANGED_CFG("http-max-streams", http_max_streams, changed_str); 4975 FR_CHECK_CHANGED_CFG_STR("http-endpoint", http_endpoint, changed_str); 4976 FR_CHECK_CHANGED_CFG("http_notls_downstream", http_notls_downstream, changed_str); 4977 FR_CHECK_CHANGED_CFG("https-port", https_port, changed_str); 4978 FR_CHECK_CHANGED_CFG("tls-port", ssl_port, changed_str); 4979 FR_CHECK_CHANGED_CFG_STR("tls-protocols", tls_protocols, changed_str); 4980 FR_CHECK_CHANGED_CFG_STRLIST("proxy-protocol-port", proxy_protocol_port, changed_str); 4981 FR_CHECK_CHANGED_CFG_STRLIST("tls-additional-port", tls_additional_port, changed_str); 4982 FR_CHECK_CHANGED_CFG_STR("interface-automatic-ports", if_automatic_ports, changed_str); 4983 FR_CHECK_CHANGED_CFG("udp-upstream-without-downstream", udp_upstream_without_downstream, changed_str); 4984 4985 if(changed_str[0] != 0) { 4986 /* The new config changes some items that do not work with 4987 * fast reload. */ 4988 if(!fr_output_printf(fr, "The config changes items that are " 4989 "not compatible with fast_reload, perhaps do reload " 4990 "or restart: %s", changed_str) || 4991 !fr_output_printf(fr, "\n")) 4992 return 0; 4993 fr_send_notification(fr, fast_reload_notification_printout); 4994 return 0; 4995 } 4996 return 1; 4997 } 4998 4999 /** fast reload thread, check nopause config items */ 5000 static int 5001 fr_check_nopause_compat_cfg(struct fast_reload_thread* fr, struct config_file* newcfg) 5002 { 5003 char changed_str[1024]; 5004 struct config_file* cfg = fr->worker->env.cfg; 5005 if(!fr->fr_nopause) 5006 return 1; /* The nopause is not enabled, so no problem. */ 5007 changed_str[0]=0; 5008 5009 /* Check for iter_env. */ 5010 FR_CHECK_CHANGED_CFG("outbound-msg-retry", outbound_msg_retry, changed_str); 5011 FR_CHECK_CHANGED_CFG("max-sent-count", max_sent_count, changed_str); 5012 FR_CHECK_CHANGED_CFG("max-query-restarts", max_query_restarts, changed_str); 5013 FR_CHECK_CHANGED_CFG_STR("target-fetch-policy", target_fetch_policy, changed_str); 5014 FR_CHECK_CHANGED_CFG("do-not-query-localhost", donotquery_localhost, changed_str); 5015 FR_CHECK_CHANGED_CFG_STRLIST("do-not-query-address", donotqueryaddrs, changed_str); 5016 FR_CHECK_CHANGED_CFG_STRLIST("private-address", private_address, changed_str); 5017 FR_CHECK_CHANGED_CFG_STRLIST("private-domain", private_domain, changed_str); 5018 FR_CHECK_CHANGED_CFG_STRLIST("caps-exempt", caps_whitelist, changed_str); 5019 FR_CHECK_CHANGED_CFG("do-nat64", do_nat64, changed_str); 5020 FR_CHECK_CHANGED_CFG_STR("nat64-prefix", nat64_prefix, changed_str); 5021 5022 /* Check for val_env. */ 5023 FR_CHECK_CHANGED_CFG("val-bogus-ttl", bogus_ttl, changed_str); 5024 FR_CHECK_CHANGED_CFG("val-date-override", val_date_override, changed_str); 5025 FR_CHECK_CHANGED_CFG("val-sig-skew-min", val_sig_skew_min, changed_str); 5026 FR_CHECK_CHANGED_CFG("val-sig-skew-max", val_sig_skew_max, changed_str); 5027 FR_CHECK_CHANGED_CFG("val-max-restart", val_max_restart, changed_str); 5028 FR_CHECK_CHANGED_CFG_STR("val-nsec3-keysize-iterations", 5029 val_nsec3_key_iterations, changed_str); 5030 5031 /* Check for infra. */ 5032 FR_CHECK_CHANGED_CFG("infra-host-ttl", host_ttl, changed_str); 5033 FR_CHECK_CHANGED_CFG("infra-keep-probing", infra_keep_probing, changed_str); 5034 FR_CHECK_CHANGED_CFG("ratelimit", ratelimit, changed_str); 5035 FR_CHECK_CHANGED_CFG("ip-ratelimit", ip_ratelimit, changed_str); 5036 FR_CHECK_CHANGED_CFG("ip-ratelimit-cookie", ip_ratelimit_cookie, changed_str); 5037 FR_CHECK_CHANGED_CFG_STR2LIST("wait-limit-netblock", wait_limit_netblock, changed_str); 5038 FR_CHECK_CHANGED_CFG_STR2LIST("wait-limit-cookie-netblock", wait_limit_cookie_netblock, changed_str); 5039 FR_CHECK_CHANGED_CFG_STR2LIST("ratelimit-below-domain", ratelimit_below_domain, changed_str); 5040 FR_CHECK_CHANGED_CFG_STR2LIST("ratelimit-for-domain", ratelimit_for_domain, changed_str); 5041 5042 /* Check for dnstap. */ 5043 FR_CHECK_CHANGED_CFG("dnstap-send-identity", dnstap_send_identity, changed_str); 5044 FR_CHECK_CHANGED_CFG("dnstap-send-version", dnstap_send_version, changed_str); 5045 FR_CHECK_CHANGED_CFG_STR("dnstap-identity", dnstap_identity, changed_str); 5046 FR_CHECK_CHANGED_CFG_STR("dnstap-version", dnstap_version, changed_str); 5047 5048 if(changed_str[0] != 0) { 5049 /* The new config changes some items that need a pause, 5050 * to be able to update the variables. */ 5051 if(!fr_output_printf(fr, "The config changes items that need " 5052 "the fast_reload +p option, for nopause, " 5053 "disabled to be reloaded: %s", changed_str) || 5054 !fr_output_printf(fr, "\n")) 5055 return 0; 5056 fr_send_notification(fr, fast_reload_notification_printout); 5057 return 0; 5058 } 5059 return 1; 5060 } 5061 5062 /** fast reload thread, clear construct information, deletes items */ 5063 static void 5064 fr_construct_clear(struct fast_reload_construct* ct) 5065 { 5066 if(!ct) 5067 return; 5068 auth_zones_delete(ct->auth_zones); 5069 forwards_delete(ct->fwds); 5070 hints_delete(ct->hints); 5071 respip_set_delete(ct->respip_set); 5072 local_zones_delete(ct->local_zones); 5073 acl_list_delete(ct->acl); 5074 acl_list_delete(ct->acl_interface); 5075 tcl_list_delete(ct->tcl); 5076 edns_strings_delete(ct->edns_strings); 5077 anchors_delete(ct->anchors); 5078 views_delete(ct->views); 5079 free(ct->nsec3_keysize); 5080 free(ct->nsec3_maxiter); 5081 free(ct->target_fetch_policy); 5082 donotq_delete(ct->donotq); 5083 priv_delete(ct->priv); 5084 caps_white_delete(ct->caps_white); 5085 wait_limits_free(&ct->wait_limits_netblock); 5086 wait_limits_free(&ct->wait_limits_cookie_netblock); 5087 domain_limits_free(&ct->domain_limits); 5088 #ifdef HAVE_SSL 5089 /* The SSL contexts can be SSL_CTX_free here. It is reference 5090 * counted. So ongoing transfers with can continue. 5091 * Once they are done, the context is freed. */ 5092 SSL_CTX_free((SSL_CTX*)ct->listen_dot_sslctx); 5093 SSL_CTX_free((SSL_CTX*)ct->connect_dot_sslctx); 5094 SSL_CTX_free((SSL_CTX*)ct->listen_doh_sslctx); 5095 #endif /* HAVE_SSL */ 5096 #ifdef HAVE_NGTCP2 5097 SSL_CTX_free((SSL_CTX*)ct->listen_quic_sslctx); 5098 #endif 5099 free(ct->ssl_service_key); 5100 free(ct->ssl_service_pem); 5101 /* Delete the log identity here so that the global value is not 5102 * reset by config_delete. */ 5103 if(ct->oldcfg && ct->oldcfg->log_identity) { 5104 free(ct->oldcfg->log_identity); 5105 ct->oldcfg->log_identity = NULL; 5106 } 5107 config_delete(ct->oldcfg); 5108 } 5109 5110 /** get memory for strlist */ 5111 static size_t 5112 getmem_config_strlist(struct config_strlist* p) 5113 { 5114 size_t m = 0; 5115 struct config_strlist* s; 5116 for(s = p; s; s = s->next) 5117 m += sizeof(*s) + getmem_str(s->str); 5118 return m; 5119 } 5120 5121 /** get memory for str2list */ 5122 static size_t 5123 getmem_config_str2list(struct config_str2list* p) 5124 { 5125 size_t m = 0; 5126 struct config_str2list* s; 5127 for(s = p; s; s = s->next) 5128 m += sizeof(*s) + getmem_str(s->str) + getmem_str(s->str2); 5129 return m; 5130 } 5131 5132 /** get memory for str3list */ 5133 static size_t 5134 getmem_config_str3list(struct config_str3list* p) 5135 { 5136 size_t m = 0; 5137 struct config_str3list* s; 5138 for(s = p; s; s = s->next) 5139 m += sizeof(*s) + getmem_str(s->str) + getmem_str(s->str2) 5140 + getmem_str(s->str3); 5141 return m; 5142 } 5143 5144 /** get memory for strbytelist */ 5145 static size_t 5146 getmem_config_strbytelist(struct config_strbytelist* p) 5147 { 5148 size_t m = 0; 5149 struct config_strbytelist* s; 5150 for(s = p; s; s = s->next) 5151 m += sizeof(*s) + getmem_str(s->str) + (s->str2?s->str2len:0); 5152 return m; 5153 } 5154 5155 /** get memory used by ifs array */ 5156 static size_t 5157 getmem_ifs(int numifs, char** ifs) 5158 { 5159 size_t m = 0; 5160 int i; 5161 m += numifs * sizeof(char*); 5162 for(i=0; i<numifs; i++) 5163 m += getmem_str(ifs[i]); 5164 return m; 5165 } 5166 5167 /** get memory for config_stub */ 5168 static size_t 5169 getmem_config_stub(struct config_stub* p) 5170 { 5171 size_t m = 0; 5172 struct config_stub* s; 5173 for(s = p; s; s = s->next) 5174 m += sizeof(*s) + getmem_str(s->name) 5175 + getmem_config_strlist(s->hosts) 5176 + getmem_config_strlist(s->addrs); 5177 return m; 5178 } 5179 5180 /** get memory for config_auth */ 5181 static size_t 5182 getmem_config_auth(struct config_auth* p) 5183 { 5184 size_t m = 0; 5185 struct config_auth* s; 5186 for(s = p; s; s = s->next) 5187 m += sizeof(*s) + getmem_str(s->name) 5188 + getmem_config_strlist(s->masters) 5189 + getmem_config_strlist(s->urls) 5190 + getmem_config_strlist(s->allow_notify) 5191 + getmem_str(s->zonefile) 5192 + s->rpz_taglistlen 5193 + getmem_str(s->rpz_action_override) 5194 + getmem_str(s->rpz_log_name) 5195 + getmem_str(s->rpz_cname); 5196 return m; 5197 } 5198 5199 /** get memory for config_view */ 5200 static size_t 5201 getmem_config_view(struct config_view* p) 5202 { 5203 size_t m = 0; 5204 struct config_view* s; 5205 for(s = p; s; s = s->next) 5206 m += sizeof(*s) + getmem_str(s->name) 5207 + getmem_config_str2list(s->local_zones) 5208 + getmem_config_strlist(s->local_data) 5209 + getmem_config_strlist(s->local_zones_nodefault) 5210 #ifdef USE_IPSET 5211 + getmem_config_strlist(s->local_zones_ipset) 5212 #endif 5213 + getmem_config_str2list(s->respip_actions) 5214 + getmem_config_str2list(s->respip_data); 5215 5216 return m; 5217 } 5218 5219 /** get memory used by config_file item, estimate */ 5220 static size_t 5221 config_file_getmem(struct config_file* cfg) 5222 { 5223 size_t m = 0; 5224 m += sizeof(*cfg); 5225 m += getmem_config_strlist(cfg->proxy_protocol_port); 5226 m += getmem_str(cfg->ssl_service_key); 5227 m += getmem_str(cfg->ssl_service_pem); 5228 m += getmem_str(cfg->tls_cert_bundle); 5229 m += getmem_config_strlist(cfg->tls_additional_port); 5230 m += getmem_config_strlist(cfg->tls_session_ticket_keys.first); 5231 m += getmem_str(cfg->tls_ciphers); 5232 m += getmem_str(cfg->tls_ciphersuites); 5233 m += getmem_str(cfg->tls_protocols); 5234 m += getmem_str(cfg->http_endpoint); 5235 m += (cfg->outgoing_avail_ports?65536*sizeof(int):0); 5236 m += getmem_str(cfg->target_fetch_policy); 5237 m += getmem_str(cfg->if_automatic_ports); 5238 m += getmem_ifs(cfg->num_ifs, cfg->ifs); 5239 m += getmem_ifs(cfg->num_out_ifs, cfg->out_ifs); 5240 m += getmem_config_strlist(cfg->root_hints); 5241 m += getmem_config_stub(cfg->stubs); 5242 m += getmem_config_stub(cfg->forwards); 5243 m += getmem_config_auth(cfg->auths); 5244 m += getmem_config_view(cfg->views); 5245 m += getmem_config_strlist(cfg->donotqueryaddrs); 5246 #ifdef CLIENT_SUBNET 5247 m += getmem_config_strlist(cfg->client_subnet); 5248 m += getmem_config_strlist(cfg->client_subnet_zone); 5249 #endif 5250 m += getmem_config_str2list(cfg->acls); 5251 m += getmem_config_str2list(cfg->tcp_connection_limits); 5252 m += getmem_config_strlist(cfg->caps_whitelist); 5253 m += getmem_config_strlist(cfg->private_address); 5254 m += getmem_config_strlist(cfg->private_domain); 5255 m += getmem_str(cfg->chrootdir); 5256 m += getmem_str(cfg->username); 5257 m += getmem_str(cfg->directory); 5258 m += getmem_str(cfg->logfile); 5259 m += getmem_str(cfg->pidfile); 5260 m += getmem_str(cfg->log_identity); 5261 m += getmem_str(cfg->identity); 5262 m += getmem_str(cfg->version); 5263 m += getmem_str(cfg->http_user_agent); 5264 m += getmem_str(cfg->nsid_cfg_str); 5265 m += (cfg->nsid?cfg->nsid_len:0); 5266 m += getmem_str(cfg->module_conf); 5267 m += getmem_config_strlist(cfg->trust_anchor_file_list); 5268 m += getmem_config_strlist(cfg->trust_anchor_list); 5269 m += getmem_config_strlist(cfg->auto_trust_anchor_file_list); 5270 m += getmem_config_strlist(cfg->trusted_keys_file_list); 5271 m += getmem_config_strlist(cfg->domain_insecure); 5272 m += getmem_str(cfg->val_nsec3_key_iterations); 5273 m += getmem_config_str2list(cfg->local_zones); 5274 m += getmem_config_strlist(cfg->local_zones_nodefault); 5275 #ifdef USE_IPSET 5276 m += getmem_config_strlist(cfg->local_zones_ipset); 5277 #endif 5278 m += getmem_config_strlist(cfg->local_data); 5279 m += getmem_config_str3list(cfg->local_zone_overrides); 5280 m += getmem_config_strbytelist(cfg->local_zone_tags); 5281 m += getmem_config_strbytelist(cfg->acl_tags); 5282 m += getmem_config_str3list(cfg->acl_tag_actions); 5283 m += getmem_config_str3list(cfg->acl_tag_datas); 5284 m += getmem_config_str2list(cfg->acl_view); 5285 m += getmem_config_str2list(cfg->interface_actions); 5286 m += getmem_config_strbytelist(cfg->interface_tags); 5287 m += getmem_config_str3list(cfg->interface_tag_actions); 5288 m += getmem_config_str3list(cfg->interface_tag_datas); 5289 m += getmem_config_str2list(cfg->interface_view); 5290 m += getmem_config_strbytelist(cfg->respip_tags); 5291 m += getmem_config_str2list(cfg->respip_actions); 5292 m += getmem_config_str2list(cfg->respip_data); 5293 m += getmem_ifs(cfg->num_tags, cfg->tagname); 5294 m += getmem_config_strlist(cfg->control_ifs.first); 5295 m += getmem_str(cfg->server_key_file); 5296 m += getmem_str(cfg->server_cert_file); 5297 m += getmem_str(cfg->control_key_file); 5298 m += getmem_str(cfg->control_cert_file); 5299 m += getmem_config_strlist(cfg->python_script); 5300 m += getmem_config_strlist(cfg->dynlib_file); 5301 m += getmem_str(cfg->dns64_prefix); 5302 m += getmem_config_strlist(cfg->dns64_ignore_aaaa); 5303 m += getmem_str(cfg->nat64_prefix); 5304 m += getmem_str(cfg->dnstap_socket_path); 5305 m += getmem_str(cfg->dnstap_ip); 5306 m += getmem_str(cfg->dnstap_tls_server_name); 5307 m += getmem_str(cfg->dnstap_tls_cert_bundle); 5308 m += getmem_str(cfg->dnstap_tls_client_key_file); 5309 m += getmem_str(cfg->dnstap_tls_client_cert_file); 5310 m += getmem_str(cfg->dnstap_identity); 5311 m += getmem_str(cfg->dnstap_version); 5312 m += getmem_config_str2list(cfg->ratelimit_for_domain); 5313 m += getmem_config_str2list(cfg->ratelimit_below_domain); 5314 m += getmem_config_str2list(cfg->edns_client_strings); 5315 m += getmem_str(cfg->dnscrypt_provider); 5316 m += getmem_config_strlist(cfg->dnscrypt_secret_key); 5317 m += getmem_config_strlist(cfg->dnscrypt_provider_cert); 5318 m += getmem_config_strlist(cfg->dnscrypt_provider_cert_rotated); 5319 #ifdef USE_IPSECMOD 5320 m += getmem_config_strlist(cfg->ipsecmod_whitelist); 5321 m += getmem_str(cfg->ipsecmod_hook); 5322 #endif 5323 #ifdef USE_CACHEDB 5324 m += getmem_str(cfg->cachedb_backend); 5325 m += getmem_str(cfg->cachedb_secret); 5326 #ifdef USE_REDIS 5327 m += getmem_str(cfg->redis_server_host); 5328 m += getmem_str(cfg->redis_replica_server_host); 5329 m += getmem_str(cfg->redis_server_path); 5330 m += getmem_str(cfg->redis_replica_server_path); 5331 m += getmem_str(cfg->redis_server_password); 5332 m += getmem_str(cfg->redis_replica_server_password); 5333 #endif 5334 #endif 5335 #ifdef USE_IPSET 5336 m += getmem_str(cfg->ipset_name_v4); 5337 m += getmem_str(cfg->ipset_name_v6); 5338 #endif 5339 return m; 5340 } 5341 5342 /** fast reload thread, print memory used by construct of items. */ 5343 static int 5344 fr_printmem(struct fast_reload_thread* fr, 5345 struct config_file* newcfg, struct fast_reload_construct* ct) 5346 { 5347 size_t mem = 0; 5348 if(fr_poll_for_quit(fr)) 5349 return 1; 5350 mem += getmem_str(ct->ssl_service_key); 5351 mem += getmem_str(ct->ssl_service_pem); 5352 mem += views_get_mem(ct->views); 5353 mem += respip_set_get_mem(ct->respip_set); 5354 mem += auth_zones_get_mem(ct->auth_zones); 5355 mem += forwards_get_mem(ct->fwds); 5356 mem += hints_get_mem(ct->hints); 5357 mem += local_zones_get_mem(ct->local_zones); 5358 mem += acl_list_get_mem(ct->acl); 5359 mem += acl_list_get_mem(ct->acl_interface); 5360 mem += tcl_list_get_mem(ct->tcl); 5361 mem += edns_strings_get_mem(ct->edns_strings); 5362 mem += anchors_get_mem(ct->anchors); 5363 mem += sizeof(*ct->oldcfg); 5364 mem += config_file_getmem(newcfg); 5365 5366 if(!fr_output_printf(fr, "memory use %d bytes\n", (int)mem)) 5367 return 0; 5368 fr_send_notification(fr, fast_reload_notification_printout); 5369 5370 return 1; 5371 } 5372 5373 /** fast reload thread, setup the acl_interface for the ports that 5374 * the server has. */ 5375 static int 5376 ct_acl_interface_setup_ports(struct acl_list* acl_interface, 5377 struct daemon* daemon) 5378 { 5379 /* clean acl_interface */ 5380 acl_interface_init(acl_interface); 5381 if(!setup_acl_for_ports(acl_interface, daemon->ports[0])) 5382 return 0; 5383 if(daemon->reuseport) { 5384 size_t i; 5385 for(i=1; i<daemon->num_ports; i++) { 5386 if(!setup_acl_for_ports(acl_interface, 5387 daemon->ports[i])) 5388 return 0; 5389 } 5390 } 5391 return 1; 5392 } 5393 5394 /** fast reload, add new change to list of auth zones */ 5395 static int 5396 fr_add_auth_zone_change(struct fast_reload_thread* fr, struct auth_zone* old_z, 5397 struct auth_zone* new_z, int is_deleted, int is_added, int is_changed) 5398 { 5399 struct fast_reload_auth_change* item; 5400 item = calloc(1, sizeof(*item)); 5401 if(!item) { 5402 log_err("malloc failure in add auth zone change"); 5403 return 0; 5404 } 5405 item->old_z = old_z; 5406 item->new_z = new_z; 5407 item->is_deleted = is_deleted; 5408 item->is_added = is_added; 5409 item->is_changed = is_changed; 5410 5411 item->next = fr->auth_zone_change_list; 5412 fr->auth_zone_change_list = item; 5413 return 1; 5414 } 5415 5416 /** See if auth master is equal */ 5417 static int 5418 xfr_auth_master_equal(struct auth_master* m1, struct auth_master* m2) 5419 { 5420 if(!m1 && !m2) 5421 return 1; 5422 if(!m1 || !m2) 5423 return 0; 5424 5425 if((m1->host && !m2->host) || (!m1->host && m2->host)) 5426 return 0; 5427 if(m1->host && m2->host && strcmp(m1->host, m2->host) != 0) 5428 return 0; 5429 5430 if((m1->file && !m2->file) || (!m1->file && m2->file)) 5431 return 0; 5432 if(m1->file && m2->file && strcmp(m1->file, m2->file) != 0) 5433 return 0; 5434 5435 if((m1->http && !m2->http) || (!m1->http && m2->http)) 5436 return 0; 5437 if((m1->ixfr && !m2->ixfr) || (!m1->ixfr && m2->ixfr)) 5438 return 0; 5439 if((m1->allow_notify && !m2->allow_notify) || (!m1->allow_notify && m2->allow_notify)) 5440 return 0; 5441 if((m1->ssl && !m2->ssl) || (!m1->ssl && m2->ssl)) 5442 return 0; 5443 if(m1->port != m2->port) 5444 return 0; 5445 return 1; 5446 } 5447 5448 /** See if list of auth masters is equal */ 5449 static int 5450 xfr_masterlist_equal(struct auth_master* list1, struct auth_master* list2) 5451 { 5452 struct auth_master* p1 = list1, *p2 = list2; 5453 while(p1 && p2) { 5454 if(!xfr_auth_master_equal(p1, p2)) 5455 return 0; 5456 p1 = p1->next; 5457 p2 = p2->next; 5458 } 5459 if(!p1 && !p2) 5460 return 1; 5461 return 0; 5462 } 5463 5464 /** See if the list of masters has changed. */ 5465 static int 5466 xfr_masters_equal(struct auth_xfer* xfr1, struct auth_xfer* xfr2) 5467 { 5468 if(xfr1 == NULL && xfr2 == NULL) 5469 return 1; 5470 if(xfr1 == NULL && xfr2 != NULL) 5471 return 0; 5472 if(xfr1 != NULL && xfr2 == NULL) 5473 return 0; 5474 if(xfr_masterlist_equal(xfr1->task_probe->masters, 5475 xfr2->task_probe->masters) && 5476 xfr_masterlist_equal(xfr1->task_transfer->masters, 5477 xfr2->task_transfer->masters)) 5478 return 1; 5479 return 0; 5480 } 5481 5482 /** Check what has changed in auth zones, like added and deleted zones */ 5483 static int 5484 auth_zones_check_changes(struct fast_reload_thread* fr, 5485 struct fast_reload_construct* ct) 5486 { 5487 /* Check every zone in turn. */ 5488 struct auth_zone* new_z, *old_z; 5489 struct module_env* env = &fr->worker->env; 5490 5491 fr->old_auth_zones = ct->auth_zones; 5492 /* Nobody is using the new ct version yet. 5493 * Also the ct lock is picked up before the env lock for auth_zones. */ 5494 lock_rw_rdlock(&ct->auth_zones->lock); 5495 5496 /* Find deleted zones by looping over the current list and looking 5497 * up in the new tree. */ 5498 lock_rw_rdlock(&env->auth_zones->lock); 5499 RBTREE_FOR(old_z, struct auth_zone*, &env->auth_zones->ztree) { 5500 new_z = auth_zone_find(ct->auth_zones, old_z->name, 5501 old_z->namelen, old_z->dclass); 5502 if(!new_z) { 5503 /* The zone has been removed. */ 5504 if(!fr_add_auth_zone_change(fr, old_z, NULL, 1, 0, 5505 0)) { 5506 lock_rw_unlock(&env->auth_zones->lock); 5507 lock_rw_unlock(&ct->auth_zones->lock); 5508 return 0; 5509 } 5510 } 5511 } 5512 lock_rw_unlock(&env->auth_zones->lock); 5513 5514 /* Find added zones by looping over new list and lookup in current. */ 5515 RBTREE_FOR(new_z, struct auth_zone*, &ct->auth_zones->ztree) { 5516 lock_rw_rdlock(&env->auth_zones->lock); 5517 old_z = auth_zone_find(env->auth_zones, new_z->name, 5518 new_z->namelen, new_z->dclass); 5519 if(!old_z) { 5520 /* The zone has been added. */ 5521 lock_rw_unlock(&env->auth_zones->lock); 5522 if(!fr_add_auth_zone_change(fr, NULL, new_z, 0, 1, 5523 0)) { 5524 lock_rw_unlock(&ct->auth_zones->lock); 5525 return 0; 5526 } 5527 } else { 5528 uint32_t old_serial = 0, new_serial = 0; 5529 int have_old = 0, have_new = 0; 5530 struct auth_xfer* old_xfr, *new_xfr; 5531 lock_rw_rdlock(&new_z->lock); 5532 lock_rw_rdlock(&old_z->lock); 5533 new_xfr = auth_xfer_find(ct->auth_zones, new_z->name, 5534 new_z->namelen, new_z->dclass); 5535 old_xfr = auth_xfer_find(env->auth_zones, old_z->name, 5536 old_z->namelen, old_z->dclass); 5537 if(new_xfr) { 5538 lock_basic_lock(&new_xfr->lock); 5539 } 5540 if(old_xfr) { 5541 lock_basic_lock(&old_xfr->lock); 5542 } 5543 lock_rw_unlock(&env->auth_zones->lock); 5544 5545 /* Change in the auth zone can be detected. */ 5546 /* A change in serial number means that auth_xfer 5547 * has to be updated. */ 5548 have_old = (auth_zone_get_serial(old_z, 5549 &old_serial)!=0); 5550 have_new = (auth_zone_get_serial(new_z, 5551 &new_serial)!=0); 5552 if(have_old != have_new || old_serial != new_serial 5553 || !xfr_masters_equal(old_xfr, new_xfr)) { 5554 /* The zone has been changed. */ 5555 if(!fr_add_auth_zone_change(fr, old_z, new_z, 5556 0, 0, 1)) { 5557 lock_rw_unlock(&old_z->lock); 5558 lock_rw_unlock(&new_z->lock); 5559 lock_rw_unlock(&ct->auth_zones->lock); 5560 if(new_xfr) { 5561 lock_basic_unlock(&new_xfr->lock); 5562 } 5563 if(old_xfr) { 5564 lock_basic_unlock(&old_xfr->lock); 5565 } 5566 return 0; 5567 } 5568 } 5569 5570 if(new_xfr) { 5571 lock_basic_unlock(&new_xfr->lock); 5572 } 5573 if(old_xfr) { 5574 lock_basic_unlock(&old_xfr->lock); 5575 } 5576 lock_rw_unlock(&old_z->lock); 5577 lock_rw_unlock(&new_z->lock); 5578 } 5579 } 5580 5581 lock_rw_unlock(&ct->auth_zones->lock); 5582 return 1; 5583 } 5584 5585 /** Check if the sslctxs have changed. */ 5586 static int 5587 fr_check_sslctx_change(struct fast_reload_thread* fr, 5588 struct config_file* newcfg) 5589 { 5590 #ifdef HAVE_SSL 5591 struct daemon* daemon = fr->worker->daemon; 5592 if(newcfg->ssl_service_key && newcfg->ssl_service_key[0]) { 5593 if(!daemon->ssl_service_key || 5594 ssl_cert_changed(daemon, newcfg)) 5595 return 1; 5596 } else { 5597 if(daemon->ssl_service_key) 5598 return 1; /* it is removed */ 5599 } 5600 if((daemon->cfg->tls_cert_bundle && !newcfg->tls_cert_bundle) || 5601 (!daemon->cfg->tls_cert_bundle && newcfg->tls_cert_bundle) || 5602 (daemon->cfg->tls_cert_bundle && newcfg->tls_cert_bundle && 5603 strcmp(daemon->cfg->tls_cert_bundle, newcfg->tls_cert_bundle)!=0)) 5604 return 1; /* The tls-cert-bundle has changed and return 5605 true here makes it reload the connect_dot_sslctx. */ 5606 #else 5607 (void)fr; (void)newcfg; 5608 #endif /* HAVE_SSL */ 5609 return 0; 5610 } 5611 5612 /** Create the SSL CTXs when they have changed. */ 5613 static int 5614 ct_create_sslctxs(struct fast_reload_construct* ct, 5615 struct config_file* newcfg, struct daemon* daemon) 5616 { 5617 #ifdef HAVE_SSL 5618 char* chroot = daemon->chroot; 5619 char* key = newcfg->ssl_service_key; 5620 char* pem = newcfg->ssl_service_pem; 5621 5622 if(!(newcfg->ssl_service_key && newcfg->ssl_service_key[0])) { 5623 /* Leave listen ctxs and file str at NULL */ 5624 ct->connect_dot_sslctx = daemon_setup_connect_dot_sslctx( 5625 daemon, newcfg); 5626 return 1; 5627 } 5628 5629 if(chroot && strncmp(key, chroot, strlen(chroot)) == 0) 5630 key += strlen(chroot); 5631 if(chroot && pem && strncmp(pem, chroot, strlen(chroot)) == 0) 5632 pem += strlen(chroot); 5633 5634 ct->listen_dot_sslctx = daemon_setup_listen_dot_sslctx(daemon, newcfg); 5635 #ifdef HAVE_NGHTTP2_NGHTTP2_H 5636 if(cfg_has_https(newcfg)) { 5637 ct->listen_doh_sslctx = daemon_setup_listen_doh_sslctx( 5638 daemon, newcfg); 5639 } 5640 #endif 5641 #ifdef HAVE_NGTCP2 5642 if(cfg_has_quic(newcfg)) { 5643 ct->listen_quic_sslctx = daemon_setup_listen_quic_sslctx( 5644 daemon, newcfg); 5645 } 5646 #endif /* HAVE_NGTCP2 */ 5647 ct->connect_dot_sslctx = daemon_setup_connect_dot_sslctx(daemon, 5648 newcfg); 5649 5650 /* Store mtime and names */ 5651 ct->ssl_service_key = strdup(newcfg->ssl_service_key); 5652 if(!ct->ssl_service_key) { 5653 log_err("ct_create_sslctxs: out of memory"); 5654 return 0; 5655 } 5656 ct->ssl_service_pem = strdup(newcfg->ssl_service_pem); 5657 if(!ct->ssl_service_pem) { 5658 log_err("ct_create_sslctxs: out of memory"); 5659 return 0; 5660 } 5661 if(!file_get_mtime(key, &ct->mtime_ssl_service_key, 5662 &ct->mtime_ns_ssl_service_key, NULL)) 5663 log_err("Could not stat(%s): %s", 5664 key, strerror(errno)); 5665 if(!file_get_mtime(pem, &ct->mtime_ssl_service_pem, 5666 &ct->mtime_ns_ssl_service_pem, NULL)) 5667 log_err("Could not stat(%s): %s", 5668 pem, strerror(errno)); 5669 #else 5670 (void)ct; (void)newcfg; (void)daemon; 5671 #endif /* HAVE_SSL */ 5672 return 1; 5673 } 5674 5675 /** fast reload thread, construct from config the new items */ 5676 static int 5677 fr_construct_from_config(struct fast_reload_thread* fr, 5678 struct config_file* newcfg, struct fast_reload_construct* ct) 5679 { 5680 int have_view_respip_cfg = 0; 5681 5682 fr->sslctxs_changed = fr_check_sslctx_change(fr, newcfg); 5683 if(fr->sslctxs_changed) { 5684 if(!ct_create_sslctxs(ct, newcfg, fr->worker->daemon)) { 5685 fr_construct_clear(ct); 5686 return 0; 5687 } 5688 } 5689 if(!(ct->views = views_create())) { 5690 fr_construct_clear(ct); 5691 return 0; 5692 } 5693 if(!views_apply_cfg(ct->views, newcfg)) { 5694 fr_construct_clear(ct); 5695 return 0; 5696 } 5697 if(fr_poll_for_quit(fr)) 5698 return 1; 5699 5700 if(!(ct->acl = acl_list_create())) { 5701 fr_construct_clear(ct); 5702 return 0; 5703 } 5704 if(!acl_list_apply_cfg(ct->acl, newcfg, ct->views)) { 5705 fr_construct_clear(ct); 5706 return 0; 5707 } 5708 if(fr_poll_for_quit(fr)) 5709 return 1; 5710 5711 if(!(ct->acl_interface = acl_list_create())) { 5712 fr_construct_clear(ct); 5713 return 0; 5714 } 5715 if(!ct_acl_interface_setup_ports(ct->acl_interface, 5716 fr->worker->daemon)) { 5717 fr_construct_clear(ct); 5718 return 0; 5719 } 5720 if(!acl_interface_apply_cfg(ct->acl_interface, newcfg, ct->views)) { 5721 fr_construct_clear(ct); 5722 return 0; 5723 } 5724 if(fr_poll_for_quit(fr)) 5725 return 1; 5726 5727 if(!(ct->tcl = tcl_list_create())) { 5728 fr_construct_clear(ct); 5729 return 0; 5730 } 5731 if(!tcl_list_apply_cfg(ct->tcl, newcfg)) { 5732 fr_construct_clear(ct); 5733 return 0; 5734 } 5735 if(fr->worker->daemon->tcl->tree.count != 0) 5736 fr->worker->daemon->fast_reload_tcl_has_changes = 1; 5737 else fr->worker->daemon->fast_reload_tcl_has_changes = 0; 5738 if(fr_poll_for_quit(fr)) 5739 return 1; 5740 5741 if(!(ct->auth_zones = auth_zones_create())) { 5742 fr_construct_clear(ct); 5743 return 0; 5744 } 5745 if(!auth_zones_apply_cfg(ct->auth_zones, newcfg, 1, &ct->use_rpz, 5746 fr->worker->daemon->env, &fr->worker->daemon->mods)) { 5747 fr_construct_clear(ct); 5748 return 0; 5749 } 5750 if(!auth_zones_check_changes(fr, ct)) { 5751 fr_construct_clear(ct); 5752 return 0; 5753 } 5754 if(fr_poll_for_quit(fr)) 5755 return 1; 5756 5757 if(!(ct->fwds = forwards_create())) { 5758 fr_construct_clear(ct); 5759 return 0; 5760 } 5761 if(!forwards_apply_cfg(ct->fwds, newcfg)) { 5762 fr_construct_clear(ct); 5763 return 0; 5764 } 5765 if(fr_poll_for_quit(fr)) 5766 return 1; 5767 5768 if(!(ct->hints = hints_create())) { 5769 fr_construct_clear(ct); 5770 return 0; 5771 } 5772 if(!hints_apply_cfg(ct->hints, newcfg)) { 5773 fr_construct_clear(ct); 5774 return 0; 5775 } 5776 if(fr_poll_for_quit(fr)) 5777 return 1; 5778 5779 if(!(ct->local_zones = local_zones_create())) { 5780 fr_construct_clear(ct); 5781 return 0; 5782 } 5783 if(!local_zones_apply_cfg(ct->local_zones, newcfg)) { 5784 fr_construct_clear(ct); 5785 return 0; 5786 } 5787 if(fr_poll_for_quit(fr)) 5788 return 1; 5789 5790 if(!(ct->respip_set = respip_set_create())) { 5791 fr_construct_clear(ct); 5792 return 0; 5793 } 5794 if(!respip_global_apply_cfg(ct->respip_set, newcfg)) { 5795 fr_construct_clear(ct); 5796 return 0; 5797 } 5798 if(fr_poll_for_quit(fr)) 5799 return 1; 5800 if(!respip_views_apply_cfg(ct->views, newcfg, &have_view_respip_cfg)) { 5801 fr_construct_clear(ct); 5802 return 0; 5803 } 5804 ct->use_response_ip = !respip_set_is_empty(ct->respip_set) || 5805 have_view_respip_cfg; 5806 if(fr_poll_for_quit(fr)) 5807 return 1; 5808 5809 if(!(ct->edns_strings = edns_strings_create())) { 5810 fr_construct_clear(ct); 5811 return 0; 5812 } 5813 if(!edns_strings_apply_cfg(ct->edns_strings, newcfg)) { 5814 fr_construct_clear(ct); 5815 return 0; 5816 } 5817 if(fr_poll_for_quit(fr)) 5818 return 1; 5819 5820 if(fr->worker->env.anchors) { 5821 /* There are trust anchors already, so create it for reload. */ 5822 if(!(ct->anchors = anchors_create())) { 5823 fr_construct_clear(ct); 5824 return 0; 5825 } 5826 if(!anchors_apply_cfg(ct->anchors, newcfg)) { 5827 fr_construct_clear(ct); 5828 return 0; 5829 } 5830 if(fr_poll_for_quit(fr)) 5831 return 1; 5832 } 5833 5834 if(!val_env_parse_key_iter(newcfg->val_nsec3_key_iterations, 5835 &ct->nsec3_keysize, &ct->nsec3_maxiter, 5836 &ct->nsec3_keyiter_count)) { 5837 fr_construct_clear(ct); 5838 return 0; 5839 } 5840 if(fr_poll_for_quit(fr)) 5841 return 1; 5842 5843 if(!read_fetch_policy(&ct->target_fetch_policy, 5844 &ct->max_dependency_depth, newcfg->target_fetch_policy)) { 5845 fr_construct_clear(ct); 5846 return 0; 5847 } 5848 if(!(ct->donotq = donotq_create())) { 5849 fr_construct_clear(ct); 5850 return 0; 5851 } 5852 if(!donotq_apply_cfg(ct->donotq, newcfg)) { 5853 fr_construct_clear(ct); 5854 return 0; 5855 } 5856 if(!(ct->priv = priv_create())) { 5857 fr_construct_clear(ct); 5858 return 0; 5859 } 5860 if(!priv_apply_cfg(ct->priv, newcfg)) { 5861 fr_construct_clear(ct); 5862 return 0; 5863 } 5864 if(newcfg->caps_whitelist) { 5865 if(!(ct->caps_white = caps_white_create())) { 5866 fr_construct_clear(ct); 5867 return 0; 5868 } 5869 if(!caps_white_apply_cfg(ct->caps_white, newcfg)) { 5870 fr_construct_clear(ct); 5871 return 0; 5872 } 5873 } 5874 if(!nat64_apply_cfg(&ct->nat64, newcfg)) { 5875 fr_construct_clear(ct); 5876 return 0; 5877 } 5878 if(fr_poll_for_quit(fr)) 5879 return 1; 5880 5881 if(!setup_wait_limits(&ct->wait_limits_netblock, 5882 &ct->wait_limits_cookie_netblock, newcfg)) { 5883 fr_construct_clear(ct); 5884 return 0; 5885 } 5886 if(!setup_domain_limits(&ct->domain_limits, newcfg)) { 5887 fr_construct_clear(ct); 5888 return 0; 5889 } 5890 if(fr_poll_for_quit(fr)) 5891 return 1; 5892 5893 if(!(ct->oldcfg = (struct config_file*)calloc(1, 5894 sizeof(*ct->oldcfg)))) { 5895 fr_construct_clear(ct); 5896 log_err("out of memory"); 5897 return 0; 5898 } 5899 if(fr->fr_verb >= 2) { 5900 if(!fr_printmem(fr, newcfg, ct)) 5901 return 0; 5902 } 5903 return 1; 5904 } 5905 5906 /** fast reload thread, finish timers */ 5907 static int 5908 fr_finish_time(struct fast_reload_thread* fr, struct timeval* time_start, 5909 struct timeval* time_read, struct timeval* time_construct, 5910 struct timeval* time_reload, struct timeval* time_end) 5911 { 5912 struct timeval total, readtime, constructtime, reloadtime, deletetime; 5913 if(gettimeofday(time_end, NULL) < 0) 5914 log_err("gettimeofday: %s", strerror(errno)); 5915 5916 timeval_subtract(&total, time_end, time_start); 5917 timeval_subtract(&readtime, time_read, time_start); 5918 timeval_subtract(&constructtime, time_construct, time_read); 5919 timeval_subtract(&reloadtime, time_reload, time_construct); 5920 timeval_subtract(&deletetime, time_end, time_reload); 5921 if(!fr_output_printf(fr, "read disk %3d.%6.6ds\n", 5922 (int)readtime.tv_sec, (int)readtime.tv_usec)) 5923 return 0; 5924 if(!fr_output_printf(fr, "construct %3d.%6.6ds\n", 5925 (int)constructtime.tv_sec, (int)constructtime.tv_usec)) 5926 return 0; 5927 if(!fr_output_printf(fr, "reload %3d.%6.6ds\n", 5928 (int)reloadtime.tv_sec, (int)reloadtime.tv_usec)) 5929 return 0; 5930 if(!fr_output_printf(fr, "deletes %3d.%6.6ds\n", 5931 (int)deletetime.tv_sec, (int)deletetime.tv_usec)) 5932 return 0; 5933 if(!fr_output_printf(fr, "total time %3d.%6.6ds\n", (int)total.tv_sec, 5934 (int)total.tv_usec)) 5935 return 0; 5936 fr_send_notification(fr, fast_reload_notification_printout); 5937 return 1; 5938 } 5939 5940 /** Swap auth zone information */ 5941 static void 5942 auth_zones_swap(struct auth_zones* az, struct auth_zones* data) 5943 { 5944 rbtree_type oldztree = az->ztree; 5945 int old_have_downstream = az->have_downstream; 5946 struct auth_zone* old_rpz_first = az->rpz_first; 5947 5948 az->ztree = data->ztree; 5949 data->ztree = oldztree; 5950 5951 az->have_downstream = data->have_downstream; 5952 data->have_downstream = old_have_downstream; 5953 5954 /* Leave num_query_up and num_query_down, the statistics can 5955 * remain counted. */ 5956 5957 az->rpz_first = data->rpz_first; 5958 data->rpz_first = old_rpz_first; 5959 5960 /* The xtree is not swapped. This contains the auth_xfer elements 5961 * that contain tasks in progress, like zone transfers. 5962 * The unchanged zones can keep their tasks in the tree, and thus 5963 * the xfer elements can continue to be their callbacks. */ 5964 } 5965 5966 /** Swap two void* */ 5967 static void 5968 void_ptr_swap(void** a, void **b) 5969 { 5970 void* tmp = *a; 5971 *a = *b; 5972 *b = tmp; 5973 } 5974 5975 /** Swap two char* */ 5976 static void 5977 char_ptr_swap(char** a, char **b) 5978 { 5979 char* tmp = *a; 5980 *a = *b; 5981 *b = tmp; 5982 } 5983 5984 /** Swap and set ssl ctx information */ 5985 static void 5986 sslctxs_swap(struct daemon* daemon, struct fast_reload_construct* ct) 5987 { 5988 void_ptr_swap(&daemon->listen_dot_sslctx, &ct->listen_dot_sslctx); 5989 void_ptr_swap(&daemon->connect_dot_sslctx, &ct->connect_dot_sslctx); 5990 #ifdef HAVE_NGHTTP2_NGHTTP2_H 5991 void_ptr_swap(&daemon->listen_doh_sslctx, &ct->listen_doh_sslctx); 5992 #endif 5993 #ifdef HAVE_NGTCP2 5994 void_ptr_swap(&daemon->listen_quic_sslctx, &ct->listen_quic_sslctx); 5995 #endif /* HAVE_NGTCP2 */ 5996 char_ptr_swap(&daemon->ssl_service_key, &ct->ssl_service_key); 5997 char_ptr_swap(&daemon->ssl_service_pem, &ct->ssl_service_pem); 5998 daemon->mtime_ssl_service_key = ct->mtime_ssl_service_key; 5999 daemon->mtime_ns_ssl_service_key = ct->mtime_ns_ssl_service_key; 6000 daemon->mtime_ssl_service_pem = ct->mtime_ssl_service_pem; 6001 daemon->mtime_ns_ssl_service_pem = ct->mtime_ns_ssl_service_pem; 6002 } 6003 6004 #if defined(ATOMIC_POINTER_LOCK_FREE) && defined(HAVE_LINK_ATOMIC_STORE) 6005 /** Fast reload thread, if atomics are available, copy the config items 6006 * one by one with atomic store operations. */ 6007 static void 6008 fr_atomic_copy_cfg(struct config_file* oldcfg, struct config_file* cfg, 6009 struct config_file* newcfg) 6010 { 6011 #define COPY_VAR_int(var) oldcfg->var = cfg->var; atomic_store((_Atomic int*)&cfg->var, newcfg->var); newcfg->var = 0; 6012 #define COPY_VAR_ptr(var) oldcfg->var = cfg->var; atomic_store((void* _Atomic*)&cfg->var, newcfg->var); newcfg->var = 0; 6013 #define COPY_VAR_unsigned_int(var) oldcfg->var = cfg->var; atomic_store((_Atomic unsigned*)&cfg->var, newcfg->var); newcfg->var = 0; 6014 #define COPY_VAR_size_t(var) oldcfg->var = cfg->var; atomic_store((_Atomic size_t*)&cfg->var, newcfg->var); newcfg->var = 0; 6015 #define COPY_VAR_uint8_t(var) oldcfg->var = cfg->var; atomic_store((_Atomic uint8_t*)&cfg->var, newcfg->var); newcfg->var = 0; 6016 #define COPY_VAR_uint16_t(var) oldcfg->var = cfg->var; atomic_store((_Atomic uint16_t*)&cfg->var, newcfg->var); newcfg->var = 0; 6017 #define COPY_VAR_uint32_t(var) oldcfg->var = cfg->var; atomic_store((_Atomic uint32_t*)&cfg->var, newcfg->var); newcfg->var = 0; 6018 #define COPY_VAR_int32_t(var) oldcfg->var = cfg->var; atomic_store((_Atomic int32_t*)&cfg->var, newcfg->var); newcfg->var = 0; 6019 /* If config file items are missing from this list, they are 6020 * not updated by fast-reload +p. */ 6021 /* For missing items, the oldcfg item is not updated, still NULL, 6022 * and the cfg stays the same. The newcfg item is untouched. 6023 * The newcfg item is then deleted later. */ 6024 /* Items that need synchronisation are omitted from the list. 6025 * Use fast-reload without +p to update them together. */ 6026 COPY_VAR_int(verbosity); 6027 COPY_VAR_int(stat_interval); 6028 COPY_VAR_int(stat_cumulative); 6029 COPY_VAR_int(stat_extended); 6030 COPY_VAR_int(stat_inhibit_zero); 6031 COPY_VAR_int(num_threads); 6032 COPY_VAR_int(port); 6033 COPY_VAR_int(do_ip4); 6034 COPY_VAR_int(do_ip6); 6035 COPY_VAR_int(do_nat64); 6036 COPY_VAR_int(prefer_ip4); 6037 COPY_VAR_int(prefer_ip6); 6038 COPY_VAR_int(do_udp); 6039 COPY_VAR_int(do_tcp); 6040 COPY_VAR_size_t(max_reuse_tcp_queries); 6041 COPY_VAR_int(tcp_reuse_timeout); 6042 COPY_VAR_int(tcp_auth_query_timeout); 6043 COPY_VAR_int(tcp_upstream); 6044 COPY_VAR_int(udp_upstream_without_downstream); 6045 COPY_VAR_int(tcp_mss); 6046 COPY_VAR_int(outgoing_tcp_mss); 6047 COPY_VAR_int(tcp_idle_timeout); 6048 COPY_VAR_int(do_tcp_keepalive); 6049 COPY_VAR_int(tcp_keepalive_timeout); 6050 COPY_VAR_int(sock_queue_timeout); 6051 COPY_VAR_ptr(proxy_protocol_port); 6052 COPY_VAR_ptr(ssl_service_key); 6053 COPY_VAR_ptr(ssl_service_pem); 6054 COPY_VAR_int(ssl_port); 6055 COPY_VAR_int(ssl_upstream); 6056 COPY_VAR_ptr(tls_cert_bundle); 6057 COPY_VAR_int(tls_win_cert); 6058 COPY_VAR_ptr(tls_additional_port); 6059 /* The first is used to walk through the list but last is 6060 * only used during config read. */ 6061 COPY_VAR_ptr(tls_session_ticket_keys.first); 6062 COPY_VAR_ptr(tls_session_ticket_keys.last); 6063 COPY_VAR_ptr(tls_ciphers); 6064 COPY_VAR_ptr(tls_ciphersuites); 6065 COPY_VAR_ptr(tls_protocols); 6066 COPY_VAR_int(tls_use_sni); 6067 COPY_VAR_int(https_port); 6068 COPY_VAR_ptr(http_endpoint); 6069 COPY_VAR_uint32_t(http_max_streams); 6070 COPY_VAR_size_t(http_query_buffer_size); 6071 COPY_VAR_size_t(http_response_buffer_size); 6072 COPY_VAR_int(http_nodelay); 6073 COPY_VAR_int(http_notls_downstream); 6074 COPY_VAR_int(outgoing_num_ports); 6075 COPY_VAR_size_t(outgoing_num_tcp); 6076 COPY_VAR_size_t(incoming_num_tcp); 6077 COPY_VAR_ptr(outgoing_avail_ports); 6078 COPY_VAR_size_t(edns_buffer_size); 6079 COPY_VAR_size_t(stream_wait_size); 6080 COPY_VAR_size_t(msg_buffer_size); 6081 COPY_VAR_size_t(msg_cache_size); 6082 COPY_VAR_size_t(msg_cache_slabs); 6083 COPY_VAR_size_t(num_queries_per_thread); 6084 COPY_VAR_size_t(jostle_time); 6085 COPY_VAR_size_t(rrset_cache_size); 6086 COPY_VAR_size_t(rrset_cache_slabs); 6087 COPY_VAR_int(host_ttl); 6088 COPY_VAR_size_t(infra_cache_slabs); 6089 COPY_VAR_size_t(infra_cache_numhosts); 6090 COPY_VAR_int(infra_cache_min_rtt); 6091 COPY_VAR_int(infra_cache_max_rtt); 6092 COPY_VAR_int(infra_keep_probing); 6093 COPY_VAR_int(delay_close); 6094 COPY_VAR_int(udp_connect); 6095 COPY_VAR_ptr(target_fetch_policy); 6096 COPY_VAR_int(fast_server_permil); 6097 COPY_VAR_size_t(fast_server_num); 6098 COPY_VAR_int(if_automatic); 6099 COPY_VAR_ptr(if_automatic_ports); 6100 COPY_VAR_size_t(so_rcvbuf); 6101 COPY_VAR_size_t(so_sndbuf); 6102 COPY_VAR_int(so_reuseport); 6103 COPY_VAR_int(ip_transparent); 6104 COPY_VAR_int(ip_freebind); 6105 COPY_VAR_int(ip_dscp); 6106 /* Not copied because the length and items could then not match. 6107 num_ifs, ifs, num_out_ifs, out_ifs 6108 */ 6109 COPY_VAR_ptr(root_hints); 6110 COPY_VAR_ptr(stubs); 6111 COPY_VAR_ptr(forwards); 6112 COPY_VAR_ptr(auths); 6113 COPY_VAR_ptr(views); 6114 COPY_VAR_ptr(donotqueryaddrs); 6115 #ifdef CLIENT_SUBNET 6116 COPY_VAR_ptr(client_subnet); 6117 COPY_VAR_ptr(client_subnet_zone); 6118 COPY_VAR_uint16_t(client_subnet_opcode); 6119 COPY_VAR_int(client_subnet_always_forward); 6120 COPY_VAR_uint8_t(max_client_subnet_ipv4); 6121 COPY_VAR_uint8_t(max_client_subnet_ipv6); 6122 COPY_VAR_uint8_t(min_client_subnet_ipv4); 6123 COPY_VAR_uint8_t(min_client_subnet_ipv6); 6124 COPY_VAR_uint32_t(max_ecs_tree_size_ipv4); 6125 COPY_VAR_uint32_t(max_ecs_tree_size_ipv6); 6126 #endif 6127 COPY_VAR_ptr(acls); 6128 COPY_VAR_int(donotquery_localhost); 6129 COPY_VAR_ptr(tcp_connection_limits); 6130 COPY_VAR_int(harden_short_bufsize); 6131 COPY_VAR_int(harden_large_queries); 6132 COPY_VAR_int(harden_glue); 6133 COPY_VAR_int(harden_dnssec_stripped); 6134 COPY_VAR_int(harden_below_nxdomain); 6135 COPY_VAR_int(harden_referral_path); 6136 COPY_VAR_int(harden_algo_downgrade); 6137 COPY_VAR_int(harden_unknown_additional); 6138 COPY_VAR_int(use_caps_bits_for_id); 6139 COPY_VAR_ptr(caps_whitelist); 6140 COPY_VAR_ptr(private_address); 6141 COPY_VAR_ptr(private_domain); 6142 COPY_VAR_size_t(unwanted_threshold); 6143 COPY_VAR_int(max_ttl); 6144 COPY_VAR_int(min_ttl); 6145 COPY_VAR_int(max_negative_ttl); 6146 COPY_VAR_int(min_negative_ttl); 6147 COPY_VAR_int(prefetch); 6148 COPY_VAR_int(prefetch_key); 6149 COPY_VAR_int(deny_any); 6150 COPY_VAR_ptr(chrootdir); 6151 COPY_VAR_ptr(username); 6152 COPY_VAR_ptr(directory); 6153 COPY_VAR_ptr(logfile); 6154 COPY_VAR_ptr(pidfile); 6155 COPY_VAR_int(use_syslog); 6156 COPY_VAR_int(log_time_ascii); 6157 COPY_VAR_int(log_queries); 6158 COPY_VAR_int(log_replies); 6159 COPY_VAR_int(log_tag_queryreply); 6160 COPY_VAR_int(log_local_actions); 6161 COPY_VAR_int(log_servfail); 6162 COPY_VAR_ptr(log_identity); 6163 COPY_VAR_int(log_destaddr); 6164 COPY_VAR_int(log_thread_id); 6165 COPY_VAR_int(hide_identity); 6166 COPY_VAR_int(hide_version); 6167 COPY_VAR_int(hide_trustanchor); 6168 COPY_VAR_int(hide_http_user_agent); 6169 COPY_VAR_ptr(identity); 6170 COPY_VAR_ptr(version); 6171 COPY_VAR_ptr(http_user_agent); 6172 COPY_VAR_ptr(nsid_cfg_str); 6173 /* Not copied because the length and items could then not match. 6174 nsid; 6175 nsid_len; 6176 */ 6177 COPY_VAR_ptr(module_conf); 6178 COPY_VAR_ptr(trust_anchor_file_list); 6179 COPY_VAR_ptr(trust_anchor_list); 6180 COPY_VAR_ptr(auto_trust_anchor_file_list); 6181 COPY_VAR_ptr(trusted_keys_file_list); 6182 COPY_VAR_ptr(domain_insecure); 6183 COPY_VAR_int(trust_anchor_signaling); 6184 COPY_VAR_int(root_key_sentinel); 6185 COPY_VAR_int32_t(val_date_override); 6186 COPY_VAR_int32_t(val_sig_skew_min); 6187 COPY_VAR_int32_t(val_sig_skew_max); 6188 COPY_VAR_int32_t(val_max_restart); 6189 COPY_VAR_int(bogus_ttl); 6190 COPY_VAR_int(val_clean_additional); 6191 COPY_VAR_int(val_log_level); 6192 COPY_VAR_int(val_log_squelch); 6193 COPY_VAR_int(val_permissive_mode); 6194 COPY_VAR_int(aggressive_nsec); 6195 COPY_VAR_int(ignore_cd); 6196 COPY_VAR_int(disable_edns_do); 6197 COPY_VAR_int(serve_expired); 6198 COPY_VAR_int(serve_expired_ttl); 6199 COPY_VAR_int(serve_expired_ttl_reset); 6200 COPY_VAR_int(serve_expired_reply_ttl); 6201 COPY_VAR_int(serve_expired_client_timeout); 6202 COPY_VAR_int(ede_serve_expired); 6203 COPY_VAR_int(dns_error_reporting); 6204 COPY_VAR_int(serve_original_ttl); 6205 COPY_VAR_ptr(val_nsec3_key_iterations); 6206 COPY_VAR_int(zonemd_permissive_mode); 6207 COPY_VAR_unsigned_int(add_holddown); 6208 COPY_VAR_unsigned_int(del_holddown); 6209 COPY_VAR_unsigned_int(keep_missing); 6210 COPY_VAR_int(permit_small_holddown); 6211 COPY_VAR_size_t(key_cache_size); 6212 COPY_VAR_size_t(key_cache_slabs); 6213 COPY_VAR_size_t(neg_cache_size); 6214 COPY_VAR_ptr(local_zones); 6215 COPY_VAR_ptr(local_zones_nodefault); 6216 #ifdef USE_IPSET 6217 COPY_VAR_ptr(local_zones_ipset); 6218 #endif 6219 COPY_VAR_int(local_zones_disable_default); 6220 COPY_VAR_ptr(local_data); 6221 COPY_VAR_ptr(local_zone_overrides); 6222 COPY_VAR_int(unblock_lan_zones); 6223 COPY_VAR_int(insecure_lan_zones); 6224 /* These reference tags 6225 COPY_VAR_ptr(local_zone_tags); 6226 COPY_VAR_ptr(acl_tags); 6227 COPY_VAR_ptr(acl_tag_actions); 6228 COPY_VAR_ptr(acl_tag_datas); 6229 */ 6230 COPY_VAR_ptr(acl_view); 6231 COPY_VAR_ptr(interface_actions); 6232 /* These reference tags 6233 COPY_VAR_ptr(interface_tags); 6234 COPY_VAR_ptr(interface_tag_actions); 6235 COPY_VAR_ptr(interface_tag_datas); 6236 */ 6237 COPY_VAR_ptr(interface_view); 6238 /* This references tags 6239 COPY_VAR_ptr(respip_tags); 6240 */ 6241 COPY_VAR_ptr(respip_actions); 6242 COPY_VAR_ptr(respip_data); 6243 /* Not copied because the length and items could then not match. 6244 * also the respip module keeps a pointer to the array in its state. 6245 tagname, num_tags 6246 */ 6247 COPY_VAR_int(remote_control_enable); 6248 /* The first is used to walk through the list but last is 6249 * only used during config read. */ 6250 COPY_VAR_ptr(control_ifs.first); 6251 COPY_VAR_ptr(control_ifs.last); 6252 COPY_VAR_int(control_use_cert); 6253 COPY_VAR_int(control_port); 6254 COPY_VAR_ptr(server_key_file); 6255 COPY_VAR_ptr(server_cert_file); 6256 COPY_VAR_ptr(control_key_file); 6257 COPY_VAR_ptr(control_cert_file); 6258 COPY_VAR_ptr(python_script); 6259 COPY_VAR_ptr(dynlib_file); 6260 COPY_VAR_int(use_systemd); 6261 COPY_VAR_int(do_daemonize); 6262 COPY_VAR_int(minimal_responses); 6263 COPY_VAR_int(rrset_roundrobin); 6264 COPY_VAR_int(unknown_server_time_limit); 6265 COPY_VAR_int(discard_timeout); 6266 COPY_VAR_int(wait_limit); 6267 COPY_VAR_int(wait_limit_cookie); 6268 COPY_VAR_ptr(wait_limit_netblock); 6269 COPY_VAR_ptr(wait_limit_cookie_netblock); 6270 COPY_VAR_size_t(max_udp_size); 6271 COPY_VAR_ptr(dns64_prefix); 6272 COPY_VAR_int(dns64_synthall); 6273 COPY_VAR_ptr(dns64_ignore_aaaa); 6274 COPY_VAR_ptr(nat64_prefix); 6275 COPY_VAR_int(dnstap); 6276 COPY_VAR_int(dnstap_bidirectional); 6277 COPY_VAR_ptr(dnstap_socket_path); 6278 COPY_VAR_ptr(dnstap_ip); 6279 COPY_VAR_int(dnstap_tls); 6280 COPY_VAR_ptr(dnstap_tls_server_name); 6281 COPY_VAR_ptr(dnstap_tls_cert_bundle); 6282 COPY_VAR_ptr(dnstap_tls_client_key_file); 6283 COPY_VAR_ptr(dnstap_tls_client_cert_file); 6284 COPY_VAR_int(dnstap_send_identity); 6285 COPY_VAR_int(dnstap_send_version); 6286 COPY_VAR_ptr(dnstap_identity); 6287 COPY_VAR_ptr(dnstap_version); 6288 COPY_VAR_int(dnstap_sample_rate); 6289 COPY_VAR_int(dnstap_log_resolver_query_messages); 6290 COPY_VAR_int(dnstap_log_resolver_response_messages); 6291 COPY_VAR_int(dnstap_log_client_query_messages); 6292 COPY_VAR_int(dnstap_log_client_response_messages); 6293 COPY_VAR_int(dnstap_log_forwarder_query_messages); 6294 COPY_VAR_int(dnstap_log_forwarder_response_messages); 6295 COPY_VAR_int(disable_dnssec_lame_check); 6296 COPY_VAR_int(ip_ratelimit); 6297 COPY_VAR_int(ip_ratelimit_cookie); 6298 COPY_VAR_size_t(ip_ratelimit_slabs); 6299 COPY_VAR_size_t(ip_ratelimit_size); 6300 COPY_VAR_int(ip_ratelimit_factor); 6301 COPY_VAR_int(ip_ratelimit_backoff); 6302 COPY_VAR_int(ratelimit); 6303 COPY_VAR_size_t(ratelimit_slabs); 6304 COPY_VAR_size_t(ratelimit_size); 6305 COPY_VAR_ptr(ratelimit_for_domain); 6306 COPY_VAR_ptr(ratelimit_below_domain); 6307 COPY_VAR_int(ratelimit_factor); 6308 COPY_VAR_int(ratelimit_backoff); 6309 COPY_VAR_int(outbound_msg_retry); 6310 COPY_VAR_int(max_sent_count); 6311 COPY_VAR_int(max_query_restarts); 6312 COPY_VAR_int(qname_minimisation); 6313 COPY_VAR_int(qname_minimisation_strict); 6314 COPY_VAR_int(shm_enable); 6315 COPY_VAR_int(shm_key); 6316 COPY_VAR_ptr(edns_client_strings); 6317 COPY_VAR_uint16_t(edns_client_string_opcode); 6318 COPY_VAR_int(dnscrypt); 6319 COPY_VAR_int(dnscrypt_port); 6320 COPY_VAR_ptr(dnscrypt_provider); 6321 COPY_VAR_ptr(dnscrypt_secret_key); 6322 COPY_VAR_ptr(dnscrypt_provider_cert); 6323 COPY_VAR_ptr(dnscrypt_provider_cert_rotated); 6324 COPY_VAR_size_t(dnscrypt_shared_secret_cache_size); 6325 COPY_VAR_size_t(dnscrypt_shared_secret_cache_slabs); 6326 COPY_VAR_size_t(dnscrypt_nonce_cache_size); 6327 COPY_VAR_size_t(dnscrypt_nonce_cache_slabs); 6328 COPY_VAR_int(pad_responses); 6329 COPY_VAR_size_t(pad_responses_block_size); 6330 COPY_VAR_int(pad_queries); 6331 COPY_VAR_size_t(pad_queries_block_size); 6332 #ifdef USE_IPSECMOD 6333 COPY_VAR_int(ipsecmod_enabled); 6334 COPY_VAR_ptr(ipsecmod_whitelist); 6335 COPY_VAR_ptr(ipsecmod_hook); 6336 COPY_VAR_int(ipsecmod_ignore_bogus); 6337 COPY_VAR_int(ipsecmod_max_ttl); 6338 COPY_VAR_int(ipsecmod_strict); 6339 #endif 6340 #ifdef USE_CACHEDB 6341 COPY_VAR_ptr(cachedb_backend); 6342 COPY_VAR_ptr(cachedb_secret); 6343 COPY_VAR_int(cachedb_no_store); 6344 COPY_VAR_int(cachedb_check_when_serve_expired); 6345 #ifdef USE_REDIS 6346 COPY_VAR_ptr(redis_server_host); 6347 COPY_VAR_ptr(redis_replica_server_host); 6348 COPY_VAR_int(redis_server_port); 6349 COPY_VAR_int(redis_replica_server_port); 6350 COPY_VAR_ptr(redis_server_path); 6351 COPY_VAR_ptr(redis_replica_server_path); 6352 COPY_VAR_ptr(redis_server_password); 6353 COPY_VAR_ptr(redis_replica_server_password); 6354 COPY_VAR_int(redis_timeout); 6355 COPY_VAR_int(redis_replica_timeout); 6356 COPY_VAR_int(redis_command_timeout); 6357 COPY_VAR_int(redis_replica_command_timeout); 6358 COPY_VAR_int(redis_connect_timeout); 6359 COPY_VAR_int(redis_replica_connect_timeout); 6360 COPY_VAR_int(redis_expire_records); 6361 COPY_VAR_int(redis_logical_db); 6362 COPY_VAR_int(redis_replica_logical_db); 6363 #endif 6364 #endif 6365 COPY_VAR_int(do_answer_cookie); 6366 /* Not copied because the length and content could then not match. 6367 cookie_secret[40], cookie_secret_len 6368 */ 6369 #ifdef USE_IPSET 6370 COPY_VAR_ptr(ipset_name_v4); 6371 COPY_VAR_ptr(ipset_name_v6); 6372 #endif 6373 COPY_VAR_int(ede); 6374 COPY_VAR_int(iter_scrub_ns); 6375 COPY_VAR_int(iter_scrub_cname); 6376 COPY_VAR_int(iter_scrub_rrsig); 6377 COPY_VAR_int(max_global_quota); 6378 COPY_VAR_int(iter_scrub_promiscuous); 6379 6380 #undef COPY_VAR_int 6381 #undef COPY_VAR_ptr 6382 #undef COPY_VAR_unsigned_int 6383 #undef COPY_VAR_size_t 6384 #undef COPY_VAR_uint8_t 6385 #undef COPY_VAR_uint16_t 6386 #undef COPY_VAR_uint32_t 6387 #undef COPY_VAR_int32_t 6388 } 6389 #endif /* ATOMIC_POINTER_LOCK_FREE && HAVE_LINK_ATOMIC_STORE */ 6390 6391 /** fast reload thread, adjust the cache sizes */ 6392 static void 6393 fr_adjust_cache(struct module_env* env, struct config_file* oldcfg) 6394 { 6395 if(env->cfg->msg_cache_size != oldcfg->msg_cache_size) 6396 slabhash_adjust_size(env->msg_cache, env->cfg->msg_cache_size); 6397 if(env->cfg->rrset_cache_size != oldcfg->rrset_cache_size) 6398 slabhash_adjust_size(&env->rrset_cache->table, 6399 env->cfg->rrset_cache_size); 6400 if(env->key_cache && 6401 env->cfg->key_cache_size != oldcfg->key_cache_size) 6402 slabhash_adjust_size(env->key_cache->slab, 6403 env->cfg->key_cache_size); 6404 if(env->cfg->infra_cache_numhosts != oldcfg->infra_cache_numhosts) { 6405 size_t inframem = env->cfg->infra_cache_numhosts * 6406 (sizeof(struct infra_key) + sizeof(struct infra_data) 6407 + INFRA_BYTES_NAME); 6408 slabhash_adjust_size(env->infra_cache->hosts, inframem); 6409 } 6410 if(env->cfg->ratelimit_size != oldcfg->ratelimit_size) { 6411 slabhash_adjust_size(env->infra_cache->domain_rates, 6412 env->cfg->ratelimit_size); 6413 slabhash_adjust_size(env->infra_cache->client_ip_rates, 6414 env->cfg->ratelimit_size); 6415 } 6416 if(env->neg_cache && 6417 env->cfg->neg_cache_size != oldcfg->neg_cache_size) { 6418 val_neg_adjust_size(env->neg_cache, env->cfg->neg_cache_size); 6419 } 6420 } 6421 6422 /** fast reload thread, adjust the iterator env */ 6423 static void 6424 fr_adjust_iter_env(struct module_env* env, struct fast_reload_construct* ct) 6425 { 6426 int m; 6427 struct iter_env* iter_env = NULL; 6428 /* There is no comparison here to see if no options changed and thus 6429 * no swap is needed, the trees with addresses and domains can be 6430 * large and that would take too long. Instead the trees are 6431 * swapped in. */ 6432 6433 /* Because the iterator env is not locked, the update cannot happen 6434 * when fr nopause is used. Without it the fast reload pauses the 6435 * other threads, so they are not currently using the structure. */ 6436 m = modstack_find(env->modstack, "iterator"); 6437 if(m != -1) iter_env = (struct iter_env*)env->modinfo[m]; 6438 if(iter_env) { 6439 /* Swap the data so that the delete happens afterwards. */ 6440 int* oldtargetfetchpolicy = iter_env->target_fetch_policy; 6441 int oldmaxdependencydepth = iter_env->max_dependency_depth; 6442 struct iter_donotq* olddonotq = iter_env->donotq; 6443 struct iter_priv* oldpriv = iter_env->priv; 6444 struct rbtree_type* oldcapswhite = iter_env->caps_white; 6445 struct iter_nat64 oldnat64 = iter_env->nat64; 6446 6447 iter_env->target_fetch_policy = ct->target_fetch_policy; 6448 iter_env->max_dependency_depth = ct->max_dependency_depth; 6449 iter_env->donotq = ct->donotq; 6450 iter_env->priv = ct->priv; 6451 iter_env->caps_white = ct->caps_white; 6452 iter_env->nat64 = ct->nat64; 6453 iter_env->outbound_msg_retry = env->cfg->outbound_msg_retry; 6454 iter_env->max_sent_count = env->cfg->max_sent_count; 6455 iter_env->max_query_restarts = env->cfg->max_query_restarts; 6456 6457 ct->target_fetch_policy = oldtargetfetchpolicy; 6458 ct->max_dependency_depth = oldmaxdependencydepth; 6459 ct->donotq = olddonotq; 6460 ct->priv = oldpriv; 6461 ct->caps_white = oldcapswhite; 6462 ct->nat64 = oldnat64; 6463 } 6464 } 6465 6466 /** fast reload thread, adjust the validator env */ 6467 static void 6468 fr_adjust_val_env(struct module_env* env, struct fast_reload_construct* ct, 6469 struct config_file* oldcfg) 6470 { 6471 int m; 6472 struct val_env* val_env = NULL; 6473 if(env->cfg->bogus_ttl == oldcfg->bogus_ttl && 6474 env->cfg->val_date_override == oldcfg->val_date_override && 6475 env->cfg->val_sig_skew_min == oldcfg->val_sig_skew_min && 6476 env->cfg->val_sig_skew_max == oldcfg->val_sig_skew_max && 6477 env->cfg->val_max_restart == oldcfg->val_max_restart && 6478 strcmp(env->cfg->val_nsec3_key_iterations, 6479 oldcfg->val_nsec3_key_iterations) == 0) 6480 return; /* no changes */ 6481 6482 /* Because the validator env is not locked, the update cannot happen 6483 * when fr nopause is used. Without it the fast reload pauses the 6484 * other threads, so they are not currently using the structure. */ 6485 m = modstack_find(env->modstack, "validator"); 6486 if(m != -1) val_env = (struct val_env*)env->modinfo[m]; 6487 if(val_env) { 6488 /* Swap the arrays so that the delete happens afterwards. */ 6489 size_t* oldkeysize = val_env->nsec3_keysize; 6490 size_t* oldmaxiter = val_env->nsec3_maxiter; 6491 val_env->nsec3_keysize = NULL; 6492 val_env->nsec3_maxiter = NULL; 6493 val_env_apply_cfg(val_env, env->cfg, ct->nsec3_keysize, 6494 ct->nsec3_maxiter, ct->nsec3_keyiter_count); 6495 ct->nsec3_keysize = oldkeysize; 6496 ct->nsec3_maxiter = oldmaxiter; 6497 if(env->neg_cache) { 6498 lock_basic_lock(&env->neg_cache->lock); 6499 env->neg_cache->nsec3_max_iter = val_env-> 6500 nsec3_maxiter[val_env->nsec3_keyiter_count-1]; 6501 lock_basic_unlock(&env->neg_cache->lock); 6502 } 6503 } 6504 } 6505 6506 /** fast reload thread, adjust the infra cache parameters */ 6507 static void 6508 fr_adjust_infra(struct module_env* env, struct fast_reload_construct* ct) 6509 { 6510 struct infra_cache* infra = env->infra_cache; 6511 struct config_file* cfg = env->cfg; 6512 struct rbtree_type oldwaitlim = infra->wait_limits_netblock; 6513 struct rbtree_type oldwaitlimcookie = 6514 infra->wait_limits_cookie_netblock; 6515 struct rbtree_type olddomainlim = infra->domain_limits; 6516 6517 /* The size of the infra cache and ip rates is changed 6518 * in fr_adjust_cache. */ 6519 infra->host_ttl = cfg->host_ttl; 6520 infra->infra_keep_probing = cfg->infra_keep_probing; 6521 infra_dp_ratelimit = cfg->ratelimit; 6522 infra_ip_ratelimit = cfg->ip_ratelimit; 6523 infra_ip_ratelimit_cookie = cfg->ip_ratelimit_cookie; 6524 infra->wait_limits_netblock = ct->wait_limits_netblock; 6525 infra->wait_limits_cookie_netblock = ct->wait_limits_cookie_netblock; 6526 infra->domain_limits = ct->domain_limits; 6527 6528 ct->wait_limits_netblock = oldwaitlim; 6529 ct->wait_limits_cookie_netblock = oldwaitlimcookie; 6530 ct->domain_limits = olddomainlim; 6531 } 6532 6533 /** fast reload thread, reload config with putting the new config items 6534 * in place and swapping out the old items. */ 6535 static int 6536 fr_reload_config(struct fast_reload_thread* fr, struct config_file* newcfg, 6537 struct fast_reload_construct* ct) 6538 { 6539 struct daemon* daemon = fr->worker->daemon; 6540 struct module_env* env = daemon->env; 6541 6542 /* These are constructed in the fr_construct_from_config routine. */ 6543 log_assert(ct->oldcfg); 6544 log_assert(ct->fwds); 6545 log_assert(ct->hints); 6546 6547 /* Grab big locks to satisfy lock conditions. */ 6548 lock_rw_wrlock(&ct->views->lock); 6549 lock_rw_wrlock(&env->views->lock); 6550 lock_rw_wrlock(&ct->respip_set->lock); 6551 lock_rw_wrlock(&env->respip_set->lock); 6552 lock_rw_wrlock(&ct->local_zones->lock); 6553 lock_rw_wrlock(&daemon->local_zones->lock); 6554 lock_rw_wrlock(&ct->auth_zones->rpz_lock); 6555 lock_rw_wrlock(&env->auth_zones->rpz_lock); 6556 lock_rw_wrlock(&ct->auth_zones->lock); 6557 lock_rw_wrlock(&env->auth_zones->lock); 6558 lock_rw_wrlock(&ct->fwds->lock); 6559 lock_rw_wrlock(&env->fwds->lock); 6560 lock_rw_wrlock(&ct->hints->lock); 6561 lock_rw_wrlock(&env->hints->lock); 6562 if(ct->anchors) { 6563 lock_basic_lock(&ct->anchors->lock); 6564 lock_basic_lock(&env->anchors->lock); 6565 } 6566 6567 #if defined(ATOMIC_POINTER_LOCK_FREE) && defined(HAVE_LINK_ATOMIC_STORE) 6568 if(fr->fr_nopause) { 6569 fr_atomic_copy_cfg(ct->oldcfg, env->cfg, newcfg); 6570 } else { 6571 #endif 6572 /* Store old config elements. */ 6573 *ct->oldcfg = *env->cfg; 6574 /* Insert new config elements. */ 6575 *env->cfg = *newcfg; 6576 #if defined(ATOMIC_POINTER_LOCK_FREE) && defined(HAVE_LINK_ATOMIC_STORE) 6577 } 6578 #endif 6579 6580 if(env->cfg->log_identity || ct->oldcfg->log_identity) { 6581 /* pick up new log_identity string to use for log output. */ 6582 log_ident_set_or_default(env->cfg->log_identity); 6583 } 6584 /* the newcfg elements are in env->cfg, so should not be freed here. */ 6585 #if defined(ATOMIC_POINTER_LOCK_FREE) && defined(HAVE_LINK_ATOMIC_STORE) 6586 /* if used, the routine that copies the config has zeroed items. */ 6587 if(!fr->fr_nopause) 6588 #endif 6589 memset(newcfg, 0, sizeof(*newcfg)); 6590 6591 /* Quickly swap the tree roots themselves with the already allocated 6592 * elements. This is a quick swap operation on the pointer. 6593 * The other threads are stopped and locks are held, so that a 6594 * consistent view of the configuration, before, and after, exists 6595 * towards the state machine for query resolution. */ 6596 forwards_swap_tree(env->fwds, ct->fwds); 6597 hints_swap_tree(env->hints, ct->hints); 6598 views_swap_tree(env->views, ct->views); 6599 acl_list_swap_tree(daemon->acl, ct->acl); 6600 acl_list_swap_tree(daemon->acl_interface, ct->acl_interface); 6601 tcl_list_swap_tree(daemon->tcl, ct->tcl); 6602 local_zones_swap_tree(daemon->local_zones, ct->local_zones); 6603 respip_set_swap_tree(env->respip_set, ct->respip_set); 6604 daemon->use_response_ip = ct->use_response_ip; 6605 daemon->use_rpz = ct->use_rpz; 6606 auth_zones_swap(env->auth_zones, ct->auth_zones); 6607 edns_strings_swap_tree(env->edns_strings, ct->edns_strings); 6608 anchors_swap_tree(env->anchors, ct->anchors); 6609 #ifdef USE_CACHEDB 6610 daemon->env->cachedb_enabled = cachedb_is_enabled(&daemon->mods, 6611 daemon->env); 6612 #endif 6613 if(fr->sslctxs_changed) { 6614 sslctxs_swap(daemon, ct); 6615 } 6616 #ifdef USE_DNSTAP 6617 if(env->cfg->dnstap) { 6618 if(!fr->fr_nopause) 6619 dt_apply_cfg(daemon->dtenv, env->cfg); 6620 else dt_apply_logcfg(daemon->dtenv, env->cfg); 6621 } 6622 #endif 6623 fr_adjust_cache(env, ct->oldcfg); 6624 if(!fr->fr_nopause) { 6625 fr_adjust_iter_env(env, ct); 6626 fr_adjust_val_env(env, ct, ct->oldcfg); 6627 fr_adjust_infra(env, ct); 6628 } 6629 6630 /* Set globals with new config. */ 6631 config_apply(env->cfg); 6632 6633 lock_rw_unlock(&ct->views->lock); 6634 lock_rw_unlock(&env->views->lock); 6635 lock_rw_unlock(&ct->respip_set->lock); 6636 lock_rw_unlock(&env->respip_set->lock); 6637 lock_rw_unlock(&ct->local_zones->lock); 6638 lock_rw_unlock(&daemon->local_zones->lock); 6639 lock_rw_unlock(&ct->auth_zones->lock); 6640 lock_rw_unlock(&env->auth_zones->lock); 6641 lock_rw_unlock(&ct->auth_zones->rpz_lock); 6642 lock_rw_unlock(&env->auth_zones->rpz_lock); 6643 lock_rw_unlock(&ct->fwds->lock); 6644 lock_rw_unlock(&env->fwds->lock); 6645 lock_rw_unlock(&ct->hints->lock); 6646 lock_rw_unlock(&env->hints->lock); 6647 if(ct->anchors) { 6648 lock_basic_unlock(&ct->anchors->lock); 6649 lock_basic_unlock(&env->anchors->lock); 6650 } 6651 6652 return 1; 6653 } 6654 6655 /** fast reload, poll for ack incoming. */ 6656 static void 6657 fr_poll_for_ack(struct fast_reload_thread* fr) 6658 { 6659 int loopexit = 0, bcount = 0; 6660 uint32_t cmd; 6661 ssize_t ret; 6662 6663 if(fr->need_to_quit) 6664 return; 6665 /* Is there data? */ 6666 if(!sock_poll_timeout(fr->commpair[1], -1, 1, 0, NULL)) { 6667 log_err("fr_poll_for_ack: poll failed"); 6668 return; 6669 } 6670 6671 /* Read the data */ 6672 while(1) { 6673 if(++loopexit > IPC_LOOP_MAX) { 6674 log_err("fr_poll_for_ack: recv loops %s", 6675 sock_strerror(errno)); 6676 return; 6677 } 6678 ret = recv(fr->commpair[1], ((char*)&cmd)+bcount, 6679 sizeof(cmd)-bcount, 0); 6680 if(ret == -1) { 6681 if( 6682 #ifndef USE_WINSOCK 6683 errno == EINTR || errno == EAGAIN 6684 # ifdef EWOULDBLOCK 6685 || errno == EWOULDBLOCK 6686 # endif 6687 #else 6688 WSAGetLastError() == WSAEINTR || 6689 WSAGetLastError() == WSAEINPROGRESS || 6690 WSAGetLastError() == WSAEWOULDBLOCK 6691 #endif 6692 ) 6693 continue; /* Try again. */ 6694 log_err("fr_poll_for_ack: recv: %s", 6695 sock_strerror(errno)); 6696 return; 6697 } else if(ret+(ssize_t)bcount != sizeof(cmd)) { 6698 bcount += ret; 6699 if((size_t)bcount < sizeof(cmd)) 6700 continue; 6701 } 6702 break; 6703 } 6704 if(cmd == fast_reload_notification_exit) { 6705 fr->need_to_quit = 1; 6706 verbose(VERB_ALGO, "fast reload wait for ack: " 6707 "exit notification received"); 6708 return; 6709 } 6710 if(cmd != fast_reload_notification_reload_ack) { 6711 verbose(VERB_ALGO, "fast reload wait for ack: " 6712 "wrong notification %d", (int)cmd); 6713 } 6714 } 6715 6716 /** fast reload thread, reload ipc communication to stop and start threads. */ 6717 static int 6718 fr_reload_ipc(struct fast_reload_thread* fr, struct config_file* newcfg, 6719 struct fast_reload_construct* ct) 6720 { 6721 int result = 1; 6722 if(!fr->fr_nopause) { 6723 fr_send_notification(fr, fast_reload_notification_reload_stop); 6724 fr_poll_for_ack(fr); 6725 } 6726 if(!fr_reload_config(fr, newcfg, ct)) { 6727 result = 0; 6728 } 6729 if(!fr->fr_nopause) { 6730 fr_send_notification(fr, fast_reload_notification_reload_start); 6731 fr_poll_for_ack(fr); 6732 } 6733 return result; 6734 } 6735 6736 /** fast reload thread, load config */ 6737 static int 6738 fr_load_config(struct fast_reload_thread* fr, struct timeval* time_read, 6739 struct timeval* time_construct, struct timeval* time_reload) 6740 { 6741 struct fast_reload_construct ct; 6742 struct config_file* newcfg = NULL; 6743 memset(&ct, 0, sizeof(ct)); 6744 6745 /* Read file. */ 6746 if(!fr_read_config(fr, &newcfg)) 6747 return 0; 6748 if(gettimeofday(time_read, NULL) < 0) 6749 log_err("gettimeofday: %s", strerror(errno)); 6750 if(fr_poll_for_quit(fr)) { 6751 config_delete(newcfg); 6752 return 1; 6753 } 6754 6755 /* Check if the config can be loaded */ 6756 if(!fr_check_tag_defines(fr, newcfg)) { 6757 config_delete(newcfg); 6758 return 0; 6759 } 6760 if(!fr_check_compat_cfg(fr, newcfg)) { 6761 config_delete(newcfg); 6762 return 0; 6763 } 6764 if(!fr_check_nopause_compat_cfg(fr, newcfg)) { 6765 config_delete(newcfg); 6766 return 0; 6767 } 6768 if(fr_poll_for_quit(fr)) { 6769 config_delete(newcfg); 6770 return 1; 6771 } 6772 6773 /* Construct items. */ 6774 if(!fr_construct_from_config(fr, newcfg, &ct)) { 6775 config_delete(newcfg); 6776 if(!fr_output_printf(fr, "Could not construct from the " 6777 "config, check for errors with unbound-checkconf, or " 6778 "out of memory. The parse errors are printed in " 6779 "the log.\n")) 6780 return 0; 6781 fr_send_notification(fr, fast_reload_notification_printout); 6782 return 0; 6783 } 6784 if(gettimeofday(time_construct, NULL) < 0) 6785 log_err("gettimeofday: %s", strerror(errno)); 6786 if(fr_poll_for_quit(fr)) { 6787 config_delete(newcfg); 6788 fr_construct_clear(&ct); 6789 return 1; 6790 } 6791 6792 /* Reload server. */ 6793 if(!fr_reload_ipc(fr, newcfg, &ct)) { 6794 config_delete(newcfg); 6795 fr_construct_clear(&ct); 6796 if(!fr_output_printf(fr, "error: reload failed\n")) 6797 return 0; 6798 fr_send_notification(fr, fast_reload_notification_printout); 6799 return 0; 6800 } 6801 if(gettimeofday(time_reload, NULL) < 0) 6802 log_err("gettimeofday: %s", strerror(errno)); 6803 6804 if(fr_poll_for_quit(fr)) { 6805 config_delete(newcfg); 6806 fr_construct_clear(&ct); 6807 return 1; 6808 } 6809 if(fr->fr_nopause) { 6810 /* Poll every thread, with a no-work poll item over the 6811 * command pipe. This makes the worker thread surely move 6812 * to deal with that event, and thus the thread is no longer 6813 * holding, eg. a string item from the old config struct. 6814 * And then the old config struct can safely be deleted. 6815 * Only needed when nopause is used, because without that 6816 * the worker threads are already waiting on a command pipe 6817 * item. This nopause command pipe item does not take work, 6818 * it returns immediately, so it does not delay the workers. 6819 * They can be polled one at a time. But its processing causes 6820 * the worker to have released data items from old config. 6821 * This also makes sure the threads are not holding locks on 6822 * individual items in the local_zones, views, respip_set. */ 6823 fr_send_notification(fr, 6824 fast_reload_notification_reload_nopause_poll); 6825 fr_poll_for_ack(fr); 6826 } 6827 6828 /* Delete old. */ 6829 config_delete(newcfg); 6830 fr_construct_clear(&ct); 6831 return 1; 6832 } 6833 6834 /** fast reload thread. the thread main function */ 6835 static void* fast_reload_thread_main(void* arg) 6836 { 6837 struct fast_reload_thread* fast_reload_thread = (struct fast_reload_thread*)arg; 6838 struct timeval time_start, time_read, time_construct, time_reload, 6839 time_end; 6840 const char name[16] = "unbound/freload"; /* seems to be the safest size 6841 between different OSes */ 6842 6843 #if defined(HAVE_GETTID) && !defined(THREADS_DISABLED) 6844 fast_reload_thread->thread_tid = gettid(); 6845 if(fast_reload_thread->thread_tid_log) 6846 log_thread_set(&fast_reload_thread->thread_tid); 6847 else 6848 #endif 6849 log_thread_set(&fast_reload_thread->threadnum); 6850 6851 ub_thread_setname(fast_reload_thread->tid, name); 6852 (void)name; /* When setname is not defined, ignore the name variable. */ 6853 6854 verbose(VERB_ALGO, "start fast reload thread"); 6855 if(fast_reload_thread->fr_verb >= 1) { 6856 fr_init_time(&time_start, &time_read, &time_construct, 6857 &time_reload, &time_end); 6858 if(fr_poll_for_quit(fast_reload_thread)) 6859 goto done; 6860 } 6861 6862 /* print output to the client */ 6863 if(fast_reload_thread->fr_verb >= 1) { 6864 if(!fr_output_printf(fast_reload_thread, "thread started\n")) 6865 goto done_error; 6866 fr_send_notification(fast_reload_thread, 6867 fast_reload_notification_printout); 6868 if(fr_poll_for_quit(fast_reload_thread)) 6869 goto done; 6870 } 6871 6872 if(!fr_load_config(fast_reload_thread, &time_read, &time_construct, 6873 &time_reload)) 6874 goto done_error; 6875 if(fr_poll_for_quit(fast_reload_thread)) 6876 goto done; 6877 6878 if(fast_reload_thread->fr_verb >= 1) { 6879 if(!fr_finish_time(fast_reload_thread, &time_start, &time_read, 6880 &time_construct, &time_reload, &time_end)) 6881 goto done_error; 6882 if(fr_poll_for_quit(fast_reload_thread)) 6883 goto done; 6884 } 6885 6886 if(!fr_output_printf(fast_reload_thread, "ok\n")) 6887 goto done_error; 6888 fr_send_notification(fast_reload_thread, 6889 fast_reload_notification_printout); 6890 verbose(VERB_ALGO, "stop fast reload thread"); 6891 /* If this is not an exit due to quit earlier, send regular done. */ 6892 if(!fast_reload_thread->need_to_quit) 6893 fr_send_notification(fast_reload_thread, 6894 fast_reload_notification_done); 6895 /* If during the fast_reload_notification_done send, 6896 * fast_reload_notification_exit was received, ack it. If the 6897 * thread is exiting due to quit received earlier, also ack it.*/ 6898 done: 6899 if(fast_reload_thread->need_to_quit) 6900 fr_send_notification(fast_reload_thread, 6901 fast_reload_notification_exited); 6902 return NULL; 6903 done_error: 6904 verbose(VERB_ALGO, "stop fast reload thread with done_error"); 6905 fr_send_notification(fast_reload_thread, 6906 fast_reload_notification_done_error); 6907 return NULL; 6908 } 6909 #endif /* !THREADS_DISABLED */ 6910 6911 /** create a socketpair for bidirectional communication, false on failure */ 6912 static int 6913 create_socketpair(int* pair, struct ub_randstate* rand) 6914 { 6915 #ifndef USE_WINSOCK 6916 if(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1) { 6917 log_err("socketpair: %s", strerror(errno)); 6918 return 0; 6919 } 6920 (void)rand; 6921 #else 6922 struct sockaddr_in addr, baddr, accaddr, connaddr; 6923 socklen_t baddrlen, accaddrlen, connaddrlen; 6924 uint8_t localhost[] = {127, 0, 0, 1}; 6925 uint8_t nonce[16], recvnonce[16]; 6926 size_t i; 6927 int lst, pollin_event, bcount, loopcount; 6928 int connect_poll_timeout = 200; /* msec to wait for connection */ 6929 ssize_t ret; 6930 pair[0] = -1; 6931 pair[1] = -1; 6932 for(i=0; i<sizeof(nonce); i++) { 6933 nonce[i] = ub_random_max(rand, 256); 6934 } 6935 lst = socket(AF_INET, SOCK_STREAM, 0); 6936 if(lst == -1) { 6937 log_err("create_socketpair: socket: %s", sock_strerror(errno)); 6938 return 0; 6939 } 6940 memset(&addr, 0, sizeof(addr)); 6941 addr.sin_family = AF_INET; 6942 addr.sin_port = 0; 6943 memcpy(&addr.sin_addr, localhost, 4); 6944 if(bind(lst, (struct sockaddr*)&addr, (socklen_t)sizeof(addr)) 6945 == -1) { 6946 log_err("create socketpair: bind: %s", sock_strerror(errno)); 6947 sock_close(lst); 6948 return 0; 6949 } 6950 if(listen(lst, 12) == -1) { 6951 log_err("create socketpair: listen: %s", sock_strerror(errno)); 6952 sock_close(lst); 6953 return 0; 6954 } 6955 6956 pair[1] = socket(AF_INET, SOCK_STREAM, 0); 6957 if(pair[1] == -1) { 6958 log_err("create socketpair: socket: %s", sock_strerror(errno)); 6959 sock_close(lst); 6960 return 0; 6961 } 6962 baddrlen = (socklen_t)sizeof(baddr); 6963 if(getsockname(lst, (struct sockaddr*)&baddr, &baddrlen) == -1) { 6964 log_err("create socketpair: getsockname: %s", 6965 sock_strerror(errno)); 6966 sock_close(lst); 6967 sock_close(pair[1]); 6968 pair[1] = -1; 6969 return 0; 6970 } 6971 if(baddrlen > (socklen_t)sizeof(baddr)) { 6972 log_err("create socketpair: getsockname returned addr too big"); 6973 sock_close(lst); 6974 sock_close(pair[1]); 6975 pair[1] = -1; 6976 return 0; 6977 } 6978 /* the socket is blocking */ 6979 if(connect(pair[1], (struct sockaddr*)&baddr, baddrlen) == -1) { 6980 log_err("create socketpair: connect: %s", 6981 sock_strerror(errno)); 6982 sock_close(lst); 6983 sock_close(pair[1]); 6984 pair[1] = -1; 6985 return 0; 6986 } 6987 if(!sock_poll_timeout(lst, connect_poll_timeout, 1, 0, &pollin_event)) { 6988 log_err("create socketpair: poll for accept failed: %s", 6989 sock_strerror(errno)); 6990 sock_close(lst); 6991 sock_close(pair[1]); 6992 pair[1] = -1; 6993 return 0; 6994 } 6995 if(!pollin_event) { 6996 log_err("create socketpair: poll timeout for accept"); 6997 sock_close(lst); 6998 sock_close(pair[1]); 6999 pair[1] = -1; 7000 return 0; 7001 } 7002 accaddrlen = (socklen_t)sizeof(accaddr); 7003 pair[0] = accept(lst, (struct sockaddr*)&accaddr, &accaddrlen); 7004 if(pair[0] == -1) { 7005 log_err("create socketpair: accept: %s", sock_strerror(errno)); 7006 sock_close(lst); 7007 sock_close(pair[1]); 7008 pair[1] = -1; 7009 return 0; 7010 } 7011 if(accaddrlen > (socklen_t)sizeof(accaddr)) { 7012 log_err("create socketpair: accept returned addr too big"); 7013 sock_close(lst); 7014 sock_close(pair[0]); 7015 sock_close(pair[1]); 7016 pair[0] = -1; 7017 pair[1] = -1; 7018 return 0; 7019 } 7020 if(accaddr.sin_family != AF_INET || 7021 memcmp(localhost, &accaddr.sin_addr, 4) != 0) { 7022 log_err("create socketpair: accept from wrong address"); 7023 sock_close(lst); 7024 sock_close(pair[0]); 7025 sock_close(pair[1]); 7026 pair[0] = -1; 7027 pair[1] = -1; 7028 return 0; 7029 } 7030 connaddrlen = (socklen_t)sizeof(connaddr); 7031 if(getsockname(pair[1], (struct sockaddr*)&connaddr, &connaddrlen) 7032 == -1) { 7033 log_err("create socketpair: getsockname connectedaddr: %s", 7034 sock_strerror(errno)); 7035 sock_close(lst); 7036 sock_close(pair[0]); 7037 sock_close(pair[1]); 7038 pair[0] = -1; 7039 pair[1] = -1; 7040 return 0; 7041 } 7042 if(connaddrlen > (socklen_t)sizeof(connaddr)) { 7043 log_err("create socketpair: getsockname connectedaddr returned addr too big"); 7044 sock_close(lst); 7045 sock_close(pair[0]); 7046 sock_close(pair[1]); 7047 pair[0] = -1; 7048 pair[1] = -1; 7049 return 0; 7050 } 7051 if(connaddr.sin_family != AF_INET || 7052 memcmp(localhost, &connaddr.sin_addr, 4) != 0) { 7053 log_err("create socketpair: getsockname connectedaddr returned wrong address"); 7054 sock_close(lst); 7055 sock_close(pair[0]); 7056 sock_close(pair[1]); 7057 pair[0] = -1; 7058 pair[1] = -1; 7059 return 0; 7060 } 7061 if(accaddr.sin_port != connaddr.sin_port) { 7062 log_err("create socketpair: accept from wrong port"); 7063 sock_close(lst); 7064 sock_close(pair[0]); 7065 sock_close(pair[1]); 7066 pair[0] = -1; 7067 pair[1] = -1; 7068 return 0; 7069 } 7070 sock_close(lst); 7071 7072 loopcount = 0; 7073 bcount = 0; 7074 while(1) { 7075 if(++loopcount > IPC_LOOP_MAX) { 7076 log_err("create socketpair: send failed due to loop"); 7077 sock_close(pair[0]); 7078 sock_close(pair[1]); 7079 pair[0] = -1; 7080 pair[1] = -1; 7081 return 0; 7082 } 7083 ret = send(pair[1], (void*)(nonce+bcount), 7084 sizeof(nonce)-bcount, 0); 7085 if(ret == -1) { 7086 if( 7087 #ifndef USE_WINSOCK 7088 errno == EINTR || errno == EAGAIN 7089 # ifdef EWOULDBLOCK 7090 || errno == EWOULDBLOCK 7091 # endif 7092 #else 7093 WSAGetLastError() == WSAEINTR || 7094 WSAGetLastError() == WSAEINPROGRESS || 7095 WSAGetLastError() == WSAEWOULDBLOCK 7096 #endif 7097 ) 7098 continue; /* Try again. */ 7099 log_err("create socketpair: send: %s", sock_strerror(errno)); 7100 sock_close(pair[0]); 7101 sock_close(pair[1]); 7102 pair[0] = -1; 7103 pair[1] = -1; 7104 return 0; 7105 } else if(ret+(ssize_t)bcount != sizeof(nonce)) { 7106 bcount += ret; 7107 if((size_t)bcount < sizeof(nonce)) 7108 continue; 7109 } 7110 break; 7111 } 7112 7113 if(!sock_poll_timeout(pair[0], connect_poll_timeout, 1, 0, &pollin_event)) { 7114 log_err("create socketpair: poll failed: %s", 7115 sock_strerror(errno)); 7116 sock_close(pair[0]); 7117 sock_close(pair[1]); 7118 pair[0] = -1; 7119 pair[1] = -1; 7120 return 0; 7121 } 7122 if(!pollin_event) { 7123 log_err("create socketpair: poll timeout for recv"); 7124 sock_close(pair[0]); 7125 sock_close(pair[1]); 7126 pair[0] = -1; 7127 pair[1] = -1; 7128 return 0; 7129 } 7130 7131 loopcount = 0; 7132 bcount = 0; 7133 while(1) { 7134 if(++loopcount > IPC_LOOP_MAX) { 7135 log_err("create socketpair: recv failed due to loop"); 7136 sock_close(pair[0]); 7137 sock_close(pair[1]); 7138 pair[0] = -1; 7139 pair[1] = -1; 7140 return 0; 7141 } 7142 ret = recv(pair[0], (void*)(recvnonce+bcount), 7143 sizeof(nonce)-bcount, 0); 7144 if(ret == -1) { 7145 if( 7146 #ifndef USE_WINSOCK 7147 errno == EINTR || errno == EAGAIN 7148 # ifdef EWOULDBLOCK 7149 || errno == EWOULDBLOCK 7150 # endif 7151 #else 7152 WSAGetLastError() == WSAEINTR || 7153 WSAGetLastError() == WSAEINPROGRESS || 7154 WSAGetLastError() == WSAEWOULDBLOCK 7155 #endif 7156 ) 7157 continue; /* Try again. */ 7158 log_err("create socketpair: recv: %s", sock_strerror(errno)); 7159 sock_close(pair[0]); 7160 sock_close(pair[1]); 7161 pair[0] = -1; 7162 pair[1] = -1; 7163 return 0; 7164 } else if(ret == 0) { 7165 log_err("create socketpair: stream closed"); 7166 sock_close(pair[0]); 7167 sock_close(pair[1]); 7168 pair[0] = -1; 7169 pair[1] = -1; 7170 return 0; 7171 } else if(ret+(ssize_t)bcount != sizeof(nonce)) { 7172 bcount += ret; 7173 if((size_t)bcount < sizeof(nonce)) 7174 continue; 7175 } 7176 break; 7177 } 7178 7179 if(memcmp(nonce, recvnonce, sizeof(nonce)) != 0) { 7180 log_err("create socketpair: recv wrong nonce"); 7181 sock_close(pair[0]); 7182 sock_close(pair[1]); 7183 pair[0] = -1; 7184 pair[1] = -1; 7185 return 0; 7186 } 7187 #endif 7188 return 1; 7189 } 7190 7191 /** fast reload thread. setup the thread info */ 7192 static int 7193 fast_reload_thread_setup(struct worker* worker, int fr_verb, int fr_nopause, 7194 int fr_drop_mesh) 7195 { 7196 struct fast_reload_thread* fr; 7197 int numworkers = worker->daemon->num; 7198 worker->daemon->fast_reload_thread = (struct fast_reload_thread*) 7199 calloc(1, sizeof(*worker->daemon->fast_reload_thread)); 7200 if(!worker->daemon->fast_reload_thread) 7201 return 0; 7202 fr = worker->daemon->fast_reload_thread; 7203 fr->fr_verb = fr_verb; 7204 fr->fr_nopause = fr_nopause; 7205 fr->fr_drop_mesh = fr_drop_mesh; 7206 worker->daemon->fast_reload_drop_mesh = fr->fr_drop_mesh; 7207 /* The thread id printed in logs, numworker+1 is the dnstap thread. 7208 * This is numworkers+2. */ 7209 fr->threadnum = numworkers+2; 7210 fr->commpair[0] = -1; 7211 fr->commpair[1] = -1; 7212 fr->commreload[0] = -1; 7213 fr->commreload[1] = -1; 7214 if(!create_socketpair(fr->commpair, worker->daemon->rand)) { 7215 free(fr); 7216 worker->daemon->fast_reload_thread = NULL; 7217 return 0; 7218 } 7219 fr->worker = worker; 7220 fr->fr_output = (struct config_strlist_head*)calloc(1, 7221 sizeof(*fr->fr_output)); 7222 if(!fr->fr_output) { 7223 sock_close(fr->commpair[0]); 7224 sock_close(fr->commpair[1]); 7225 free(fr); 7226 worker->daemon->fast_reload_thread = NULL; 7227 return 0; 7228 } 7229 if(!create_socketpair(fr->commreload, worker->daemon->rand)) { 7230 sock_close(fr->commpair[0]); 7231 sock_close(fr->commpair[1]); 7232 free(fr->fr_output); 7233 free(fr); 7234 worker->daemon->fast_reload_thread = NULL; 7235 return 0; 7236 } 7237 lock_basic_init(&fr->fr_output_lock); 7238 lock_protect(&fr->fr_output_lock, fr->fr_output, 7239 sizeof(*fr->fr_output)); 7240 #ifdef HAVE_GETTID 7241 fr->thread_tid_log = worker->env.cfg->log_thread_id; 7242 #endif 7243 return 1; 7244 } 7245 7246 /** fast reload, delete auth zone change list */ 7247 static void 7248 fr_auth_change_list_delete( 7249 struct fast_reload_auth_change* auth_zone_change_list) 7250 { 7251 struct fast_reload_auth_change* item, *next; 7252 item = auth_zone_change_list; 7253 while(item) { 7254 next = item->next; 7255 free(item); 7256 item = next; 7257 } 7258 } 7259 7260 /** fast reload thread. desetup and delete the thread info. */ 7261 static void 7262 fast_reload_thread_desetup(struct fast_reload_thread* fast_reload_thread) 7263 { 7264 if(!fast_reload_thread) 7265 return; 7266 if(fast_reload_thread->service_event && 7267 fast_reload_thread->service_event_is_added) { 7268 ub_event_del(fast_reload_thread->service_event); 7269 fast_reload_thread->service_event_is_added = 0; 7270 } 7271 if(fast_reload_thread->service_event) 7272 ub_event_free(fast_reload_thread->service_event); 7273 sock_close(fast_reload_thread->commpair[0]); 7274 sock_close(fast_reload_thread->commpair[1]); 7275 sock_close(fast_reload_thread->commreload[0]); 7276 sock_close(fast_reload_thread->commreload[1]); 7277 if(fast_reload_thread->printq) { 7278 fr_main_perform_printout(fast_reload_thread); 7279 /* If it is empty now, there is nothing to print on fd. */ 7280 if(fr_printq_empty(fast_reload_thread->printq)) { 7281 fr_printq_delete(fast_reload_thread->printq); 7282 } else { 7283 /* Keep the printq around to printout the remaining 7284 * text to the remote client. Until it is done, it 7285 * sits on a list, that is in the daemon struct. 7286 * The event can then spool the remaining text to the 7287 * remote client and eventually delete itself from the 7288 * callback. */ 7289 fr_printq_list_insert(fast_reload_thread->printq, 7290 fast_reload_thread->worker->daemon); 7291 fast_reload_thread->printq = NULL; 7292 } 7293 } 7294 lock_basic_destroy(&fast_reload_thread->fr_output_lock); 7295 if(fast_reload_thread->fr_output) { 7296 config_delstrlist(fast_reload_thread->fr_output->first); 7297 free(fast_reload_thread->fr_output); 7298 } 7299 fr_auth_change_list_delete(fast_reload_thread->auth_zone_change_list); 7300 7301 free(fast_reload_thread); 7302 } 7303 7304 /** 7305 * Fast reload thread, send a command to the thread. Blocking on timeout. 7306 * It handles received input from the thread, if any is received. 7307 */ 7308 static void 7309 fr_send_cmd_to(struct fast_reload_thread* fr, 7310 enum fast_reload_notification status, int check_cmds, int blocking) 7311 { 7312 int outevent, loopexit = 0, bcount = 0; 7313 uint32_t cmd; 7314 ssize_t ret; 7315 verbose(VERB_ALGO, "send notification to fast reload thread: %s", 7316 fr_notification_to_string(status)); 7317 cmd = status; 7318 while(1) { 7319 if(++loopexit > IPC_LOOP_MAX) { 7320 log_err("send notification to fast reload: could not send notification: loop"); 7321 return; 7322 } 7323 if(check_cmds) 7324 fr_check_cmd_from_thread(fr); 7325 /* wait for socket to become writable */ 7326 if(!sock_poll_timeout(fr->commpair[0], 7327 (blocking?-1:IPC_NOTIFICATION_WAIT), 7328 0, 1, &outevent)) { 7329 log_err("send notification to fast reload: poll failed"); 7330 return; 7331 } 7332 if(!outevent) 7333 continue; 7334 /* keep static analyzer happy; send(-1,..) */ 7335 log_assert(fr->commpair[0] >= 0); 7336 ret = send(fr->commpair[0], ((char*)&cmd)+bcount, 7337 sizeof(cmd)-bcount, 0); 7338 if(ret == -1) { 7339 if( 7340 #ifndef USE_WINSOCK 7341 errno == EINTR || errno == EAGAIN 7342 # ifdef EWOULDBLOCK 7343 || errno == EWOULDBLOCK 7344 # endif 7345 #else 7346 WSAGetLastError() == WSAEINTR || 7347 WSAGetLastError() == WSAEINPROGRESS || 7348 WSAGetLastError() == WSAEWOULDBLOCK 7349 #endif 7350 ) 7351 continue; /* Try again. */ 7352 log_err("send notification to fast reload: send: %s", 7353 sock_strerror(errno)); 7354 return; 7355 } else if(ret+(ssize_t)bcount != sizeof(cmd)) { 7356 bcount += ret; 7357 if((size_t)bcount < sizeof(cmd)) 7358 continue; 7359 } 7360 break; 7361 } 7362 } 7363 7364 /** Fast reload, the main thread handles that the fast reload thread has 7365 * exited. */ 7366 static void 7367 fr_main_perform_done(struct fast_reload_thread* fr) 7368 { 7369 struct worker* worker = fr->worker; 7370 verbose(VERB_ALGO, "join with fastreload thread"); 7371 ub_thread_join(fr->tid); 7372 verbose(VERB_ALGO, "joined with fastreload thread"); 7373 fast_reload_thread_desetup(fr); 7374 worker->daemon->fast_reload_thread = NULL; 7375 } 7376 7377 /** Append strlist after strlist */ 7378 static void 7379 cfg_strlist_append_listhead(struct config_strlist_head* list, 7380 struct config_strlist_head* more) 7381 { 7382 if(!more->first) 7383 return; 7384 if(list->last) 7385 list->last->next = more->first; 7386 else 7387 list->first = more->first; 7388 list->last = more->last; 7389 } 7390 7391 /** Fast reload, the remote control thread handles that the fast reload thread 7392 * has output to be printed, on the linked list that is locked. */ 7393 static void 7394 fr_main_perform_printout(struct fast_reload_thread* fr) 7395 { 7396 struct config_strlist_head out; 7397 7398 /* Fetch the list of items to be printed */ 7399 lock_basic_lock(&fr->fr_output_lock); 7400 out.first = fr->fr_output->first; 7401 out.last = fr->fr_output->last; 7402 fr->fr_output->first = NULL; 7403 fr->fr_output->last = NULL; 7404 lock_basic_unlock(&fr->fr_output_lock); 7405 7406 if(!fr->printq || !fr->printq->client_cp) { 7407 /* There is no output socket, delete it. */ 7408 config_delstrlist(out.first); 7409 return; 7410 } 7411 7412 /* Put them on the output list, not locked because the list 7413 * producer and consumer are both owned by the remote control thread, 7414 * it moves the items to the list for printing in the event callback 7415 * for the client_cp. */ 7416 cfg_strlist_append_listhead(fr->printq->to_print, &out); 7417 7418 /* Set the client_cp to output if not already */ 7419 if(!fr->printq->client_cp->event_added) 7420 comm_point_listen_for_rw(fr->printq->client_cp, 0, 1); 7421 } 7422 7423 /** fast reload, receive ack from workers that they are waiting, run 7424 * by the mainthr after sending them reload_stop. */ 7425 static void 7426 fr_read_ack_from_workers(struct fast_reload_thread* fr) 7427 { 7428 struct daemon* daemon = fr->worker->daemon; 7429 /* Every worker sends one byte, wait for num-1 bytes. */ 7430 int count=0, total=daemon->num-1; 7431 while(count < total) { 7432 uint8_t r; 7433 ssize_t ret; 7434 ret = recv(fr->commreload[0], (void*)&r, 1, 0); 7435 if(ret == -1) { 7436 if( 7437 #ifndef USE_WINSOCK 7438 errno == EINTR || errno == EAGAIN 7439 # ifdef EWOULDBLOCK 7440 || errno == EWOULDBLOCK 7441 # endif 7442 #else 7443 WSAGetLastError() == WSAEINTR || 7444 WSAGetLastError() == WSAEINPROGRESS || 7445 WSAGetLastError() == WSAEWOULDBLOCK 7446 #endif 7447 ) 7448 continue; /* Try again */ 7449 log_err("worker reload ack: recv failed: %s", 7450 sock_strerror(errno)); 7451 return; 7452 } 7453 count++; 7454 verbose(VERB_ALGO, "worker reload ack from (uint8_t)%d", 7455 (int)r); 7456 } 7457 } 7458 7459 /** fast reload, poll for reload_start in mainthr waiting on a notification 7460 * from the fast reload thread. */ 7461 static void 7462 fr_poll_for_reload_start(struct fast_reload_thread* fr) 7463 { 7464 int loopexit = 0, bcount = 0; 7465 uint32_t cmd; 7466 ssize_t ret; 7467 7468 /* Is there data? */ 7469 if(!sock_poll_timeout(fr->commpair[0], -1, 1, 0, NULL)) { 7470 log_err("fr_poll_for_reload_start: poll failed"); 7471 return; 7472 } 7473 7474 /* Read the data */ 7475 while(1) { 7476 if(++loopexit > IPC_LOOP_MAX) { 7477 log_err("fr_poll_for_reload_start: recv loops %s", 7478 sock_strerror(errno)); 7479 return; 7480 } 7481 ret = recv(fr->commpair[0], ((char*)&cmd)+bcount, 7482 sizeof(cmd)-bcount, 0); 7483 if(ret == -1) { 7484 if( 7485 #ifndef USE_WINSOCK 7486 errno == EINTR || errno == EAGAIN 7487 # ifdef EWOULDBLOCK 7488 || errno == EWOULDBLOCK 7489 # endif 7490 #else 7491 WSAGetLastError() == WSAEINTR || 7492 WSAGetLastError() == WSAEINPROGRESS || 7493 WSAGetLastError() == WSAEWOULDBLOCK 7494 #endif 7495 ) 7496 continue; /* Try again. */ 7497 log_err("fr_poll_for_reload_start: recv: %s", 7498 sock_strerror(errno)); 7499 return; 7500 } else if(ret+(ssize_t)bcount != sizeof(cmd)) { 7501 bcount += ret; 7502 if((size_t)bcount < sizeof(cmd)) 7503 continue; 7504 } 7505 break; 7506 } 7507 if(cmd != fast_reload_notification_reload_start) { 7508 verbose(VERB_ALGO, "fast reload wait for ack: " 7509 "wrong notification %d", (int)cmd); 7510 } 7511 } 7512 7513 /** Pick up the worker mesh changes, after fast reload. */ 7514 static void 7515 fr_worker_pickup_mesh(struct worker* worker) 7516 { 7517 struct mesh_area* mesh = worker->env.mesh; 7518 struct config_file* cfg = worker->env.cfg; 7519 mesh->use_response_ip = worker->daemon->use_response_ip; 7520 mesh->use_rpz = worker->daemon->use_rpz; 7521 mesh->max_reply_states = cfg->num_queries_per_thread; 7522 mesh->max_forever_states = (mesh->max_reply_states+1)/2; 7523 #ifndef S_SPLINT_S 7524 mesh->jostle_max.tv_sec = (time_t)(cfg->jostle_time / 1000); 7525 mesh->jostle_max.tv_usec = (time_t)((cfg->jostle_time % 1000)*1000); 7526 #endif 7527 } 7528 7529 /** 7530 * Remove the old tcl_addr entries from the open connections. 7531 * They are only incremented when an accept is performed on a tcp comm point. 7532 * @param front: listening comm ports of the worker. 7533 */ 7534 static void 7535 tcl_remove_old(struct listen_dnsport* front) 7536 { 7537 struct listen_list* l; 7538 l = front->cps; 7539 while(l) { 7540 if(l->com->type == comm_tcp_accept) { 7541 int i; 7542 for(i=0; i<l->com->max_tcp_count; i++) { 7543 if(l->com->tcp_handlers[i]->tcl_addr) { 7544 /* Because the increment of the 7545 * connection limit was in the old 7546 * tcl list, the new list does not 7547 * need a decrement. With NULL it is 7548 * not decremented when the connection 7549 * is done, and also there is no 7550 * reference to the old connection 7551 * limit structure. */ 7552 l->com->tcp_handlers[i]->tcl_addr = 7553 NULL; 7554 } 7555 } 7556 } 7557 l = l->next; 7558 } 7559 } 7560 7561 /** Stop zonemd lookup */ 7562 static void 7563 auth_zone_zonemd_stop_lookup(struct auth_zone* z, struct mesh_area* mesh) 7564 { 7565 struct query_info qinfo; 7566 uint16_t qflags = BIT_RD; 7567 qinfo.qname_len = z->namelen; 7568 qinfo.qname = z->name; 7569 qinfo.qclass = z->dclass; 7570 qinfo.qtype = z->zonemd_callback_qtype; 7571 qinfo.local_alias = NULL; 7572 7573 mesh_remove_callback(mesh, &qinfo, qflags, 7574 &auth_zonemd_dnskey_lookup_callback, z); 7575 } 7576 7577 /** Pick up the auth zone locks. */ 7578 static void 7579 fr_pickup_auth_locks(struct worker* worker, struct auth_zone* namez, 7580 struct auth_zone* old_z, struct auth_zone* new_z, 7581 struct auth_xfer** xfr, struct auth_xfer** loadxfr) 7582 { 7583 uint8_t nm[LDNS_MAX_DOMAINLEN+1]; 7584 size_t nmlen; 7585 uint16_t dclass; 7586 7587 log_assert(namez->namelen <= sizeof(nm)); 7588 lock_rw_rdlock(&namez->lock); 7589 nmlen = namez->namelen; 7590 dclass = namez->dclass; 7591 memmove(nm, namez->name, nmlen); 7592 lock_rw_unlock(&namez->lock); 7593 7594 lock_rw_wrlock(&worker->daemon->fast_reload_thread->old_auth_zones->lock); 7595 lock_rw_wrlock(&worker->env.auth_zones->lock); 7596 if(new_z) { 7597 lock_rw_wrlock(&new_z->lock); 7598 } 7599 if(old_z) { 7600 lock_rw_wrlock(&old_z->lock); 7601 } 7602 if(loadxfr) 7603 *loadxfr = auth_xfer_find(worker->daemon->fast_reload_thread-> 7604 old_auth_zones, nm, nmlen, dclass); 7605 if(xfr) 7606 *xfr = auth_xfer_find(worker->env.auth_zones, nm, nmlen, 7607 dclass); 7608 if(loadxfr && *loadxfr) { 7609 lock_basic_lock(&(*loadxfr)->lock); 7610 } 7611 if(xfr && *xfr) { 7612 lock_basic_lock(&(*xfr)->lock); 7613 } 7614 } 7615 7616 /** Fast reload, worker picks up deleted auth zone */ 7617 static void 7618 fr_worker_auth_del(struct worker* worker, struct fast_reload_auth_change* item, 7619 int for_change) 7620 { 7621 int released = 0; /* Did this routine release callbacks. */ 7622 struct auth_xfer* xfr = NULL; 7623 7624 lock_rw_wrlock(&item->old_z->lock); 7625 if(item->old_z->zonemd_callback_env && 7626 item->old_z->zonemd_callback_env->worker == worker){ 7627 /* This worker was performing a zonemd lookup, 7628 * stop the lookup and remove that entry. */ 7629 auth_zone_zonemd_stop_lookup(item->old_z, worker->env.mesh); 7630 item->old_z->zonemd_callback_env = NULL; 7631 } 7632 lock_rw_unlock(&item->old_z->lock); 7633 7634 fr_pickup_auth_locks(worker, item->old_z, item->old_z, NULL, &xfr, 7635 NULL); 7636 lock_rw_unlock(&worker->daemon->fast_reload_thread->old_auth_zones->lock); 7637 lock_rw_unlock(&worker->env.auth_zones->lock); 7638 lock_rw_unlock(&item->old_z->lock); 7639 if(xfr) { 7640 /* Release callbacks on the xfr, if this worker holds them. */ 7641 if(xfr->task_nextprobe->worker == worker || 7642 xfr->task_probe->worker == worker || 7643 xfr->task_transfer->worker == worker) { 7644 released = 1; 7645 xfr_disown_tasks(xfr, worker); 7646 } 7647 lock_basic_unlock(&xfr->lock); 7648 } 7649 7650 if(!for_change && (released || worker->thread_num == 0)) { 7651 /* See if the xfr item can be deleted. */ 7652 xfr = NULL; 7653 fr_pickup_auth_locks(worker, item->old_z, item->old_z, NULL, 7654 &xfr, NULL); 7655 lock_rw_unlock(&worker->daemon->fast_reload_thread->old_auth_zones->lock); 7656 lock_rw_unlock(&item->old_z->lock); 7657 if(xfr && xfr->task_nextprobe->worker == NULL && 7658 xfr->task_probe->worker == NULL && 7659 xfr->task_transfer->worker == NULL) { 7660 (void)rbtree_delete(&worker->env.auth_zones->xtree, 7661 &xfr->node); 7662 lock_rw_unlock(&worker->env.auth_zones->lock); 7663 lock_basic_unlock(&xfr->lock); 7664 auth_xfer_delete(xfr); 7665 } else { 7666 lock_rw_unlock(&worker->env.auth_zones->lock); 7667 if(xfr) { 7668 lock_basic_unlock(&xfr->lock); 7669 } 7670 } 7671 } 7672 } 7673 7674 /** Fast reload, auth xfer config is picked up */ 7675 static void 7676 auth_xfr_pickup_config(struct auth_xfer* loadxfr, struct auth_xfer* xfr) 7677 { 7678 struct auth_master *probe_masters, *transfer_masters; 7679 log_assert(loadxfr->namelen == xfr->namelen); 7680 log_assert(loadxfr->namelabs == xfr->namelabs); 7681 log_assert(loadxfr->dclass == xfr->dclass); 7682 7683 /* The lists can be swapped in, the other xfr struct will be deleted 7684 * afterwards. */ 7685 probe_masters = xfr->task_probe->masters; 7686 transfer_masters = xfr->task_transfer->masters; 7687 xfr->task_probe->masters = loadxfr->task_probe->masters; 7688 xfr->task_transfer->masters = loadxfr->task_transfer->masters; 7689 loadxfr->task_probe->masters = probe_masters; 7690 loadxfr->task_transfer->masters = transfer_masters; 7691 } 7692 7693 /** Fast reload, worker picks up added auth zone */ 7694 static void 7695 fr_worker_auth_add(struct worker* worker, struct fast_reload_auth_change* item, 7696 int for_change) 7697 { 7698 struct auth_xfer* xfr = NULL, *loadxfr = NULL; 7699 7700 /* Start zone transfers and lookups. */ 7701 fr_pickup_auth_locks(worker, item->new_z, NULL, item->new_z, &xfr, 7702 &loadxfr); 7703 if(xfr == NULL && item->new_z->zone_is_slave) { 7704 /* The xfr item needs to be created. The auth zones lock 7705 * is held to make this possible. */ 7706 xfr = auth_xfer_create(worker->env.auth_zones, item->new_z); 7707 auth_xfr_pickup_config(loadxfr, xfr); 7708 /* Serial information is copied into the xfr struct. */ 7709 if(!xfr_find_soa(item->new_z, xfr)) { 7710 xfr->serial = 0; 7711 } 7712 } else if(for_change && xfr) { 7713 if(!xfr_find_soa(item->new_z, xfr)) { 7714 xfr->serial = 0; 7715 } 7716 } 7717 auth_zone_pickup_initial_zone(item->new_z, &worker->env); 7718 lock_rw_unlock(&item->new_z->lock); 7719 lock_rw_unlock(&worker->env.auth_zones->lock); 7720 lock_rw_unlock(&worker->daemon->fast_reload_thread->old_auth_zones->lock); 7721 if(loadxfr) { 7722 lock_basic_unlock(&loadxfr->lock); 7723 } 7724 if(xfr) { 7725 auth_xfer_pickup_initial_zone(xfr, &worker->env); 7726 if(for_change) { 7727 xfr->task_probe->only_lookup = 0; 7728 } 7729 lock_basic_unlock(&xfr->lock); 7730 } 7731 7732 /* Perform ZONEMD verification lookups. */ 7733 lock_rw_wrlock(&item->new_z->lock); 7734 /* holding only the new_z lock */ 7735 auth_zone_verify_zonemd(item->new_z, &worker->env, 7736 &worker->env.mesh->mods, NULL, 0, 1); 7737 lock_rw_unlock(&item->new_z->lock); 7738 } 7739 7740 /** Fast reload, worker picks up changed auth zone */ 7741 static void 7742 fr_worker_auth_cha(struct worker* worker, struct fast_reload_auth_change* item) 7743 { 7744 int todelete = 0; 7745 struct auth_xfer* loadxfr = NULL, *xfr = NULL; 7746 /* Since the zone has been changed, by rereading it from zone file, 7747 * existing transfers and probes are likely for the old version. 7748 * Stop them, and start new ones if needed. */ 7749 fr_worker_auth_del(worker, item, 1); 7750 7751 if(worker->thread_num != 0) 7752 return; 7753 7754 /* The old callbacks are stopped, tasks have been disowned. The 7755 * new config contents can be picked up. SOA information is picked 7756 * up in the auth_add routine, as it has the new_z ready. */ 7757 7758 fr_pickup_auth_locks(worker, item->new_z, item->old_z, item->new_z, 7759 &xfr, &loadxfr); 7760 7761 /* The xfr is not there any more if the zone is not set to have 7762 * zone transfers. Or the xfr needs to be created if it is set to 7763 * have zone transfers. */ 7764 if(loadxfr && xfr) { 7765 /* Copy the config from loadxfr to the xfr in current use. */ 7766 auth_xfr_pickup_config(loadxfr, xfr); 7767 } else if(!loadxfr && xfr) { 7768 /* Delete the xfr. */ 7769 (void)rbtree_delete(&worker->env.auth_zones->xtree, 7770 &xfr->node); 7771 todelete = 1; 7772 item->new_z->zone_is_slave = 0; 7773 } else if(loadxfr && !xfr) { 7774 /* Create the xfr. */ 7775 xfr = auth_xfer_create(worker->env.auth_zones, item->new_z); 7776 auth_xfr_pickup_config(loadxfr, xfr); 7777 item->new_z->zone_is_slave = 1; 7778 } 7779 lock_rw_unlock(&item->new_z->lock); 7780 lock_rw_unlock(&item->old_z->lock); 7781 lock_rw_unlock(&worker->daemon->fast_reload_thread->old_auth_zones->lock); 7782 lock_rw_unlock(&worker->env.auth_zones->lock); 7783 if(loadxfr) { 7784 lock_basic_unlock(&loadxfr->lock); 7785 } 7786 if(xfr) { 7787 lock_basic_unlock(&xfr->lock); 7788 } 7789 if(todelete) { 7790 auth_xfer_delete(xfr); 7791 } 7792 7793 fr_worker_auth_add(worker, item, 1); 7794 } 7795 7796 /** Fast reload, the worker picks up changes in auth zones. */ 7797 static void 7798 fr_worker_pickup_auth_changes(struct worker* worker, 7799 struct fast_reload_auth_change* auth_zone_change_list) 7800 { 7801 struct fast_reload_auth_change* item; 7802 for(item = auth_zone_change_list; item; item = item->next) { 7803 if(item->is_deleted) { 7804 fr_worker_auth_del(worker, item, 0); 7805 } 7806 if(item->is_added) { 7807 if(worker->thread_num == 0) { 7808 fr_worker_auth_add(worker, item, 0); 7809 } 7810 } 7811 if(item->is_changed) { 7812 fr_worker_auth_cha(worker, item); 7813 } 7814 } 7815 } 7816 7817 /** Fast reload, the worker picks up changes in listen_dnsport. */ 7818 static void 7819 fr_worker_pickup_listen_dnsport(struct worker* worker) 7820 { 7821 struct listen_dnsport* front = worker->front; 7822 struct daemon* daemon = worker->daemon; 7823 if(worker->daemon->fast_reload_thread->sslctxs_changed) { 7824 struct listen_list* ll; 7825 void* dot_sslctx = daemon->listen_dot_sslctx; 7826 void* doh_sslctx = daemon->listen_doh_sslctx; 7827 #ifdef HAVE_NGTCP2 7828 void* quic_sslctx = daemon->listen_quic_sslctx; 7829 #endif /* HAVE_NGTCP2 */ 7830 for(ll = front->cps; ll; ll = ll->next) { 7831 struct comm_point* cp = ll->com; 7832 if(cp->type == comm_tcp_accept && 7833 cp->tcp_handlers && 7834 cp->max_tcp_count > 0 && 7835 cp->tcp_handlers[0]->type == comm_http) { 7836 if(cp->ssl) 7837 cp->ssl = doh_sslctx; 7838 } else if(cp->type == comm_tcp_accept) { 7839 if(cp->ssl) 7840 cp->ssl = dot_sslctx; 7841 #ifdef HAVE_NGTCP2 7842 } else if(cp->type == comm_doq) { 7843 if(cp->ssl) { 7844 cp->ssl = quic_sslctx; 7845 if(cp->doq_socket) 7846 cp->doq_socket->ctx = 7847 (SSL_CTX*)quic_sslctx; 7848 } 7849 #endif /* HAVE_NGTCP2 */ 7850 } 7851 } 7852 } 7853 } 7854 7855 /** Fast reload, the worker picks up changes in outside_network. */ 7856 static void 7857 fr_worker_pickup_outside_network(struct worker* worker) 7858 { 7859 struct outside_network* outnet = worker->back; 7860 struct config_file* cfg = worker->env.cfg; 7861 outnet->use_caps_for_id = cfg->use_caps_bits_for_id; 7862 outnet->unwanted_threshold = cfg->unwanted_threshold; 7863 outnet->tls_use_sni = cfg->tls_use_sni; 7864 outnet->tcp_mss = cfg->outgoing_tcp_mss; 7865 outnet->ip_dscp = cfg->ip_dscp; 7866 outnet->max_reuse_tcp_queries = cfg->max_reuse_tcp_queries; 7867 outnet->tcp_reuse_timeout = cfg->tcp_reuse_timeout; 7868 outnet->tcp_auth_query_timeout = cfg->tcp_auth_query_timeout; 7869 outnet->delayclose = cfg->delay_close; 7870 if(worker->daemon->fast_reload_thread->sslctxs_changed) 7871 outnet->sslctx = worker->daemon->connect_dot_sslctx; 7872 if(outnet->delayclose) { 7873 #ifndef S_SPLINT_S 7874 outnet->delay_tv.tv_sec = cfg->delay_close/1000; 7875 outnet->delay_tv.tv_usec = (cfg->delay_close%1000)*1000; 7876 #endif 7877 } 7878 } 7879 7880 #ifdef USE_DNSTAP 7881 /** Fast reload, the worker picks up changes to DNSTAP configuration. */ 7882 static void 7883 fr_worker_pickup_dnstap_changes(struct worker* worker) 7884 { 7885 struct dt_env* w_dtenv = &worker->dtenv; 7886 struct dt_env* d_dtenv = worker->daemon->dtenv; 7887 log_assert(d_dtenv != NULL || !worker->daemon->cfg->dnstap); 7888 if(d_dtenv == NULL) { 7889 /* There is no environment when DNSTAP was not enabled 7890 * in the configuration. */ 7891 return; 7892 } 7893 w_dtenv->identity = d_dtenv->identity; 7894 w_dtenv->len_identity = d_dtenv->len_identity; 7895 w_dtenv->version = d_dtenv->version; 7896 w_dtenv->len_version = d_dtenv->len_version; 7897 w_dtenv->log_resolver_query_messages = 7898 d_dtenv->log_resolver_query_messages; 7899 w_dtenv->log_resolver_response_messages = 7900 d_dtenv->log_resolver_response_messages; 7901 w_dtenv->log_client_query_messages = 7902 d_dtenv->log_client_query_messages; 7903 w_dtenv->log_client_response_messages = 7904 d_dtenv->log_client_response_messages; 7905 w_dtenv->log_forwarder_query_messages = 7906 d_dtenv->log_forwarder_query_messages; 7907 w_dtenv->log_forwarder_response_messages = 7908 d_dtenv->log_forwarder_response_messages; 7909 lock_basic_lock(&d_dtenv->sample_lock); 7910 w_dtenv->sample_rate = d_dtenv->sample_rate; 7911 lock_basic_unlock(&d_dtenv->sample_lock); 7912 } 7913 #endif /* USE_DNSTAP */ 7914 7915 void 7916 fast_reload_worker_pickup_changes(struct worker* worker) 7917 { 7918 /* The pickup of changes is called when the fast reload has 7919 * a synchronized moment, and all the threads are paused and the 7920 * reload has been applied. Then the worker can pick up the new 7921 * changes and store them in worker-specific structs. 7922 * The pickup is also called when there is no pause, and then 7923 * it is called after the reload has completed, and the worker 7924 * get a signal to release old information, it can then pick 7925 * up the new information. But in the mean time, the reload has 7926 * swapped in trees, and the worker has been running with the 7927 * older information for some time. */ 7928 fr_worker_pickup_mesh(worker); 7929 7930 /* If the tcp connection limit has changed, the open connections 7931 * need to remove their reference for the old tcp limits counters. */ 7932 if(worker->daemon->fast_reload_tcl_has_changes) 7933 tcl_remove_old(worker->front); 7934 7935 /* If there are zonemd lookups, but the zone was deleted, the 7936 * lookups should be cancelled. */ 7937 fr_worker_pickup_auth_changes(worker, 7938 worker->daemon->fast_reload_thread->auth_zone_change_list); 7939 #ifdef USE_CACHEDB 7940 worker->env.cachedb_enabled = worker->daemon->env->cachedb_enabled; 7941 #endif 7942 fr_worker_pickup_listen_dnsport(worker); 7943 fr_worker_pickup_outside_network(worker); 7944 #ifdef USE_DNSTAP 7945 fr_worker_pickup_dnstap_changes(worker); 7946 #endif 7947 } 7948 7949 /** fast reload thread, handle reload_stop notification, send reload stop 7950 * to other threads over IPC and collect their ack. When that is done, 7951 * ack to the caller, the fast reload thread, and wait for it to send start. */ 7952 static void 7953 fr_main_perform_reload_stop(struct fast_reload_thread* fr) 7954 { 7955 struct daemon* daemon = fr->worker->daemon; 7956 int i; 7957 7958 /* Send reload_stop to other threads. */ 7959 for(i=0; i<daemon->num; i++) { 7960 if(i == fr->worker->thread_num) 7961 continue; /* Do not send to ourselves. */ 7962 worker_send_cmd(daemon->workers[i], worker_cmd_reload_stop); 7963 } 7964 7965 /* Wait for the other threads to ack. */ 7966 fr_read_ack_from_workers(fr); 7967 7968 /* Send ack to fast reload thread. */ 7969 fr_send_cmd_to(fr, fast_reload_notification_reload_ack, 0, 1); 7970 7971 /* Wait for reload_start from fast reload thread to resume. */ 7972 fr_poll_for_reload_start(fr); 7973 7974 /* Send reload_start to other threads */ 7975 for(i=0; i<daemon->num; i++) { 7976 if(i == fr->worker->thread_num) 7977 continue; /* Do not send to ourselves. */ 7978 worker_send_cmd(daemon->workers[i], worker_cmd_reload_start); 7979 } 7980 7981 /* Pick up changes for this worker. */ 7982 if(fr->worker->daemon->fast_reload_drop_mesh) { 7983 verbose(VERB_ALGO, "worker: drop mesh queries after reload"); 7984 mesh_delete_all(fr->worker->env.mesh); 7985 } 7986 fast_reload_worker_pickup_changes(fr->worker); 7987 7988 /* Wait for the other threads to ack. */ 7989 fr_read_ack_from_workers(fr); 7990 7991 /* Send ack to fast reload thread. */ 7992 fr_send_cmd_to(fr, fast_reload_notification_reload_ack, 0, 1); 7993 7994 verbose(VERB_ALGO, "worker resume after reload"); 7995 } 7996 7997 /** Fast reload, the main thread performs the nopause poll. It polls every 7998 * other worker thread briefly over the command pipe ipc. The command takes 7999 * no time for the worker, it can return immediately. After that it sends 8000 * an acknowledgement to the fastreload thread. */ 8001 static void 8002 fr_main_perform_reload_nopause_poll(struct fast_reload_thread* fr) 8003 { 8004 struct daemon* daemon = fr->worker->daemon; 8005 int i; 8006 8007 /* Send the reload_poll to other threads. They can respond 8008 * one at a time. */ 8009 for(i=0; i<daemon->num; i++) { 8010 if(i == fr->worker->thread_num) 8011 continue; /* Do not send to ourselves. */ 8012 worker_send_cmd(daemon->workers[i], worker_cmd_reload_poll); 8013 } 8014 8015 /* Wait for the other threads to ack. */ 8016 fr_read_ack_from_workers(fr); 8017 fast_reload_worker_pickup_changes(fr->worker); 8018 8019 /* Send ack to fast reload thread. */ 8020 fr_send_cmd_to(fr, fast_reload_notification_reload_ack, 0, 1); 8021 } 8022 8023 /** Fast reload, perform the command received from the fast reload thread */ 8024 static void 8025 fr_main_perform_cmd(struct fast_reload_thread* fr, 8026 enum fast_reload_notification status) 8027 { 8028 verbose(VERB_ALGO, "main perform fast reload status: %s", 8029 fr_notification_to_string(status)); 8030 if(status == fast_reload_notification_printout) { 8031 fr_main_perform_printout(fr); 8032 } else if(status == fast_reload_notification_done || 8033 status == fast_reload_notification_done_error || 8034 status == fast_reload_notification_exited) { 8035 fr_main_perform_done(fr); 8036 } else if(status == fast_reload_notification_reload_stop) { 8037 fr_main_perform_reload_stop(fr); 8038 } else if(status == fast_reload_notification_reload_nopause_poll) { 8039 fr_main_perform_reload_nopause_poll(fr); 8040 } else { 8041 log_err("main received unknown status from fast reload: %d %s", 8042 (int)status, fr_notification_to_string(status)); 8043 } 8044 } 8045 8046 /** Fast reload, handle command from fast reload to the main thread. */ 8047 static void 8048 fr_main_handle_cmd(struct fast_reload_thread* fr) 8049 { 8050 enum fast_reload_notification status; 8051 ssize_t ret; 8052 /* keep static analyzer happy; recv(-1,..) */ 8053 log_assert(fr->commpair[0] >= 0); 8054 ret = recv(fr->commpair[0], 8055 ((char*)&fr->service_read_cmd)+fr->service_read_cmd_count, 8056 sizeof(fr->service_read_cmd)-fr->service_read_cmd_count, 0); 8057 if(ret == -1) { 8058 if( 8059 #ifndef USE_WINSOCK 8060 errno == EINTR || errno == EAGAIN 8061 # ifdef EWOULDBLOCK 8062 || errno == EWOULDBLOCK 8063 # endif 8064 #else 8065 WSAGetLastError() == WSAEINTR || 8066 WSAGetLastError() == WSAEINPROGRESS 8067 #endif 8068 ) 8069 return; /* Continue later. */ 8070 #ifdef USE_WINSOCK 8071 if(WSAGetLastError() == WSAEWOULDBLOCK) { 8072 ub_winsock_tcp_wouldblock(fr->service_event, 8073 UB_EV_READ); 8074 return; /* Continue later. */ 8075 } 8076 #endif 8077 log_err("read cmd from fast reload thread, recv: %s", 8078 sock_strerror(errno)); 8079 return; 8080 } else if(ret == 0) { 8081 verbose(VERB_ALGO, "closed connection from fast reload thread"); 8082 fr->service_read_cmd_count = 0; 8083 /* handle this like an error */ 8084 fr->service_read_cmd = fast_reload_notification_done_error; 8085 } else if(ret + (ssize_t)fr->service_read_cmd_count < 8086 (ssize_t)sizeof(fr->service_read_cmd)) { 8087 fr->service_read_cmd_count += ret; 8088 /* Continue later. */ 8089 return; 8090 } 8091 status = fr->service_read_cmd; 8092 fr->service_read_cmd = 0; 8093 fr->service_read_cmd_count = 0; 8094 fr_main_perform_cmd(fr, status); 8095 } 8096 8097 /** Fast reload, poll for and handle cmd from fast reload thread. */ 8098 static void 8099 fr_check_cmd_from_thread(struct fast_reload_thread* fr) 8100 { 8101 int inevent = 0; 8102 struct worker* worker = fr->worker; 8103 /* Stop in case the thread has exited, or there is no read event. */ 8104 while(worker->daemon->fast_reload_thread) { 8105 if(!sock_poll_timeout(fr->commpair[0], 0, 1, 0, &inevent)) { 8106 log_err("check for cmd from fast reload thread: " 8107 "poll failed"); 8108 #ifdef USE_WINSOCK 8109 if(worker->daemon->fast_reload_thread) 8110 ub_winsock_tcp_wouldblock(worker->daemon-> 8111 fast_reload_thread->service_event, 8112 UB_EV_READ); 8113 #endif 8114 return; 8115 } 8116 if(!inevent) { 8117 #ifdef USE_WINSOCK 8118 if(worker->daemon->fast_reload_thread) 8119 ub_winsock_tcp_wouldblock(worker->daemon-> 8120 fast_reload_thread->service_event, 8121 UB_EV_READ); 8122 #endif 8123 return; 8124 } 8125 fr_main_handle_cmd(fr); 8126 } 8127 } 8128 8129 void fast_reload_service_cb(int ATTR_UNUSED(fd), short ATTR_UNUSED(bits), 8130 void* arg) 8131 { 8132 struct fast_reload_thread* fast_reload_thread = 8133 (struct fast_reload_thread*)arg; 8134 struct worker* worker = fast_reload_thread->worker; 8135 8136 /* Read and handle the command */ 8137 fr_main_handle_cmd(fast_reload_thread); 8138 if(worker->daemon->fast_reload_thread != NULL) { 8139 /* If not exited, see if there are more pending statuses 8140 * from the fast reload thread. */ 8141 fr_check_cmd_from_thread(fast_reload_thread); 8142 } 8143 } 8144 8145 #ifdef HAVE_SSL 8146 /** fast reload, send client item over SSL. Returns number of bytes 8147 * printed, 0 on wait later, or -1 on failure. */ 8148 static int 8149 fr_client_send_item_ssl(struct fast_reload_printq* printq) 8150 { 8151 int r; 8152 ERR_clear_error(); 8153 r = SSL_write(printq->remote.ssl, 8154 printq->client_item+printq->client_byte_count, 8155 printq->client_len - printq->client_byte_count); 8156 if(r <= 0) { 8157 int want = SSL_get_error(printq->remote.ssl, r); 8158 if(want == SSL_ERROR_ZERO_RETURN) { 8159 log_err("fast_reload print to remote client: " 8160 "SSL_write says connection closed."); 8161 return -1; 8162 } else if(want == SSL_ERROR_WANT_READ) { 8163 /* wait for read condition */ 8164 printq->client_cp->ssl_shake_state = comm_ssl_shake_hs_read; 8165 comm_point_listen_for_rw(printq->client_cp, 1, 0); 8166 return 0; 8167 } else if(want == SSL_ERROR_WANT_WRITE) { 8168 #ifdef USE_WINSOCK 8169 ub_winsock_tcp_wouldblock(comm_point_internal(printq->client_cp), UB_EV_WRITE); 8170 #endif 8171 return 0; /* write more later */ 8172 } else if(want == SSL_ERROR_SYSCALL) { 8173 #ifdef EPIPE 8174 if(errno == EPIPE && verbosity < 2) { 8175 /* silence 'broken pipe' */ 8176 return -1; 8177 } 8178 #endif 8179 if(errno != 0) 8180 log_err("fast_reload print to remote client: " 8181 "SSL_write syscall: %s", 8182 sock_strerror(errno)); 8183 return -1; 8184 } 8185 log_crypto_err_io("fast_reload print to remote client: " 8186 "could not SSL_write", want); 8187 return -1; 8188 } 8189 return r; 8190 } 8191 #endif /* HAVE_SSL */ 8192 8193 /** fast reload, send client item for fd, returns bytes sent, or 0 for wait 8194 * later, or -1 on failure. */ 8195 static int 8196 fr_client_send_item_fd(struct fast_reload_printq* printq) 8197 { 8198 int r; 8199 r = (int)send(printq->remote.fd, 8200 printq->client_item+printq->client_byte_count, 8201 printq->client_len - printq->client_byte_count, 0); 8202 if(r == -1) { 8203 if( 8204 #ifndef USE_WINSOCK 8205 errno == EINTR || errno == EAGAIN 8206 # ifdef EWOULDBLOCK 8207 || errno == EWOULDBLOCK 8208 # endif 8209 #else 8210 WSAGetLastError() == WSAEINTR || 8211 WSAGetLastError() == WSAEINPROGRESS || 8212 WSAGetLastError() == WSAEWOULDBLOCK 8213 #endif 8214 ) { 8215 #ifdef USE_WINSOCK 8216 ub_winsock_tcp_wouldblock(comm_point_internal(printq->client_cp), UB_EV_WRITE); 8217 #endif 8218 return 0; /* Try again. */ 8219 } 8220 log_err("fast_reload print to remote client: send failed: %s", 8221 sock_strerror(errno)); 8222 return -1; 8223 } 8224 return r; 8225 } 8226 8227 /** fast reload, send current client item. false on failure or wait later. */ 8228 static int 8229 fr_client_send_item(struct fast_reload_printq* printq) 8230 { 8231 int r; 8232 #ifdef HAVE_SSL 8233 if(printq->remote.ssl) { 8234 r = fr_client_send_item_ssl(printq); 8235 } else { 8236 #endif 8237 r = fr_client_send_item_fd(printq); 8238 #ifdef HAVE_SSL 8239 } 8240 #endif 8241 if(r == 0) { 8242 /* Wait for later. */ 8243 return 0; 8244 } else if(r == -1) { 8245 /* It failed, close comm point and stop sending. */ 8246 fr_printq_remove(printq); 8247 return 0; 8248 } 8249 printq->client_byte_count += r; 8250 if(printq->client_byte_count < printq->client_len) 8251 return 0; /* Print more later. */ 8252 return 1; 8253 } 8254 8255 /** fast reload, pick up the next item to print */ 8256 static void 8257 fr_client_pickup_next_item(struct fast_reload_printq* printq) 8258 { 8259 struct config_strlist* item; 8260 /* Pop first off the list. */ 8261 if(!printq->to_print->first) { 8262 printq->client_item = NULL; 8263 printq->client_len = 0; 8264 printq->client_byte_count = 0; 8265 return; 8266 } 8267 item = printq->to_print->first; 8268 if(item->next) { 8269 printq->to_print->first = item->next; 8270 } else { 8271 printq->to_print->first = NULL; 8272 printq->to_print->last = NULL; 8273 } 8274 item->next = NULL; 8275 printq->client_len = 0; 8276 printq->client_byte_count = 0; 8277 printq->client_item = item->str; 8278 item->str = NULL; 8279 free(item); 8280 /* The len is the number of bytes to print out, and thus excludes 8281 * the terminator zero. */ 8282 if(printq->client_item) 8283 printq->client_len = (int)strlen(printq->client_item); 8284 } 8285 8286 int fast_reload_client_callback(struct comm_point* ATTR_UNUSED(c), void* arg, 8287 int err, struct comm_reply* ATTR_UNUSED(rep)) 8288 { 8289 struct fast_reload_printq* printq = (struct fast_reload_printq*)arg; 8290 if(!printq->client_cp) { 8291 fr_printq_remove(printq); 8292 return 0; /* the output is closed and deleted */ 8293 } 8294 if(err != NETEVENT_NOERROR) { 8295 verbose(VERB_ALGO, "fast reload client: error, close it"); 8296 fr_printq_remove(printq); 8297 return 0; 8298 } 8299 #ifdef HAVE_SSL 8300 if(printq->client_cp->ssl_shake_state == comm_ssl_shake_hs_read) { 8301 /* read condition satisfied back to writing */ 8302 comm_point_listen_for_rw(printq->client_cp, 0, 1); 8303 printq->client_cp->ssl_shake_state = comm_ssl_shake_none; 8304 } 8305 #endif /* HAVE_SSL */ 8306 8307 /* Pickup an item if there are none */ 8308 if(!printq->client_item) { 8309 fr_client_pickup_next_item(printq); 8310 } 8311 if(!printq->client_item) { 8312 if(printq->in_list) { 8313 /* Nothing more to print, it can be removed. */ 8314 fr_printq_remove(printq); 8315 return 0; 8316 } 8317 /* Done with printing for now. */ 8318 comm_point_stop_listening(printq->client_cp); 8319 return 0; 8320 } 8321 8322 /* Try to print out a number of items, if they can print in full. */ 8323 while(printq->client_item) { 8324 /* Send current item, if any. */ 8325 if(printq->client_item && printq->client_len != 0 && 8326 printq->client_byte_count < printq->client_len) { 8327 if(!fr_client_send_item(printq)) 8328 return 0; 8329 } 8330 8331 /* The current item is done. */ 8332 if(printq->client_item) { 8333 free(printq->client_item); 8334 printq->client_item = NULL; 8335 printq->client_len = 0; 8336 printq->client_byte_count = 0; 8337 } 8338 if(!printq->to_print->first) { 8339 if(printq->in_list) { 8340 /* Nothing more to print, it can be removed. */ 8341 fr_printq_remove(printq); 8342 return 0; 8343 } 8344 /* Done with printing for now. */ 8345 comm_point_stop_listening(printq->client_cp); 8346 return 0; 8347 } 8348 fr_client_pickup_next_item(printq); 8349 } 8350 8351 return 0; 8352 } 8353 8354 #ifndef THREADS_DISABLED 8355 /** fast reload printq create */ 8356 static struct fast_reload_printq* 8357 fr_printq_create(struct comm_point* c, struct worker* worker) 8358 { 8359 struct fast_reload_printq* printq = calloc(1, sizeof(*printq)); 8360 if(!printq) 8361 return NULL; 8362 printq->to_print = calloc(1, sizeof(*printq->to_print)); 8363 if(!printq->to_print) { 8364 free(printq); 8365 return NULL; 8366 } 8367 printq->worker = worker; 8368 printq->client_cp = c; 8369 printq->client_cp->callback = fast_reload_client_callback; 8370 printq->client_cp->cb_arg = printq; 8371 return printq; 8372 } 8373 #endif /* !THREADS_DISABLED */ 8374 8375 /** fast reload printq delete */ 8376 static void 8377 fr_printq_delete(struct fast_reload_printq* printq) 8378 { 8379 if(!printq) 8380 return; 8381 #ifdef HAVE_SSL 8382 if(printq->remote.ssl) { 8383 SSL_shutdown(printq->remote.ssl); 8384 SSL_free(printq->remote.ssl); 8385 } 8386 #endif 8387 comm_point_delete(printq->client_cp); 8388 if(printq->to_print) { 8389 config_delstrlist(printq->to_print->first); 8390 free(printq->to_print); 8391 } 8392 free(printq); 8393 } 8394 8395 /** fast reload printq, returns true if the list is empty and no item */ 8396 static int 8397 fr_printq_empty(struct fast_reload_printq* printq) 8398 { 8399 if(printq->to_print->first == NULL && printq->client_item == NULL) 8400 return 1; 8401 return 0; 8402 } 8403 8404 /** fast reload printq, insert onto list */ 8405 static void 8406 fr_printq_list_insert(struct fast_reload_printq* printq, struct daemon* daemon) 8407 { 8408 if(printq->in_list) 8409 return; 8410 printq->next = daemon->fast_reload_printq_list; 8411 if(printq->next) 8412 printq->next->prev = printq; 8413 printq->prev = NULL; 8414 printq->in_list = 1; 8415 daemon->fast_reload_printq_list = printq; 8416 } 8417 8418 /** fast reload printq delete list */ 8419 void 8420 fast_reload_printq_list_delete(struct fast_reload_printq* list) 8421 { 8422 struct fast_reload_printq* printq = list, *next; 8423 while(printq) { 8424 next = printq->next; 8425 fr_printq_delete(printq); 8426 printq = next; 8427 } 8428 } 8429 8430 /** fast reload printq remove the item from the printq list */ 8431 static void 8432 fr_printq_list_remove(struct fast_reload_printq* printq) 8433 { 8434 struct daemon* daemon = printq->worker->daemon; 8435 if(printq->prev == NULL) 8436 daemon->fast_reload_printq_list = printq->next; 8437 else printq->prev->next = printq->next; 8438 if(printq->next) 8439 printq->next->prev = printq->prev; 8440 printq->in_list = 0; 8441 } 8442 8443 /** fast reload printq, remove the printq when no longer needed, 8444 * like the stream is closed. */ 8445 static void 8446 fr_printq_remove(struct fast_reload_printq* printq) 8447 { 8448 if(!printq) 8449 return; 8450 if(printq->worker->daemon->fast_reload_thread && 8451 printq->worker->daemon->fast_reload_thread->printq == printq) 8452 printq->worker->daemon->fast_reload_thread->printq = NULL; 8453 if(printq->in_list) 8454 fr_printq_list_remove(printq); 8455 fr_printq_delete(printq); 8456 } 8457 8458 /** fast reload thread, send stop command to the thread, from the main thread. 8459 */ 8460 static void 8461 fr_send_stop(struct fast_reload_thread* fr) 8462 { 8463 fr_send_cmd_to(fr, fast_reload_notification_exit, 1, 0); 8464 } 8465 8466 void 8467 fast_reload_thread_start(RES* ssl, struct worker* worker, struct rc_state* s, 8468 int fr_verb, int fr_nopause, int fr_drop_mesh) 8469 { 8470 if(worker->daemon->fast_reload_thread) { 8471 log_err("fast reload thread already running"); 8472 return; 8473 } 8474 if(!fast_reload_thread_setup(worker, fr_verb, fr_nopause, 8475 fr_drop_mesh)) { 8476 if(!ssl_printf(ssl, "error could not setup thread\n")) 8477 return; 8478 return; 8479 } 8480 worker->daemon->fast_reload_thread->started = 1; 8481 8482 #ifndef THREADS_DISABLED 8483 /* Setup command listener in remote servicing thread */ 8484 /* The listener has to be nonblocking, so the the remote servicing 8485 * thread can continue to service DNS queries, the fast reload 8486 * thread is going to read the config from disk and apply it. */ 8487 /* The commpair[1] element can stay blocking, it is used by the 8488 * fast reload thread to communicate back. The thread needs to wait 8489 * at these times, when it has to check briefly it can use poll. */ 8490 fd_set_nonblock(worker->daemon->fast_reload_thread->commpair[0]); 8491 worker->daemon->fast_reload_thread->service_event = ub_event_new( 8492 comm_base_internal(worker->base), 8493 worker->daemon->fast_reload_thread->commpair[0], 8494 UB_EV_READ | UB_EV_PERSIST, fast_reload_service_cb, 8495 worker->daemon->fast_reload_thread); 8496 if(!worker->daemon->fast_reload_thread->service_event) { 8497 fast_reload_thread_desetup(worker->daemon->fast_reload_thread); 8498 if(!ssl_printf(ssl, "error out of memory\n")) 8499 return; 8500 return; 8501 } 8502 if(ub_event_add(worker->daemon->fast_reload_thread->service_event, 8503 NULL) != 0) { 8504 fast_reload_thread_desetup(worker->daemon->fast_reload_thread); 8505 if(!ssl_printf(ssl, "error out of memory adding service event\n")) 8506 return; 8507 return; 8508 } 8509 worker->daemon->fast_reload_thread->service_event_is_added = 1; 8510 8511 /* Setup the comm point to the remote control client as an event 8512 * on the remote servicing thread, which it already is. 8513 * It needs a new callback to service it. */ 8514 log_assert(s); 8515 state_list_remove_elem(&s->rc->busy_list, s->c); 8516 s->rc->active --; 8517 /* Set the comm point file descriptor to nonblocking. So that 8518 * printout to the remote control client does not block the 8519 * server thread from servicing DNS queries. */ 8520 fd_set_nonblock(s->c->fd); 8521 worker->daemon->fast_reload_thread->printq = fr_printq_create(s->c, 8522 worker); 8523 if(!worker->daemon->fast_reload_thread->printq) { 8524 fast_reload_thread_desetup(worker->daemon->fast_reload_thread); 8525 if(!ssl_printf(ssl, "error out of memory create printq\n")) 8526 return; 8527 return; 8528 } 8529 worker->daemon->fast_reload_thread->printq->remote = *ssl; 8530 s->rc = NULL; /* move away the rc state */ 8531 /* Nothing to print right now, so no need to have it active. */ 8532 comm_point_stop_listening(worker->daemon->fast_reload_thread->printq->client_cp); 8533 8534 /* Start fast reload thread */ 8535 ub_thread_create(&worker->daemon->fast_reload_thread->tid, 8536 fast_reload_thread_main, worker->daemon->fast_reload_thread); 8537 #else 8538 (void)s; 8539 #endif 8540 } 8541 8542 void 8543 fast_reload_thread_stop(struct fast_reload_thread* fast_reload_thread) 8544 { 8545 struct worker* worker = fast_reload_thread->worker; 8546 if(!fast_reload_thread) 8547 return; 8548 fr_send_stop(fast_reload_thread); 8549 if(worker->daemon->fast_reload_thread != NULL) { 8550 /* If it did not exit yet, join with the thread now. It is 8551 * going to exit because the exit command is sent to it. */ 8552 fr_main_perform_done(fast_reload_thread); 8553 } 8554 } 8555