1 /* 2 * services/outside_network.c - implement sending of queries and wait answer. 3 * 4 * Copyright (c) 2007, 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 has functions to send queries to authoritative servers and 40 * wait for the pending answer events. 41 */ 42 #include "config.h" 43 #include <ctype.h> 44 #ifdef HAVE_SYS_TYPES_H 45 # include <sys/types.h> 46 #endif 47 #include <sys/time.h> 48 #include "services/outside_network.h" 49 #include "services/listen_dnsport.h" 50 #include "services/cache/infra.h" 51 #include "iterator/iterator.h" 52 #include "util/data/msgparse.h" 53 #include "util/data/msgreply.h" 54 #include "util/data/msgencode.h" 55 #include "util/data/dname.h" 56 #include "util/netevent.h" 57 #include "util/log.h" 58 #include "util/net_help.h" 59 #include "util/random.h" 60 #include "util/fptr_wlist.h" 61 #include "util/edns.h" 62 #include "sldns/sbuffer.h" 63 #include "dnstap/dnstap.h" 64 #ifdef HAVE_OPENSSL_SSL_H 65 #include <openssl/ssl.h> 66 #endif 67 #ifdef HAVE_X509_VERIFY_PARAM_SET1_HOST 68 #include <openssl/x509v3.h> 69 #endif 70 71 #ifdef HAVE_NETDB_H 72 #include <netdb.h> 73 #endif 74 #include <fcntl.h> 75 76 /** number of times to retry making a random ID that is unique. */ 77 #define MAX_ID_RETRY 1000 78 /** number of times to retry finding interface, port that can be opened. */ 79 #define MAX_PORT_RETRY 10000 80 /** number of retries on outgoing UDP queries */ 81 #define OUTBOUND_UDP_RETRY 1 82 83 /** initiate TCP transaction for serviced query */ 84 static void serviced_tcp_initiate(struct serviced_query* sq, sldns_buffer* buff); 85 /** with a fd available, randomize and send UDP */ 86 static int randomize_and_send_udp(struct pending* pend, sldns_buffer* packet, 87 int timeout); 88 89 /** select a DNS ID for a TCP stream */ 90 static uint16_t tcp_select_id(struct outside_network* outnet, 91 struct reuse_tcp* reuse); 92 93 /** Perform serviced query UDP sending operation */ 94 static int serviced_udp_send(struct serviced_query* sq, sldns_buffer* buff); 95 96 /** Send serviced query over TCP return false on initial failure */ 97 static int serviced_tcp_send(struct serviced_query* sq, sldns_buffer* buff); 98 99 /** call the callbacks for a serviced query */ 100 static void serviced_callbacks(struct serviced_query* sq, int error, 101 struct comm_point* c, struct comm_reply* rep); 102 103 int 104 pending_cmp(const void* key1, const void* key2) 105 { 106 struct pending *p1 = (struct pending*)key1; 107 struct pending *p2 = (struct pending*)key2; 108 if(p1->id < p2->id) 109 return -1; 110 if(p1->id > p2->id) 111 return 1; 112 log_assert(p1->id == p2->id); 113 return sockaddr_cmp(&p1->addr, p1->addrlen, &p2->addr, p2->addrlen); 114 } 115 116 int 117 serviced_cmp(const void* key1, const void* key2) 118 { 119 struct serviced_query* q1 = (struct serviced_query*)key1; 120 struct serviced_query* q2 = (struct serviced_query*)key2; 121 int r; 122 if(q1->qbuflen < q2->qbuflen) 123 return -1; 124 if(q1->qbuflen > q2->qbuflen) 125 return 1; 126 log_assert(q1->qbuflen == q2->qbuflen); 127 log_assert(q1->qbuflen >= 15 /* 10 header, root, type, class */); 128 /* alternate casing of qname is still the same query */ 129 if((r = memcmp(q1->qbuf, q2->qbuf, 10)) != 0) 130 return r; 131 if((r = memcmp(q1->qbuf+q1->qbuflen-4, q2->qbuf+q2->qbuflen-4, 4)) != 0) 132 return r; 133 if(q1->dnssec != q2->dnssec) { 134 if(q1->dnssec < q2->dnssec) 135 return -1; 136 return 1; 137 } 138 if((r = query_dname_compare(q1->qbuf+10, q2->qbuf+10)) != 0) 139 return r; 140 if((r = edns_opt_list_compare(q1->opt_list, q2->opt_list)) != 0) 141 return r; 142 return sockaddr_cmp(&q1->addr, q1->addrlen, &q2->addr, q2->addrlen); 143 } 144 145 /** compare if the reuse element has the same address, port and same ssl-is 146 * used-for-it characteristic */ 147 static int 148 reuse_cmp_addrportssl(const void* key1, const void* key2) 149 { 150 struct reuse_tcp* r1 = (struct reuse_tcp*)key1; 151 struct reuse_tcp* r2 = (struct reuse_tcp*)key2; 152 int r; 153 /* compare address and port */ 154 r = sockaddr_cmp(&r1->addr, r1->addrlen, &r2->addr, r2->addrlen); 155 if(r != 0) 156 return r; 157 158 /* compare if SSL-enabled */ 159 if(r1->is_ssl && !r2->is_ssl) 160 return 1; 161 if(!r1->is_ssl && r2->is_ssl) 162 return -1; 163 164 /* compare tls_auth_name if SSL-enabled */ 165 if(r1->is_ssl) { 166 if(r1->tls_auth_name && !r2->tls_auth_name) 167 return 1; 168 if(!r1->tls_auth_name && r2->tls_auth_name) 169 return -1; 170 if(r1->tls_auth_name && r2->tls_auth_name) { 171 r = strcmp(r1->tls_auth_name, r2->tls_auth_name); 172 if(r != 0) 173 return r; 174 } 175 } 176 return 0; 177 } 178 179 int 180 reuse_cmp(const void* key1, const void* key2) 181 { 182 int r; 183 r = reuse_cmp_addrportssl(key1, key2); 184 if(r != 0) 185 return r; 186 187 /* compare ptr value */ 188 if(key1 < key2) return -1; 189 if(key1 > key2) return 1; 190 return 0; 191 } 192 193 int reuse_id_cmp(const void* key1, const void* key2) 194 { 195 struct waiting_tcp* w1 = (struct waiting_tcp*)key1; 196 struct waiting_tcp* w2 = (struct waiting_tcp*)key2; 197 if(w1->id < w2->id) 198 return -1; 199 if(w1->id > w2->id) 200 return 1; 201 return 0; 202 } 203 204 /** delete waiting_tcp entry. Does not unlink from waiting list. 205 * @param w: to delete. 206 */ 207 static void 208 waiting_tcp_delete(struct waiting_tcp* w) 209 { 210 if(!w) return; 211 free(w->tls_auth_name); 212 if(w->timer) 213 comm_timer_delete(w->timer); 214 free(w); 215 } 216 217 /** 218 * Pick random outgoing-interface of that family, and bind it. 219 * port set to 0 so OS picks a port number for us. 220 * if it is the ANY address, do not bind. 221 * @param pend: pending tcp structure, for storing the local address choice. 222 * @param w: tcp structure with destination address. 223 * @param s: socket fd. 224 * @return false on error, socket closed. 225 */ 226 static int 227 pick_outgoing_tcp(struct pending_tcp* pend, struct waiting_tcp* w, int s) 228 { 229 struct port_if* pi = NULL; 230 int num; 231 pend->pi = NULL; 232 #ifdef INET6 233 if(addr_is_ip6(&w->addr, w->addrlen)) 234 num = w->outnet->num_ip6; 235 else 236 #endif 237 num = w->outnet->num_ip4; 238 if(num == 0) { 239 log_err("no TCP outgoing interfaces of family"); 240 log_addr(VERB_OPS, "for addr", &w->addr, w->addrlen); 241 sock_close(s); 242 return 0; 243 } 244 #ifdef INET6 245 if(addr_is_ip6(&w->addr, w->addrlen)) 246 pi = &w->outnet->ip6_ifs[ub_random_max(w->outnet->rnd, num)]; 247 else 248 #endif 249 pi = &w->outnet->ip4_ifs[ub_random_max(w->outnet->rnd, num)]; 250 log_assert(pi); 251 pend->pi = pi; 252 if(addr_is_any(&pi->addr, pi->addrlen)) { 253 /* binding to the ANY interface is for listening sockets */ 254 return 1; 255 } 256 /* set port to 0 */ 257 if(addr_is_ip6(&pi->addr, pi->addrlen)) 258 ((struct sockaddr_in6*)&pi->addr)->sin6_port = 0; 259 else ((struct sockaddr_in*)&pi->addr)->sin_port = 0; 260 if(bind(s, (struct sockaddr*)&pi->addr, pi->addrlen) != 0) { 261 #ifndef USE_WINSOCK 262 #ifdef EADDRNOTAVAIL 263 if(!(verbosity < 4 && errno == EADDRNOTAVAIL)) 264 #endif 265 #else /* USE_WINSOCK */ 266 if(!(verbosity < 4 && WSAGetLastError() == WSAEADDRNOTAVAIL)) 267 #endif 268 log_err("outgoing tcp: bind: %s", sock_strerror(errno)); 269 sock_close(s); 270 return 0; 271 } 272 log_addr(VERB_ALGO, "tcp bound to src", &pi->addr, pi->addrlen); 273 return 1; 274 } 275 276 /** get TCP file descriptor for address, returns -1 on failure, 277 * tcp_mss is 0 or maxseg size to set for TCP packets. */ 278 int 279 outnet_get_tcp_fd(struct sockaddr_storage* addr, socklen_t addrlen, 280 int tcp_mss, int dscp, int nodelay) 281 { 282 int s; 283 int af; 284 char* err; 285 #if defined(SO_REUSEADDR) || defined(IP_BIND_ADDRESS_NO_PORT) \ 286 || defined(TCP_NODELAY) 287 int on = 1; 288 #endif 289 #ifdef INET6 290 if(addr_is_ip6(addr, addrlen)){ 291 s = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP); 292 af = AF_INET6; 293 } else { 294 #else 295 { 296 #endif 297 af = AF_INET; 298 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); 299 } 300 if(s == -1) { 301 log_err_addr("outgoing tcp: socket", sock_strerror(errno), 302 addr, addrlen); 303 return -1; 304 } 305 306 #ifdef SO_REUSEADDR 307 if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&on, 308 (socklen_t)sizeof(on)) < 0) { 309 verbose(VERB_ALGO, "outgoing tcp:" 310 " setsockopt(.. SO_REUSEADDR ..) failed"); 311 } 312 #endif 313 314 err = set_ip_dscp(s, af, dscp); 315 if(err != NULL) { 316 verbose(VERB_ALGO, "outgoing tcp:" 317 "error setting IP DiffServ codepoint on socket"); 318 } 319 320 if(tcp_mss > 0) { 321 #if defined(IPPROTO_TCP) && defined(TCP_MAXSEG) 322 if(setsockopt(s, IPPROTO_TCP, TCP_MAXSEG, 323 (void*)&tcp_mss, (socklen_t)sizeof(tcp_mss)) < 0) { 324 verbose(VERB_ALGO, "outgoing tcp:" 325 " setsockopt(.. TCP_MAXSEG ..) failed"); 326 } 327 #else 328 verbose(VERB_ALGO, "outgoing tcp:" 329 " setsockopt(TCP_MAXSEG) unsupported"); 330 #endif /* defined(IPPROTO_TCP) && defined(TCP_MAXSEG) */ 331 } 332 #ifdef IP_BIND_ADDRESS_NO_PORT 333 if(setsockopt(s, IPPROTO_IP, IP_BIND_ADDRESS_NO_PORT, (void*)&on, 334 (socklen_t)sizeof(on)) < 0) { 335 verbose(VERB_ALGO, "outgoing tcp:" 336 " setsockopt(.. IP_BIND_ADDRESS_NO_PORT ..) failed"); 337 } 338 #endif /* IP_BIND_ADDRESS_NO_PORT */ 339 if(nodelay) { 340 #if defined(IPPROTO_TCP) && defined(TCP_NODELAY) 341 if(setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void*)&on, 342 (socklen_t)sizeof(on)) < 0) { 343 verbose(VERB_ALGO, "outgoing tcp:" 344 " setsockopt(.. TCP_NODELAY ..) failed"); 345 } 346 #else 347 verbose(VERB_ALGO, "outgoing tcp:" 348 " setsockopt(.. TCP_NODELAY ..) unsupported"); 349 #endif /* defined(IPPROTO_TCP) && defined(TCP_NODELAY) */ 350 } 351 return s; 352 } 353 354 /** connect tcp connection to addr, 0 on failure */ 355 int 356 outnet_tcp_connect(int s, struct sockaddr_storage* addr, socklen_t addrlen) 357 { 358 if(connect(s, (struct sockaddr*)addr, addrlen) == -1) { 359 #ifndef USE_WINSOCK 360 #ifdef EINPROGRESS 361 if(errno != EINPROGRESS) { 362 #endif 363 if(tcp_connect_errno_needs_log( 364 (struct sockaddr*)addr, addrlen)) 365 log_err_addr("outgoing tcp: connect", 366 strerror(errno), addr, addrlen); 367 close(s); 368 return 0; 369 #ifdef EINPROGRESS 370 } 371 #endif 372 #else /* USE_WINSOCK */ 373 if(WSAGetLastError() != WSAEINPROGRESS && 374 WSAGetLastError() != WSAEWOULDBLOCK) { 375 closesocket(s); 376 return 0; 377 } 378 #endif 379 } 380 return 1; 381 } 382 383 /** log reuse item addr and ptr with message */ 384 static void 385 log_reuse_tcp(enum verbosity_value v, const char* msg, struct reuse_tcp* reuse) 386 { 387 uint16_t port; 388 char addrbuf[128]; 389 if(verbosity < v) return; 390 if(!reuse || !reuse->pending || !reuse->pending->c) 391 return; 392 addr_to_str(&reuse->addr, reuse->addrlen, addrbuf, sizeof(addrbuf)); 393 port = ntohs(((struct sockaddr_in*)&reuse->addr)->sin_port); 394 verbose(v, "%s %s#%u fd %d", msg, addrbuf, (unsigned)port, 395 reuse->pending->c->fd); 396 } 397 398 /** pop the first element from the writewait list */ 399 struct waiting_tcp* 400 reuse_write_wait_pop(struct reuse_tcp* reuse) 401 { 402 struct waiting_tcp* w = reuse->write_wait_first; 403 if(!w) 404 return NULL; 405 log_assert(w->write_wait_queued); 406 log_assert(!w->write_wait_prev); 407 reuse->write_wait_first = w->write_wait_next; 408 if(w->write_wait_next) 409 w->write_wait_next->write_wait_prev = NULL; 410 else reuse->write_wait_last = NULL; 411 w->write_wait_queued = 0; 412 w->write_wait_next = NULL; 413 w->write_wait_prev = NULL; 414 return w; 415 } 416 417 /** remove the element from the writewait list */ 418 void 419 reuse_write_wait_remove(struct reuse_tcp* reuse, struct waiting_tcp* w) 420 { 421 log_assert(w); 422 log_assert(w->write_wait_queued); 423 if(!w) 424 return; 425 if(!w->write_wait_queued) 426 return; 427 if(w->write_wait_prev) 428 w->write_wait_prev->write_wait_next = w->write_wait_next; 429 else reuse->write_wait_first = w->write_wait_next; 430 log_assert(!w->write_wait_prev || 431 w->write_wait_prev->write_wait_next != w->write_wait_prev); 432 if(w->write_wait_next) 433 w->write_wait_next->write_wait_prev = w->write_wait_prev; 434 else reuse->write_wait_last = w->write_wait_prev; 435 log_assert(!w->write_wait_next 436 || w->write_wait_next->write_wait_prev != w->write_wait_next); 437 w->write_wait_queued = 0; 438 w->write_wait_next = NULL; 439 w->write_wait_prev = NULL; 440 } 441 442 /** push the element after the last on the writewait list */ 443 void 444 reuse_write_wait_push_back(struct reuse_tcp* reuse, struct waiting_tcp* w) 445 { 446 if(!w) return; 447 log_assert(!w->write_wait_queued); 448 if(reuse->write_wait_last) { 449 reuse->write_wait_last->write_wait_next = w; 450 log_assert(reuse->write_wait_last->write_wait_next != 451 reuse->write_wait_last); 452 w->write_wait_prev = reuse->write_wait_last; 453 } else { 454 reuse->write_wait_first = w; 455 w->write_wait_prev = NULL; 456 } 457 w->write_wait_next = NULL; 458 reuse->write_wait_last = w; 459 w->write_wait_queued = 1; 460 } 461 462 /** insert element in tree by id */ 463 void 464 reuse_tree_by_id_insert(struct reuse_tcp* reuse, struct waiting_tcp* w) 465 { 466 #ifdef UNBOUND_DEBUG 467 rbnode_type* added; 468 #endif 469 log_assert(w->id_node.key == NULL); 470 w->id_node.key = w; 471 #ifdef UNBOUND_DEBUG 472 added = 473 #else 474 (void) 475 #endif 476 rbtree_insert(&reuse->tree_by_id, &w->id_node); 477 log_assert(added); /* should have been added */ 478 } 479 480 /** find element in tree by id */ 481 struct waiting_tcp* 482 reuse_tcp_by_id_find(struct reuse_tcp* reuse, uint16_t id) 483 { 484 struct waiting_tcp key_w; 485 rbnode_type* n; 486 memset(&key_w, 0, sizeof(key_w)); 487 key_w.id_node.key = &key_w; 488 key_w.id = id; 489 n = rbtree_search(&reuse->tree_by_id, &key_w); 490 if(!n) return NULL; 491 return (struct waiting_tcp*)n->key; 492 } 493 494 /** return ID value of rbnode in tree_by_id */ 495 static uint16_t 496 tree_by_id_get_id(rbnode_type* node) 497 { 498 struct waiting_tcp* w = (struct waiting_tcp*)node->key; 499 return w->id; 500 } 501 502 /** insert into reuse tcp tree and LRU, false on failure (duplicate) */ 503 int 504 reuse_tcp_insert(struct outside_network* outnet, struct pending_tcp* pend_tcp) 505 { 506 log_reuse_tcp(VERB_CLIENT, "reuse_tcp_insert", &pend_tcp->reuse); 507 if(pend_tcp->reuse.item_on_lru_list) { 508 if(!pend_tcp->reuse.node.key) 509 log_err("internal error: reuse_tcp_insert: " 510 "in lru list without key"); 511 return 1; 512 } 513 pend_tcp->reuse.node.key = &pend_tcp->reuse; 514 pend_tcp->reuse.pending = pend_tcp; 515 if(!rbtree_insert(&outnet->tcp_reuse, &pend_tcp->reuse.node)) { 516 /* We are not in the LRU list but we are already in the 517 * tcp_reuse tree, strange. 518 * Continue to add ourselves to the LRU list. */ 519 log_err("internal error: reuse_tcp_insert: in lru list but " 520 "not in the tree"); 521 } 522 /* insert into LRU, first is newest */ 523 pend_tcp->reuse.lru_prev = NULL; 524 if(outnet->tcp_reuse_first) { 525 pend_tcp->reuse.lru_next = outnet->tcp_reuse_first; 526 log_assert(pend_tcp->reuse.lru_next != &pend_tcp->reuse); 527 outnet->tcp_reuse_first->lru_prev = &pend_tcp->reuse; 528 log_assert(outnet->tcp_reuse_first->lru_prev != 529 outnet->tcp_reuse_first); 530 } else { 531 pend_tcp->reuse.lru_next = NULL; 532 outnet->tcp_reuse_last = &pend_tcp->reuse; 533 } 534 outnet->tcp_reuse_first = &pend_tcp->reuse; 535 pend_tcp->reuse.item_on_lru_list = 1; 536 log_assert((!outnet->tcp_reuse_first && !outnet->tcp_reuse_last) || 537 (outnet->tcp_reuse_first && outnet->tcp_reuse_last)); 538 log_assert(outnet->tcp_reuse_first != outnet->tcp_reuse_first->lru_next && 539 outnet->tcp_reuse_first != outnet->tcp_reuse_first->lru_prev); 540 log_assert(outnet->tcp_reuse_last != outnet->tcp_reuse_last->lru_next && 541 outnet->tcp_reuse_last != outnet->tcp_reuse_last->lru_prev); 542 return 1; 543 } 544 545 /** find reuse tcp stream to destination for query, or NULL if none */ 546 static struct reuse_tcp* 547 reuse_tcp_find(struct outside_network* outnet, struct sockaddr_storage* addr, 548 socklen_t addrlen, int use_ssl, char* tls_auth_name) 549 { 550 struct waiting_tcp key_w; 551 struct pending_tcp key_p; 552 struct comm_point c; 553 rbnode_type* result = NULL, *prev; 554 verbose(VERB_CLIENT, "reuse_tcp_find"); 555 memset(&key_w, 0, sizeof(key_w)); 556 memset(&key_p, 0, sizeof(key_p)); 557 memset(&c, 0, sizeof(c)); 558 key_p.query = &key_w; 559 key_p.c = &c; 560 key_p.reuse.pending = &key_p; 561 key_p.reuse.node.key = &key_p.reuse; 562 if(use_ssl) { 563 key_p.reuse.is_ssl = 1; 564 key_p.reuse.tls_auth_name = tls_auth_name; 565 } 566 if(addrlen > (socklen_t)sizeof(key_p.reuse.addr)) 567 return NULL; 568 memmove(&key_p.reuse.addr, addr, addrlen); 569 key_p.reuse.addrlen = addrlen; 570 571 verbose(VERB_CLIENT, "reuse_tcp_find: num reuse streams %u", 572 (unsigned)outnet->tcp_reuse.count); 573 if(outnet->tcp_reuse.root == NULL || 574 outnet->tcp_reuse.root == RBTREE_NULL) 575 return NULL; 576 if(rbtree_find_less_equal(&outnet->tcp_reuse, &key_p.reuse, 577 &result)) { 578 /* exact match */ 579 /* but the key is on stack, and ptr is compared, impossible */ 580 log_assert(&key_p.reuse != (struct reuse_tcp*)result); 581 log_assert(&key_p != ((struct reuse_tcp*)result)->pending); 582 } 583 584 /* It is possible that we search for something before the first element 585 * in the tree. Replace a null pointer with the first element. 586 */ 587 if (!result) { 588 verbose(VERB_CLIENT, "reuse_tcp_find: taking first"); 589 result = rbtree_first(&outnet->tcp_reuse); 590 } 591 592 /* not found, return null */ 593 if(!result || result == RBTREE_NULL) 594 return NULL; 595 596 /* It is possible that we got the previous address, but that the 597 * address we are looking for is in the tree. If the address we got 598 * is less than the address we are looking, then take the next entry. 599 */ 600 if (reuse_cmp_addrportssl(result->key, &key_p.reuse) < 0) { 601 verbose(VERB_CLIENT, "reuse_tcp_find: key too low"); 602 result = rbtree_next(result); 603 } 604 605 verbose(VERB_CLIENT, "reuse_tcp_find check inexact match"); 606 /* inexact match, find one of possibly several connections to the 607 * same destination address, with the correct port, ssl, and 608 * also less than max number of open queries, or else, fail to open 609 * a new one */ 610 /* rewind to start of sequence of same address,port,ssl */ 611 prev = rbtree_previous(result); 612 while(prev && prev != RBTREE_NULL && 613 reuse_cmp_addrportssl(prev->key, &key_p.reuse) == 0) { 614 result = prev; 615 prev = rbtree_previous(result); 616 } 617 618 /* loop to find first one that has correct characteristics */ 619 while(result && result != RBTREE_NULL && 620 reuse_cmp_addrportssl(result->key, &key_p.reuse) == 0) { 621 if(((struct reuse_tcp*)result)->tree_by_id.count < 622 outnet->max_reuse_tcp_queries) { 623 /* same address, port, ssl-yes-or-no, and has 624 * space for another query */ 625 return (struct reuse_tcp*)result; 626 } 627 result = rbtree_next(result); 628 } 629 return NULL; 630 } 631 632 /** use the buffer to setup writing the query */ 633 static void 634 outnet_tcp_take_query_setup(int s, struct pending_tcp* pend, 635 struct waiting_tcp* w) 636 { 637 struct timeval tv; 638 verbose(VERB_CLIENT, "outnet_tcp_take_query_setup: setup packet to write " 639 "len %d timeout %d msec", 640 (int)w->pkt_len, w->timeout); 641 pend->c->tcp_write_pkt = w->pkt; 642 pend->c->tcp_write_pkt_len = w->pkt_len; 643 pend->c->tcp_write_and_read = 1; 644 pend->c->tcp_write_byte_count = 0; 645 pend->c->tcp_is_reading = 0; 646 comm_point_start_listening(pend->c, s, -1); 647 /* set timer on the waiting_tcp entry, this is the write timeout 648 * for the written packet. The timer on pend->c is the timer 649 * for when there is no written packet and we have readtimeouts */ 650 #ifndef S_SPLINT_S 651 tv.tv_sec = w->timeout/1000; 652 tv.tv_usec = (w->timeout%1000)*1000; 653 #endif 654 /* if the waiting_tcp was previously waiting for a buffer in the 655 * outside_network.tcpwaitlist, then the timer is reset now that 656 * we start writing it */ 657 comm_timer_set(w->timer, &tv); 658 } 659 660 /** use next free buffer to service a tcp query */ 661 static int 662 outnet_tcp_take_into_use(struct waiting_tcp* w) 663 { 664 struct pending_tcp* pend = w->outnet->tcp_free; 665 char* tls_auth_name = NULL; 666 int s; 667 log_assert(pend); 668 log_assert(w->pkt); 669 log_assert(w->pkt_len > 0); 670 log_assert(w->addrlen > 0); 671 pend->c->tcp_do_toggle_rw = 0; 672 pend->c->tcp_do_close = 0; 673 674 /* Consistency check, if we have ssl_upstream but no sslctx, then 675 * log an error and return failure. 676 */ 677 if (w->ssl_upstream && !w->outnet->sslctx) { 678 log_err("SSL upstream requested but no SSL context"); 679 return 0; 680 } 681 682 /* open socket */ 683 s = outnet_get_tcp_fd(&w->addr, w->addrlen, w->outnet->tcp_mss, 684 w->outnet->ip_dscp, w->ssl_upstream); 685 686 if(s == -1) 687 return 0; 688 689 if(!pick_outgoing_tcp(pend, w, s)) 690 return 0; 691 692 fd_set_nonblock(s); 693 #ifdef USE_OSX_MSG_FASTOPEN 694 /* API for fast open is different here. We use a connectx() function and 695 then writes can happen as normal even using SSL.*/ 696 /* connectx requires that the len be set in the sockaddr struct*/ 697 struct sockaddr_in *addr_in = (struct sockaddr_in *)&w->addr; 698 addr_in->sin_len = w->addrlen; 699 sa_endpoints_t endpoints; 700 endpoints.sae_srcif = 0; 701 endpoints.sae_srcaddr = NULL; 702 endpoints.sae_srcaddrlen = 0; 703 endpoints.sae_dstaddr = (struct sockaddr *)&w->addr; 704 endpoints.sae_dstaddrlen = w->addrlen; 705 if (connectx(s, &endpoints, SAE_ASSOCID_ANY, 706 CONNECT_DATA_IDEMPOTENT | CONNECT_RESUME_ON_READ_WRITE, 707 NULL, 0, NULL, NULL) == -1) { 708 /* if fails, failover to connect for OSX 10.10 */ 709 #ifdef EINPROGRESS 710 if(errno != EINPROGRESS) { 711 #else 712 if(1) { 713 #endif 714 if(connect(s, (struct sockaddr*)&w->addr, w->addrlen) == -1) { 715 #else /* USE_OSX_MSG_FASTOPEN*/ 716 #ifdef USE_MSG_FASTOPEN 717 pend->c->tcp_do_fastopen = 1; 718 /* Only do TFO for TCP in which case no connect() is required here. 719 Don't combine client TFO with SSL, since OpenSSL can't 720 currently support doing a handshake on fd that already isn't connected*/ 721 if (w->outnet->sslctx && w->ssl_upstream) { 722 if(connect(s, (struct sockaddr*)&w->addr, w->addrlen) == -1) { 723 #else /* USE_MSG_FASTOPEN*/ 724 if(connect(s, (struct sockaddr*)&w->addr, w->addrlen) == -1) { 725 #endif /* USE_MSG_FASTOPEN*/ 726 #endif /* USE_OSX_MSG_FASTOPEN*/ 727 #ifndef USE_WINSOCK 728 #ifdef EINPROGRESS 729 if(errno != EINPROGRESS) { 730 #else 731 if(1) { 732 #endif 733 if(tcp_connect_errno_needs_log( 734 (struct sockaddr*)&w->addr, w->addrlen)) 735 log_err_addr("outgoing tcp: connect", 736 strerror(errno), &w->addr, w->addrlen); 737 close(s); 738 #else /* USE_WINSOCK */ 739 if(WSAGetLastError() != WSAEINPROGRESS && 740 WSAGetLastError() != WSAEWOULDBLOCK) { 741 closesocket(s); 742 #endif 743 return 0; 744 } 745 } 746 #ifdef USE_MSG_FASTOPEN 747 } 748 #endif /* USE_MSG_FASTOPEN */ 749 #ifdef USE_OSX_MSG_FASTOPEN 750 } 751 } 752 #endif /* USE_OSX_MSG_FASTOPEN */ 753 if(w->outnet->sslctx && w->ssl_upstream) { 754 pend->c->ssl = outgoing_ssl_fd(w->outnet->sslctx, s); 755 if(!pend->c->ssl) { 756 pend->c->fd = s; 757 comm_point_close(pend->c); 758 return 0; 759 } 760 verbose(VERB_ALGO, "the query is using TLS encryption, for %s", 761 (w->tls_auth_name?w->tls_auth_name:"an unauthenticated connection")); 762 #ifdef USE_WINSOCK 763 comm_point_tcp_win_bio_cb(pend->c, pend->c->ssl); 764 #endif 765 pend->c->ssl_shake_state = comm_ssl_shake_write; 766 if(w->tls_auth_name) { 767 /* strdup the auth name, while not linked the list yet, 768 * in case of failure, easy cleanup. */ 769 tls_auth_name = strdup(w->tls_auth_name); 770 if(!tls_auth_name) { 771 log_err("out of memory: alloc tls auth name"); 772 pend->c->fd = s; 773 #ifdef HAVE_SSL 774 SSL_free(pend->c->ssl); 775 #endif 776 pend->c->ssl = NULL; 777 comm_point_close(pend->c); 778 return 0; 779 } 780 } 781 if(!set_auth_name_on_ssl(pend->c->ssl, tls_auth_name, 782 w->outnet->tls_use_sni)) { 783 pend->c->fd = s; 784 #ifdef HAVE_SSL 785 SSL_free(pend->c->ssl); 786 #endif 787 pend->c->ssl = NULL; 788 comm_point_close(pend->c); 789 free(tls_auth_name); 790 return 0; 791 } 792 } 793 w->next_waiting = (void*)pend; 794 w->outnet->num_tcp_outgoing++; 795 w->outnet->tcp_free = pend->next_free; 796 pend->next_free = NULL; 797 pend->query = w; 798 pend->reuse.outnet = w->outnet; 799 pend->c->repinfo.remote_addrlen = w->addrlen; 800 pend->c->tcp_more_read_again = &pend->reuse.cp_more_read_again; 801 pend->c->tcp_more_write_again = &pend->reuse.cp_more_write_again; 802 pend->reuse.cp_more_read_again = 0; 803 pend->reuse.cp_more_write_again = 0; 804 memcpy(&pend->c->repinfo.remote_addr, &w->addr, w->addrlen); 805 pend->reuse.pending = pend; 806 807 /* Remove from tree in case the is_ssl will be different and causes the 808 * identity of the reuse_tcp to change; could result in nodes not being 809 * deleted from the tree (because the new identity does not match the 810 * previous node) but their ->key would be changed to NULL. */ 811 if(pend->reuse.node.key) 812 reuse_tcp_remove_tree_list(w->outnet, &pend->reuse); 813 814 if(pend->c->ssl) { 815 pend->reuse.is_ssl = 1; 816 if(pend->reuse.tls_auth_name) 817 free(pend->reuse.tls_auth_name); 818 pend->reuse.tls_auth_name = tls_auth_name; 819 tls_auth_name = NULL; 820 } else { 821 pend->reuse.is_ssl = 0; 822 if(pend->reuse.tls_auth_name) 823 free(pend->reuse.tls_auth_name); 824 pend->reuse.tls_auth_name = NULL; 825 } 826 /* free tls auth name if nonNULL */ 827 free(tls_auth_name); 828 /* insert in reuse by address tree if not already inserted there */ 829 (void)reuse_tcp_insert(w->outnet, pend); 830 reuse_tree_by_id_insert(&pend->reuse, w); 831 outnet_tcp_take_query_setup(s, pend, w); 832 return 1; 833 } 834 835 /** Touch the lru of a reuse_tcp element, it is in use. 836 * This moves it to the front of the list, where it is not likely to 837 * be closed. Items at the back of the list are closed to make space. */ 838 void 839 reuse_tcp_lru_touch(struct outside_network* outnet, struct reuse_tcp* reuse) 840 { 841 if(!reuse->item_on_lru_list) { 842 log_err("internal error: we need to touch the lru_list but item not in list"); 843 return; /* not on the list, no lru to modify */ 844 } 845 log_assert(reuse->lru_prev || 846 (!reuse->lru_prev && outnet->tcp_reuse_first == reuse)); 847 if(!reuse->lru_prev) 848 return; /* already first in the list */ 849 /* remove at current position */ 850 /* since it is not first, there is a previous element */ 851 reuse->lru_prev->lru_next = reuse->lru_next; 852 log_assert(reuse->lru_prev->lru_next != reuse->lru_prev); 853 if(reuse->lru_next) 854 reuse->lru_next->lru_prev = reuse->lru_prev; 855 else outnet->tcp_reuse_last = reuse->lru_prev; 856 log_assert(!reuse->lru_next || reuse->lru_next->lru_prev != reuse->lru_next); 857 log_assert(outnet->tcp_reuse_last != outnet->tcp_reuse_last->lru_next && 858 outnet->tcp_reuse_last != outnet->tcp_reuse_last->lru_prev); 859 /* insert at the front */ 860 reuse->lru_prev = NULL; 861 reuse->lru_next = outnet->tcp_reuse_first; 862 if(outnet->tcp_reuse_first) { 863 outnet->tcp_reuse_first->lru_prev = reuse; 864 } 865 log_assert(reuse->lru_next != reuse); 866 /* since it is not first, it is not the only element and 867 * lru_next is thus not NULL and thus reuse is now not the last in 868 * the list, so outnet->tcp_reuse_last does not need to be modified */ 869 outnet->tcp_reuse_first = reuse; 870 log_assert(outnet->tcp_reuse_first != outnet->tcp_reuse_first->lru_next && 871 outnet->tcp_reuse_first != outnet->tcp_reuse_first->lru_prev); 872 log_assert((!outnet->tcp_reuse_first && !outnet->tcp_reuse_last) || 873 (outnet->tcp_reuse_first && outnet->tcp_reuse_last)); 874 } 875 876 /** Snip the last reuse_tcp element off of the LRU list */ 877 struct reuse_tcp* 878 reuse_tcp_lru_snip(struct outside_network* outnet) 879 { 880 struct reuse_tcp* reuse = outnet->tcp_reuse_last; 881 if(!reuse) return NULL; 882 /* snip off of LRU */ 883 log_assert(reuse->lru_next == NULL); 884 if(reuse->lru_prev) { 885 outnet->tcp_reuse_last = reuse->lru_prev; 886 reuse->lru_prev->lru_next = NULL; 887 } else { 888 outnet->tcp_reuse_last = NULL; 889 outnet->tcp_reuse_first = NULL; 890 } 891 log_assert((!outnet->tcp_reuse_first && !outnet->tcp_reuse_last) || 892 (outnet->tcp_reuse_first && outnet->tcp_reuse_last)); 893 reuse->item_on_lru_list = 0; 894 reuse->lru_next = NULL; 895 reuse->lru_prev = NULL; 896 return reuse; 897 } 898 899 /** remove waiting tcp from the outnet waiting list */ 900 void 901 outnet_waiting_tcp_list_remove(struct outside_network* outnet, struct waiting_tcp* w) 902 { 903 struct waiting_tcp* p = outnet->tcp_wait_first, *prev = NULL; 904 w->on_tcp_waiting_list = 0; 905 while(p) { 906 if(p == w) { 907 /* remove w */ 908 if(prev) 909 prev->next_waiting = w->next_waiting; 910 else outnet->tcp_wait_first = w->next_waiting; 911 if(outnet->tcp_wait_last == w) 912 outnet->tcp_wait_last = prev; 913 w->next_waiting = NULL; 914 return; 915 } 916 prev = p; 917 p = p->next_waiting; 918 } 919 /* outnet_waiting_tcp_list_remove is currently called only with items 920 * that are already in the waiting list. */ 921 log_assert(0); 922 } 923 924 /** pop the first waiting tcp from the outnet waiting list */ 925 struct waiting_tcp* 926 outnet_waiting_tcp_list_pop(struct outside_network* outnet) 927 { 928 struct waiting_tcp* w = outnet->tcp_wait_first; 929 if(!outnet->tcp_wait_first) return NULL; 930 log_assert(w->on_tcp_waiting_list); 931 outnet->tcp_wait_first = w->next_waiting; 932 if(outnet->tcp_wait_last == w) 933 outnet->tcp_wait_last = NULL; 934 w->on_tcp_waiting_list = 0; 935 w->next_waiting = NULL; 936 return w; 937 } 938 939 /** add waiting_tcp element to the outnet tcp waiting list */ 940 void 941 outnet_waiting_tcp_list_add(struct outside_network* outnet, 942 struct waiting_tcp* w, int set_timer) 943 { 944 struct timeval tv; 945 log_assert(!w->on_tcp_waiting_list); 946 if(w->on_tcp_waiting_list) 947 return; 948 w->next_waiting = NULL; 949 if(outnet->tcp_wait_last) 950 outnet->tcp_wait_last->next_waiting = w; 951 else outnet->tcp_wait_first = w; 952 outnet->tcp_wait_last = w; 953 w->on_tcp_waiting_list = 1; 954 if(set_timer) { 955 #ifndef S_SPLINT_S 956 tv.tv_sec = w->timeout/1000; 957 tv.tv_usec = (w->timeout%1000)*1000; 958 #endif 959 comm_timer_set(w->timer, &tv); 960 } 961 } 962 963 /** add waiting_tcp element as first to the outnet tcp waiting list */ 964 void 965 outnet_waiting_tcp_list_add_first(struct outside_network* outnet, 966 struct waiting_tcp* w, int reset_timer) 967 { 968 struct timeval tv; 969 log_assert(!w->on_tcp_waiting_list); 970 if(w->on_tcp_waiting_list) 971 return; 972 w->next_waiting = outnet->tcp_wait_first; 973 log_assert(w->next_waiting != w); 974 if(!outnet->tcp_wait_last) 975 outnet->tcp_wait_last = w; 976 outnet->tcp_wait_first = w; 977 w->on_tcp_waiting_list = 1; 978 if(reset_timer) { 979 #ifndef S_SPLINT_S 980 tv.tv_sec = w->timeout/1000; 981 tv.tv_usec = (w->timeout%1000)*1000; 982 #endif 983 comm_timer_set(w->timer, &tv); 984 } 985 log_assert( 986 (!outnet->tcp_reuse_first && !outnet->tcp_reuse_last) || 987 (outnet->tcp_reuse_first && outnet->tcp_reuse_last)); 988 } 989 990 /** call callback on waiting_tcp, if not NULL */ 991 static void 992 waiting_tcp_callback(struct waiting_tcp* w, struct comm_point* c, int error, 993 struct comm_reply* reply_info) 994 { 995 if(w && w->cb) { 996 fptr_ok(fptr_whitelist_pending_tcp(w->cb)); 997 (void)(*w->cb)(c, w->cb_arg, error, reply_info); 998 } 999 } 1000 1001 /** see if buffers can be used to service TCP queries */ 1002 static void 1003 use_free_buffer(struct outside_network* outnet) 1004 { 1005 struct waiting_tcp* w; 1006 while(outnet->tcp_wait_first && !outnet->want_to_quit) { 1007 #ifdef USE_DNSTAP 1008 struct pending_tcp* pend_tcp = NULL; 1009 #endif 1010 struct reuse_tcp* reuse = NULL; 1011 w = outnet_waiting_tcp_list_pop(outnet); 1012 log_assert( 1013 (!outnet->tcp_reuse_first && !outnet->tcp_reuse_last) || 1014 (outnet->tcp_reuse_first && outnet->tcp_reuse_last)); 1015 reuse = reuse_tcp_find(outnet, &w->addr, w->addrlen, 1016 w->ssl_upstream, w->tls_auth_name); 1017 /* re-select an ID when moving to a new TCP buffer */ 1018 w->id = tcp_select_id(outnet, reuse); 1019 LDNS_ID_SET(w->pkt, w->id); 1020 if(reuse) { 1021 log_reuse_tcp(VERB_CLIENT, "use free buffer for waiting tcp: " 1022 "found reuse", reuse); 1023 #ifdef USE_DNSTAP 1024 pend_tcp = reuse->pending; 1025 #endif 1026 reuse_tcp_lru_touch(outnet, reuse); 1027 comm_timer_disable(w->timer); 1028 w->next_waiting = (void*)reuse->pending; 1029 reuse_tree_by_id_insert(reuse, w); 1030 if(reuse->pending->query) { 1031 /* on the write wait list */ 1032 reuse_write_wait_push_back(reuse, w); 1033 } else { 1034 /* write straight away */ 1035 /* stop the timer on read of the fd */ 1036 comm_point_stop_listening(reuse->pending->c); 1037 reuse->pending->query = w; 1038 outnet_tcp_take_query_setup( 1039 reuse->pending->c->fd, reuse->pending, 1040 w); 1041 } 1042 } else if(outnet->tcp_free) { 1043 struct pending_tcp* pend = w->outnet->tcp_free; 1044 rbtree_init(&pend->reuse.tree_by_id, reuse_id_cmp); 1045 pend->reuse.pending = pend; 1046 memcpy(&pend->reuse.addr, &w->addr, w->addrlen); 1047 pend->reuse.addrlen = w->addrlen; 1048 if(!outnet_tcp_take_into_use(w)) { 1049 waiting_tcp_callback(w, NULL, NETEVENT_CLOSED, 1050 NULL); 1051 waiting_tcp_delete(w); 1052 #ifdef USE_DNSTAP 1053 w = NULL; 1054 #endif 1055 } 1056 #ifdef USE_DNSTAP 1057 pend_tcp = pend; 1058 #endif 1059 } else { 1060 /* no reuse and no free buffer, put back at the start */ 1061 outnet_waiting_tcp_list_add_first(outnet, w, 0); 1062 break; 1063 } 1064 #ifdef USE_DNSTAP 1065 if(outnet->dtenv && pend_tcp && w && w->sq && 1066 (outnet->dtenv->log_resolver_query_messages || 1067 outnet->dtenv->log_forwarder_query_messages)) { 1068 sldns_buffer tmp; 1069 sldns_buffer_init_frm_data(&tmp, w->pkt, w->pkt_len); 1070 dt_msg_send_outside_query(outnet->dtenv, &w->sq->addr, 1071 &pend_tcp->pi->addr, comm_tcp, NULL, w->sq->zone, 1072 w->sq->zonelen, &tmp); 1073 } 1074 #endif 1075 } 1076 } 1077 1078 /** delete element from tree by id */ 1079 static void 1080 reuse_tree_by_id_delete(struct reuse_tcp* reuse, struct waiting_tcp* w) 1081 { 1082 #ifdef UNBOUND_DEBUG 1083 rbnode_type* rem; 1084 #endif 1085 log_assert(w->id_node.key != NULL); 1086 #ifdef UNBOUND_DEBUG 1087 rem = 1088 #else 1089 (void) 1090 #endif 1091 rbtree_delete(&reuse->tree_by_id, w); 1092 log_assert(rem); /* should have been there */ 1093 w->id_node.key = NULL; 1094 } 1095 1096 /** move writewait list to go for another connection. */ 1097 static void 1098 reuse_move_writewait_away(struct outside_network* outnet, 1099 struct pending_tcp* pend) 1100 { 1101 /* the writewait list has not been written yet, so if the 1102 * stream was closed, they have not actually been failed, only 1103 * the queries written. Other queries can get written to another 1104 * stream. For upstreams that do not support multiple queries 1105 * and answers, the stream can get closed, and then the queries 1106 * can get written on a new socket */ 1107 struct waiting_tcp* w; 1108 if(pend->query && pend->query->error_count == 0 && 1109 pend->c->tcp_write_pkt == pend->query->pkt && 1110 pend->c->tcp_write_pkt_len == pend->query->pkt_len) { 1111 /* since the current query is not written, it can also 1112 * move to a free buffer */ 1113 if(verbosity >= VERB_CLIENT && pend->query->pkt_len > 12+2+2 && 1114 LDNS_QDCOUNT(pend->query->pkt) > 0 && 1115 dname_valid(pend->query->pkt+12, pend->query->pkt_len-12)) { 1116 char buf[LDNS_MAX_DOMAINLEN]; 1117 dname_str(pend->query->pkt+12, buf); 1118 verbose(VERB_CLIENT, "reuse_move_writewait_away current %s %d bytes were written", 1119 buf, (int)pend->c->tcp_write_byte_count); 1120 } 1121 pend->c->tcp_write_pkt = NULL; 1122 pend->c->tcp_write_pkt_len = 0; 1123 pend->c->tcp_write_and_read = 0; 1124 pend->reuse.cp_more_read_again = 0; 1125 pend->reuse.cp_more_write_again = 0; 1126 pend->c->tcp_is_reading = 1; 1127 w = pend->query; 1128 pend->query = NULL; 1129 /* increase error count, so that if the next socket fails too 1130 * the server selection is run again with this query failed 1131 * and it can select a different server (if possible), or 1132 * fail the query */ 1133 w->error_count ++; 1134 reuse_tree_by_id_delete(&pend->reuse, w); 1135 outnet_waiting_tcp_list_add(outnet, w, 1); 1136 } 1137 while((w = reuse_write_wait_pop(&pend->reuse)) != NULL) { 1138 if(verbosity >= VERB_CLIENT && w->pkt_len > 12+2+2 && 1139 LDNS_QDCOUNT(w->pkt) > 0 && 1140 dname_valid(w->pkt+12, w->pkt_len-12)) { 1141 char buf[LDNS_MAX_DOMAINLEN]; 1142 dname_str(w->pkt+12, buf); 1143 verbose(VERB_CLIENT, "reuse_move_writewait_away item %s", buf); 1144 } 1145 reuse_tree_by_id_delete(&pend->reuse, w); 1146 outnet_waiting_tcp_list_add(outnet, w, 1); 1147 } 1148 } 1149 1150 /** remove reused element from tree and lru list */ 1151 void 1152 reuse_tcp_remove_tree_list(struct outside_network* outnet, 1153 struct reuse_tcp* reuse) 1154 { 1155 verbose(VERB_CLIENT, "reuse_tcp_remove_tree_list"); 1156 if(reuse->node.key) { 1157 /* delete it from reuse tree */ 1158 if(!rbtree_delete(&outnet->tcp_reuse, reuse)) { 1159 /* should not be possible, it should be there */ 1160 char buf[256]; 1161 addr_to_str(&reuse->addr, reuse->addrlen, buf, 1162 sizeof(buf)); 1163 log_err("reuse tcp delete: node not present, internal error, %s ssl %d lru %d", buf, reuse->is_ssl, reuse->item_on_lru_list); 1164 } 1165 reuse->node.key = NULL; 1166 /* defend against loops on broken tree by zeroing the 1167 * rbnode structure */ 1168 memset(&reuse->node, 0, sizeof(reuse->node)); 1169 } 1170 /* delete from reuse list */ 1171 if(reuse->item_on_lru_list) { 1172 if(reuse->lru_prev) { 1173 /* assert that members of the lru list are waiting 1174 * and thus have a pending pointer to the struct */ 1175 log_assert(reuse->lru_prev->pending); 1176 reuse->lru_prev->lru_next = reuse->lru_next; 1177 log_assert(reuse->lru_prev->lru_next != reuse->lru_prev); 1178 } else { 1179 log_assert(!reuse->lru_next || reuse->lru_next->pending); 1180 outnet->tcp_reuse_first = reuse->lru_next; 1181 log_assert(!outnet->tcp_reuse_first || 1182 (outnet->tcp_reuse_first != 1183 outnet->tcp_reuse_first->lru_next && 1184 outnet->tcp_reuse_first != 1185 outnet->tcp_reuse_first->lru_prev)); 1186 } 1187 if(reuse->lru_next) { 1188 /* assert that members of the lru list are waiting 1189 * and thus have a pending pointer to the struct */ 1190 log_assert(reuse->lru_next->pending); 1191 reuse->lru_next->lru_prev = reuse->lru_prev; 1192 log_assert(reuse->lru_next->lru_prev != reuse->lru_next); 1193 } else { 1194 log_assert(!reuse->lru_prev || reuse->lru_prev->pending); 1195 outnet->tcp_reuse_last = reuse->lru_prev; 1196 log_assert(!outnet->tcp_reuse_last || 1197 (outnet->tcp_reuse_last != 1198 outnet->tcp_reuse_last->lru_next && 1199 outnet->tcp_reuse_last != 1200 outnet->tcp_reuse_last->lru_prev)); 1201 } 1202 log_assert((!outnet->tcp_reuse_first && !outnet->tcp_reuse_last) || 1203 (outnet->tcp_reuse_first && outnet->tcp_reuse_last)); 1204 reuse->item_on_lru_list = 0; 1205 reuse->lru_next = NULL; 1206 reuse->lru_prev = NULL; 1207 } 1208 reuse->pending = NULL; 1209 } 1210 1211 /** helper function that deletes an element from the tree of readwait 1212 * elements in tcp reuse structure */ 1213 static void reuse_del_readwait_elem(rbnode_type* node, void* ATTR_UNUSED(arg)) 1214 { 1215 struct waiting_tcp* w = (struct waiting_tcp*)node->key; 1216 waiting_tcp_delete(w); 1217 } 1218 1219 /** delete readwait waiting_tcp elements, deletes the elements in the list */ 1220 void reuse_del_readwait(rbtree_type* tree_by_id) 1221 { 1222 if(tree_by_id->root == NULL || 1223 tree_by_id->root == RBTREE_NULL) 1224 return; 1225 traverse_postorder(tree_by_id, &reuse_del_readwait_elem, NULL); 1226 rbtree_init(tree_by_id, reuse_id_cmp); 1227 } 1228 1229 /** decommission a tcp buffer, closes commpoint and frees waiting_tcp entry */ 1230 static void 1231 decommission_pending_tcp(struct outside_network* outnet, 1232 struct pending_tcp* pend) 1233 { 1234 verbose(VERB_CLIENT, "decommission_pending_tcp"); 1235 /* A certain code path can lead here twice for the same pending_tcp 1236 * creating a loop in the free pending_tcp list. */ 1237 if(outnet->tcp_free != pend) { 1238 pend->next_free = outnet->tcp_free; 1239 outnet->tcp_free = pend; 1240 } 1241 if(pend->reuse.node.key) { 1242 /* needs unlink from the reuse tree to get deleted */ 1243 reuse_tcp_remove_tree_list(outnet, &pend->reuse); 1244 } 1245 if(pend->reuse.tls_auth_name) { 1246 free(pend->reuse.tls_auth_name); 1247 pend->reuse.tls_auth_name = NULL; 1248 } 1249 /* free SSL structure after remove from outnet tcp reuse tree, 1250 * because the c->ssl null or not is used for sorting in the tree */ 1251 if(pend->c->ssl) { 1252 #ifdef HAVE_SSL 1253 SSL_shutdown(pend->c->ssl); 1254 SSL_free(pend->c->ssl); 1255 pend->c->ssl = NULL; 1256 #endif 1257 } 1258 comm_point_close(pend->c); 1259 pend->reuse.cp_more_read_again = 0; 1260 pend->reuse.cp_more_write_again = 0; 1261 /* unlink the query and writewait list, it is part of the tree 1262 * nodes and is deleted */ 1263 pend->query = NULL; 1264 pend->reuse.write_wait_first = NULL; 1265 pend->reuse.write_wait_last = NULL; 1266 reuse_del_readwait(&pend->reuse.tree_by_id); 1267 } 1268 1269 /** perform failure callbacks for waiting queries in reuse read rbtree */ 1270 static void reuse_cb_readwait_for_failure(rbtree_type* tree_by_id, int err) 1271 { 1272 rbnode_type* node; 1273 if(tree_by_id->root == NULL || 1274 tree_by_id->root == RBTREE_NULL) 1275 return; 1276 node = rbtree_first(tree_by_id); 1277 while(node && node != RBTREE_NULL) { 1278 struct waiting_tcp* w = (struct waiting_tcp*)node->key; 1279 waiting_tcp_callback(w, NULL, err, NULL); 1280 node = rbtree_next(node); 1281 } 1282 } 1283 1284 /** mark the entry for being in the cb_and_decommission stage */ 1285 static void mark_for_cb_and_decommission(rbnode_type* node, 1286 void* ATTR_UNUSED(arg)) 1287 { 1288 struct waiting_tcp* w = (struct waiting_tcp*)node->key; 1289 /* Mark the waiting_tcp to signal later code (serviced_delete) that 1290 * this item is part of the backed up tree_by_id and will be deleted 1291 * later. */ 1292 w->in_cb_and_decommission = 1; 1293 /* Mark the serviced_query for deletion so that later code through 1294 * callbacks (iter_clear .. outnet_serviced_query_stop) won't 1295 * prematurely delete it. */ 1296 if(w->cb) 1297 ((struct serviced_query*)w->cb_arg)->to_be_deleted = 1; 1298 } 1299 1300 /** perform callbacks for failure and also decommission pending tcp. 1301 * the callbacks remove references in sq->pending to the waiting_tcp 1302 * members of the tree_by_id in the pending tcp. The pending_tcp is 1303 * removed before the callbacks, so that the callbacks do not modify 1304 * the pending_tcp due to its reference in the outside_network reuse tree */ 1305 static void reuse_cb_and_decommission(struct outside_network* outnet, 1306 struct pending_tcp* pend, int error) 1307 { 1308 rbtree_type store; 1309 store = pend->reuse.tree_by_id; 1310 pend->query = NULL; 1311 rbtree_init(&pend->reuse.tree_by_id, reuse_id_cmp); 1312 pend->reuse.write_wait_first = NULL; 1313 pend->reuse.write_wait_last = NULL; 1314 decommission_pending_tcp(outnet, pend); 1315 if(store.root != NULL && store.root != RBTREE_NULL) { 1316 traverse_postorder(&store, &mark_for_cb_and_decommission, NULL); 1317 } 1318 reuse_cb_readwait_for_failure(&store, error); 1319 reuse_del_readwait(&store); 1320 } 1321 1322 /** set timeout on tcp fd and setup read event to catch incoming dns msgs */ 1323 static void 1324 reuse_tcp_setup_timeout(struct pending_tcp* pend_tcp, int tcp_reuse_timeout) 1325 { 1326 log_reuse_tcp(VERB_CLIENT, "reuse_tcp_setup_timeout", &pend_tcp->reuse); 1327 comm_point_start_listening(pend_tcp->c, -1, tcp_reuse_timeout); 1328 } 1329 1330 /** set timeout on tcp fd and setup read event to catch incoming dns msgs */ 1331 static void 1332 reuse_tcp_setup_read_and_timeout(struct pending_tcp* pend_tcp, int tcp_reuse_timeout) 1333 { 1334 log_reuse_tcp(VERB_CLIENT, "reuse_tcp_setup_readtimeout", &pend_tcp->reuse); 1335 sldns_buffer_clear(pend_tcp->c->buffer); 1336 pend_tcp->c->tcp_is_reading = 1; 1337 pend_tcp->c->tcp_byte_count = 0; 1338 comm_point_stop_listening(pend_tcp->c); 1339 comm_point_start_listening(pend_tcp->c, -1, tcp_reuse_timeout); 1340 } 1341 1342 int 1343 outnet_tcp_cb(struct comm_point* c, void* arg, int error, 1344 struct comm_reply *reply_info) 1345 { 1346 struct pending_tcp* pend = (struct pending_tcp*)arg; 1347 struct outside_network* outnet = pend->reuse.outnet; 1348 struct waiting_tcp* w = NULL; 1349 log_assert(pend->reuse.item_on_lru_list && pend->reuse.node.key); 1350 verbose(VERB_ALGO, "outnettcp cb"); 1351 if(error == NETEVENT_TIMEOUT) { 1352 if(pend->c->tcp_write_and_read) { 1353 verbose(VERB_QUERY, "outnettcp got tcp timeout " 1354 "for read, ignored because write underway"); 1355 /* if we are writing, ignore readtimer, wait for write timer 1356 * or write is done */ 1357 return 0; 1358 } else { 1359 verbose(VERB_QUERY, "outnettcp got tcp timeout %s", 1360 (pend->reuse.tree_by_id.count?"for reading pkt": 1361 "for keepalive for reuse")); 1362 } 1363 /* must be timeout for reading or keepalive reuse, 1364 * close it. */ 1365 reuse_tcp_remove_tree_list(outnet, &pend->reuse); 1366 } else if(error == NETEVENT_PKT_WRITTEN) { 1367 /* the packet we want to write has been written. */ 1368 verbose(VERB_ALGO, "outnet tcp pkt was written event"); 1369 log_assert(c == pend->c); 1370 log_assert(pend->query->pkt == pend->c->tcp_write_pkt); 1371 log_assert(pend->query->pkt_len == pend->c->tcp_write_pkt_len); 1372 pend->c->tcp_write_pkt = NULL; 1373 pend->c->tcp_write_pkt_len = 0; 1374 /* the pend.query is already in tree_by_id */ 1375 log_assert(pend->query->id_node.key); 1376 pend->query = NULL; 1377 /* setup to write next packet or setup read timeout */ 1378 if(pend->reuse.write_wait_first) { 1379 verbose(VERB_ALGO, "outnet tcp setup next pkt"); 1380 /* we can write it straight away perhaps, set flag 1381 * because this callback called after a tcp write 1382 * succeeded and likely more buffer space is available 1383 * and we can write some more. */ 1384 pend->reuse.cp_more_write_again = 1; 1385 pend->query = reuse_write_wait_pop(&pend->reuse); 1386 comm_point_stop_listening(pend->c); 1387 outnet_tcp_take_query_setup(pend->c->fd, pend, 1388 pend->query); 1389 } else { 1390 verbose(VERB_ALGO, "outnet tcp writes done, wait"); 1391 pend->c->tcp_write_and_read = 0; 1392 pend->reuse.cp_more_read_again = 0; 1393 pend->reuse.cp_more_write_again = 0; 1394 pend->c->tcp_is_reading = 1; 1395 comm_point_stop_listening(pend->c); 1396 reuse_tcp_setup_timeout(pend, outnet->tcp_reuse_timeout); 1397 } 1398 return 0; 1399 } else if(error != NETEVENT_NOERROR) { 1400 verbose(VERB_QUERY, "outnettcp got tcp error %d", error); 1401 reuse_move_writewait_away(outnet, pend); 1402 /* pass error below and exit */ 1403 } else { 1404 /* check ID */ 1405 if(sldns_buffer_limit(c->buffer) < sizeof(uint16_t)) { 1406 log_addr(VERB_QUERY, 1407 "outnettcp: bad ID in reply, too short, from:", 1408 &pend->reuse.addr, pend->reuse.addrlen); 1409 error = NETEVENT_CLOSED; 1410 } else { 1411 uint16_t id = LDNS_ID_WIRE(sldns_buffer_begin( 1412 c->buffer)); 1413 /* find the query the reply is for */ 1414 w = reuse_tcp_by_id_find(&pend->reuse, id); 1415 /* Make sure that the reply we got is at least for a 1416 * sent query with the same ID; the waiting_tcp that 1417 * gets a reply is assumed to not be waiting to be 1418 * sent. */ 1419 if(w && (w->on_tcp_waiting_list || w->write_wait_queued)) 1420 w = NULL; 1421 } 1422 } 1423 if(error == NETEVENT_NOERROR && !w) { 1424 /* no struct waiting found in tree, no reply to call */ 1425 log_addr(VERB_QUERY, "outnettcp: bad ID in reply, from:", 1426 &pend->reuse.addr, pend->reuse.addrlen); 1427 error = NETEVENT_CLOSED; 1428 } 1429 if(error == NETEVENT_NOERROR) { 1430 /* add to reuse tree so it can be reused, if not a failure. 1431 * This is possible if the state machine wants to make a tcp 1432 * query again to the same destination. */ 1433 if(outnet->tcp_reuse.count < outnet->tcp_reuse_max) { 1434 (void)reuse_tcp_insert(outnet, pend); 1435 } 1436 } 1437 if(w) { 1438 log_assert(!w->on_tcp_waiting_list); 1439 log_assert(!w->write_wait_queued); 1440 reuse_tree_by_id_delete(&pend->reuse, w); 1441 verbose(VERB_CLIENT, "outnet tcp callback query err %d buflen %d", 1442 error, (int)sldns_buffer_limit(c->buffer)); 1443 waiting_tcp_callback(w, c, error, reply_info); 1444 waiting_tcp_delete(w); 1445 } 1446 verbose(VERB_CLIENT, "outnet_tcp_cb reuse after cb"); 1447 if(error == NETEVENT_NOERROR && pend->reuse.node.key) { 1448 verbose(VERB_CLIENT, "outnet_tcp_cb reuse after cb: keep it"); 1449 /* it is in the reuse_tcp tree, with other queries, or 1450 * on the empty list. do not decommission it */ 1451 /* if there are more outstanding queries, we could try to 1452 * read again, to see if it is on the input, 1453 * because this callback called after a successful read 1454 * and there could be more bytes to read on the input */ 1455 if(pend->reuse.tree_by_id.count != 0) 1456 pend->reuse.cp_more_read_again = 1; 1457 reuse_tcp_setup_read_and_timeout(pend, outnet->tcp_reuse_timeout); 1458 return 0; 1459 } 1460 verbose(VERB_CLIENT, "outnet_tcp_cb reuse after cb: decommission it"); 1461 /* no queries on it, no space to keep it. or timeout or closed due 1462 * to error. Close it */ 1463 reuse_cb_and_decommission(outnet, pend, (error==NETEVENT_TIMEOUT? 1464 NETEVENT_TIMEOUT:NETEVENT_CLOSED)); 1465 use_free_buffer(outnet); 1466 return 0; 1467 } 1468 1469 /** lower use count on pc, see if it can be closed */ 1470 static void 1471 portcomm_loweruse(struct outside_network* outnet, struct port_comm* pc) 1472 { 1473 struct port_if* pif; 1474 pc->num_outstanding--; 1475 if(pc->num_outstanding > 0) { 1476 return; 1477 } 1478 /* close it and replace in unused list */ 1479 verbose(VERB_ALGO, "close of port %d", pc->number); 1480 comm_point_close(pc->cp); 1481 pif = pc->pif; 1482 log_assert(pif->inuse > 0); 1483 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 1484 shared_ports_return_port(outnet->shared_ports, pif->shpif, pc->number); 1485 #endif 1486 pif->inuse--; 1487 pif->out[pc->index] = pif->out[pif->inuse]; 1488 pif->out[pc->index]->index = pc->index; 1489 pc->next = outnet->unused_fds; 1490 outnet->unused_fds = pc; 1491 } 1492 1493 /** try to send waiting UDP queries */ 1494 static void 1495 outnet_send_wait_udp(struct outside_network* outnet) 1496 { 1497 struct pending* pend; 1498 /* process waiting queries */ 1499 while(outnet->udp_wait_first && outnet->unused_fds 1500 && !outnet->want_to_quit) { 1501 pend = outnet->udp_wait_first; 1502 outnet->udp_wait_first = pend->next_waiting; 1503 if(!pend->next_waiting) outnet->udp_wait_last = NULL; 1504 sldns_buffer_clear(outnet->udp_buff); 1505 sldns_buffer_write(outnet->udp_buff, pend->pkt, pend->pkt_len); 1506 sldns_buffer_flip(outnet->udp_buff); 1507 free(pend->pkt); /* freeing now makes get_mem correct */ 1508 pend->pkt = NULL; 1509 pend->pkt_len = 0; 1510 log_assert(!pend->sq->busy); 1511 pend->sq->busy = 1; 1512 if(!randomize_and_send_udp(pend, outnet->udp_buff, 1513 pend->timeout)) { 1514 /* callback error on pending */ 1515 if(pend->cb) { 1516 fptr_ok(fptr_whitelist_pending_udp(pend->cb)); 1517 (void)(*pend->cb)(outnet->unused_fds->cp, pend->cb_arg, 1518 NETEVENT_CLOSED, NULL); 1519 } 1520 pending_delete(outnet, pend); 1521 } else { 1522 pend->sq->busy = 0; 1523 } 1524 } 1525 } 1526 1527 int 1528 outnet_udp_cb(struct comm_point* c, void* arg, int error, 1529 struct comm_reply *reply_info) 1530 { 1531 struct outside_network* outnet = (struct outside_network*)arg; 1532 struct pending key; 1533 struct pending* p; 1534 verbose(VERB_ALGO, "answer cb"); 1535 1536 if(error != NETEVENT_NOERROR) { 1537 verbose(VERB_QUERY, "outnetudp got udp error %d", error); 1538 return 0; 1539 } 1540 if(sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE) { 1541 verbose(VERB_QUERY, "outnetudp udp too short"); 1542 return 0; 1543 } 1544 log_assert(reply_info); 1545 1546 /* setup lookup key */ 1547 key.id = (unsigned)LDNS_ID_WIRE(sldns_buffer_begin(c->buffer)); 1548 memcpy(&key.addr, &reply_info->remote_addr, reply_info->remote_addrlen); 1549 key.addrlen = reply_info->remote_addrlen; 1550 verbose(VERB_ALGO, "Incoming reply id = %4.4x", key.id); 1551 log_addr(VERB_ALGO, "Incoming reply addr =", 1552 &reply_info->remote_addr, reply_info->remote_addrlen); 1553 1554 /* find it, see if this thing is a valid query response */ 1555 verbose(VERB_ALGO, "lookup size is %d entries", (int)outnet->pending->count); 1556 p = (struct pending*)rbtree_search(outnet->pending, &key); 1557 if(!p) { 1558 verbose(VERB_QUERY, "received unwanted or unsolicited udp reply dropped."); 1559 log_buf(VERB_ALGO, "dropped message", c->buffer); 1560 outnet->unwanted_replies++; 1561 if(outnet->unwanted_threshold && ++outnet->unwanted_total 1562 >= outnet->unwanted_threshold) { 1563 log_warn("unwanted reply total reached threshold (%u)" 1564 " you may be under attack." 1565 " defensive action: clearing the cache", 1566 (unsigned)outnet->unwanted_threshold); 1567 fptr_ok(fptr_whitelist_alloc_cleanup( 1568 outnet->unwanted_action)); 1569 (*outnet->unwanted_action)(outnet->unwanted_param); 1570 outnet->unwanted_total = 0; 1571 } 1572 return 0; 1573 } 1574 1575 verbose(VERB_ALGO, "received udp reply."); 1576 log_buf(VERB_ALGO, "udp message", c->buffer); 1577 if(p->pc->cp != c) { 1578 verbose(VERB_QUERY, "received reply id,addr on wrong port. " 1579 "dropped."); 1580 outnet->unwanted_replies++; 1581 if(outnet->unwanted_threshold && ++outnet->unwanted_total 1582 >= outnet->unwanted_threshold) { 1583 log_warn("unwanted reply total reached threshold (%u)" 1584 " you may be under attack." 1585 " defensive action: clearing the cache", 1586 (unsigned)outnet->unwanted_threshold); 1587 fptr_ok(fptr_whitelist_alloc_cleanup( 1588 outnet->unwanted_action)); 1589 (*outnet->unwanted_action)(outnet->unwanted_param); 1590 outnet->unwanted_total = 0; 1591 } 1592 return 0; 1593 } 1594 comm_timer_disable(p->timer); 1595 verbose(VERB_ALGO, "outnet handle udp reply"); 1596 /* delete from tree first in case callback creates a retry */ 1597 (void)rbtree_delete(outnet->pending, p->node.key); 1598 if(p->cb) { 1599 fptr_ok(fptr_whitelist_pending_udp(p->cb)); 1600 (void)(*p->cb)(p->pc->cp, p->cb_arg, NETEVENT_NOERROR, reply_info); 1601 } 1602 portcomm_loweruse(outnet, p->pc); 1603 pending_delete(NULL, p); 1604 outnet_send_wait_udp(outnet); 1605 return 0; 1606 } 1607 1608 /** calculate number of ip4 and ip6 interfaces*/ 1609 static void 1610 calc_num46(char** ifs, int num_ifs, int do_ip4, int do_ip6, 1611 int* num_ip4, int* num_ip6) 1612 { 1613 int i; 1614 *num_ip4 = 0; 1615 *num_ip6 = 0; 1616 if(num_ifs <= 0) { 1617 if(do_ip4) 1618 *num_ip4 = 1; 1619 if(do_ip6) 1620 *num_ip6 = 1; 1621 return; 1622 } 1623 for(i=0; i<num_ifs; i++) 1624 { 1625 if(str_is_ip6(ifs[i])) { 1626 if(do_ip6) 1627 (*num_ip6)++; 1628 } else { 1629 if(do_ip4) 1630 (*num_ip4)++; 1631 } 1632 } 1633 } 1634 1635 void 1636 pending_udp_timer_delay_cb(void* arg) 1637 { 1638 struct pending* p = (struct pending*)arg; 1639 struct outside_network* outnet = p->outnet; 1640 verbose(VERB_ALGO, "timeout udp with delay"); 1641 portcomm_loweruse(outnet, p->pc); 1642 pending_delete(outnet, p); 1643 outnet_send_wait_udp(outnet); 1644 } 1645 1646 void 1647 pending_udp_timer_cb(void *arg) 1648 { 1649 struct pending* p = (struct pending*)arg; 1650 struct outside_network* outnet = p->outnet; 1651 /* it timed out */ 1652 verbose(VERB_ALGO, "timeout udp"); 1653 if(p->cb) { 1654 fptr_ok(fptr_whitelist_pending_udp(p->cb)); 1655 (void)(*p->cb)(p->pc->cp, p->cb_arg, NETEVENT_TIMEOUT, NULL); 1656 } 1657 /* if delayclose, keep port open for a longer time. 1658 * But if the udpwaitlist exists, then we are struggling to 1659 * keep up with demand for sockets, so do not wait, but service 1660 * the customer (customer service more important than portICMPs) */ 1661 if(outnet->delayclose && !outnet->udp_wait_first) { 1662 p->cb = NULL; 1663 p->timer->callback = &pending_udp_timer_delay_cb; 1664 comm_timer_set(p->timer, &outnet->delay_tv); 1665 return; 1666 } 1667 portcomm_loweruse(outnet, p->pc); 1668 pending_delete(outnet, p); 1669 outnet_send_wait_udp(outnet); 1670 } 1671 1672 /** create pending_tcp buffers */ 1673 static int 1674 create_pending_tcp(struct outside_network* outnet, size_t bufsize) 1675 { 1676 size_t i; 1677 if(outnet->num_tcp == 0) 1678 return 1; /* no tcp needed, nothing to do */ 1679 if(!(outnet->tcp_conns = (struct pending_tcp **)calloc( 1680 outnet->num_tcp, sizeof(struct pending_tcp*)))) 1681 return 0; 1682 for(i=0; i<outnet->num_tcp; i++) { 1683 if(!(outnet->tcp_conns[i] = (struct pending_tcp*)calloc(1, 1684 sizeof(struct pending_tcp)))) 1685 return 0; 1686 outnet->tcp_conns[i]->next_free = outnet->tcp_free; 1687 outnet->tcp_free = outnet->tcp_conns[i]; 1688 outnet->tcp_conns[i]->c = comm_point_create_tcp_out( 1689 outnet->base, bufsize, outnet_tcp_cb, 1690 outnet->tcp_conns[i]); 1691 if(!outnet->tcp_conns[i]->c) 1692 return 0; 1693 } 1694 return 1; 1695 } 1696 1697 /** setup an outgoing interface, ready address */ 1698 static int setup_if(struct port_if* pif, const char* addrstr, size_t numfd, 1699 struct shared_ports* shp) 1700 { 1701 if(!ipstrtoaddr(addrstr, UNBOUND_DNS_PORT, &pif->addr, &pif->addrlen) && 1702 !netblockstrtoaddr(addrstr, UNBOUND_DNS_PORT, 1703 &pif->addr, &pif->addrlen, &pif->pfxlen)) 1704 return 0; 1705 #ifdef INT_MAX 1706 if(numfd > (size_t)INT_MAX) { 1707 log_err("num_ports exceeds INT_MAX"); 1708 return 0; 1709 } 1710 #endif 1711 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 1712 pif->shpif = shared_ports_find_if(shp, &pif->addr, pif->addrlen, 1713 pif->pfxlen); 1714 #else 1715 (void)shp; 1716 #endif 1717 pif->maxout = (int)numfd; 1718 pif->inuse = 0; 1719 pif->out = (struct port_comm**)calloc(numfd, 1720 sizeof(struct port_comm*)); 1721 if(!pif->out) 1722 return 0; 1723 return 1; 1724 } 1725 1726 struct outside_network* 1727 outside_network_create(struct comm_base *base, size_t bufsize, 1728 size_t num_ports, char** ifs, int num_ifs, int do_ip4, 1729 int do_ip6, size_t num_tcp, int dscp, struct infra_cache* infra, 1730 struct ub_randstate* rnd, int use_caps_for_id, 1731 size_t unwanted_threshold, int tcp_mss, 1732 void (*unwanted_action)(void*), void* unwanted_param, int do_udp, 1733 void* sslctx, int delayclose, int tls_use_sni, struct dt_env* dtenv, 1734 int udp_connect, int max_reuse_tcp_queries, int tcp_reuse_timeout, 1735 int tcp_auth_query_timeout, struct shared_ports* shared_ports) 1736 { 1737 struct outside_network* outnet = (struct outside_network*) 1738 calloc(1, sizeof(struct outside_network)); 1739 size_t k; 1740 if(!outnet) { 1741 log_err("malloc failed"); 1742 return NULL; 1743 } 1744 comm_base_timept(base, &outnet->now_secs, &outnet->now_tv); 1745 outnet->base = base; 1746 outnet->num_tcp = num_tcp; 1747 outnet->max_reuse_tcp_queries = max_reuse_tcp_queries; 1748 outnet->tcp_reuse_timeout= tcp_reuse_timeout; 1749 outnet->tcp_auth_query_timeout = tcp_auth_query_timeout; 1750 outnet->num_tcp_outgoing = 0; 1751 outnet->num_udp_outgoing = 0; 1752 outnet->infra = infra; 1753 outnet->rnd = rnd; 1754 outnet->sslctx = sslctx; 1755 outnet->tls_use_sni = tls_use_sni; 1756 #ifdef USE_DNSTAP 1757 outnet->dtenv = dtenv; 1758 #else 1759 (void)dtenv; 1760 #endif 1761 outnet->svcd_overhead = 0; 1762 outnet->want_to_quit = 0; 1763 outnet->unwanted_threshold = unwanted_threshold; 1764 outnet->unwanted_action = unwanted_action; 1765 outnet->unwanted_param = unwanted_param; 1766 outnet->use_caps_for_id = use_caps_for_id; 1767 outnet->do_udp = do_udp; 1768 outnet->tcp_mss = tcp_mss; 1769 outnet->ip_dscp = dscp; 1770 outnet->shared_ports = shared_ports; 1771 #ifndef S_SPLINT_S 1772 if(delayclose) { 1773 outnet->delayclose = 1; 1774 outnet->delay_tv.tv_sec = delayclose/1000; 1775 outnet->delay_tv.tv_usec = (delayclose%1000)*1000; 1776 } 1777 #endif 1778 if(udp_connect) { 1779 outnet->udp_connect = 1; 1780 } 1781 if(num_ports == 0) { 1782 log_err("no outgoing ports available"); 1783 outside_network_delete(outnet); 1784 return NULL; 1785 } 1786 #ifdef INT_MAX 1787 if(num_ports > (size_t)INT_MAX) { 1788 log_err("outgoing num_ports exceeds INT_MAX"); 1789 outside_network_delete(outnet); 1790 return NULL; 1791 } 1792 #endif 1793 #ifndef INET6 1794 do_ip6 = 0; 1795 #endif 1796 calc_num46(ifs, num_ifs, do_ip4, do_ip6, 1797 &outnet->num_ip4, &outnet->num_ip6); 1798 if(outnet->num_ip4 != 0) { 1799 if(!(outnet->ip4_ifs = (struct port_if*)calloc( 1800 (size_t)outnet->num_ip4, sizeof(struct port_if)))) { 1801 log_err("malloc failed"); 1802 outside_network_delete(outnet); 1803 return NULL; 1804 } 1805 } 1806 if(outnet->num_ip6 != 0) { 1807 if(!(outnet->ip6_ifs = (struct port_if*)calloc( 1808 (size_t)outnet->num_ip6, sizeof(struct port_if)))) { 1809 log_err("malloc failed"); 1810 outside_network_delete(outnet); 1811 return NULL; 1812 } 1813 } 1814 if( !(outnet->udp_buff = sldns_buffer_new(bufsize)) || 1815 !(outnet->pending = rbtree_create(pending_cmp)) || 1816 !(outnet->serviced = rbtree_create(serviced_cmp)) || 1817 !create_pending_tcp(outnet, bufsize)) { 1818 log_err("malloc failed"); 1819 outside_network_delete(outnet); 1820 return NULL; 1821 } 1822 rbtree_init(&outnet->tcp_reuse, reuse_cmp); 1823 outnet->tcp_reuse_max = num_tcp; 1824 1825 /* allocate commpoints */ 1826 for(k=0; k<num_ports; k++) { 1827 struct port_comm* pc; 1828 pc = (struct port_comm*)calloc(1, sizeof(*pc)); 1829 if(!pc) { 1830 log_err("malloc failed"); 1831 outside_network_delete(outnet); 1832 return NULL; 1833 } 1834 pc->cp = comm_point_create_udp(outnet->base, -1, 1835 outnet->udp_buff, 0, outnet_udp_cb, outnet, NULL); 1836 if(!pc->cp) { 1837 log_err("malloc failed"); 1838 free(pc); 1839 outside_network_delete(outnet); 1840 return NULL; 1841 } 1842 pc->next = outnet->unused_fds; 1843 outnet->unused_fds = pc; 1844 } 1845 1846 /* allocate interfaces */ 1847 if(num_ifs == 0) { 1848 if(do_ip4 && !setup_if(&outnet->ip4_ifs[0], "0.0.0.0", 1849 num_ports, outnet->shared_ports)) { 1850 log_err("malloc failed"); 1851 outside_network_delete(outnet); 1852 return NULL; 1853 } 1854 if(do_ip6 && !setup_if(&outnet->ip6_ifs[0], "::", 1855 num_ports, outnet->shared_ports)) { 1856 log_err("malloc failed"); 1857 outside_network_delete(outnet); 1858 return NULL; 1859 } 1860 } else { 1861 size_t done_4 = 0, done_6 = 0; 1862 int i; 1863 for(i=0; i<num_ifs; i++) { 1864 if(str_is_ip6(ifs[i]) && do_ip6) { 1865 if(!setup_if(&outnet->ip6_ifs[done_6], ifs[i], 1866 num_ports, outnet->shared_ports)){ 1867 log_err("malloc failed"); 1868 outside_network_delete(outnet); 1869 return NULL; 1870 } 1871 done_6++; 1872 } 1873 if(!str_is_ip6(ifs[i]) && do_ip4) { 1874 if(!setup_if(&outnet->ip4_ifs[done_4], ifs[i], 1875 num_ports, outnet->shared_ports)){ 1876 log_err("malloc failed"); 1877 outside_network_delete(outnet); 1878 return NULL; 1879 } 1880 done_4++; 1881 } 1882 } 1883 } 1884 return outnet; 1885 } 1886 1887 /** helper pending delete */ 1888 static void 1889 pending_node_del(rbnode_type* node, void* arg) 1890 { 1891 struct pending* pend = (struct pending*)node; 1892 struct outside_network* outnet = (struct outside_network*)arg; 1893 pending_delete(outnet, pend); 1894 } 1895 1896 /** helper serviced delete */ 1897 static void 1898 serviced_node_del(rbnode_type* node, void* ATTR_UNUSED(arg)) 1899 { 1900 struct serviced_query* sq = (struct serviced_query*)node; 1901 alloc_reg_release(sq->alloc, sq->region); 1902 if(sq->timer) 1903 comm_timer_delete(sq->timer); 1904 free(sq); 1905 } 1906 1907 void 1908 outside_network_quit_prepare(struct outside_network* outnet) 1909 { 1910 if(!outnet) 1911 return; 1912 /* prevent queued items from being sent */ 1913 outnet->want_to_quit = 1; 1914 } 1915 1916 void 1917 outside_network_delete(struct outside_network* outnet) 1918 { 1919 if(!outnet) 1920 return; 1921 outnet->want_to_quit = 1; 1922 /* check every element, since we can be called on malloc error */ 1923 if(outnet->pending) { 1924 /* free pending elements, but do no unlink from tree. */ 1925 traverse_postorder(outnet->pending, pending_node_del, NULL); 1926 free(outnet->pending); 1927 } 1928 if(outnet->serviced) { 1929 traverse_postorder(outnet->serviced, serviced_node_del, NULL); 1930 free(outnet->serviced); 1931 } 1932 if(outnet->udp_buff) 1933 sldns_buffer_free(outnet->udp_buff); 1934 if(outnet->unused_fds) { 1935 struct port_comm* p = outnet->unused_fds, *np; 1936 while(p) { 1937 np = p->next; 1938 comm_point_delete(p->cp); 1939 free(p); 1940 p = np; 1941 } 1942 outnet->unused_fds = NULL; 1943 } 1944 if(outnet->ip4_ifs) { 1945 int i, k; 1946 for(i=0; i<outnet->num_ip4; i++) { 1947 for(k=0; k<outnet->ip4_ifs[i].inuse; k++) { 1948 struct port_comm* pc = outnet->ip4_ifs[i]. 1949 out[k]; 1950 comm_point_delete(pc->cp); 1951 free(pc); 1952 } 1953 free(outnet->ip4_ifs[i].out); 1954 } 1955 free(outnet->ip4_ifs); 1956 } 1957 if(outnet->ip6_ifs) { 1958 int i, k; 1959 for(i=0; i<outnet->num_ip6; i++) { 1960 for(k=0; k<outnet->ip6_ifs[i].inuse; k++) { 1961 struct port_comm* pc = outnet->ip6_ifs[i]. 1962 out[k]; 1963 comm_point_delete(pc->cp); 1964 free(pc); 1965 } 1966 free(outnet->ip6_ifs[i].out); 1967 } 1968 free(outnet->ip6_ifs); 1969 } 1970 if(outnet->tcp_conns) { 1971 size_t i; 1972 for(i=0; i<outnet->num_tcp; i++) 1973 if(outnet->tcp_conns[i]) { 1974 struct pending_tcp* pend; 1975 pend = outnet->tcp_conns[i]; 1976 if(pend->reuse.item_on_lru_list) { 1977 /* delete waiting_tcp elements that 1978 * the tcp conn is working on */ 1979 decommission_pending_tcp(outnet, pend); 1980 } 1981 if(pend->reuse.tls_auth_name) { 1982 free(pend->reuse.tls_auth_name); 1983 pend->reuse.tls_auth_name = NULL; 1984 } 1985 comm_point_delete(outnet->tcp_conns[i]->c); 1986 free(outnet->tcp_conns[i]); 1987 outnet->tcp_conns[i] = NULL; 1988 } 1989 free(outnet->tcp_conns); 1990 outnet->tcp_conns = NULL; 1991 } 1992 if(outnet->tcp_wait_first) { 1993 struct waiting_tcp* p = outnet->tcp_wait_first, *np; 1994 while(p) { 1995 np = p->next_waiting; 1996 waiting_tcp_delete(p); 1997 p = np; 1998 } 1999 } 2000 /* was allocated in struct pending that was deleted above */ 2001 rbtree_init(&outnet->tcp_reuse, reuse_cmp); 2002 outnet->tcp_reuse_first = NULL; 2003 outnet->tcp_reuse_last = NULL; 2004 if(outnet->udp_wait_first) { 2005 struct pending* p = outnet->udp_wait_first, *np; 2006 while(p) { 2007 np = p->next_waiting; 2008 pending_delete(NULL, p); 2009 p = np; 2010 } 2011 } 2012 free(outnet); 2013 } 2014 2015 void 2016 pending_delete(struct outside_network* outnet, struct pending* p) 2017 { 2018 if(!p) 2019 return; 2020 if(outnet && outnet->udp_wait_first && 2021 (p->next_waiting || p == outnet->udp_wait_last) ) { 2022 /* delete from waiting list, if it is in the waiting list */ 2023 struct pending* prev = NULL, *x = outnet->udp_wait_first; 2024 while(x && x != p) { 2025 prev = x; 2026 x = x->next_waiting; 2027 } 2028 if(x) { 2029 log_assert(x == p); 2030 if(prev) 2031 prev->next_waiting = p->next_waiting; 2032 else outnet->udp_wait_first = p->next_waiting; 2033 if(outnet->udp_wait_last == p) 2034 outnet->udp_wait_last = prev; 2035 } 2036 } 2037 if(outnet) { 2038 (void)rbtree_delete(outnet->pending, p->node.key); 2039 } 2040 if(p->timer) 2041 comm_timer_delete(p->timer); 2042 free(p->pkt); 2043 free(p); 2044 } 2045 2046 static void 2047 sai6_putrandom(struct sockaddr_in6 *sa, int pfxlen, struct ub_randstate *rnd) 2048 { 2049 int i, last; 2050 if(!(pfxlen > 0 && pfxlen < 128)) 2051 return; 2052 for(i = 0; i < (128 - pfxlen) / 8; i++) { 2053 sa->sin6_addr.s6_addr[15-i] = (uint8_t)ub_random_max(rnd, 256); 2054 } 2055 last = pfxlen & 7; 2056 if(last != 0) { 2057 sa->sin6_addr.s6_addr[15-i] |= 2058 ((0xFF >> last) & ub_random_max(rnd, 256)); 2059 } 2060 } 2061 2062 /** 2063 * Try to open a UDP socket for outgoing communication. 2064 * Sets sockets options as needed. 2065 * @param addr: socket address. 2066 * @param addrlen: length of address. 2067 * @param pfxlen: length of network prefix (for address randomisation). 2068 * @param port: port override for addr. 2069 * @param inuse: if -1 is returned, this bool means the port was in use. 2070 * @param rnd: random state (for address randomisation). 2071 * @param dscp: DSCP to use. 2072 * @return fd or -1 2073 */ 2074 static int 2075 udp_sockport(struct sockaddr_storage* addr, socklen_t addrlen, int pfxlen, 2076 int port, int* inuse, struct ub_randstate* rnd, int dscp) 2077 { 2078 int fd, noproto; 2079 if(addr_is_ip6(addr, addrlen)) { 2080 int freebind = 0; 2081 struct sockaddr_in6 sa = *(struct sockaddr_in6*)addr; 2082 sa.sin6_port = (in_port_t)htons((uint16_t)port); 2083 sa.sin6_flowinfo = 0; 2084 sa.sin6_scope_id = 0; 2085 if(pfxlen != 0) { 2086 freebind = 1; 2087 sai6_putrandom(&sa, pfxlen, rnd); 2088 } 2089 fd = create_udp_sock(AF_INET6, SOCK_DGRAM, 2090 (struct sockaddr*)&sa, addrlen, 1, inuse, &noproto, 2091 0, 0, 0, NULL, 0, freebind, 0, dscp); 2092 } else { 2093 struct sockaddr_in* sa = (struct sockaddr_in*)addr; 2094 sa->sin_port = (in_port_t)htons((uint16_t)port); 2095 fd = create_udp_sock(AF_INET, SOCK_DGRAM, 2096 (struct sockaddr*)addr, addrlen, 1, inuse, &noproto, 2097 0, 0, 0, NULL, 0, 0, 0, dscp); 2098 } 2099 return fd; 2100 } 2101 2102 /** Select random ID */ 2103 static int 2104 select_id(struct outside_network* outnet, struct pending* pend, 2105 sldns_buffer* packet) 2106 { 2107 int id_tries = 0; 2108 pend->id = GET_RANDOM_ID(outnet->rnd); 2109 LDNS_ID_SET(sldns_buffer_begin(packet), pend->id); 2110 2111 /* insert in tree */ 2112 pend->node.key = pend; 2113 while(!rbtree_insert(outnet->pending, &pend->node)) { 2114 /* change ID to avoid collision */ 2115 pend->id = GET_RANDOM_ID(outnet->rnd); 2116 LDNS_ID_SET(sldns_buffer_begin(packet), pend->id); 2117 id_tries++; 2118 if(id_tries == MAX_ID_RETRY) { 2119 pend->id=99999; /* non existent ID */ 2120 log_err("failed to generate unique ID, drop msg"); 2121 return 0; 2122 } 2123 } 2124 verbose(VERB_ALGO, "inserted new pending reply id=%4.4x", pend->id); 2125 return 1; 2126 } 2127 2128 /** return true is UDP connect error needs to be logged */ 2129 static int udp_connect_needs_log(int err, struct sockaddr_storage* addr, 2130 socklen_t addrlen) 2131 { 2132 switch(err) { 2133 case ECONNREFUSED: 2134 # ifdef ENETUNREACH 2135 case ENETUNREACH: 2136 # endif 2137 # ifdef EHOSTDOWN 2138 case EHOSTDOWN: 2139 # endif 2140 # ifdef EHOSTUNREACH 2141 case EHOSTUNREACH: 2142 # endif 2143 # ifdef ENETDOWN 2144 case ENETDOWN: 2145 # endif 2146 # ifdef EADDRNOTAVAIL 2147 case EADDRNOTAVAIL: 2148 # endif 2149 case EPERM: 2150 case EACCES: 2151 if(verbosity >= VERB_ALGO) 2152 return 1; 2153 return 0; 2154 case EINVAL: 2155 /* Stop 'Invalid argument for fe80::/10' addresses appearing 2156 * in the logs, at low verbosity. They cannot be sent to. */ 2157 if(addr_is_ip6linklocal(addr, addrlen)) { 2158 if(verbosity >= VERB_ALGO) 2159 return 1; 2160 return 0; 2161 } 2162 break; 2163 default: 2164 break; 2165 } 2166 return 1; 2167 } 2168 2169 2170 /** Select random interface and port */ 2171 static int 2172 select_ifport(struct outside_network* outnet, struct pending* pend, 2173 int num_if, struct port_if* ifs) 2174 { 2175 int my_if, fd, portno, inuse, tries=0; 2176 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 2177 int reused; 2178 #endif 2179 struct port_if* pif; 2180 /* randomly select interface and port */ 2181 if(num_if == 0) { 2182 verbose(VERB_QUERY, "Need to send query but have no " 2183 "outgoing interfaces of that family"); 2184 return 0; 2185 } 2186 log_assert(outnet->unused_fds); 2187 tries = 0; 2188 while(1) { 2189 my_if = ub_random_max(outnet->rnd, num_if); 2190 pif = &ifs[my_if]; 2191 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 2192 if(!shared_ports_fetch_random(outnet->shared_ports, 2193 pif->shpif, outnet->rnd, outnet->udp_connect, 2194 pif->inuse, &portno, &reused)) { 2195 tries++; 2196 if(tries < MAX_PORT_RETRY) 2197 continue; 2198 log_err("failed to find an open port, drop msg"); 2199 return 0; 2200 } 2201 if(reused) { 2202 /* port already open */ 2203 log_assert(portno < pif->inuse); 2204 pend->pc = pif->out[portno]; 2205 verbose(VERB_ALGO, "using UDP if=%d port=%d", 2206 my_if, pend->pc->number); 2207 break; 2208 } 2209 #else 2210 portno = 0; 2211 #endif 2212 /* try to open new port, if fails, loop to try again */ 2213 fd = udp_sockport(&pif->addr, pif->addrlen, pif->pfxlen, 2214 portno, &inuse, outnet->rnd, outnet->ip_dscp); 2215 if(fd == -1 && !inuse) { 2216 /* nonrecoverable error making socket */ 2217 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 2218 shared_ports_return_port(outnet->shared_ports, 2219 pif->shpif, portno); 2220 #endif 2221 return 0; 2222 } 2223 if(fd != -1) { 2224 verbose(VERB_ALGO, "opened UDP if=%d port=%d", 2225 my_if, portno); 2226 if(outnet->udp_connect) { 2227 /* connect() to the destination */ 2228 if(connect(fd, (struct sockaddr*)&pend->addr, 2229 pend->addrlen) < 0) { 2230 if(udp_connect_needs_log(errno, 2231 &pend->addr, pend->addrlen)) { 2232 log_err_addr("udp connect failed", 2233 strerror(errno), &pend->addr, 2234 pend->addrlen); 2235 } 2236 sock_close(fd); 2237 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 2238 shared_ports_return_port( 2239 outnet->shared_ports, 2240 pif->shpif, portno); 2241 #endif 2242 return 0; 2243 } 2244 } 2245 /* grab fd */ 2246 pend->pc = outnet->unused_fds; 2247 outnet->unused_fds = pend->pc->next; 2248 2249 /* setup portcomm */ 2250 pend->pc->next = NULL; 2251 pend->pc->number = portno; 2252 pend->pc->pif = pif; 2253 pend->pc->index = pif->inuse; 2254 pend->pc->num_outstanding = 0; 2255 comm_point_start_listening(pend->pc->cp, fd, -1); 2256 2257 /* grab port in interface */ 2258 pif->out[pif->inuse] = pend->pc; 2259 pif->inuse++; 2260 break; 2261 } 2262 /* failed, already in use */ 2263 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 2264 shared_ports_return_port(outnet->shared_ports, pif->shpif, 2265 portno); 2266 #endif 2267 verbose(VERB_QUERY, "port %d in use, trying another", portno); 2268 tries++; 2269 if(tries == MAX_PORT_RETRY) { 2270 log_err("failed to find an open port, drop msg"); 2271 return 0; 2272 } 2273 } 2274 log_assert(pend->pc); 2275 pend->pc->num_outstanding++; 2276 2277 return 1; 2278 } 2279 2280 static int 2281 randomize_and_send_udp(struct pending* pend, sldns_buffer* packet, int timeout) 2282 { 2283 struct timeval tv; 2284 struct outside_network* outnet = pend->sq->outnet; 2285 2286 /* select id */ 2287 if(!select_id(outnet, pend, packet)) { 2288 return 0; 2289 } 2290 2291 /* select src_if, port */ 2292 if(addr_is_ip6(&pend->addr, pend->addrlen)) { 2293 if(!select_ifport(outnet, pend, 2294 outnet->num_ip6, outnet->ip6_ifs)) 2295 return 0; 2296 } else { 2297 if(!select_ifport(outnet, pend, 2298 outnet->num_ip4, outnet->ip4_ifs)) 2299 return 0; 2300 } 2301 log_assert(pend->pc && pend->pc->cp); 2302 2303 /* send it over the commlink */ 2304 if(!comm_point_send_udp_msg(pend->pc->cp, packet, 2305 (struct sockaddr*)&pend->addr, pend->addrlen, outnet->udp_connect)) { 2306 portcomm_loweruse(outnet, pend->pc); 2307 return 0; 2308 } 2309 outnet->num_udp_outgoing++; 2310 2311 /* system calls to set timeout after sending UDP to make roundtrip 2312 smaller. */ 2313 #ifndef S_SPLINT_S 2314 tv.tv_sec = timeout/1000; 2315 tv.tv_usec = (timeout%1000)*1000; 2316 #endif 2317 comm_timer_set(pend->timer, &tv); 2318 2319 #ifdef USE_DNSTAP 2320 /* 2321 * sending src (local service)/dst (upstream) addresses over DNSTAP 2322 * There are no chances to get the src (local service) addr if unbound 2323 * is not configured with specific outgoing IP-addresses. So we will 2324 * pass 0.0.0.0 (::) to argument for 2325 * dt_msg_send_outside_query()/dt_msg_send_outside_response() calls. 2326 */ 2327 if(outnet->dtenv && 2328 (outnet->dtenv->log_resolver_query_messages || 2329 outnet->dtenv->log_forwarder_query_messages)) { 2330 log_addr(VERB_ALGO, "from local addr", &pend->pc->pif->addr, pend->pc->pif->addrlen); 2331 log_addr(VERB_ALGO, "request to upstream", &pend->addr, pend->addrlen); 2332 dt_msg_send_outside_query(outnet->dtenv, &pend->addr, &pend->pc->pif->addr, comm_udp, NULL, 2333 pend->sq->zone, pend->sq->zonelen, packet); 2334 } 2335 #endif 2336 return 1; 2337 } 2338 2339 struct pending* 2340 pending_udp_query(struct serviced_query* sq, struct sldns_buffer* packet, 2341 int timeout, comm_point_callback_type* cb, void* cb_arg) 2342 { 2343 struct pending* pend = (struct pending*)calloc(1, sizeof(*pend)); 2344 if(!pend) return NULL; 2345 pend->outnet = sq->outnet; 2346 pend->sq = sq; 2347 pend->addrlen = sq->addrlen; 2348 memmove(&pend->addr, &sq->addr, sq->addrlen); 2349 pend->cb = cb; 2350 pend->cb_arg = cb_arg; 2351 pend->node.key = pend; 2352 pend->timer = comm_timer_create(sq->outnet->base, pending_udp_timer_cb, 2353 pend); 2354 if(!pend->timer) { 2355 free(pend); 2356 return NULL; 2357 } 2358 2359 if(sq->outnet->unused_fds == NULL) { 2360 /* no unused fd, cannot create a new port (randomly) */ 2361 verbose(VERB_ALGO, "no fds available, udp query waiting"); 2362 pend->timeout = timeout; 2363 pend->pkt_len = sldns_buffer_limit(packet); 2364 pend->pkt = (uint8_t*)memdup(sldns_buffer_begin(packet), 2365 pend->pkt_len); 2366 if(!pend->pkt) { 2367 comm_timer_delete(pend->timer); 2368 free(pend); 2369 return NULL; 2370 } 2371 /* put at end of waiting list */ 2372 if(sq->outnet->udp_wait_last) 2373 sq->outnet->udp_wait_last->next_waiting = pend; 2374 else 2375 sq->outnet->udp_wait_first = pend; 2376 sq->outnet->udp_wait_last = pend; 2377 return pend; 2378 } 2379 log_assert(!sq->busy); 2380 sq->busy = 1; 2381 if(!randomize_and_send_udp(pend, packet, timeout)) { 2382 pending_delete(sq->outnet, pend); 2383 return NULL; 2384 } 2385 sq->busy = 0; 2386 return pend; 2387 } 2388 2389 void 2390 outnet_tcptimer(void* arg) 2391 { 2392 struct waiting_tcp* w = (struct waiting_tcp*)arg; 2393 struct outside_network* outnet = w->outnet; 2394 verbose(VERB_CLIENT, "outnet_tcptimer"); 2395 if(w->on_tcp_waiting_list) { 2396 /* it is on the waiting list */ 2397 outnet_waiting_tcp_list_remove(outnet, w); 2398 waiting_tcp_callback(w, NULL, NETEVENT_TIMEOUT, NULL); 2399 waiting_tcp_delete(w); 2400 } else { 2401 /* it was in use */ 2402 struct pending_tcp* pend=(struct pending_tcp*)w->next_waiting; 2403 reuse_cb_and_decommission(outnet, pend, NETEVENT_TIMEOUT); 2404 } 2405 use_free_buffer(outnet); 2406 } 2407 2408 /** close the oldest reuse_tcp connection to make a fd and struct pend 2409 * available for a new stream connection */ 2410 static void 2411 reuse_tcp_close_oldest(struct outside_network* outnet) 2412 { 2413 struct reuse_tcp* reuse; 2414 verbose(VERB_CLIENT, "reuse_tcp_close_oldest"); 2415 reuse = reuse_tcp_lru_snip(outnet); 2416 if(!reuse) return; 2417 /* free up */ 2418 reuse_cb_and_decommission(outnet, reuse->pending, NETEVENT_CLOSED); 2419 } 2420 2421 static uint16_t 2422 tcp_select_id(struct outside_network* outnet, struct reuse_tcp* reuse) 2423 { 2424 if(reuse) 2425 return reuse_tcp_select_id(reuse, outnet); 2426 return GET_RANDOM_ID(outnet->rnd); 2427 } 2428 2429 /** find spare ID value for reuse tcp stream. That is random and also does 2430 * not collide with an existing query ID that is in use or waiting */ 2431 uint16_t 2432 reuse_tcp_select_id(struct reuse_tcp* reuse, struct outside_network* outnet) 2433 { 2434 uint16_t id = 0, curid, nextid; 2435 const int try_random = 2000; 2436 int i; 2437 unsigned select, count, space; 2438 rbnode_type* node; 2439 2440 /* make really sure the tree is not empty */ 2441 if(reuse->tree_by_id.count == 0) { 2442 id = GET_RANDOM_ID(outnet->rnd); 2443 return id; 2444 } 2445 2446 /* try to find random empty spots by picking them */ 2447 for(i = 0; i<try_random; i++) { 2448 id = GET_RANDOM_ID(outnet->rnd); 2449 if(!reuse_tcp_by_id_find(reuse, id)) { 2450 return id; 2451 } 2452 } 2453 2454 /* equally pick a random unused element from the tree that is 2455 * not in use. Pick a the n-th index of an unused number, 2456 * then loop over the empty spaces in the tree and find it */ 2457 log_assert(reuse->tree_by_id.count < 0xffff); 2458 select = ub_random_max(outnet->rnd, 0xffff - reuse->tree_by_id.count); 2459 /* select value now in 0 .. num free - 1 */ 2460 2461 count = 0; /* number of free spaces passed by */ 2462 node = rbtree_first(&reuse->tree_by_id); 2463 log_assert(node && node != RBTREE_NULL); /* tree not empty */ 2464 /* see if select is before first node */ 2465 if(select < (unsigned)tree_by_id_get_id(node)) 2466 return select; 2467 count += tree_by_id_get_id(node); 2468 /* perhaps select is between nodes */ 2469 while(node && node != RBTREE_NULL) { 2470 rbnode_type* next = rbtree_next(node); 2471 if(next && next != RBTREE_NULL) { 2472 curid = tree_by_id_get_id(node); 2473 nextid = tree_by_id_get_id(next); 2474 log_assert(curid < nextid); 2475 if(curid != 0xffff && curid + 1 < nextid) { 2476 /* space between nodes */ 2477 space = nextid - curid - 1; 2478 log_assert(select >= count); 2479 if(select < count + space) { 2480 /* here it is */ 2481 return curid + 1 + (select - count); 2482 } 2483 count += space; 2484 } 2485 } 2486 node = next; 2487 } 2488 2489 /* select is after the last node */ 2490 /* count is the number of free positions before the nodes in the 2491 * tree */ 2492 node = rbtree_last(&reuse->tree_by_id); 2493 log_assert(node && node != RBTREE_NULL); /* tree not empty */ 2494 curid = tree_by_id_get_id(node); 2495 log_assert(count + (0xffff-curid) + reuse->tree_by_id.count == 0xffff); 2496 return curid + 1 + (select - count); 2497 } 2498 2499 struct waiting_tcp* 2500 pending_tcp_query(struct serviced_query* sq, sldns_buffer* packet, 2501 int timeout, comm_point_callback_type* callback, void* callback_arg) 2502 { 2503 struct pending_tcp* pend = sq->outnet->tcp_free; 2504 struct reuse_tcp* reuse = NULL; 2505 struct waiting_tcp* w; 2506 2507 verbose(VERB_CLIENT, "pending_tcp_query"); 2508 if(sldns_buffer_limit(packet) < sizeof(uint16_t)) { 2509 verbose(VERB_ALGO, "pending tcp query with too short buffer < 2"); 2510 return NULL; 2511 } 2512 2513 /* find out if a reused stream to the target exists */ 2514 /* if so, take it into use */ 2515 reuse = reuse_tcp_find(sq->outnet, &sq->addr, sq->addrlen, 2516 sq->ssl_upstream, sq->tls_auth_name); 2517 if(reuse) { 2518 log_reuse_tcp(VERB_CLIENT, "pending_tcp_query: found reuse", reuse); 2519 log_assert(reuse->pending); 2520 pend = reuse->pending; 2521 reuse_tcp_lru_touch(sq->outnet, reuse); 2522 } 2523 2524 log_assert(!reuse || (reuse && pend)); 2525 /* if !pend but we have reuse streams, close a reuse stream 2526 * to be able to open a new one to this target, no use waiting 2527 * to reuse a file descriptor while another query needs to use 2528 * that buffer and file descriptor now. */ 2529 if(!pend) { 2530 reuse_tcp_close_oldest(sq->outnet); 2531 pend = sq->outnet->tcp_free; 2532 log_assert(!reuse || (pend == reuse->pending)); 2533 } 2534 2535 /* allocate space to store query */ 2536 w = (struct waiting_tcp*)malloc(sizeof(struct waiting_tcp) 2537 + sldns_buffer_limit(packet)); 2538 if(!w) { 2539 return NULL; 2540 } 2541 if(!(w->timer = comm_timer_create(sq->outnet->base, outnet_tcptimer, w))) { 2542 free(w); 2543 return NULL; 2544 } 2545 w->pkt = (uint8_t*)w + sizeof(struct waiting_tcp); 2546 w->pkt_len = sldns_buffer_limit(packet); 2547 memmove(w->pkt, sldns_buffer_begin(packet), w->pkt_len); 2548 w->id = tcp_select_id(sq->outnet, reuse); 2549 LDNS_ID_SET(w->pkt, w->id); 2550 memcpy(&w->addr, &sq->addr, sq->addrlen); 2551 w->addrlen = sq->addrlen; 2552 w->outnet = sq->outnet; 2553 w->on_tcp_waiting_list = 0; 2554 w->next_waiting = NULL; 2555 w->cb = callback; 2556 w->cb_arg = callback_arg; 2557 w->ssl_upstream = sq->ssl_upstream; 2558 if(sq->tls_auth_name) { 2559 w->tls_auth_name = strdup(sq->tls_auth_name); 2560 if(!w->tls_auth_name) { 2561 comm_timer_delete(w->timer); 2562 free(w); 2563 return NULL; 2564 } 2565 } else { 2566 w->tls_auth_name = NULL; 2567 } 2568 w->timeout = timeout; 2569 w->id_node.key = NULL; 2570 w->write_wait_prev = NULL; 2571 w->write_wait_next = NULL; 2572 w->write_wait_queued = 0; 2573 w->error_count = 0; 2574 #ifdef USE_DNSTAP 2575 w->sq = NULL; 2576 #endif 2577 w->in_cb_and_decommission = 0; 2578 if(pend) { 2579 /* we have a buffer available right now */ 2580 if(reuse) { 2581 log_assert(reuse == &pend->reuse); 2582 /* reuse existing fd, write query and continue */ 2583 /* store query in tree by id */ 2584 verbose(VERB_CLIENT, "pending_tcp_query: reuse, store"); 2585 w->next_waiting = (void*)pend; 2586 reuse_tree_by_id_insert(&pend->reuse, w); 2587 /* can we write right now? */ 2588 if(pend->query == NULL) { 2589 /* write straight away */ 2590 /* stop the timer on read of the fd */ 2591 comm_point_stop_listening(pend->c); 2592 pend->query = w; 2593 outnet_tcp_take_query_setup(pend->c->fd, pend, 2594 w); 2595 } else { 2596 /* put it in the waiting list for 2597 * this stream */ 2598 reuse_write_wait_push_back(&pend->reuse, w); 2599 } 2600 } else { 2601 /* create new fd and connect to addr, setup to 2602 * write query */ 2603 verbose(VERB_CLIENT, "pending_tcp_query: new fd, connect"); 2604 rbtree_init(&pend->reuse.tree_by_id, reuse_id_cmp); 2605 pend->reuse.pending = pend; 2606 memcpy(&pend->reuse.addr, &sq->addr, sq->addrlen); 2607 pend->reuse.addrlen = sq->addrlen; 2608 if(!outnet_tcp_take_into_use(w)) { 2609 waiting_tcp_delete(w); 2610 return NULL; 2611 } 2612 } 2613 #ifdef USE_DNSTAP 2614 if(sq->outnet->dtenv && 2615 (sq->outnet->dtenv->log_resolver_query_messages || 2616 sq->outnet->dtenv->log_forwarder_query_messages)) { 2617 /* use w->pkt, because it has the ID value */ 2618 sldns_buffer tmp; 2619 sldns_buffer_init_frm_data(&tmp, w->pkt, w->pkt_len); 2620 dt_msg_send_outside_query(sq->outnet->dtenv, &sq->addr, 2621 &pend->pi->addr, comm_tcp, NULL, sq->zone, 2622 sq->zonelen, &tmp); 2623 } 2624 #endif 2625 } else { 2626 /* queue up */ 2627 /* waiting for a buffer on the outside network buffer wait 2628 * list */ 2629 verbose(VERB_CLIENT, "pending_tcp_query: queue to wait"); 2630 #ifdef USE_DNSTAP 2631 w->sq = sq; 2632 #endif 2633 outnet_waiting_tcp_list_add(sq->outnet, w, 1); 2634 } 2635 return w; 2636 } 2637 2638 /** create query for serviced queries */ 2639 static void 2640 serviced_gen_query(sldns_buffer* buff, uint8_t* qname, size_t qnamelen, 2641 uint16_t qtype, uint16_t qclass, uint16_t flags) 2642 { 2643 sldns_buffer_clear(buff); 2644 /* skip id */ 2645 sldns_buffer_write_u16(buff, flags); 2646 sldns_buffer_write_u16(buff, 1); /* qdcount */ 2647 sldns_buffer_write_u16(buff, 0); /* ancount */ 2648 sldns_buffer_write_u16(buff, 0); /* nscount */ 2649 sldns_buffer_write_u16(buff, 0); /* arcount */ 2650 sldns_buffer_write(buff, qname, qnamelen); 2651 sldns_buffer_write_u16(buff, qtype); 2652 sldns_buffer_write_u16(buff, qclass); 2653 sldns_buffer_flip(buff); 2654 } 2655 2656 /** lookup serviced query in serviced query rbtree */ 2657 static struct serviced_query* 2658 lookup_serviced(struct outside_network* outnet, sldns_buffer* buff, int dnssec, 2659 struct sockaddr_storage* addr, socklen_t addrlen, 2660 struct edns_option* opt_list) 2661 { 2662 struct serviced_query key; 2663 key.node.key = &key; 2664 key.qbuf = sldns_buffer_begin(buff); 2665 key.qbuflen = sldns_buffer_limit(buff); 2666 key.dnssec = dnssec; 2667 memcpy(&key.addr, addr, addrlen); 2668 key.addrlen = addrlen; 2669 key.outnet = outnet; 2670 key.opt_list = opt_list; 2671 return (struct serviced_query*)rbtree_search(outnet->serviced, &key); 2672 } 2673 2674 void 2675 serviced_timer_cb(void* arg) 2676 { 2677 struct serviced_query* sq = (struct serviced_query*)arg; 2678 struct outside_network* outnet = sq->outnet; 2679 verbose(VERB_ALGO, "serviced send timer"); 2680 /* By the time this cb is called, if we don't have any registered 2681 * callbacks for this serviced_query anymore; do not send. */ 2682 if(!sq->cblist) 2683 goto delete; 2684 /* perform first network action */ 2685 if(outnet->do_udp && !(sq->tcp_upstream || sq->ssl_upstream)) { 2686 if(!serviced_udp_send(sq, outnet->udp_buff)) 2687 goto delete; 2688 } else { 2689 if(!serviced_tcp_send(sq, outnet->udp_buff)) 2690 goto delete; 2691 } 2692 /* Maybe by this time we don't have callbacks attached anymore. Don't 2693 * proactively try to delete; let it run and maybe another callback 2694 * will get attached by the time we get an answer. */ 2695 return; 2696 delete: 2697 serviced_callbacks(sq, NETEVENT_CLOSED, NULL, NULL); 2698 } 2699 2700 /** Create new serviced entry */ 2701 static struct serviced_query* 2702 serviced_create(struct outside_network* outnet, sldns_buffer* buff, int dnssec, 2703 int want_dnssec, int nocaps, int tcp_upstream, int ssl_upstream, 2704 char* tls_auth_name, struct sockaddr_storage* addr, socklen_t addrlen, 2705 uint8_t* zone, size_t zonelen, int qtype, struct edns_option* opt_list, 2706 size_t pad_queries_block_size, struct alloc_cache* alloc, 2707 struct regional* region) 2708 { 2709 struct serviced_query* sq = (struct serviced_query*)malloc(sizeof(*sq)); 2710 struct timeval t; 2711 #ifdef UNBOUND_DEBUG 2712 rbnode_type* ins; 2713 #endif 2714 if(!sq) { 2715 alloc_reg_release(alloc, region); 2716 return NULL; 2717 } 2718 sq->node.key = sq; 2719 sq->alloc = alloc; 2720 sq->region = region; 2721 sq->qbuf = regional_alloc_init(region, sldns_buffer_begin(buff), 2722 sldns_buffer_limit(buff)); 2723 if(!sq->qbuf) { 2724 alloc_reg_release(alloc, region); 2725 free(sq); 2726 return NULL; 2727 } 2728 sq->qbuflen = sldns_buffer_limit(buff); 2729 sq->zone = regional_alloc_init(region, zone, zonelen); 2730 if(!sq->zone) { 2731 alloc_reg_release(alloc, region); 2732 free(sq); 2733 return NULL; 2734 } 2735 sq->zonelen = zonelen; 2736 sq->qtype = qtype; 2737 sq->dnssec = dnssec; 2738 sq->want_dnssec = want_dnssec; 2739 sq->nocaps = nocaps; 2740 sq->tcp_upstream = tcp_upstream; 2741 sq->ssl_upstream = ssl_upstream; 2742 if(tls_auth_name) { 2743 sq->tls_auth_name = regional_strdup(region, tls_auth_name); 2744 if(!sq->tls_auth_name) { 2745 alloc_reg_release(alloc, region); 2746 free(sq); 2747 return NULL; 2748 } 2749 } else { 2750 sq->tls_auth_name = NULL; 2751 } 2752 memcpy(&sq->addr, addr, addrlen); 2753 sq->addrlen = addrlen; 2754 sq->opt_list = opt_list; 2755 sq->busy = 0; 2756 sq->timer = comm_timer_create(outnet->base, serviced_timer_cb, sq); 2757 if(!sq->timer) { 2758 alloc_reg_release(alloc, region); 2759 free(sq); 2760 return NULL; 2761 } 2762 memset(&t, 0, sizeof(t)); 2763 comm_timer_set(sq->timer, &t); 2764 sq->outnet = outnet; 2765 sq->cblist = NULL; 2766 sq->pending = NULL; 2767 sq->status = serviced_initial; 2768 sq->retry = 0; 2769 sq->to_be_deleted = 0; 2770 sq->padding_block_size = pad_queries_block_size; 2771 #ifdef UNBOUND_DEBUG 2772 ins = 2773 #else 2774 (void) 2775 #endif 2776 rbtree_insert(outnet->serviced, &sq->node); 2777 log_assert(ins != NULL); /* must not be already present */ 2778 return sq; 2779 } 2780 2781 /** reuse tcp stream, remove serviced query from stream, 2782 * return true if the stream is kept, false if it is to be closed */ 2783 static int 2784 reuse_tcp_remove_serviced_keep(struct waiting_tcp* w, 2785 struct serviced_query* sq) 2786 { 2787 struct pending_tcp* pend_tcp = (struct pending_tcp*)w->next_waiting; 2788 verbose(VERB_CLIENT, "reuse_tcp_remove_serviced_keep"); 2789 /* remove the callback. let query continue to write to not cancel 2790 * the stream itself. also keep it as an entry in the tree_by_id, 2791 * in case the answer returns (that we no longer want), but we cannot 2792 * pick the same ID number meanwhile */ 2793 w->cb = NULL; 2794 /* see if can be entered in reuse tree 2795 * for that the FD has to be non-1 */ 2796 if(pend_tcp->c->fd == -1) { 2797 verbose(VERB_CLIENT, "reuse_tcp_remove_serviced_keep: -1 fd"); 2798 return 0; 2799 } 2800 /* if in tree and used by other queries */ 2801 if(pend_tcp->reuse.node.key) { 2802 verbose(VERB_CLIENT, "reuse_tcp_remove_serviced_keep: in use by other queries"); 2803 /* do not reset the keepalive timer, for that 2804 * we'd need traffic, and this is where the serviced is 2805 * removed due to state machine internal reasons, 2806 * eg. iterator no longer interested in this query */ 2807 return 1; 2808 } 2809 /* if still open and want to keep it open */ 2810 if(pend_tcp->c->fd != -1 && sq->outnet->tcp_reuse.count < 2811 sq->outnet->tcp_reuse_max) { 2812 verbose(VERB_CLIENT, "reuse_tcp_remove_serviced_keep: keep open"); 2813 /* set a keepalive timer on it */ 2814 if(!reuse_tcp_insert(sq->outnet, pend_tcp)) { 2815 return 0; 2816 } 2817 reuse_tcp_setup_timeout(pend_tcp, sq->outnet->tcp_reuse_timeout); 2818 return 1; 2819 } 2820 return 0; 2821 } 2822 2823 /** cleanup serviced query entry */ 2824 static void 2825 serviced_delete(struct serviced_query* sq) 2826 { 2827 verbose(VERB_CLIENT, "serviced_delete"); 2828 if(sq->pending) { 2829 /* clear up the pending query */ 2830 if(sq->status == serviced_query_UDP_EDNS || 2831 sq->status == serviced_query_UDP || 2832 sq->status == serviced_query_UDP_EDNS_FRAG || 2833 sq->status == serviced_query_UDP_EDNS_fallback) { 2834 struct pending* p = (struct pending*)sq->pending; 2835 verbose(VERB_CLIENT, "serviced_delete: UDP"); 2836 if(p->pc) 2837 portcomm_loweruse(sq->outnet, p->pc); 2838 pending_delete(sq->outnet, p); 2839 /* this call can cause reentrant calls back into the 2840 * mesh */ 2841 outnet_send_wait_udp(sq->outnet); 2842 } else { 2843 struct waiting_tcp* w = (struct waiting_tcp*) 2844 sq->pending; 2845 verbose(VERB_CLIENT, "serviced_delete: TCP"); 2846 log_assert(!(w->write_wait_queued && w->on_tcp_waiting_list)); 2847 /* if on stream-write-waiting list then 2848 * remove from waiting list and waiting_tcp_delete */ 2849 if(w->write_wait_queued) { 2850 struct pending_tcp* pend = 2851 (struct pending_tcp*)w->next_waiting; 2852 verbose(VERB_CLIENT, "serviced_delete: writewait"); 2853 if(!w->in_cb_and_decommission) 2854 reuse_tree_by_id_delete(&pend->reuse, w); 2855 reuse_write_wait_remove(&pend->reuse, w); 2856 if(!w->in_cb_and_decommission) 2857 waiting_tcp_delete(w); 2858 } else if(!w->on_tcp_waiting_list) { 2859 struct pending_tcp* pend = 2860 (struct pending_tcp*)w->next_waiting; 2861 verbose(VERB_CLIENT, "serviced_delete: tcpreusekeep"); 2862 /* w needs to stay on tree_by_id to not assign 2863 * the same ID; remove the callback since its 2864 * serviced_query will be gone. */ 2865 w->cb = NULL; 2866 if(!reuse_tcp_remove_serviced_keep(w, sq)) { 2867 if(!w->in_cb_and_decommission) 2868 reuse_cb_and_decommission(sq->outnet, 2869 pend, NETEVENT_CLOSED); 2870 use_free_buffer(sq->outnet); 2871 } 2872 sq->pending = NULL; 2873 } else { 2874 verbose(VERB_CLIENT, "serviced_delete: tcpwait"); 2875 outnet_waiting_tcp_list_remove(sq->outnet, w); 2876 if(!w->in_cb_and_decommission) 2877 waiting_tcp_delete(w); 2878 } 2879 } 2880 } 2881 /* does not delete from tree, caller has to do that */ 2882 serviced_node_del(&sq->node, NULL); 2883 } 2884 2885 /** perturb a dname capitalization randomly */ 2886 static void 2887 serviced_perturb_qname(struct ub_randstate* rnd, uint8_t* qbuf, size_t len) 2888 { 2889 uint8_t lablen; 2890 uint8_t* d = qbuf + 10; 2891 long int random = 0; 2892 int bits = 0; 2893 log_assert(len >= 10 + 5 /* offset qname, root, qtype, qclass */); 2894 (void)len; 2895 lablen = *d++; 2896 while(lablen) { 2897 while(lablen--) { 2898 /* only perturb A-Z, a-z */ 2899 if(isalpha((unsigned char)*d)) { 2900 /* get a random bit */ 2901 if(bits == 0) { 2902 random = ub_random(rnd); 2903 bits = 30; 2904 } 2905 if((random & 0x1)) { 2906 *d = (uint8_t)toupper((unsigned char)*d); 2907 } else { 2908 *d = (uint8_t)tolower((unsigned char)*d); 2909 } 2910 random >>= 1; 2911 bits--; 2912 } 2913 d++; 2914 } 2915 lablen = *d++; 2916 } 2917 if(verbosity >= VERB_ALGO) { 2918 char buf[LDNS_MAX_DOMAINLEN]; 2919 dname_str(qbuf+10, buf); 2920 verbose(VERB_ALGO, "qname perturbed to %s", buf); 2921 } 2922 } 2923 2924 static uint16_t 2925 serviced_query_udp_size(struct serviced_query* sq, enum serviced_query_status status) { 2926 uint16_t udp_size; 2927 if(status == serviced_query_UDP_EDNS_FRAG) { 2928 if(addr_is_ip6(&sq->addr, sq->addrlen)) { 2929 if(EDNS_FRAG_SIZE_IP6 < EDNS_ADVERTISED_SIZE) 2930 udp_size = EDNS_FRAG_SIZE_IP6; 2931 else udp_size = EDNS_ADVERTISED_SIZE; 2932 } else { 2933 if(EDNS_FRAG_SIZE_IP4 < EDNS_ADVERTISED_SIZE) 2934 udp_size = EDNS_FRAG_SIZE_IP4; 2935 else udp_size = EDNS_ADVERTISED_SIZE; 2936 } 2937 } else { 2938 udp_size = EDNS_ADVERTISED_SIZE; 2939 } 2940 return udp_size; 2941 } 2942 2943 /** put serviced query into a buffer */ 2944 static void 2945 serviced_encode(struct serviced_query* sq, sldns_buffer* buff, int with_edns) 2946 { 2947 /* if we are using 0x20 bits for ID randomness, perturb them */ 2948 if(sq->outnet->use_caps_for_id && !sq->nocaps) { 2949 serviced_perturb_qname(sq->outnet->rnd, sq->qbuf, sq->qbuflen); 2950 } 2951 /* generate query */ 2952 sldns_buffer_clear(buff); 2953 sldns_buffer_write_u16(buff, 0); /* id placeholder */ 2954 sldns_buffer_write(buff, sq->qbuf, sq->qbuflen); 2955 sldns_buffer_flip(buff); 2956 if(with_edns) { 2957 /* add edns section */ 2958 struct edns_data edns; 2959 struct edns_option padding_option; 2960 edns.edns_present = 1; 2961 edns.ext_rcode = 0; 2962 edns.edns_version = EDNS_ADVERTISED_VERSION; 2963 edns.opt_list_in = NULL; 2964 edns.opt_list_out = sq->opt_list; 2965 edns.opt_list_inplace_cb_out = NULL; 2966 edns.udp_size = serviced_query_udp_size(sq, sq->status); 2967 edns.bits = 0; 2968 if((sq->dnssec & EDNS_DO)) 2969 edns.bits = EDNS_DO; 2970 if((sq->dnssec & BIT_CD)) 2971 LDNS_CD_SET(sldns_buffer_begin(buff)); 2972 if (sq->ssl_upstream && sq->padding_block_size) { 2973 padding_option.opt_code = LDNS_EDNS_PADDING; 2974 padding_option.opt_len = 0; 2975 padding_option.opt_data = NULL; 2976 padding_option.next = edns.opt_list_out; 2977 edns.opt_list_out = &padding_option; 2978 edns.padding_block_size = sq->padding_block_size; 2979 } 2980 attach_edns_record(buff, &edns); 2981 } 2982 } 2983 2984 /** 2985 * Perform serviced query UDP sending operation. 2986 * Sends UDP with EDNS, unless infra host marked non EDNS. 2987 * @param sq: query to send. 2988 * @param buff: buffer scratch space. 2989 * @return 0 on error. 2990 */ 2991 static int 2992 serviced_udp_send(struct serviced_query* sq, sldns_buffer* buff) 2993 { 2994 int rtt, vs; 2995 uint8_t edns_lame_known; 2996 time_t now = *sq->outnet->now_secs; 2997 2998 if(!infra_host(sq->outnet->infra, &sq->addr, sq->addrlen, sq->zone, 2999 sq->zonelen, now, &vs, &edns_lame_known, &rtt)) 3000 return 0; 3001 sq->last_rtt = rtt; 3002 verbose(VERB_ALGO, "EDNS lookup known=%d vs=%d", edns_lame_known, vs); 3003 if(sq->status == serviced_initial) { 3004 if(vs != -1) { 3005 sq->status = serviced_query_UDP_EDNS; 3006 } else { 3007 sq->status = serviced_query_UDP; 3008 } 3009 } 3010 serviced_encode(sq, buff, (sq->status == serviced_query_UDP_EDNS) || 3011 (sq->status == serviced_query_UDP_EDNS_FRAG)); 3012 sq->last_sent_time = *sq->outnet->now_tv; 3013 sq->edns_lame_known = (int)edns_lame_known; 3014 verbose(VERB_ALGO, "serviced query UDP timeout=%d msec", rtt); 3015 sq->pending = pending_udp_query(sq, buff, rtt, 3016 serviced_udp_callback, sq); 3017 if(!sq->pending) 3018 return 0; 3019 return 1; 3020 } 3021 3022 /** check that perturbed qname is identical */ 3023 static int 3024 serviced_check_qname(sldns_buffer* pkt, uint8_t* qbuf, size_t qbuflen) 3025 { 3026 uint8_t* d1 = sldns_buffer_begin(pkt)+12; 3027 uint8_t* d2 = qbuf+10; 3028 uint8_t len1, len2; 3029 int count = 0; 3030 if(sldns_buffer_limit(pkt) < 12+1+4) /* packet too small for qname */ 3031 return 0; 3032 log_assert(qbuflen >= 15 /* 10 header, root, type, class */); 3033 len1 = *d1++; 3034 len2 = *d2++; 3035 while(len1 != 0 || len2 != 0) { 3036 if(LABEL_IS_PTR(len1)) { 3037 /* check if we can read *d1 with compression ptr rest */ 3038 if(d1 >= sldns_buffer_at(pkt, sldns_buffer_limit(pkt))) 3039 return 0; 3040 d1 = sldns_buffer_begin(pkt)+PTR_OFFSET(len1, *d1); 3041 /* check if we can read the destination *d1 */ 3042 if(d1 >= sldns_buffer_at(pkt, sldns_buffer_limit(pkt))) 3043 return 0; 3044 len1 = *d1++; 3045 if(count++ > MAX_COMPRESS_PTRS) 3046 return 0; 3047 continue; 3048 } 3049 if(d2 > qbuf+qbuflen) 3050 return 0; 3051 if(len1 != len2) 3052 return 0; 3053 if(len1 > LDNS_MAX_LABELLEN) 3054 return 0; 3055 /* check len1 + 1(next length) are okay to read */ 3056 if(d1+len1 >= sldns_buffer_at(pkt, sldns_buffer_limit(pkt))) 3057 return 0; 3058 log_assert(len1 <= LDNS_MAX_LABELLEN); 3059 log_assert(len2 <= LDNS_MAX_LABELLEN); 3060 log_assert(len1 == len2 && len1 != 0); 3061 /* compare the labels - bitwise identical */ 3062 if(memcmp(d1, d2, len1) != 0) 3063 return 0; 3064 d1 += len1; 3065 d2 += len2; 3066 len1 = *d1++; 3067 len2 = *d2++; 3068 } 3069 return 1; 3070 } 3071 3072 /** call the callbacks for a serviced query */ 3073 static void 3074 serviced_callbacks(struct serviced_query* sq, int error, struct comm_point* c, 3075 struct comm_reply* rep) 3076 { 3077 struct service_callback* p; 3078 int dobackup = (sq->cblist && sq->cblist->next); /* >1 cb*/ 3079 uint8_t *backup_p = NULL; 3080 size_t backlen = 0; 3081 #ifdef UNBOUND_DEBUG 3082 rbnode_type* rem = 3083 #else 3084 (void) 3085 #endif 3086 /* remove from tree, and schedule for deletion, so that callbacks 3087 * can safely deregister themselves and even create new serviced 3088 * queries that are identical to this one. */ 3089 rbtree_delete(sq->outnet->serviced, sq); 3090 log_assert(rem); /* should have been present */ 3091 sq->to_be_deleted = 1; 3092 verbose(VERB_ALGO, "svcd callbacks start"); 3093 if(sq->outnet->use_caps_for_id && error == NETEVENT_NOERROR && c && 3094 !sq->nocaps && sq->qtype != LDNS_RR_TYPE_PTR) { 3095 /* for type PTR do not check perturbed name in answer, 3096 * compatibility with cisco dns guard boxes that mess up 3097 * reverse queries 0x20 contents */ 3098 /* noerror and nxdomain must have a qname in reply */ 3099 if(sldns_buffer_read_u16_at(c->buffer, 4) == 0 && 3100 (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) 3101 == LDNS_RCODE_NOERROR || 3102 LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) 3103 == LDNS_RCODE_NXDOMAIN)) { 3104 verbose(VERB_DETAIL, "no qname in reply to check 0x20ID"); 3105 log_addr(VERB_DETAIL, "from server", 3106 &sq->addr, sq->addrlen); 3107 log_buf(VERB_DETAIL, "for packet", c->buffer); 3108 error = NETEVENT_CLOSED; 3109 c = NULL; 3110 } else if(sldns_buffer_read_u16_at(c->buffer, 4) > 0 && 3111 !serviced_check_qname(c->buffer, sq->qbuf, 3112 sq->qbuflen)) { 3113 verbose(VERB_DETAIL, "wrong 0x20-ID in reply qname"); 3114 log_addr(VERB_DETAIL, "from server", 3115 &sq->addr, sq->addrlen); 3116 log_buf(VERB_DETAIL, "for packet", c->buffer); 3117 error = NETEVENT_CAPSFAIL; 3118 /* and cleanup too */ 3119 pkt_dname_tolower(c->buffer, 3120 sldns_buffer_at(c->buffer, 12)); 3121 } else { 3122 verbose(VERB_ALGO, "good 0x20-ID in reply qname"); 3123 /* cleanup caps, prettier cache contents. */ 3124 pkt_dname_tolower(c->buffer, 3125 sldns_buffer_at(c->buffer, 12)); 3126 } 3127 } 3128 if(dobackup && c) { 3129 /* make a backup of the query, since the querystate processing 3130 * may send outgoing queries that overwrite the buffer. 3131 * use secondary buffer to store the query. 3132 * This is a data copy, but faster than packet to server */ 3133 backlen = sldns_buffer_limit(c->buffer); 3134 backup_p = regional_alloc_init(sq->region, 3135 sldns_buffer_begin(c->buffer), backlen); 3136 if(!backup_p) { 3137 log_err("malloc failure in serviced query callbacks"); 3138 error = NETEVENT_CLOSED; 3139 c = NULL; 3140 } 3141 sq->outnet->svcd_overhead = backlen; 3142 } 3143 /* test the actual sq->cblist, because the next elem could be deleted*/ 3144 while((p=sq->cblist) != NULL) { 3145 sq->cblist = p->next; /* remove this element */ 3146 if(dobackup && c) { 3147 sldns_buffer_clear(c->buffer); 3148 sldns_buffer_write(c->buffer, backup_p, backlen); 3149 sldns_buffer_flip(c->buffer); 3150 } 3151 fptr_ok(fptr_whitelist_serviced_query(p->cb)); 3152 (void)(*p->cb)(c, p->cb_arg, error, rep); 3153 } 3154 if(backup_p) { 3155 sq->outnet->svcd_overhead = 0; 3156 } 3157 verbose(VERB_ALGO, "svcd callbacks end"); 3158 log_assert(sq->cblist == NULL); 3159 serviced_delete(sq); 3160 } 3161 3162 int 3163 serviced_tcp_callback(struct comm_point* c, void* arg, int error, 3164 struct comm_reply* rep) 3165 { 3166 struct serviced_query* sq = (struct serviced_query*)arg; 3167 struct comm_reply r2; 3168 #ifdef USE_DNSTAP 3169 struct waiting_tcp* w = (struct waiting_tcp*)sq->pending; 3170 struct pending_tcp* pend_tcp = NULL; 3171 struct port_if* pi = NULL; 3172 if(w && !w->on_tcp_waiting_list && w->next_waiting) { 3173 pend_tcp = (struct pending_tcp*)w->next_waiting; 3174 pi = pend_tcp->pi; 3175 } 3176 #endif 3177 sq->pending = NULL; /* removed after this callback */ 3178 if(error != NETEVENT_NOERROR) 3179 log_addr(VERB_QUERY, "tcp error for address", 3180 &sq->addr, sq->addrlen); 3181 if(error==NETEVENT_NOERROR) 3182 infra_update_tcp_works(sq->outnet->infra, &sq->addr, 3183 sq->addrlen, sq->zone, sq->zonelen); 3184 #ifdef USE_DNSTAP 3185 /* 3186 * sending src (local service)/dst (upstream) addresses over DNSTAP 3187 */ 3188 if(error==NETEVENT_NOERROR && pi && sq->outnet->dtenv && 3189 (sq->outnet->dtenv->log_resolver_response_messages || 3190 sq->outnet->dtenv->log_forwarder_response_messages)) { 3191 log_addr(VERB_ALGO, "response from upstream", &sq->addr, sq->addrlen); 3192 log_addr(VERB_ALGO, "to local addr", &pi->addr, pi->addrlen); 3193 dt_msg_send_outside_response(sq->outnet->dtenv, &sq->addr, 3194 &pi->addr, c->type, c->ssl, sq->zone, sq->zonelen, sq->qbuf, 3195 sq->qbuflen, &sq->last_sent_time, sq->outnet->now_tv, 3196 c->buffer); 3197 } 3198 #endif 3199 if(error==NETEVENT_NOERROR && sq->status == serviced_query_TCP_EDNS && 3200 (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) == 3201 LDNS_RCODE_FORMERR || LDNS_RCODE_WIRE(sldns_buffer_begin( 3202 c->buffer)) == LDNS_RCODE_NOTIMPL) ) { 3203 /* attempt to fallback to nonEDNS */ 3204 sq->status = serviced_query_TCP_EDNS_fallback; 3205 serviced_tcp_initiate(sq, c->buffer); 3206 return 0; 3207 } else if(error==NETEVENT_NOERROR && 3208 sq->status == serviced_query_TCP_EDNS_fallback && 3209 (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) == 3210 LDNS_RCODE_NOERROR || LDNS_RCODE_WIRE( 3211 sldns_buffer_begin(c->buffer)) == LDNS_RCODE_NXDOMAIN 3212 || LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) 3213 == LDNS_RCODE_YXDOMAIN)) { 3214 /* the fallback produced a result that looks promising, note 3215 * that this server should be approached without EDNS */ 3216 /* only store noEDNS in cache if domain is noDNSSEC */ 3217 if(!sq->want_dnssec) 3218 if(!infra_edns_update(sq->outnet->infra, &sq->addr, 3219 sq->addrlen, sq->zone, sq->zonelen, -1, 3220 *sq->outnet->now_secs)) 3221 log_err("Out of memory caching no edns for host"); 3222 sq->status = serviced_query_TCP; 3223 } 3224 if(sq->tcp_upstream || sq->ssl_upstream) { 3225 struct timeval now = *sq->outnet->now_tv; 3226 if(error!=NETEVENT_NOERROR) { 3227 if(!infra_rtt_update(sq->outnet->infra, &sq->addr, 3228 sq->addrlen, sq->zone, sq->zonelen, sq->qtype, 3229 -1, sq->last_rtt, (time_t)now.tv_sec)) 3230 log_err("out of memory in TCP exponential backoff."); 3231 } else if(now.tv_sec > sq->last_sent_time.tv_sec || 3232 (now.tv_sec == sq->last_sent_time.tv_sec && 3233 now.tv_usec > sq->last_sent_time.tv_usec)) { 3234 /* convert from microseconds to milliseconds */ 3235 int roundtime = ((int)(now.tv_sec - sq->last_sent_time.tv_sec))*1000 3236 + ((int)now.tv_usec - (int)sq->last_sent_time.tv_usec)/1000; 3237 verbose(VERB_ALGO, "measured TCP-time at %d msec", roundtime); 3238 log_assert(roundtime >= 0); 3239 /* only store if less then AUTH_TIMEOUT seconds, it could be 3240 * huge due to system-hibernated and we woke up */ 3241 if(roundtime < 60000) { 3242 if(!infra_rtt_update(sq->outnet->infra, &sq->addr, 3243 sq->addrlen, sq->zone, sq->zonelen, sq->qtype, 3244 roundtime, sq->last_rtt, (time_t)now.tv_sec)) 3245 log_err("out of memory noting rtt."); 3246 } 3247 } 3248 } 3249 /* insert address into reply info */ 3250 if(!rep) { 3251 /* create one if there isn't (on errors) */ 3252 rep = &r2; 3253 r2.c = c; 3254 } 3255 memcpy(&rep->remote_addr, &sq->addr, sq->addrlen); 3256 rep->remote_addrlen = sq->addrlen; 3257 serviced_callbacks(sq, error, c, rep); 3258 return 0; 3259 } 3260 3261 static void 3262 serviced_tcp_initiate(struct serviced_query* sq, sldns_buffer* buff) 3263 { 3264 verbose(VERB_ALGO, "initiate TCP query %s", 3265 sq->status==serviced_query_TCP_EDNS?"EDNS":""); 3266 serviced_encode(sq, buff, sq->status == serviced_query_TCP_EDNS); 3267 sq->last_sent_time = *sq->outnet->now_tv; 3268 log_assert(!sq->busy); 3269 sq->busy = 1; 3270 sq->pending = pending_tcp_query(sq, buff, sq->outnet->tcp_auth_query_timeout, 3271 serviced_tcp_callback, sq); 3272 sq->busy = 0; 3273 if(!sq->pending) { 3274 /* delete from tree so that a retry by above layer does not 3275 * clash with this entry */ 3276 verbose(VERB_ALGO, "serviced_tcp_initiate: failed to send tcp query"); 3277 serviced_callbacks(sq, NETEVENT_CLOSED, NULL, NULL); 3278 } 3279 } 3280 3281 /** Send serviced query over TCP return false on initial failure */ 3282 static int 3283 serviced_tcp_send(struct serviced_query* sq, sldns_buffer* buff) 3284 { 3285 int vs, rtt, timeout; 3286 uint8_t edns_lame_known; 3287 if(!infra_host(sq->outnet->infra, &sq->addr, sq->addrlen, sq->zone, 3288 sq->zonelen, *sq->outnet->now_secs, &vs, &edns_lame_known, 3289 &rtt)) 3290 return 0; 3291 sq->last_rtt = rtt; 3292 if(vs != -1) 3293 sq->status = serviced_query_TCP_EDNS; 3294 else sq->status = serviced_query_TCP; 3295 serviced_encode(sq, buff, sq->status == serviced_query_TCP_EDNS); 3296 sq->last_sent_time = *sq->outnet->now_tv; 3297 if(sq->tcp_upstream || sq->ssl_upstream) { 3298 timeout = rtt; 3299 if(rtt >= UNKNOWN_SERVER_NICENESS && rtt < sq->outnet->tcp_auth_query_timeout) 3300 timeout = sq->outnet->tcp_auth_query_timeout; 3301 } else { 3302 timeout = sq->outnet->tcp_auth_query_timeout; 3303 } 3304 log_assert(!sq->busy); 3305 sq->busy = 1; 3306 sq->pending = pending_tcp_query(sq, buff, timeout, 3307 serviced_tcp_callback, sq); 3308 sq->busy = 0; 3309 return sq->pending != NULL; 3310 } 3311 3312 /* see if packet is edns malformed; got zeroes at start. 3313 * This is from servers that return malformed packets to EDNS0 queries, 3314 * but they return good packets for nonEDNS0 queries. 3315 * We try to detect their output; without resorting to a full parse or 3316 * check for too many bytes after the end of the packet. */ 3317 static int 3318 packet_edns_malformed(struct sldns_buffer* buf, int qtype) 3319 { 3320 size_t len; 3321 if(sldns_buffer_limit(buf) < LDNS_HEADER_SIZE) 3322 return 1; /* malformed */ 3323 /* they have NOERROR rcode, 1 answer. */ 3324 if(LDNS_RCODE_WIRE(sldns_buffer_begin(buf)) != LDNS_RCODE_NOERROR) 3325 return 0; 3326 /* one query (to skip) and answer records */ 3327 if(LDNS_QDCOUNT(sldns_buffer_begin(buf)) != 1 || 3328 LDNS_ANCOUNT(sldns_buffer_begin(buf)) == 0) 3329 return 0; 3330 /* skip qname */ 3331 len = dname_valid(sldns_buffer_at(buf, LDNS_HEADER_SIZE), 3332 sldns_buffer_limit(buf)-LDNS_HEADER_SIZE); 3333 if(len == 0) 3334 return 0; 3335 if(len == 1 && qtype == 0) 3336 return 0; /* we asked for '.' and type 0 */ 3337 /* and then 4 bytes (type and class of query) */ 3338 if(sldns_buffer_limit(buf) < LDNS_HEADER_SIZE + len + 4 + 3) 3339 return 0; 3340 3341 /* and start with 11 zeroes as the answer RR */ 3342 /* so check the qtype of the answer record, qname=0, type=0 */ 3343 if(sldns_buffer_at(buf, LDNS_HEADER_SIZE+len+4)[0] == 0 && 3344 sldns_buffer_at(buf, LDNS_HEADER_SIZE+len+4)[1] == 0 && 3345 sldns_buffer_at(buf, LDNS_HEADER_SIZE+len+4)[2] == 0) 3346 return 1; 3347 return 0; 3348 } 3349 3350 int 3351 serviced_udp_callback(struct comm_point* c, void* arg, int error, 3352 struct comm_reply* rep) 3353 { 3354 struct serviced_query* sq = (struct serviced_query*)arg; 3355 struct outside_network* outnet = sq->outnet; 3356 struct timeval now = *sq->outnet->now_tv; 3357 #ifdef USE_DNSTAP 3358 struct pending* p = (struct pending*)sq->pending; 3359 #endif 3360 3361 sq->pending = NULL; /* removed after callback */ 3362 if(error == NETEVENT_TIMEOUT) { 3363 if(sq->status == serviced_query_UDP_EDNS && sq->last_rtt < 5000 && 3364 (serviced_query_udp_size(sq, serviced_query_UDP_EDNS_FRAG) < serviced_query_udp_size(sq, serviced_query_UDP_EDNS))) { 3365 /* fallback to 1472/1232 */ 3366 sq->status = serviced_query_UDP_EDNS_FRAG; 3367 log_name_addr(VERB_ALGO, "try edns1xx2", sq->qbuf+10, 3368 &sq->addr, sq->addrlen); 3369 if(!serviced_udp_send(sq, c->buffer)) { 3370 serviced_callbacks(sq, NETEVENT_CLOSED, c, rep); 3371 } 3372 return 0; 3373 } 3374 if(sq->status == serviced_query_UDP_EDNS_FRAG) { 3375 /* fragmentation size did not fix it */ 3376 sq->status = serviced_query_UDP_EDNS; 3377 } 3378 sq->retry++; 3379 if(!infra_rtt_update(outnet->infra, &sq->addr, sq->addrlen, 3380 sq->zone, sq->zonelen, sq->qtype, -1, sq->last_rtt, 3381 (time_t)now.tv_sec)) 3382 log_err("out of memory in UDP exponential backoff"); 3383 if(sq->retry < OUTBOUND_UDP_RETRY) { 3384 log_name_addr(VERB_ALGO, "retry query", sq->qbuf+10, 3385 &sq->addr, sq->addrlen); 3386 if(!serviced_udp_send(sq, c->buffer)) { 3387 serviced_callbacks(sq, NETEVENT_CLOSED, c, rep); 3388 } 3389 return 0; 3390 } 3391 } 3392 if(error != NETEVENT_NOERROR) { 3393 /* udp returns error (due to no ID or interface available) */ 3394 serviced_callbacks(sq, error, c, rep); 3395 return 0; 3396 } 3397 #ifdef USE_DNSTAP 3398 /* 3399 * sending src (local service)/dst (upstream) addresses over DNSTAP 3400 */ 3401 if(error == NETEVENT_NOERROR && outnet->dtenv && p->pc && 3402 (outnet->dtenv->log_resolver_response_messages || 3403 outnet->dtenv->log_forwarder_response_messages)) { 3404 log_addr(VERB_ALGO, "response from upstream", &sq->addr, sq->addrlen); 3405 log_addr(VERB_ALGO, "to local addr", &p->pc->pif->addr, 3406 p->pc->pif->addrlen); 3407 dt_msg_send_outside_response(outnet->dtenv, &sq->addr, 3408 &p->pc->pif->addr, c->type, c->ssl, sq->zone, sq->zonelen, 3409 sq->qbuf, sq->qbuflen, &sq->last_sent_time, 3410 sq->outnet->now_tv, c->buffer); 3411 } 3412 #endif 3413 if( (sq->status == serviced_query_UDP_EDNS 3414 ||sq->status == serviced_query_UDP_EDNS_FRAG) 3415 && (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) 3416 == LDNS_RCODE_FORMERR || LDNS_RCODE_WIRE( 3417 sldns_buffer_begin(c->buffer)) == LDNS_RCODE_NOTIMPL 3418 || packet_edns_malformed(c->buffer, sq->qtype) 3419 )) { 3420 /* try to get an answer by falling back without EDNS */ 3421 verbose(VERB_ALGO, "serviced query: attempt without EDNS"); 3422 sq->status = serviced_query_UDP_EDNS_fallback; 3423 sq->retry = 0; 3424 if(!serviced_udp_send(sq, c->buffer)) { 3425 serviced_callbacks(sq, NETEVENT_CLOSED, c, rep); 3426 } 3427 return 0; 3428 } else if(sq->status == serviced_query_UDP_EDNS && 3429 !sq->edns_lame_known) { 3430 /* now we know that edns queries received answers store that */ 3431 log_addr(VERB_ALGO, "serviced query: EDNS works for", 3432 &sq->addr, sq->addrlen); 3433 if(!infra_edns_update(outnet->infra, &sq->addr, sq->addrlen, 3434 sq->zone, sq->zonelen, 0, (time_t)now.tv_sec)) { 3435 log_err("Out of memory caching edns works"); 3436 } 3437 sq->edns_lame_known = 1; 3438 } else if(sq->status == serviced_query_UDP_EDNS_fallback && 3439 !sq->edns_lame_known && (LDNS_RCODE_WIRE( 3440 sldns_buffer_begin(c->buffer)) == LDNS_RCODE_NOERROR || 3441 LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) == 3442 LDNS_RCODE_NXDOMAIN || LDNS_RCODE_WIRE(sldns_buffer_begin( 3443 c->buffer)) == LDNS_RCODE_YXDOMAIN)) { 3444 /* the fallback produced a result that looks promising, note 3445 * that this server should be approached without EDNS */ 3446 /* only store noEDNS in cache if domain is noDNSSEC */ 3447 if(!sq->want_dnssec) { 3448 log_addr(VERB_ALGO, "serviced query: EDNS fails for", 3449 &sq->addr, sq->addrlen); 3450 if(!infra_edns_update(outnet->infra, &sq->addr, sq->addrlen, 3451 sq->zone, sq->zonelen, -1, (time_t)now.tv_sec)) { 3452 log_err("Out of memory caching no edns for host"); 3453 } 3454 } else { 3455 log_addr(VERB_ALGO, "serviced query: EDNS fails, but " 3456 "not stored because need DNSSEC for", &sq->addr, 3457 sq->addrlen); 3458 } 3459 sq->status = serviced_query_UDP; 3460 } 3461 if(now.tv_sec > sq->last_sent_time.tv_sec || 3462 (now.tv_sec == sq->last_sent_time.tv_sec && 3463 now.tv_usec > sq->last_sent_time.tv_usec)) { 3464 /* convert from microseconds to milliseconds */ 3465 int roundtime = ((int)(now.tv_sec - sq->last_sent_time.tv_sec))*1000 3466 + ((int)now.tv_usec - (int)sq->last_sent_time.tv_usec)/1000; 3467 verbose(VERB_ALGO, "measured roundtrip at %d msec", roundtime); 3468 log_assert(roundtime >= 0); 3469 /* in case the system hibernated, do not enter a huge value, 3470 * above this value gives trouble with server selection */ 3471 if(roundtime < 60000) { 3472 if(!infra_rtt_update(outnet->infra, &sq->addr, sq->addrlen, 3473 sq->zone, sq->zonelen, sq->qtype, roundtime, 3474 sq->last_rtt, (time_t)now.tv_sec)) 3475 log_err("out of memory noting rtt."); 3476 } 3477 } 3478 /* perform TC flag check and TCP fallback after updating our 3479 * cache entries for EDNS status and RTT times */ 3480 if(LDNS_TC_WIRE(sldns_buffer_begin(c->buffer))) { 3481 /* fallback to TCP */ 3482 /* this discards partial UDP contents */ 3483 if(sq->status == serviced_query_UDP_EDNS || 3484 sq->status == serviced_query_UDP_EDNS_FRAG || 3485 sq->status == serviced_query_UDP_EDNS_fallback) 3486 /* if we have unfinished EDNS_fallback, start again */ 3487 sq->status = serviced_query_TCP_EDNS; 3488 else sq->status = serviced_query_TCP; 3489 serviced_tcp_initiate(sq, c->buffer); 3490 return 0; 3491 } 3492 /* yay! an answer */ 3493 serviced_callbacks(sq, error, c, rep); 3494 return 0; 3495 } 3496 3497 struct serviced_query* 3498 outnet_serviced_query(struct outside_network* outnet, 3499 struct query_info* qinfo, uint16_t flags, int dnssec, int want_dnssec, 3500 int nocaps, int check_ratelimit, int tcp_upstream, int ssl_upstream, 3501 char* tls_auth_name, struct sockaddr_storage* addr, socklen_t addrlen, 3502 uint8_t* zone, size_t zonelen, struct module_qstate* qstate, 3503 comm_point_callback_type* callback, void* callback_arg, 3504 sldns_buffer* buff, struct module_env* env, int* was_ratelimited, 3505 int* ratelimit_incremented) 3506 { 3507 struct serviced_query* sq; 3508 struct service_callback* cb; 3509 struct edns_string_addr* client_string_addr; 3510 struct regional* region; 3511 struct edns_option* backed_up_opt_list = qstate->edns_opts_back_out; 3512 struct edns_option* per_upstream_opt_list = NULL; 3513 time_t timenow = 0; 3514 3515 /* If we have an already populated EDNS option list make a copy since 3516 * we may now add upstream specific EDNS options. */ 3517 /* Use a region that could be attached to a serviced_query, if it needs 3518 * to be created. If an existing one is found then this region will be 3519 * destroyed here. */ 3520 region = alloc_reg_obtain(env->alloc); 3521 if(!region) return NULL; 3522 if(qstate->edns_opts_back_out) { 3523 per_upstream_opt_list = edns_opt_copy_region( 3524 qstate->edns_opts_back_out, region); 3525 if(!per_upstream_opt_list) { 3526 alloc_reg_release(env->alloc, region); 3527 return NULL; 3528 } 3529 qstate->edns_opts_back_out = per_upstream_opt_list; 3530 } 3531 3532 if(!inplace_cb_query_call(env, qinfo, flags, addr, addrlen, zone, 3533 zonelen, qstate, region)) { 3534 alloc_reg_release(env->alloc, region); 3535 return NULL; 3536 } 3537 /* Restore the option list; we can explicitly use the copied one from 3538 * now on. */ 3539 per_upstream_opt_list = qstate->edns_opts_back_out; 3540 qstate->edns_opts_back_out = backed_up_opt_list; 3541 3542 if((client_string_addr = edns_string_addr_lookup( 3543 &env->edns_strings->client_strings, addr, addrlen))) { 3544 edns_opt_list_append(&per_upstream_opt_list, 3545 env->edns_strings->client_string_opcode, 3546 client_string_addr->string_len, 3547 client_string_addr->string, region); 3548 } 3549 3550 serviced_gen_query(buff, qinfo->qname, qinfo->qname_len, qinfo->qtype, 3551 qinfo->qclass, flags); 3552 sq = lookup_serviced(outnet, buff, dnssec, addr, addrlen, 3553 per_upstream_opt_list); 3554 if(!sq) { 3555 /* Check ratelimit only for new serviced_query */ 3556 if(check_ratelimit) { 3557 timenow = *env->now; 3558 if(!infra_ratelimit_inc(env->infra_cache, zone, 3559 zonelen, timenow, env->cfg->ratelimit_backoff, 3560 &qstate->qinfo, 3561 qstate->mesh_info->reply_list 3562 ?&qstate->mesh_info->reply_list->query_reply 3563 :NULL)) { 3564 /* Can we pass through with slip factor? */ 3565 if(env->cfg->ratelimit_factor == 0 || 3566 ub_random_max(env->rnd, 3567 env->cfg->ratelimit_factor) != 1) { 3568 *was_ratelimited = 1; 3569 alloc_reg_release(env->alloc, region); 3570 return NULL; 3571 } 3572 log_nametypeclass(VERB_ALGO, 3573 "ratelimit allowed through for " 3574 "delegation point", zone, 3575 LDNS_RR_TYPE_NS, LDNS_RR_CLASS_IN); 3576 } 3577 *ratelimit_incremented = 1; 3578 } 3579 /* make new serviced query entry */ 3580 sq = serviced_create(outnet, buff, dnssec, want_dnssec, nocaps, 3581 tcp_upstream, ssl_upstream, tls_auth_name, addr, 3582 addrlen, zone, zonelen, (int)qinfo->qtype, 3583 per_upstream_opt_list, 3584 ( ssl_upstream && env->cfg->pad_queries 3585 ? env->cfg->pad_queries_block_size : 0 ), 3586 env->alloc, region); 3587 if(!sq) { 3588 if(check_ratelimit) { 3589 infra_ratelimit_dec(env->infra_cache, 3590 zone, zonelen, timenow); 3591 } 3592 return NULL; 3593 } 3594 if(!(cb = (struct service_callback*)regional_alloc( 3595 sq->region, sizeof(*cb)))) { 3596 if(check_ratelimit) { 3597 infra_ratelimit_dec(env->infra_cache, 3598 zone, zonelen, timenow); 3599 } 3600 (void)rbtree_delete(outnet->serviced, sq); 3601 serviced_node_del(&sq->node, NULL); 3602 return NULL; 3603 } 3604 /* No network action at this point; it will be invoked with the 3605 * serviced_query timer instead to run outside of the mesh. */ 3606 } else { 3607 /* We don't need this region anymore. */ 3608 alloc_reg_release(env->alloc, region); 3609 /* duplicate entries are included in the callback list, because 3610 * there is a counterpart registration by our caller that needs 3611 * to be doubly-removed (with callbacks perhaps). */ 3612 if(!(cb = (struct service_callback*)regional_alloc( 3613 sq->region, sizeof(*cb)))) { 3614 return NULL; 3615 } 3616 } 3617 /* add callback to list of callbacks */ 3618 cb->cb = callback; 3619 cb->cb_arg = callback_arg; 3620 cb->next = sq->cblist; 3621 sq->cblist = cb; 3622 return sq; 3623 } 3624 3625 /** remove callback from list */ 3626 static void 3627 callback_list_remove(struct serviced_query* sq, void* cb_arg) 3628 { 3629 struct service_callback** pp = &sq->cblist; 3630 while(*pp) { 3631 if((*pp)->cb_arg == cb_arg) { 3632 struct service_callback* del = *pp; 3633 *pp = del->next; 3634 return; 3635 } 3636 pp = &(*pp)->next; 3637 } 3638 } 3639 3640 void outnet_serviced_query_stop(struct serviced_query* sq, void* cb_arg) 3641 { 3642 if(!sq) 3643 return; 3644 callback_list_remove(sq, cb_arg); 3645 /* if callbacks() routine scheduled deletion, let it do that */ 3646 if(!sq->cblist && !sq->busy && !sq->to_be_deleted) { 3647 (void)rbtree_delete(sq->outnet->serviced, sq); 3648 serviced_delete(sq); 3649 } 3650 } 3651 3652 /** create fd to send to this destination */ 3653 static int 3654 fd_for_dest(struct outside_network* outnet, struct sockaddr_storage* to_addr, 3655 socklen_t to_addrlen) 3656 { 3657 struct sockaddr_storage* addr; 3658 socklen_t addrlen; 3659 int i, try, dscp; 3660 struct port_if* pif; 3661 3662 /* create fd */ 3663 dscp = outnet->ip_dscp; 3664 for(try = 0; try<1000; try++) { 3665 int port = 0; 3666 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 3667 int reused = 0; 3668 #endif 3669 int freebind = 0; 3670 int noproto = 0; 3671 int inuse = 0; 3672 int fd = -1; 3673 3674 /* select interface */ 3675 if(addr_is_ip6(to_addr, to_addrlen)) { 3676 if(outnet->num_ip6 == 0) { 3677 char to[64]; 3678 addr_to_str(to_addr, to_addrlen, to, sizeof(to)); 3679 verbose(VERB_QUERY, "need ipv6 to send, but no ipv6 outgoing interfaces, for %s", to); 3680 return -1; 3681 } 3682 i = ub_random_max(outnet->rnd, outnet->num_ip6); 3683 pif = &outnet->ip6_ifs[i]; 3684 } else { 3685 if(outnet->num_ip4 == 0) { 3686 char to[64]; 3687 addr_to_str(to_addr, to_addrlen, to, sizeof(to)); 3688 verbose(VERB_QUERY, "need ipv4 to send, but no ipv4 outgoing interfaces, for %s", to); 3689 return -1; 3690 } 3691 i = ub_random_max(outnet->rnd, outnet->num_ip4); 3692 pif = &outnet->ip4_ifs[i]; 3693 } 3694 addr = &pif->addr; 3695 addrlen = pif->addrlen; 3696 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 3697 if(!shared_ports_fetch_random(outnet->shared_ports, 3698 pif->shpif, outnet->rnd, 0, pif->inuse, 3699 &port, &reused)) { 3700 /* try again, perhaps another interface. */ 3701 continue; 3702 } 3703 if(reused) { 3704 log_assert(port < pif->inuse); 3705 port = pif->out[port]->number; 3706 } 3707 #else 3708 port = 0; 3709 #endif 3710 if(addr_is_ip6(to_addr, to_addrlen)) { 3711 struct sockaddr_in6 sa = *(struct sockaddr_in6*)addr; 3712 sa.sin6_port = (in_port_t)htons((uint16_t)port); 3713 fd = create_udp_sock(AF_INET6, SOCK_DGRAM, 3714 (struct sockaddr*)&sa, addrlen, 1, &inuse, &noproto, 3715 0, 0, 0, NULL, 0, freebind, 0, dscp); 3716 } else { 3717 struct sockaddr_in* sa = (struct sockaddr_in*)addr; 3718 sa->sin_port = (in_port_t)htons((uint16_t)port); 3719 fd = create_udp_sock(AF_INET, SOCK_DGRAM, 3720 (struct sockaddr*)addr, addrlen, 1, &inuse, &noproto, 3721 0, 0, 0, NULL, 0, freebind, 0, dscp); 3722 } 3723 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 3724 if(!reused) { 3725 /* Return the port to the pool, since the caller does 3726 * not keep track of it, also have done fd, and bind. */ 3727 shared_ports_return_port(outnet->shared_ports, 3728 pif->shpif, port); 3729 } 3730 #endif 3731 if(fd != -1) { 3732 return fd; 3733 } 3734 if(!inuse) { 3735 return -1; 3736 } 3737 } 3738 /* too many tries */ 3739 log_err("cannot send probe, ports are in use"); 3740 return -1; 3741 } 3742 3743 struct comm_point* 3744 outnet_comm_point_for_udp(struct outside_network* outnet, 3745 comm_point_callback_type* cb, void* cb_arg, 3746 struct sockaddr_storage* to_addr, socklen_t to_addrlen) 3747 { 3748 struct comm_point* cp; 3749 int fd = fd_for_dest(outnet, to_addr, to_addrlen); 3750 if(fd == -1) { 3751 return NULL; 3752 } 3753 cp = comm_point_create_udp(outnet->base, fd, outnet->udp_buff, 0, 3754 cb, cb_arg, NULL); 3755 if(!cp) { 3756 log_err("malloc failure"); 3757 close(fd); 3758 return NULL; 3759 } 3760 return cp; 3761 } 3762 3763 /** setup SSL for comm point */ 3764 static int 3765 setup_comm_ssl(struct comm_point* cp, struct outside_network* outnet, 3766 int fd, char* host) 3767 { 3768 cp->ssl = outgoing_ssl_fd(outnet->sslctx, fd); 3769 if(!cp->ssl) { 3770 log_err("cannot create SSL object"); 3771 return 0; 3772 } 3773 #ifdef USE_WINSOCK 3774 comm_point_tcp_win_bio_cb(cp, cp->ssl); 3775 #endif 3776 cp->ssl_shake_state = comm_ssl_shake_write; 3777 /* https verification */ 3778 #ifdef HAVE_SSL 3779 if(outnet->tls_use_sni) { 3780 (void)SSL_set_tlsext_host_name(cp->ssl, host); 3781 } 3782 #endif 3783 #ifdef HAVE_SSL_SET1_DNSNAME 3784 if((SSL_CTX_get_verify_mode(outnet->sslctx)&SSL_VERIFY_PEER)) { 3785 /* because we set SSL_VERIFY_PEER, in netevent in 3786 * ssl_handshake, it'll check if the certificate 3787 * verification has succeeded */ 3788 /* SSL_VERIFY_PEER is set on the sslctx */ 3789 /* and the certificates to verify with are loaded into 3790 * it with SSL_load_verify_locations or 3791 * SSL_CTX_set_default_verify_paths */ 3792 /* setting the hostname makes openssl verify the 3793 * host name in the x509 certificate in the 3794 * SSL connection*/ 3795 struct sockaddr_storage tmpaddr; 3796 socklen_t tmpaddrlen = (socklen_t)sizeof(tmpaddr); 3797 if(ipstrtoaddr(host, UNBOUND_DNS_PORT, &tmpaddr, &tmpaddrlen)) { 3798 if(!SSL_set1_ipaddr(cp->ssl, host)) { 3799 log_err("SSL_set1_ipaddr failed"); 3800 return 0; 3801 } 3802 } else { 3803 if(!SSL_set1_dnsname(cp->ssl, host)) { 3804 log_err("SSL_set1_dnsname failed"); 3805 return 0; 3806 } 3807 } 3808 } 3809 #elif defined(HAVE_SSL_SET1_HOST) 3810 if((SSL_CTX_get_verify_mode(outnet->sslctx)&SSL_VERIFY_PEER)) { 3811 /* because we set SSL_VERIFY_PEER, in netevent in 3812 * ssl_handshake, it'll check if the certificate 3813 * verification has succeeded */ 3814 /* SSL_VERIFY_PEER is set on the sslctx */ 3815 /* and the certificates to verify with are loaded into 3816 * it with SSL_load_verify_locations or 3817 * SSL_CTX_set_default_verify_paths */ 3818 /* setting the hostname makes openssl verify the 3819 * host name in the x509 certificate in the 3820 * SSL connection*/ 3821 if(!SSL_set1_host(cp->ssl, host)) { 3822 log_err("SSL_set1_host failed"); 3823 return 0; 3824 } 3825 } 3826 #elif defined(HAVE_X509_VERIFY_PARAM_SET1_HOST) 3827 /* openssl 1.0.2 has this function that can be used for 3828 * set1_host like verification */ 3829 if((SSL_CTX_get_verify_mode(outnet->sslctx)&SSL_VERIFY_PEER)) { 3830 X509_VERIFY_PARAM* param = SSL_get0_param(cp->ssl); 3831 # ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS 3832 X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); 3833 # endif 3834 if(!X509_VERIFY_PARAM_set1_host(param, host, strlen(host))) { 3835 log_err("X509_VERIFY_PARAM_set1_host failed"); 3836 return 0; 3837 } 3838 } 3839 #else 3840 (void)host; 3841 #endif /* HAVE_SSL_SET1_HOST */ 3842 return 1; 3843 } 3844 3845 struct comm_point* 3846 outnet_comm_point_for_tcp(struct outside_network* outnet, 3847 comm_point_callback_type* cb, void* cb_arg, 3848 struct sockaddr_storage* to_addr, socklen_t to_addrlen, 3849 sldns_buffer* query, int timeout, int ssl, char* host) 3850 { 3851 struct comm_point* cp; 3852 int fd = outnet_get_tcp_fd(to_addr, to_addrlen, outnet->tcp_mss, 3853 outnet->ip_dscp, ssl); 3854 if(fd == -1) { 3855 return 0; 3856 } 3857 fd_set_nonblock(fd); 3858 if(!outnet_tcp_connect(fd, to_addr, to_addrlen)) { 3859 /* outnet_tcp_connect has closed fd on error for us */ 3860 return 0; 3861 } 3862 cp = comm_point_create_tcp_out(outnet->base, 65552, cb, cb_arg); 3863 if(!cp) { 3864 log_err("malloc failure"); 3865 close(fd); 3866 return 0; 3867 } 3868 cp->repinfo.remote_addrlen = to_addrlen; 3869 memcpy(&cp->repinfo.remote_addr, to_addr, to_addrlen); 3870 3871 /* setup for SSL (if needed) */ 3872 if(ssl) { 3873 if(!setup_comm_ssl(cp, outnet, fd, host)) { 3874 log_err("cannot setup XoT"); 3875 comm_point_delete(cp); 3876 return NULL; 3877 } 3878 } 3879 3880 /* set timeout on TCP connection */ 3881 comm_point_start_listening(cp, fd, timeout); 3882 /* copy scratch buffer to cp->buffer */ 3883 sldns_buffer_copy(cp->buffer, query); 3884 return cp; 3885 } 3886 3887 /** setup the User-Agent HTTP header based on http-user-agent configuration */ 3888 static void 3889 setup_http_user_agent(sldns_buffer* buf, struct config_file* cfg) 3890 { 3891 if(cfg->hide_http_user_agent) return; 3892 if(cfg->http_user_agent==NULL || cfg->http_user_agent[0] == 0) { 3893 sldns_buffer_printf(buf, "User-Agent: %s/%s\r\n", PACKAGE_NAME, 3894 PACKAGE_VERSION); 3895 } else { 3896 sldns_buffer_printf(buf, "User-Agent: %s\r\n", cfg->http_user_agent); 3897 } 3898 } 3899 3900 /** setup http request headers in buffer for sending query to destination */ 3901 static int 3902 setup_http_request(sldns_buffer* buf, char* host, char* path, 3903 struct config_file* cfg) 3904 { 3905 sldns_buffer_clear(buf); 3906 sldns_buffer_printf(buf, "GET /%s HTTP/1.1\r\n", path); 3907 sldns_buffer_printf(buf, "Host: %s\r\n", host); 3908 setup_http_user_agent(buf, cfg); 3909 /* We do not really do multiple queries per connection, 3910 * but this header setting is also not needed. 3911 * sldns_buffer_printf(buf, "Connection: close\r\n") */ 3912 sldns_buffer_printf(buf, "\r\n"); 3913 if(sldns_buffer_position(buf)+10 > sldns_buffer_capacity(buf)) 3914 return 0; /* somehow buffer too short, but it is about 60K 3915 and the request is only a couple bytes long. */ 3916 sldns_buffer_flip(buf); 3917 return 1; 3918 } 3919 3920 struct comm_point* 3921 outnet_comm_point_for_http(struct outside_network* outnet, 3922 comm_point_callback_type* cb, void* cb_arg, 3923 struct sockaddr_storage* to_addr, socklen_t to_addrlen, int timeout, 3924 int ssl, char* host, char* path, struct config_file* cfg) 3925 { 3926 /* cp calls cb with err=NETEVENT_DONE when transfer is done */ 3927 struct comm_point* cp; 3928 int fd = outnet_get_tcp_fd(to_addr, to_addrlen, outnet->tcp_mss, 3929 outnet->ip_dscp, ssl); 3930 if(fd == -1) { 3931 return 0; 3932 } 3933 fd_set_nonblock(fd); 3934 if(!outnet_tcp_connect(fd, to_addr, to_addrlen)) { 3935 /* outnet_tcp_connect has closed fd on error for us */ 3936 return 0; 3937 } 3938 cp = comm_point_create_http_out(outnet->base, 3939 sldns_buffer_capacity(outnet->udp_buff), cb, cb_arg, 3940 outnet->udp_buff); 3941 if(!cp) { 3942 log_err("malloc failure"); 3943 close(fd); 3944 return 0; 3945 } 3946 cp->repinfo.remote_addrlen = to_addrlen; 3947 memcpy(&cp->repinfo.remote_addr, to_addr, to_addrlen); 3948 3949 /* setup for SSL (if needed) */ 3950 if(ssl) { 3951 if(!setup_comm_ssl(cp, outnet, fd, host)) { 3952 log_err("cannot setup https"); 3953 comm_point_delete(cp); 3954 return NULL; 3955 } 3956 } 3957 3958 /* set timeout on TCP connection */ 3959 comm_point_start_listening(cp, fd, timeout); 3960 3961 /* setup http request in cp->buffer */ 3962 if(!setup_http_request(cp->buffer, host, path, cfg)) { 3963 log_err("error setting up http request"); 3964 comm_point_delete(cp); 3965 return NULL; 3966 } 3967 return cp; 3968 } 3969 3970 /** get memory used by waiting tcp entry (in use or not) */ 3971 static size_t 3972 waiting_tcp_get_mem(struct waiting_tcp* w) 3973 { 3974 size_t s; 3975 if(!w) return 0; 3976 s = sizeof(*w) + w->pkt_len; 3977 if(w->timer) 3978 s += comm_timer_get_mem(w->timer); 3979 return s; 3980 } 3981 3982 /** get memory used by port if */ 3983 static size_t 3984 if_get_mem(struct port_if* pif) 3985 { 3986 size_t s; 3987 int i; 3988 s = sizeof(*pif) + sizeof(struct port_comm*)*pif->maxout; 3989 for(i=0; i<pif->inuse; i++) 3990 s += sizeof(*pif->out[i]) + 3991 comm_point_get_mem(pif->out[i]->cp); 3992 return s; 3993 } 3994 3995 /** get memory used by waiting udp */ 3996 static size_t 3997 waiting_udp_get_mem(struct pending* w) 3998 { 3999 size_t s; 4000 s = sizeof(*w) + comm_timer_get_mem(w->timer) + w->pkt_len; 4001 return s; 4002 } 4003 4004 size_t outnet_get_mem(struct outside_network* outnet) 4005 { 4006 size_t i; 4007 int k; 4008 struct waiting_tcp* w; 4009 struct pending* u; 4010 struct serviced_query* sq; 4011 struct service_callback* sb; 4012 struct port_comm* pc; 4013 size_t s = sizeof(*outnet) + sizeof(*outnet->base) + 4014 sizeof(*outnet->udp_buff) + 4015 sldns_buffer_capacity(outnet->udp_buff); 4016 /* second buffer is not ours */ 4017 for(pc = outnet->unused_fds; pc; pc = pc->next) { 4018 s += sizeof(*pc) + comm_point_get_mem(pc->cp); 4019 } 4020 for(k=0; k<outnet->num_ip4; k++) 4021 s += if_get_mem(&outnet->ip4_ifs[k]); 4022 for(k=0; k<outnet->num_ip6; k++) 4023 s += if_get_mem(&outnet->ip6_ifs[k]); 4024 for(u=outnet->udp_wait_first; u; u=u->next_waiting) 4025 s += waiting_udp_get_mem(u); 4026 4027 s += sizeof(struct pending_tcp*)*outnet->num_tcp; 4028 for(i=0; i<outnet->num_tcp; i++) { 4029 s += sizeof(struct pending_tcp); 4030 s += comm_point_get_mem(outnet->tcp_conns[i]->c); 4031 if(outnet->tcp_conns[i]->query) 4032 s += waiting_tcp_get_mem(outnet->tcp_conns[i]->query); 4033 } 4034 for(w=outnet->tcp_wait_first; w; w = w->next_waiting) 4035 s += waiting_tcp_get_mem(w); 4036 s += sizeof(*outnet->pending); 4037 s += (sizeof(struct pending) + comm_timer_get_mem(NULL)) * 4038 outnet->pending->count; 4039 s += sizeof(*outnet->serviced); 4040 s += outnet->svcd_overhead; 4041 RBTREE_FOR(sq, struct serviced_query*, outnet->serviced) { 4042 s += sizeof(*sq) + sq->qbuflen; 4043 for(sb = sq->cblist; sb; sb = sb->next) 4044 s += sizeof(*sb); 4045 } 4046 return s; 4047 } 4048 4049 size_t 4050 serviced_get_mem(struct serviced_query* sq) 4051 { 4052 struct service_callback* sb; 4053 size_t s; 4054 s = sizeof(*sq) + sq->qbuflen; 4055 for(sb = sq->cblist; sb; sb = sb->next) 4056 s += sizeof(*sb); 4057 if(sq->status == serviced_query_UDP_EDNS || 4058 sq->status == serviced_query_UDP || 4059 sq->status == serviced_query_UDP_EDNS_FRAG || 4060 sq->status == serviced_query_UDP_EDNS_fallback) { 4061 s += sizeof(struct pending); 4062 s += comm_timer_get_mem(NULL); 4063 } else { 4064 /* does not have size of the pkt pointer */ 4065 /* always has a timer except on malloc failures */ 4066 4067 /* these sizes are part of the main outside network mem */ 4068 /* 4069 s += sizeof(struct waiting_tcp); 4070 s += comm_timer_get_mem(NULL); 4071 */ 4072 } 4073 return s; 4074 } 4075 4076 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 4077 /** Setup shared port interface */ 4078 static int shared_ports_setup_if(struct shared_ports_if* shpif, char* str, 4079 int* availports, int numavailports) 4080 { 4081 shpif->avail_ports = (int*)memdup(availports, 4082 (size_t)numavailports*sizeof(int)); 4083 if(!shpif->avail_ports) 4084 return 0; 4085 shpif->avail_total = numavailports; 4086 shpif->inuse = 0; 4087 shpif->pfxlen = 0; 4088 if(!ipstrtoaddr(str, UNBOUND_DNS_PORT, &shpif->addr, &shpif->addrlen) && 4089 !netblockstrtoaddr(str, UNBOUND_DNS_PORT, &shpif->addr, 4090 &shpif->addrlen, &shpif->pfxlen)) 4091 return 0; 4092 return 1; 4093 } 4094 #endif 4095 4096 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 4097 /** Allocate shared ports interfaces */ 4098 static int shared_ports_alloc_ifs(struct shared_ports* shp, char** ifs, 4099 int num_ifs, int do_ip4, int do_ip6, int* availports, 4100 int numavailports) 4101 { 4102 #ifndef INET6 4103 do_ip6 = 0; 4104 #endif 4105 calc_num46(ifs, num_ifs, do_ip4, do_ip6, 4106 &shp->num_ip4, &shp->num_ip6); 4107 if(shp->num_ip4 != 0) { 4108 if(!(shp->ip4_ifs = (struct shared_ports_if*)calloc( 4109 (size_t)shp->num_ip4, 4110 sizeof(struct shared_ports_if)))) 4111 return 0; 4112 } 4113 if(shp->num_ip6 != 0) { 4114 if(!(shp->ip6_ifs = (struct shared_ports_if*)calloc( 4115 (size_t)shp->num_ip6, 4116 sizeof(struct shared_ports_if)))) 4117 return 0; 4118 } 4119 if(num_ifs == 0) { 4120 if(do_ip4 && !shared_ports_setup_if(&shp->ip4_ifs[0], 4121 "0.0.0.0", availports, numavailports)) 4122 return 0; 4123 if(do_ip6 && !shared_ports_setup_if(&shp->ip6_ifs[0], 4124 "::", availports, numavailports)) 4125 return 0; 4126 } else { 4127 size_t done_4 = 0, done_6 = 0; 4128 int i; 4129 for(i=0; i<num_ifs; i++) { 4130 if(str_is_ip6(ifs[i]) && do_ip6 && 4131 (int)done_6 < shp->num_ip6) { 4132 if(!shared_ports_setup_if(&shp->ip6_ifs[done_6], 4133 ifs[i], availports, numavailports)) 4134 return 0; 4135 done_6++; 4136 } 4137 if(!str_is_ip6(ifs[i]) && do_ip4 && 4138 (int)done_4 < shp->num_ip4) { 4139 if(!shared_ports_setup_if(&shp->ip4_ifs[done_4], 4140 ifs[i], availports, numavailports)) 4141 return 0; 4142 done_4++; 4143 } 4144 } 4145 } 4146 return 1; 4147 } 4148 #endif 4149 4150 struct shared_ports* shared_ports_create(char** ifs, int num_ifs, int do_ip4, 4151 int do_ip6, int* availports, int numavailports) 4152 { 4153 struct shared_ports* shp = calloc(1, sizeof(*shp)); 4154 if(!shp) { 4155 log_err("malloc failed"); 4156 return NULL; 4157 } 4158 lock_basic_init(&shp->lock); 4159 lock_protect(&shp->lock, &shp->ip4_ifs, sizeof(shp->ip4_ifs)); 4160 lock_protect(&shp->lock, &shp->num_ip4, sizeof(shp->num_ip4)); 4161 lock_protect(&shp->lock, &shp->ip6_ifs, sizeof(shp->ip6_ifs)); 4162 lock_protect(&shp->lock, &shp->num_ip6, sizeof(shp->num_ip6)); 4163 4164 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 4165 /* Allocate interfaces */ 4166 lock_basic_lock(&shp->lock); 4167 if(!shared_ports_alloc_ifs(shp, ifs, num_ifs, do_ip4, do_ip6, 4168 availports, numavailports)) { 4169 log_err("malloc failed"); 4170 shared_ports_delete(shp); 4171 return NULL; 4172 } 4173 lock_basic_unlock(&shp->lock); 4174 #else 4175 (void)ifs; (void)num_ifs; (void)do_ip4; (void)do_ip6; 4176 (void)availports; (void)numavailports; 4177 #endif 4178 return shp; 4179 } 4180 4181 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 4182 /** Delete shared ports interface structure */ 4183 static void shared_ports_if_delete(struct shared_ports_if* shpif) 4184 { 4185 if(!shpif) 4186 return; 4187 free(shpif->avail_ports); 4188 } 4189 #endif 4190 4191 void shared_ports_delete(struct shared_ports* shp) 4192 { 4193 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 4194 int i; 4195 #endif 4196 if(!shp) 4197 return; 4198 lock_basic_destroy(&shp->lock); 4199 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 4200 for(i=0; i<shp->num_ip4; i++) { 4201 shared_ports_if_delete(&shp->ip4_ifs[i]); 4202 } 4203 free(shp->ip4_ifs); 4204 for(i=0; i<shp->num_ip6; i++) { 4205 shared_ports_if_delete(&shp->ip6_ifs[i]); 4206 } 4207 free(shp->ip6_ifs); 4208 #endif 4209 free(shp); 4210 } 4211 4212 struct shared_ports_if* shared_ports_find_if(struct shared_ports* shp, 4213 struct sockaddr_storage* addr, socklen_t addrlen, int pfxlen) 4214 { 4215 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 4216 struct shared_ports_if* ret, *ifs = NULL; 4217 int i, num_ifs = 0; 4218 lock_basic_lock(&shp->lock); 4219 if(addr_is_ip6(addr, addrlen)) { 4220 ifs = shp->ip6_ifs; 4221 num_ifs = shp->num_ip6; 4222 } else { 4223 ifs = shp->ip4_ifs; 4224 num_ifs = shp->num_ip4; 4225 } 4226 for(i=0; i<num_ifs; i++) { 4227 if(sockaddr_cmp(addr, addrlen, &ifs[i].addr, 4228 ifs[i].addrlen) == 0 4229 && pfxlen == ifs[i].pfxlen) { 4230 ret = &ifs[i]; 4231 lock_basic_unlock(&shp->lock); 4232 return ret; 4233 } 4234 } 4235 lock_basic_unlock(&shp->lock); 4236 return NULL; 4237 #else 4238 (void)shp; (void)addr; (void)addrlen; (void)pfxlen; 4239 return NULL; 4240 #endif 4241 } 4242 4243 int shared_ports_fetch_random(struct shared_ports* shp, 4244 struct shared_ports_if* shpif, struct ub_randstate* rnd, 4245 int udp_connect, int reusenum, int* port, int* reused) 4246 { 4247 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 4248 int portno = 0, my_port = 0; 4249 if(!shpif) 4250 return 0; 4251 # ifdef THREADS_DISABLED 4252 (void)shp; 4253 # endif 4254 lock_basic_lock(&shp->lock); 4255 if(udp_connect) { 4256 /* if we connect() we cannot reuse fds for a port. */ 4257 if(shpif->inuse >= shpif->avail_total) { 4258 lock_basic_unlock(&shp->lock); 4259 return 0; 4260 } 4261 my_port = ub_random_max(rnd, 4262 shpif->avail_total - shpif->inuse); 4263 } else { 4264 /* select from free ports and open ports on this thread. */ 4265 if(shpif->inuse >= shpif->avail_total) { 4266 lock_basic_unlock(&shp->lock); 4267 if(reusenum == 0) { 4268 return 0; 4269 } 4270 my_port = ub_random_max(rnd, reusenum); 4271 *port = my_port; 4272 *reused = 1; 4273 return 1; 4274 } 4275 my_port = ub_random_max(rnd, shpif->avail_total - shpif->inuse 4276 + reusenum); 4277 if(my_port < reusenum) { 4278 /* port already open */ 4279 lock_basic_unlock(&shp->lock); 4280 *port = my_port; 4281 *reused = 1; 4282 return 1; 4283 } 4284 my_port -= reusenum; 4285 } 4286 log_assert(shpif->inuse < shpif->avail_total); 4287 log_assert(my_port >= 0 && my_port < shpif->avail_total); 4288 portno = shpif->avail_ports[my_port]; 4289 shpif->avail_ports[my_port] = 4290 shpif->avail_ports[shpif->avail_total-shpif->inuse-1]; 4291 shpif->inuse++; 4292 lock_basic_unlock(&shp->lock); 4293 *port = portno; 4294 *reused = 0; 4295 return 1; 4296 #else 4297 (void)shp; (void)shpif; (void)rnd; (void)udp_connect; 4298 (void)reusenum; 4299 *port = 0; 4300 *reused = 0; 4301 return 1; 4302 #endif 4303 } 4304 4305 void shared_ports_return_port(struct shared_ports* shp, 4306 struct shared_ports_if* shpif, int port) 4307 { 4308 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION 4309 if(!shpif) 4310 return; 4311 # ifdef THREADS_DISABLED 4312 (void)shp; 4313 # endif 4314 lock_basic_lock(&shp->lock); 4315 log_assert(shpif->inuse > 0); 4316 shpif->avail_ports[shpif->avail_total - shpif->inuse] = port; 4317 shpif->inuse--; 4318 lock_basic_unlock(&shp->lock); 4319 #else 4320 (void)shp; (void)shpif; (void)port; 4321 #endif 4322 } 4323