2 * services/outside_network.c - implement sending of queries and wait answer.
4 * Copyright (c) 2007, NLnet Labs. All rights reserved.
6 * This software is open source.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
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.
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.
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.
39 * This file has functions to send queries to authoritative servers and
40 * wait for the pending answer events.
44 #ifdef HAVE_SYS_TYPES_H
45 # include <sys/types.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"
58 #include "util/net_help.h"
59 #include "util/random.h"
60 #include "util/fptr_wlist.h"
61 #include "sldns/sbuffer.h"
62 #include "dnstap/dnstap.h"
63 #ifdef HAVE_OPENSSL_SSL_H
64 #include <openssl/ssl.h>
66 #ifdef HAVE_X509_VERIFY_PARAM_SET1_HOST
67 #include <openssl/x509v3.h>
75 /** number of times to retry making a random ID that is unique. */
76 #define MAX_ID_RETRY 1000
77 /** number of times to retry finding interface, port that can be opened. */
78 #define MAX_PORT_RETRY 10000
79 /** number of retries on outgoing UDP queries */
80 #define OUTBOUND_UDP_RETRY 1
82 /** initiate TCP transaction for serviced query */
83 static void serviced_tcp_initiate(struct serviced_query* sq, sldns_buffer* buff);
84 /** with a fd available, randomize and send UDP */
85 static int randomize_and_send_udp(struct pending* pend, sldns_buffer* packet,
88 /** remove waiting tcp from the outnet waiting list */
89 static void waiting_list_remove(struct outside_network* outnet,
90 struct waiting_tcp* w);
93 pending_cmp(const void* key1, const void* key2)
95 struct pending *p1 = (struct pending*)key1;
96 struct pending *p2 = (struct pending*)key2;
101 log_assert(p1->id == p2->id);
102 return sockaddr_cmp(&p1->addr, p1->addrlen, &p2->addr, p2->addrlen);
106 serviced_cmp(const void* key1, const void* key2)
108 struct serviced_query* q1 = (struct serviced_query*)key1;
109 struct serviced_query* q2 = (struct serviced_query*)key2;
111 if(q1->qbuflen < q2->qbuflen)
113 if(q1->qbuflen > q2->qbuflen)
115 log_assert(q1->qbuflen == q2->qbuflen);
116 log_assert(q1->qbuflen >= 15 /* 10 header, root, type, class */);
117 /* alternate casing of qname is still the same query */
118 if((r = memcmp(q1->qbuf, q2->qbuf, 10)) != 0)
120 if((r = memcmp(q1->qbuf+q1->qbuflen-4, q2->qbuf+q2->qbuflen-4, 4)) != 0)
122 if(q1->dnssec != q2->dnssec) {
123 if(q1->dnssec < q2->dnssec)
127 if((r = query_dname_compare(q1->qbuf+10, q2->qbuf+10)) != 0)
129 if((r = edns_opt_list_compare(q1->opt_list, q2->opt_list)) != 0)
131 return sockaddr_cmp(&q1->addr, q1->addrlen, &q2->addr, q2->addrlen);
134 /** delete waiting_tcp entry. Does not unlink from waiting list.
135 * @param w: to delete.
138 waiting_tcp_delete(struct waiting_tcp* w)
142 comm_timer_delete(w->timer);
147 * Pick random outgoing-interface of that family, and bind it.
148 * port set to 0 so OS picks a port number for us.
149 * if it is the ANY address, do not bind.
150 * @param w: tcp structure with destination address.
151 * @param s: socket fd.
152 * @return false on error, socket closed.
155 pick_outgoing_tcp(struct waiting_tcp* w, int s)
157 struct port_if* pi = NULL;
160 if(addr_is_ip6(&w->addr, w->addrlen))
161 num = w->outnet->num_ip6;
164 num = w->outnet->num_ip4;
166 log_err("no TCP outgoing interfaces of family");
167 log_addr(VERB_OPS, "for addr", &w->addr, w->addrlen);
176 if(addr_is_ip6(&w->addr, w->addrlen))
177 pi = &w->outnet->ip6_ifs[ub_random_max(w->outnet->rnd, num)];
180 pi = &w->outnet->ip4_ifs[ub_random_max(w->outnet->rnd, num)];
182 if(addr_is_any(&pi->addr, pi->addrlen)) {
183 /* binding to the ANY interface is for listening sockets */
187 if(addr_is_ip6(&pi->addr, pi->addrlen))
188 ((struct sockaddr_in6*)&pi->addr)->sin6_port = 0;
189 else ((struct sockaddr_in*)&pi->addr)->sin_port = 0;
190 if(bind(s, (struct sockaddr*)&pi->addr, pi->addrlen) != 0) {
192 log_err("outgoing tcp: bind: %s", strerror(errno));
195 log_err("outgoing tcp: bind: %s",
196 wsa_strerror(WSAGetLastError()));
201 log_addr(VERB_ALGO, "tcp bound to src", &pi->addr, pi->addrlen);
205 /** get TCP file descriptor for address, returns -1 on failure,
206 * tcp_mss is 0 or maxseg size to set for TCP packets. */
208 outnet_get_tcp_fd(struct sockaddr_storage* addr, socklen_t addrlen, int tcp_mss, int dscp)
217 if(addr_is_ip6(addr, addrlen)){
218 s = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
225 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
229 log_err_addr("outgoing tcp: socket", strerror(errno),
232 log_err_addr("outgoing tcp: socket",
233 wsa_strerror(WSAGetLastError()), addr, addrlen);
239 if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&on,
240 (socklen_t)sizeof(on)) < 0) {
241 verbose(VERB_ALGO, "outgoing tcp:"
242 " setsockopt(.. SO_REUSEADDR ..) failed");
246 err = set_ip_dscp(s, af, dscp);
248 verbose(VERB_ALGO, "outgoing tcp:"
249 "error setting IP DiffServ codepoint on socket");
253 #if defined(IPPROTO_TCP) && defined(TCP_MAXSEG)
254 if(setsockopt(s, IPPROTO_TCP, TCP_MAXSEG,
255 (void*)&tcp_mss, (socklen_t)sizeof(tcp_mss)) < 0) {
256 verbose(VERB_ALGO, "outgoing tcp:"
257 " setsockopt(.. TCP_MAXSEG ..) failed");
260 verbose(VERB_ALGO, "outgoing tcp:"
261 " setsockopt(TCP_MAXSEG) unsupported");
262 #endif /* defined(IPPROTO_TCP) && defined(TCP_MAXSEG) */
268 /** connect tcp connection to addr, 0 on failure */
270 outnet_tcp_connect(int s, struct sockaddr_storage* addr, socklen_t addrlen)
272 if(connect(s, (struct sockaddr*)addr, addrlen) == -1) {
275 if(errno != EINPROGRESS) {
277 if(tcp_connect_errno_needs_log(
278 (struct sockaddr*)addr, addrlen))
279 log_err_addr("outgoing tcp: connect",
280 strerror(errno), addr, addrlen);
286 #else /* USE_WINSOCK */
287 if(WSAGetLastError() != WSAEINPROGRESS &&
288 WSAGetLastError() != WSAEWOULDBLOCK) {
297 /** use next free buffer to service a tcp query */
299 outnet_tcp_take_into_use(struct waiting_tcp* w, uint8_t* pkt, size_t pkt_len)
301 struct pending_tcp* pend = w->outnet->tcp_free;
305 log_assert(w->addrlen > 0);
307 s = outnet_get_tcp_fd(&w->addr, w->addrlen, w->outnet->tcp_mss, w->outnet->ip_dscp);
312 if(!pick_outgoing_tcp(w, s))
316 #ifdef USE_OSX_MSG_FASTOPEN
317 /* API for fast open is different here. We use a connectx() function and
318 then writes can happen as normal even using SSL.*/
319 /* connectx requires that the len be set in the sockaddr struct*/
320 struct sockaddr_in *addr_in = (struct sockaddr_in *)&w->addr;
321 addr_in->sin_len = w->addrlen;
322 sa_endpoints_t endpoints;
323 endpoints.sae_srcif = 0;
324 endpoints.sae_srcaddr = NULL;
325 endpoints.sae_srcaddrlen = 0;
326 endpoints.sae_dstaddr = (struct sockaddr *)&w->addr;
327 endpoints.sae_dstaddrlen = w->addrlen;
328 if (connectx(s, &endpoints, SAE_ASSOCID_ANY,
329 CONNECT_DATA_IDEMPOTENT | CONNECT_RESUME_ON_READ_WRITE,
330 NULL, 0, NULL, NULL) == -1) {
331 /* if fails, failover to connect for OSX 10.10 */
333 if(errno != EINPROGRESS) {
337 if(connect(s, (struct sockaddr*)&w->addr, w->addrlen) == -1) {
338 #else /* USE_OSX_MSG_FASTOPEN*/
339 #ifdef USE_MSG_FASTOPEN
340 pend->c->tcp_do_fastopen = 1;
341 /* Only do TFO for TCP in which case no connect() is required here.
342 Don't combine client TFO with SSL, since OpenSSL can't
343 currently support doing a handshake on fd that already isn't connected*/
344 if (w->outnet->sslctx && w->ssl_upstream) {
345 if(connect(s, (struct sockaddr*)&w->addr, w->addrlen) == -1) {
346 #else /* USE_MSG_FASTOPEN*/
347 if(connect(s, (struct sockaddr*)&w->addr, w->addrlen) == -1) {
348 #endif /* USE_MSG_FASTOPEN*/
349 #endif /* USE_OSX_MSG_FASTOPEN*/
352 if(errno != EINPROGRESS) {
356 if(tcp_connect_errno_needs_log(
357 (struct sockaddr*)&w->addr, w->addrlen))
358 log_err_addr("outgoing tcp: connect",
359 strerror(errno), &w->addr, w->addrlen);
361 #else /* USE_WINSOCK */
362 if(WSAGetLastError() != WSAEINPROGRESS &&
363 WSAGetLastError() != WSAEWOULDBLOCK) {
369 #ifdef USE_MSG_FASTOPEN
371 #endif /* USE_MSG_FASTOPEN */
372 #ifdef USE_OSX_MSG_FASTOPEN
375 #endif /* USE_OSX_MSG_FASTOPEN */
376 if(w->outnet->sslctx && w->ssl_upstream) {
377 pend->c->ssl = outgoing_ssl_fd(w->outnet->sslctx, s);
380 comm_point_close(pend->c);
383 verbose(VERB_ALGO, "the query is using TLS encryption, for %s",
384 (w->tls_auth_name?w->tls_auth_name:"an unauthenticated connection"));
386 comm_point_tcp_win_bio_cb(pend->c, pend->c->ssl);
388 pend->c->ssl_shake_state = comm_ssl_shake_write;
389 if(!set_auth_name_on_ssl(pend->c->ssl, w->tls_auth_name,
390 w->outnet->tls_use_sni)) {
393 SSL_free(pend->c->ssl);
396 comm_point_close(pend->c);
401 w->next_waiting = (void*)pend;
402 pend->id = LDNS_ID_WIRE(pkt);
403 w->outnet->num_tcp_outgoing++;
404 w->outnet->tcp_free = pend->next_free;
405 pend->next_free = NULL;
407 pend->c->repinfo.addrlen = w->addrlen;
408 memcpy(&pend->c->repinfo.addr, &w->addr, w->addrlen);
409 sldns_buffer_clear(pend->c->buffer);
410 sldns_buffer_write(pend->c->buffer, pkt, pkt_len);
411 sldns_buffer_flip(pend->c->buffer);
412 pend->c->tcp_is_reading = 0;
413 pend->c->tcp_byte_count = 0;
414 comm_point_start_listening(pend->c, s, -1);
418 /** see if buffers can be used to service TCP queries */
420 use_free_buffer(struct outside_network* outnet)
422 struct waiting_tcp* w;
423 while(outnet->tcp_free && outnet->tcp_wait_first
424 && !outnet->want_to_quit) {
425 w = outnet->tcp_wait_first;
426 outnet->tcp_wait_first = w->next_waiting;
427 if(outnet->tcp_wait_last == w)
428 outnet->tcp_wait_last = NULL;
429 if(!outnet_tcp_take_into_use(w, w->pkt, w->pkt_len)) {
430 comm_point_callback_type* cb = w->cb;
431 void* cb_arg = w->cb_arg;
432 waiting_tcp_delete(w);
433 fptr_ok(fptr_whitelist_pending_tcp(cb));
434 (void)(*cb)(NULL, cb_arg, NETEVENT_CLOSED, NULL);
439 /** decommission a tcp buffer, closes commpoint and frees waiting_tcp entry */
441 decommission_pending_tcp(struct outside_network* outnet,
442 struct pending_tcp* pend)
446 SSL_shutdown(pend->c->ssl);
447 SSL_free(pend->c->ssl);
451 comm_point_close(pend->c);
452 pend->next_free = outnet->tcp_free;
453 outnet->tcp_free = pend;
454 waiting_tcp_delete(pend->query);
456 use_free_buffer(outnet);
460 outnet_tcp_cb(struct comm_point* c, void* arg, int error,
461 struct comm_reply *reply_info)
463 struct pending_tcp* pend = (struct pending_tcp*)arg;
464 struct outside_network* outnet = pend->query->outnet;
465 verbose(VERB_ALGO, "outnettcp cb");
466 if(error != NETEVENT_NOERROR) {
467 verbose(VERB_QUERY, "outnettcp got tcp error %d", error);
468 /* pass error below and exit */
471 if(sldns_buffer_limit(c->buffer) < sizeof(uint16_t) ||
472 LDNS_ID_WIRE(sldns_buffer_begin(c->buffer))!=pend->id) {
474 "outnettcp: bad ID in reply, from:",
475 &pend->query->addr, pend->query->addrlen);
476 error = NETEVENT_CLOSED;
479 fptr_ok(fptr_whitelist_pending_tcp(pend->query->cb));
480 (void)(*pend->query->cb)(c, pend->query->cb_arg, error, reply_info);
481 decommission_pending_tcp(outnet, pend);
485 /** lower use count on pc, see if it can be closed */
487 portcomm_loweruse(struct outside_network* outnet, struct port_comm* pc)
490 pc->num_outstanding--;
491 if(pc->num_outstanding > 0) {
494 /* close it and replace in unused list */
495 verbose(VERB_ALGO, "close of port %d", pc->number);
496 comm_point_close(pc->cp);
498 log_assert(pif->inuse > 0);
499 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
500 pif->avail_ports[pif->avail_total - pif->inuse] = pc->number;
503 pif->out[pc->index] = pif->out[pif->inuse];
504 pif->out[pc->index]->index = pc->index;
505 pc->next = outnet->unused_fds;
506 outnet->unused_fds = pc;
509 /** try to send waiting UDP queries */
511 outnet_send_wait_udp(struct outside_network* outnet)
513 struct pending* pend;
514 /* process waiting queries */
515 while(outnet->udp_wait_first && outnet->unused_fds
516 && !outnet->want_to_quit) {
517 pend = outnet->udp_wait_first;
518 outnet->udp_wait_first = pend->next_waiting;
519 if(!pend->next_waiting) outnet->udp_wait_last = NULL;
520 sldns_buffer_clear(outnet->udp_buff);
521 sldns_buffer_write(outnet->udp_buff, pend->pkt, pend->pkt_len);
522 sldns_buffer_flip(outnet->udp_buff);
523 free(pend->pkt); /* freeing now makes get_mem correct */
526 if(!randomize_and_send_udp(pend, outnet->udp_buff,
528 /* callback error on pending */
530 fptr_ok(fptr_whitelist_pending_udp(pend->cb));
531 (void)(*pend->cb)(outnet->unused_fds->cp, pend->cb_arg,
532 NETEVENT_CLOSED, NULL);
534 pending_delete(outnet, pend);
540 outnet_udp_cb(struct comm_point* c, void* arg, int error,
541 struct comm_reply *reply_info)
543 struct outside_network* outnet = (struct outside_network*)arg;
546 verbose(VERB_ALGO, "answer cb");
548 if(error != NETEVENT_NOERROR) {
549 verbose(VERB_QUERY, "outnetudp got udp error %d", error);
552 if(sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE) {
553 verbose(VERB_QUERY, "outnetudp udp too short");
556 log_assert(reply_info);
558 /* setup lookup key */
559 key.id = (unsigned)LDNS_ID_WIRE(sldns_buffer_begin(c->buffer));
560 memcpy(&key.addr, &reply_info->addr, reply_info->addrlen);
561 key.addrlen = reply_info->addrlen;
562 verbose(VERB_ALGO, "Incoming reply id = %4.4x", key.id);
563 log_addr(VERB_ALGO, "Incoming reply addr =",
564 &reply_info->addr, reply_info->addrlen);
566 /* find it, see if this thing is a valid query response */
567 verbose(VERB_ALGO, "lookup size is %d entries", (int)outnet->pending->count);
568 p = (struct pending*)rbtree_search(outnet->pending, &key);
570 verbose(VERB_QUERY, "received unwanted or unsolicited udp reply dropped.");
571 log_buf(VERB_ALGO, "dropped message", c->buffer);
572 outnet->unwanted_replies++;
573 if(outnet->unwanted_threshold && ++outnet->unwanted_total
574 >= outnet->unwanted_threshold) {
575 log_warn("unwanted reply total reached threshold (%u)"
576 " you may be under attack."
577 " defensive action: clearing the cache",
578 (unsigned)outnet->unwanted_threshold);
579 fptr_ok(fptr_whitelist_alloc_cleanup(
580 outnet->unwanted_action));
581 (*outnet->unwanted_action)(outnet->unwanted_param);
582 outnet->unwanted_total = 0;
587 verbose(VERB_ALGO, "received udp reply.");
588 log_buf(VERB_ALGO, "udp message", c->buffer);
590 verbose(VERB_QUERY, "received reply id,addr on wrong port. "
592 outnet->unwanted_replies++;
593 if(outnet->unwanted_threshold && ++outnet->unwanted_total
594 >= outnet->unwanted_threshold) {
595 log_warn("unwanted reply total reached threshold (%u)"
596 " you may be under attack."
597 " defensive action: clearing the cache",
598 (unsigned)outnet->unwanted_threshold);
599 fptr_ok(fptr_whitelist_alloc_cleanup(
600 outnet->unwanted_action));
601 (*outnet->unwanted_action)(outnet->unwanted_param);
602 outnet->unwanted_total = 0;
606 comm_timer_disable(p->timer);
607 verbose(VERB_ALGO, "outnet handle udp reply");
608 /* delete from tree first in case callback creates a retry */
609 (void)rbtree_delete(outnet->pending, p->node.key);
611 fptr_ok(fptr_whitelist_pending_udp(p->cb));
612 (void)(*p->cb)(p->pc->cp, p->cb_arg, NETEVENT_NOERROR, reply_info);
614 portcomm_loweruse(outnet, p->pc);
615 pending_delete(NULL, p);
616 outnet_send_wait_udp(outnet);
620 /** calculate number of ip4 and ip6 interfaces*/
622 calc_num46(char** ifs, int num_ifs, int do_ip4, int do_ip6,
623 int* num_ip4, int* num_ip6)
635 for(i=0; i<num_ifs; i++)
637 if(str_is_ip6(ifs[i])) {
649 pending_udp_timer_delay_cb(void* arg)
651 struct pending* p = (struct pending*)arg;
652 struct outside_network* outnet = p->outnet;
653 verbose(VERB_ALGO, "timeout udp with delay");
654 portcomm_loweruse(outnet, p->pc);
655 pending_delete(outnet, p);
656 outnet_send_wait_udp(outnet);
660 pending_udp_timer_cb(void *arg)
662 struct pending* p = (struct pending*)arg;
663 struct outside_network* outnet = p->outnet;
665 verbose(VERB_ALGO, "timeout udp");
667 fptr_ok(fptr_whitelist_pending_udp(p->cb));
668 (void)(*p->cb)(p->pc->cp, p->cb_arg, NETEVENT_TIMEOUT, NULL);
670 /* if delayclose, keep port open for a longer time.
671 * But if the udpwaitlist exists, then we are struggling to
672 * keep up with demand for sockets, so do not wait, but service
673 * the customer (customer service more important than portICMPs) */
674 if(outnet->delayclose && !outnet->udp_wait_first) {
676 p->timer->callback = &pending_udp_timer_delay_cb;
677 comm_timer_set(p->timer, &outnet->delay_tv);
680 portcomm_loweruse(outnet, p->pc);
681 pending_delete(outnet, p);
682 outnet_send_wait_udp(outnet);
685 /** create pending_tcp buffers */
687 create_pending_tcp(struct outside_network* outnet, size_t bufsize)
690 if(outnet->num_tcp == 0)
691 return 1; /* no tcp needed, nothing to do */
692 if(!(outnet->tcp_conns = (struct pending_tcp **)calloc(
693 outnet->num_tcp, sizeof(struct pending_tcp*))))
695 for(i=0; i<outnet->num_tcp; i++) {
696 if(!(outnet->tcp_conns[i] = (struct pending_tcp*)calloc(1,
697 sizeof(struct pending_tcp))))
699 outnet->tcp_conns[i]->next_free = outnet->tcp_free;
700 outnet->tcp_free = outnet->tcp_conns[i];
701 outnet->tcp_conns[i]->c = comm_point_create_tcp_out(
702 outnet->base, bufsize, outnet_tcp_cb,
703 outnet->tcp_conns[i]);
704 if(!outnet->tcp_conns[i]->c)
710 /** setup an outgoing interface, ready address */
711 static int setup_if(struct port_if* pif, const char* addrstr,
712 int* avail, int numavail, size_t numfd)
714 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
715 pif->avail_total = numavail;
716 pif->avail_ports = (int*)memdup(avail, (size_t)numavail*sizeof(int));
717 if(!pif->avail_ports)
720 if(!ipstrtoaddr(addrstr, UNBOUND_DNS_PORT, &pif->addr, &pif->addrlen) &&
721 !netblockstrtoaddr(addrstr, UNBOUND_DNS_PORT,
722 &pif->addr, &pif->addrlen, &pif->pfxlen))
724 pif->maxout = (int)numfd;
726 pif->out = (struct port_comm**)calloc(numfd,
727 sizeof(struct port_comm*));
733 struct outside_network*
734 outside_network_create(struct comm_base *base, size_t bufsize,
735 size_t num_ports, char** ifs, int num_ifs, int do_ip4,
736 int do_ip6, size_t num_tcp, int dscp, struct infra_cache* infra,
737 struct ub_randstate* rnd, int use_caps_for_id, int* availports,
738 int numavailports, size_t unwanted_threshold, int tcp_mss,
739 void (*unwanted_action)(void*), void* unwanted_param, int do_udp,
740 void* sslctx, int delayclose, int tls_use_sni, struct dt_env* dtenv)
742 struct outside_network* outnet = (struct outside_network*)
743 calloc(1, sizeof(struct outside_network));
746 log_err("malloc failed");
749 comm_base_timept(base, &outnet->now_secs, &outnet->now_tv);
751 outnet->num_tcp = num_tcp;
752 outnet->num_tcp_outgoing = 0;
753 outnet->infra = infra;
755 outnet->sslctx = sslctx;
756 outnet->tls_use_sni = tls_use_sni;
758 outnet->dtenv = dtenv;
762 outnet->svcd_overhead = 0;
763 outnet->want_to_quit = 0;
764 outnet->unwanted_threshold = unwanted_threshold;
765 outnet->unwanted_action = unwanted_action;
766 outnet->unwanted_param = unwanted_param;
767 outnet->use_caps_for_id = use_caps_for_id;
768 outnet->do_udp = do_udp;
769 outnet->tcp_mss = tcp_mss;
770 outnet->ip_dscp = dscp;
773 outnet->delayclose = 1;
774 outnet->delay_tv.tv_sec = delayclose/1000;
775 outnet->delay_tv.tv_usec = (delayclose%1000)*1000;
778 if(numavailports == 0 || num_ports == 0) {
779 log_err("no outgoing ports available");
780 outside_network_delete(outnet);
786 calc_num46(ifs, num_ifs, do_ip4, do_ip6,
787 &outnet->num_ip4, &outnet->num_ip6);
788 if(outnet->num_ip4 != 0) {
789 if(!(outnet->ip4_ifs = (struct port_if*)calloc(
790 (size_t)outnet->num_ip4, sizeof(struct port_if)))) {
791 log_err("malloc failed");
792 outside_network_delete(outnet);
796 if(outnet->num_ip6 != 0) {
797 if(!(outnet->ip6_ifs = (struct port_if*)calloc(
798 (size_t)outnet->num_ip6, sizeof(struct port_if)))) {
799 log_err("malloc failed");
800 outside_network_delete(outnet);
804 if( !(outnet->udp_buff = sldns_buffer_new(bufsize)) ||
805 !(outnet->pending = rbtree_create(pending_cmp)) ||
806 !(outnet->serviced = rbtree_create(serviced_cmp)) ||
807 !create_pending_tcp(outnet, bufsize)) {
808 log_err("malloc failed");
809 outside_network_delete(outnet);
813 /* allocate commpoints */
814 for(k=0; k<num_ports; k++) {
815 struct port_comm* pc;
816 pc = (struct port_comm*)calloc(1, sizeof(*pc));
818 log_err("malloc failed");
819 outside_network_delete(outnet);
822 pc->cp = comm_point_create_udp(outnet->base, -1,
823 outnet->udp_buff, outnet_udp_cb, outnet);
825 log_err("malloc failed");
827 outside_network_delete(outnet);
830 pc->next = outnet->unused_fds;
831 outnet->unused_fds = pc;
834 /* allocate interfaces */
836 if(do_ip4 && !setup_if(&outnet->ip4_ifs[0], "0.0.0.0",
837 availports, numavailports, num_ports)) {
838 log_err("malloc failed");
839 outside_network_delete(outnet);
842 if(do_ip6 && !setup_if(&outnet->ip6_ifs[0], "::",
843 availports, numavailports, num_ports)) {
844 log_err("malloc failed");
845 outside_network_delete(outnet);
849 size_t done_4 = 0, done_6 = 0;
851 for(i=0; i<num_ifs; i++) {
852 if(str_is_ip6(ifs[i]) && do_ip6) {
853 if(!setup_if(&outnet->ip6_ifs[done_6], ifs[i],
854 availports, numavailports, num_ports)){
855 log_err("malloc failed");
856 outside_network_delete(outnet);
861 if(!str_is_ip6(ifs[i]) && do_ip4) {
862 if(!setup_if(&outnet->ip4_ifs[done_4], ifs[i],
863 availports, numavailports, num_ports)){
864 log_err("malloc failed");
865 outside_network_delete(outnet);
875 /** helper pending delete */
877 pending_node_del(rbnode_type* node, void* arg)
879 struct pending* pend = (struct pending*)node;
880 struct outside_network* outnet = (struct outside_network*)arg;
881 pending_delete(outnet, pend);
884 /** helper serviced delete */
886 serviced_node_del(rbnode_type* node, void* ATTR_UNUSED(arg))
888 struct serviced_query* sq = (struct serviced_query*)node;
889 struct service_callback* p = sq->cblist, *np;
892 free(sq->tls_auth_name);
893 edns_opt_list_free(sq->opt_list);
903 outside_network_quit_prepare(struct outside_network* outnet)
907 /* prevent queued items from being sent */
908 outnet->want_to_quit = 1;
912 outside_network_delete(struct outside_network* outnet)
916 outnet->want_to_quit = 1;
917 /* check every element, since we can be called on malloc error */
918 if(outnet->pending) {
919 /* free pending elements, but do no unlink from tree. */
920 traverse_postorder(outnet->pending, pending_node_del, NULL);
921 free(outnet->pending);
923 if(outnet->serviced) {
924 traverse_postorder(outnet->serviced, serviced_node_del, NULL);
925 free(outnet->serviced);
928 sldns_buffer_free(outnet->udp_buff);
929 if(outnet->unused_fds) {
930 struct port_comm* p = outnet->unused_fds, *np;
933 comm_point_delete(p->cp);
937 outnet->unused_fds = NULL;
939 if(outnet->ip4_ifs) {
941 for(i=0; i<outnet->num_ip4; i++) {
942 for(k=0; k<outnet->ip4_ifs[i].inuse; k++) {
943 struct port_comm* pc = outnet->ip4_ifs[i].
945 comm_point_delete(pc->cp);
948 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
949 free(outnet->ip4_ifs[i].avail_ports);
951 free(outnet->ip4_ifs[i].out);
953 free(outnet->ip4_ifs);
955 if(outnet->ip6_ifs) {
957 for(i=0; i<outnet->num_ip6; i++) {
958 for(k=0; k<outnet->ip6_ifs[i].inuse; k++) {
959 struct port_comm* pc = outnet->ip6_ifs[i].
961 comm_point_delete(pc->cp);
964 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
965 free(outnet->ip6_ifs[i].avail_ports);
967 free(outnet->ip6_ifs[i].out);
969 free(outnet->ip6_ifs);
971 if(outnet->tcp_conns) {
973 for(i=0; i<outnet->num_tcp; i++)
974 if(outnet->tcp_conns[i]) {
975 comm_point_delete(outnet->tcp_conns[i]->c);
976 waiting_tcp_delete(outnet->tcp_conns[i]->query);
977 free(outnet->tcp_conns[i]);
979 free(outnet->tcp_conns);
981 if(outnet->tcp_wait_first) {
982 struct waiting_tcp* p = outnet->tcp_wait_first, *np;
984 np = p->next_waiting;
985 waiting_tcp_delete(p);
989 if(outnet->udp_wait_first) {
990 struct pending* p = outnet->udp_wait_first, *np;
992 np = p->next_waiting;
993 pending_delete(NULL, p);
1001 pending_delete(struct outside_network* outnet, struct pending* p)
1005 if(outnet && outnet->udp_wait_first &&
1006 (p->next_waiting || p == outnet->udp_wait_last) ) {
1007 /* delete from waiting list, if it is in the waiting list */
1008 struct pending* prev = NULL, *x = outnet->udp_wait_first;
1009 while(x && x != p) {
1011 x = x->next_waiting;
1016 prev->next_waiting = p->next_waiting;
1017 else outnet->udp_wait_first = p->next_waiting;
1018 if(outnet->udp_wait_last == p)
1019 outnet->udp_wait_last = prev;
1023 (void)rbtree_delete(outnet->pending, p->node.key);
1026 comm_timer_delete(p->timer);
1032 sai6_putrandom(struct sockaddr_in6 *sa, int pfxlen, struct ub_randstate *rnd)
1035 if(!(pfxlen > 0 && pfxlen < 128))
1037 for(i = 0; i < (128 - pfxlen) / 8; i++) {
1038 sa->sin6_addr.s6_addr[15-i] = (uint8_t)ub_random_max(rnd, 256);
1042 sa->sin6_addr.s6_addr[15-i] |=
1043 ((0xFF >> last) & ub_random_max(rnd, 256));
1048 * Try to open a UDP socket for outgoing communication.
1049 * Sets sockets options as needed.
1050 * @param addr: socket address.
1051 * @param addrlen: length of address.
1052 * @param pfxlen: length of network prefix (for address randomisation).
1053 * @param port: port override for addr.
1054 * @param inuse: if -1 is returned, this bool means the port was in use.
1055 * @param rnd: random state (for address randomisation).
1056 * @param dscp: DSCP to use.
1060 udp_sockport(struct sockaddr_storage* addr, socklen_t addrlen, int pfxlen,
1061 int port, int* inuse, struct ub_randstate* rnd, int dscp)
1064 if(addr_is_ip6(addr, addrlen)) {
1066 struct sockaddr_in6 sa = *(struct sockaddr_in6*)addr;
1067 sa.sin6_port = (in_port_t)htons((uint16_t)port);
1068 sa.sin6_flowinfo = 0;
1069 sa.sin6_scope_id = 0;
1072 sai6_putrandom(&sa, pfxlen, rnd);
1074 fd = create_udp_sock(AF_INET6, SOCK_DGRAM,
1075 (struct sockaddr*)&sa, addrlen, 1, inuse, &noproto,
1076 0, 0, 0, NULL, 0, freebind, 0, dscp);
1078 struct sockaddr_in* sa = (struct sockaddr_in*)addr;
1079 sa->sin_port = (in_port_t)htons((uint16_t)port);
1080 fd = create_udp_sock(AF_INET, SOCK_DGRAM,
1081 (struct sockaddr*)addr, addrlen, 1, inuse, &noproto,
1082 0, 0, 0, NULL, 0, 0, 0, dscp);
1087 /** Select random ID */
1089 select_id(struct outside_network* outnet, struct pending* pend,
1090 sldns_buffer* packet)
1093 pend->id = ((unsigned)ub_random(outnet->rnd)>>8) & 0xffff;
1094 LDNS_ID_SET(sldns_buffer_begin(packet), pend->id);
1096 /* insert in tree */
1097 pend->node.key = pend;
1098 while(!rbtree_insert(outnet->pending, &pend->node)) {
1099 /* change ID to avoid collision */
1100 pend->id = ((unsigned)ub_random(outnet->rnd)>>8) & 0xffff;
1101 LDNS_ID_SET(sldns_buffer_begin(packet), pend->id);
1103 if(id_tries == MAX_ID_RETRY) {
1104 pend->id=99999; /* non existant ID */
1105 log_err("failed to generate unique ID, drop msg");
1109 verbose(VERB_ALGO, "inserted new pending reply id=%4.4x", pend->id);
1113 /** Select random interface and port */
1115 select_ifport(struct outside_network* outnet, struct pending* pend,
1116 int num_if, struct port_if* ifs)
1118 int my_if, my_port, fd, portno, inuse, tries=0;
1119 struct port_if* pif;
1120 /* randomly select interface and port */
1122 verbose(VERB_QUERY, "Need to send query but have no "
1123 "outgoing interfaces of that family");
1126 log_assert(outnet->unused_fds);
1129 my_if = ub_random_max(outnet->rnd, num_if);
1131 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
1132 my_port = ub_random_max(outnet->rnd, pif->avail_total);
1133 if(my_port < pif->inuse) {
1134 /* port already open */
1135 pend->pc = pif->out[my_port];
1136 verbose(VERB_ALGO, "using UDP if=%d port=%d",
1137 my_if, pend->pc->number);
1140 /* try to open new port, if fails, loop to try again */
1141 log_assert(pif->inuse < pif->maxout);
1142 portno = pif->avail_ports[my_port - pif->inuse];
1144 my_port = portno = 0;
1146 fd = udp_sockport(&pif->addr, pif->addrlen, pif->pfxlen,
1147 portno, &inuse, outnet->rnd, outnet->ip_dscp);
1148 if(fd == -1 && !inuse) {
1149 /* nonrecoverable error making socket */
1153 verbose(VERB_ALGO, "opened UDP if=%d port=%d",
1156 pend->pc = outnet->unused_fds;
1157 outnet->unused_fds = pend->pc->next;
1159 /* setup portcomm */
1160 pend->pc->next = NULL;
1161 pend->pc->number = portno;
1162 pend->pc->pif = pif;
1163 pend->pc->index = pif->inuse;
1164 pend->pc->num_outstanding = 0;
1165 comm_point_start_listening(pend->pc->cp, fd, -1);
1167 /* grab port in interface */
1168 pif->out[pif->inuse] = pend->pc;
1169 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
1170 pif->avail_ports[my_port - pif->inuse] =
1171 pif->avail_ports[pif->avail_total-pif->inuse-1];
1176 /* failed, already in use */
1177 verbose(VERB_QUERY, "port %d in use, trying another", portno);
1179 if(tries == MAX_PORT_RETRY) {
1180 log_err("failed to find an open port, drop msg");
1184 log_assert(pend->pc);
1185 pend->pc->num_outstanding++;
1191 randomize_and_send_udp(struct pending* pend, sldns_buffer* packet, int timeout)
1194 struct outside_network* outnet = pend->sq->outnet;
1197 if(!select_id(outnet, pend, packet)) {
1201 /* select src_if, port */
1202 if(addr_is_ip6(&pend->addr, pend->addrlen)) {
1203 if(!select_ifport(outnet, pend,
1204 outnet->num_ip6, outnet->ip6_ifs))
1207 if(!select_ifport(outnet, pend,
1208 outnet->num_ip4, outnet->ip4_ifs))
1211 log_assert(pend->pc && pend->pc->cp);
1213 /* send it over the commlink */
1214 if(!comm_point_send_udp_msg(pend->pc->cp, packet,
1215 (struct sockaddr*)&pend->addr, pend->addrlen)) {
1216 portcomm_loweruse(outnet, pend->pc);
1220 /* system calls to set timeout after sending UDP to make roundtrip
1223 tv.tv_sec = timeout/1000;
1224 tv.tv_usec = (timeout%1000)*1000;
1226 comm_timer_set(pend->timer, &tv);
1230 (outnet->dtenv->log_resolver_query_messages ||
1231 outnet->dtenv->log_forwarder_query_messages))
1232 dt_msg_send_outside_query(outnet->dtenv, &pend->addr, comm_udp,
1233 pend->sq->zone, pend->sq->zonelen, packet);
1239 pending_udp_query(struct serviced_query* sq, struct sldns_buffer* packet,
1240 int timeout, comm_point_callback_type* cb, void* cb_arg)
1242 struct pending* pend = (struct pending*)calloc(1, sizeof(*pend));
1243 if(!pend) return NULL;
1244 pend->outnet = sq->outnet;
1246 pend->addrlen = sq->addrlen;
1247 memmove(&pend->addr, &sq->addr, sq->addrlen);
1249 pend->cb_arg = cb_arg;
1250 pend->node.key = pend;
1251 pend->timer = comm_timer_create(sq->outnet->base, pending_udp_timer_cb,
1258 if(sq->outnet->unused_fds == NULL) {
1259 /* no unused fd, cannot create a new port (randomly) */
1260 verbose(VERB_ALGO, "no fds available, udp query waiting");
1261 pend->timeout = timeout;
1262 pend->pkt_len = sldns_buffer_limit(packet);
1263 pend->pkt = (uint8_t*)memdup(sldns_buffer_begin(packet),
1266 comm_timer_delete(pend->timer);
1270 /* put at end of waiting list */
1271 if(sq->outnet->udp_wait_last)
1272 sq->outnet->udp_wait_last->next_waiting = pend;
1274 sq->outnet->udp_wait_first = pend;
1275 sq->outnet->udp_wait_last = pend;
1278 if(!randomize_and_send_udp(pend, packet, timeout)) {
1279 pending_delete(sq->outnet, pend);
1286 outnet_tcptimer(void* arg)
1288 struct waiting_tcp* w = (struct waiting_tcp*)arg;
1289 struct outside_network* outnet = w->outnet;
1290 comm_point_callback_type* cb;
1293 /* it is on the waiting list */
1294 waiting_list_remove(outnet, w);
1297 struct pending_tcp* pend=(struct pending_tcp*)w->next_waiting;
1300 SSL_shutdown(pend->c->ssl);
1301 SSL_free(pend->c->ssl);
1302 pend->c->ssl = NULL;
1305 comm_point_close(pend->c);
1307 pend->next_free = outnet->tcp_free;
1308 outnet->tcp_free = pend;
1312 waiting_tcp_delete(w);
1313 fptr_ok(fptr_whitelist_pending_tcp(cb));
1314 (void)(*cb)(NULL, cb_arg, NETEVENT_TIMEOUT, NULL);
1315 use_free_buffer(outnet);
1319 pending_tcp_query(struct serviced_query* sq, sldns_buffer* packet,
1320 int timeout, comm_point_callback_type* callback, void* callback_arg)
1322 struct pending_tcp* pend = sq->outnet->tcp_free;
1323 struct waiting_tcp* w;
1326 /* if no buffer is free allocate space to store query */
1327 w = (struct waiting_tcp*)malloc(sizeof(struct waiting_tcp)
1328 + (pend?0:sldns_buffer_limit(packet)));
1332 if(!(w->timer = comm_timer_create(sq->outnet->base, outnet_tcptimer, w))) {
1338 id = ((unsigned)ub_random(sq->outnet->rnd)>>8) & 0xffff;
1339 LDNS_ID_SET(sldns_buffer_begin(packet), id);
1340 memcpy(&w->addr, &sq->addr, sq->addrlen);
1341 w->addrlen = sq->addrlen;
1342 w->outnet = sq->outnet;
1344 w->cb_arg = callback_arg;
1345 w->ssl_upstream = sq->ssl_upstream;
1346 w->tls_auth_name = sq->tls_auth_name;
1348 tv.tv_sec = timeout/1000;
1349 tv.tv_usec = (timeout%1000)*1000;
1351 comm_timer_set(w->timer, &tv);
1353 /* we have a buffer available right now */
1354 if(!outnet_tcp_take_into_use(w, sldns_buffer_begin(packet),
1355 sldns_buffer_limit(packet))) {
1356 waiting_tcp_delete(w);
1360 if(sq->outnet->dtenv &&
1361 (sq->outnet->dtenv->log_resolver_query_messages ||
1362 sq->outnet->dtenv->log_forwarder_query_messages))
1363 dt_msg_send_outside_query(sq->outnet->dtenv, &sq->addr,
1364 comm_tcp, sq->zone, sq->zonelen, packet);
1368 w->pkt = (uint8_t*)w + sizeof(struct waiting_tcp);
1369 w->pkt_len = sldns_buffer_limit(packet);
1370 memmove(w->pkt, sldns_buffer_begin(packet), w->pkt_len);
1371 w->next_waiting = NULL;
1372 if(sq->outnet->tcp_wait_last)
1373 sq->outnet->tcp_wait_last->next_waiting = w;
1374 else sq->outnet->tcp_wait_first = w;
1375 sq->outnet->tcp_wait_last = w;
1380 /** create query for serviced queries */
1382 serviced_gen_query(sldns_buffer* buff, uint8_t* qname, size_t qnamelen,
1383 uint16_t qtype, uint16_t qclass, uint16_t flags)
1385 sldns_buffer_clear(buff);
1387 sldns_buffer_write_u16(buff, flags);
1388 sldns_buffer_write_u16(buff, 1); /* qdcount */
1389 sldns_buffer_write_u16(buff, 0); /* ancount */
1390 sldns_buffer_write_u16(buff, 0); /* nscount */
1391 sldns_buffer_write_u16(buff, 0); /* arcount */
1392 sldns_buffer_write(buff, qname, qnamelen);
1393 sldns_buffer_write_u16(buff, qtype);
1394 sldns_buffer_write_u16(buff, qclass);
1395 sldns_buffer_flip(buff);
1398 /** lookup serviced query in serviced query rbtree */
1399 static struct serviced_query*
1400 lookup_serviced(struct outside_network* outnet, sldns_buffer* buff, int dnssec,
1401 struct sockaddr_storage* addr, socklen_t addrlen,
1402 struct edns_option* opt_list)
1404 struct serviced_query key;
1405 key.node.key = &key;
1406 key.qbuf = sldns_buffer_begin(buff);
1407 key.qbuflen = sldns_buffer_limit(buff);
1408 key.dnssec = dnssec;
1409 memcpy(&key.addr, addr, addrlen);
1410 key.addrlen = addrlen;
1411 key.outnet = outnet;
1412 key.opt_list = opt_list;
1413 return (struct serviced_query*)rbtree_search(outnet->serviced, &key);
1416 /** Create new serviced entry */
1417 static struct serviced_query*
1418 serviced_create(struct outside_network* outnet, sldns_buffer* buff, int dnssec,
1419 int want_dnssec, int nocaps, int tcp_upstream, int ssl_upstream,
1420 char* tls_auth_name, struct sockaddr_storage* addr, socklen_t addrlen,
1421 uint8_t* zone, size_t zonelen, int qtype, struct edns_option* opt_list)
1423 struct serviced_query* sq = (struct serviced_query*)malloc(sizeof(*sq));
1424 #ifdef UNBOUND_DEBUG
1430 sq->qbuf = memdup(sldns_buffer_begin(buff), sldns_buffer_limit(buff));
1435 sq->qbuflen = sldns_buffer_limit(buff);
1436 sq->zone = memdup(zone, zonelen);
1442 sq->zonelen = zonelen;
1444 sq->dnssec = dnssec;
1445 sq->want_dnssec = want_dnssec;
1446 sq->nocaps = nocaps;
1447 sq->tcp_upstream = tcp_upstream;
1448 sq->ssl_upstream = ssl_upstream;
1450 sq->tls_auth_name = strdup(tls_auth_name);
1451 if(!sq->tls_auth_name) {
1458 sq->tls_auth_name = NULL;
1460 memcpy(&sq->addr, addr, addrlen);
1461 sq->addrlen = addrlen;
1462 sq->opt_list = NULL;
1464 sq->opt_list = edns_opt_copy_alloc(opt_list);
1466 free(sq->tls_auth_name);
1473 sq->outnet = outnet;
1476 sq->status = serviced_initial;
1478 sq->to_be_deleted = 0;
1479 #ifdef UNBOUND_DEBUG
1484 rbtree_insert(outnet->serviced, &sq->node);
1485 log_assert(ins != NULL); /* must not be already present */
1489 /** remove waiting tcp from the outnet waiting list */
1491 waiting_list_remove(struct outside_network* outnet, struct waiting_tcp* w)
1493 struct waiting_tcp* p = outnet->tcp_wait_first, *prev = NULL;
1498 prev->next_waiting = w->next_waiting;
1499 else outnet->tcp_wait_first = w->next_waiting;
1500 if(outnet->tcp_wait_last == w)
1501 outnet->tcp_wait_last = prev;
1505 p = p->next_waiting;
1509 /** cleanup serviced query entry */
1511 serviced_delete(struct serviced_query* sq)
1514 /* clear up the pending query */
1515 if(sq->status == serviced_query_UDP_EDNS ||
1516 sq->status == serviced_query_UDP ||
1517 sq->status == serviced_query_UDP_EDNS_FRAG ||
1518 sq->status == serviced_query_UDP_EDNS_fallback) {
1519 struct pending* p = (struct pending*)sq->pending;
1521 portcomm_loweruse(sq->outnet, p->pc);
1522 pending_delete(sq->outnet, p);
1523 /* this call can cause reentrant calls back into the
1525 outnet_send_wait_udp(sq->outnet);
1527 struct waiting_tcp* p = (struct waiting_tcp*)
1529 if(p->pkt == NULL) {
1530 decommission_pending_tcp(sq->outnet,
1531 (struct pending_tcp*)p->next_waiting);
1533 waiting_list_remove(sq->outnet, p);
1534 waiting_tcp_delete(p);
1538 /* does not delete from tree, caller has to do that */
1539 serviced_node_del(&sq->node, NULL);
1542 /** perturb a dname capitalization randomly */
1544 serviced_perturb_qname(struct ub_randstate* rnd, uint8_t* qbuf, size_t len)
1547 uint8_t* d = qbuf + 10;
1548 long int random = 0;
1550 log_assert(len >= 10 + 5 /* offset qname, root, qtype, qclass */);
1555 /* only perturb A-Z, a-z */
1556 if(isalpha((unsigned char)*d)) {
1557 /* get a random bit */
1559 random = ub_random(rnd);
1563 *d = (uint8_t)toupper((unsigned char)*d);
1565 *d = (uint8_t)tolower((unsigned char)*d);
1574 if(verbosity >= VERB_ALGO) {
1575 char buf[LDNS_MAX_DOMAINLEN+1];
1576 dname_str(qbuf+10, buf);
1577 verbose(VERB_ALGO, "qname perturbed to %s", buf);
1581 /** put serviced query into a buffer */
1583 serviced_encode(struct serviced_query* sq, sldns_buffer* buff, int with_edns)
1585 /* if we are using 0x20 bits for ID randomness, perturb them */
1586 if(sq->outnet->use_caps_for_id && !sq->nocaps) {
1587 serviced_perturb_qname(sq->outnet->rnd, sq->qbuf, sq->qbuflen);
1589 /* generate query */
1590 sldns_buffer_clear(buff);
1591 sldns_buffer_write_u16(buff, 0); /* id placeholder */
1592 sldns_buffer_write(buff, sq->qbuf, sq->qbuflen);
1593 sldns_buffer_flip(buff);
1595 /* add edns section */
1596 struct edns_data edns;
1597 edns.edns_present = 1;
1599 edns.edns_version = EDNS_ADVERTISED_VERSION;
1600 edns.opt_list = sq->opt_list;
1601 if(sq->status == serviced_query_UDP_EDNS_FRAG) {
1602 if(addr_is_ip6(&sq->addr, sq->addrlen)) {
1603 if(EDNS_FRAG_SIZE_IP6 < EDNS_ADVERTISED_SIZE)
1604 edns.udp_size = EDNS_FRAG_SIZE_IP6;
1605 else edns.udp_size = EDNS_ADVERTISED_SIZE;
1607 if(EDNS_FRAG_SIZE_IP4 < EDNS_ADVERTISED_SIZE)
1608 edns.udp_size = EDNS_FRAG_SIZE_IP4;
1609 else edns.udp_size = EDNS_ADVERTISED_SIZE;
1612 edns.udp_size = EDNS_ADVERTISED_SIZE;
1615 if(sq->dnssec & EDNS_DO)
1616 edns.bits = EDNS_DO;
1617 if(sq->dnssec & BIT_CD)
1618 LDNS_CD_SET(sldns_buffer_begin(buff));
1619 attach_edns_record(buff, &edns);
1624 * Perform serviced query UDP sending operation.
1625 * Sends UDP with EDNS, unless infra host marked non EDNS.
1626 * @param sq: query to send.
1627 * @param buff: buffer scratch space.
1628 * @return 0 on error.
1631 serviced_udp_send(struct serviced_query* sq, sldns_buffer* buff)
1634 uint8_t edns_lame_known;
1635 time_t now = *sq->outnet->now_secs;
1637 if(!infra_host(sq->outnet->infra, &sq->addr, sq->addrlen, sq->zone,
1638 sq->zonelen, now, &vs, &edns_lame_known, &rtt))
1641 verbose(VERB_ALGO, "EDNS lookup known=%d vs=%d", edns_lame_known, vs);
1642 if(sq->status == serviced_initial) {
1644 sq->status = serviced_query_UDP_EDNS;
1646 sq->status = serviced_query_UDP;
1649 serviced_encode(sq, buff, (sq->status == serviced_query_UDP_EDNS) ||
1650 (sq->status == serviced_query_UDP_EDNS_FRAG));
1651 sq->last_sent_time = *sq->outnet->now_tv;
1652 sq->edns_lame_known = (int)edns_lame_known;
1653 verbose(VERB_ALGO, "serviced query UDP timeout=%d msec", rtt);
1654 sq->pending = pending_udp_query(sq, buff, rtt,
1655 serviced_udp_callback, sq);
1661 /** check that perturbed qname is identical */
1663 serviced_check_qname(sldns_buffer* pkt, uint8_t* qbuf, size_t qbuflen)
1665 uint8_t* d1 = sldns_buffer_begin(pkt)+12;
1666 uint8_t* d2 = qbuf+10;
1669 if(sldns_buffer_limit(pkt) < 12+1+4) /* packet too small for qname */
1671 log_assert(qbuflen >= 15 /* 10 header, root, type, class */);
1674 while(len1 != 0 || len2 != 0) {
1675 if(LABEL_IS_PTR(len1)) {
1676 /* check if we can read *d1 with compression ptr rest */
1677 if(d1 >= sldns_buffer_at(pkt, sldns_buffer_limit(pkt)))
1679 d1 = sldns_buffer_begin(pkt)+PTR_OFFSET(len1, *d1);
1680 /* check if we can read the destination *d1 */
1681 if(d1 >= sldns_buffer_at(pkt, sldns_buffer_limit(pkt)))
1684 if(count++ > MAX_COMPRESS_PTRS)
1688 if(d2 > qbuf+qbuflen)
1692 if(len1 > LDNS_MAX_LABELLEN)
1694 /* check len1 + 1(next length) are okay to read */
1695 if(d1+len1 >= sldns_buffer_at(pkt, sldns_buffer_limit(pkt)))
1697 log_assert(len1 <= LDNS_MAX_LABELLEN);
1698 log_assert(len2 <= LDNS_MAX_LABELLEN);
1699 log_assert(len1 == len2 && len1 != 0);
1700 /* compare the labels - bitwise identical */
1701 if(memcmp(d1, d2, len1) != 0)
1711 /** call the callbacks for a serviced query */
1713 serviced_callbacks(struct serviced_query* sq, int error, struct comm_point* c,
1714 struct comm_reply* rep)
1716 struct service_callback* p;
1717 int dobackup = (sq->cblist && sq->cblist->next); /* >1 cb*/
1718 uint8_t *backup_p = NULL;
1720 #ifdef UNBOUND_DEBUG
1725 /* remove from tree, and schedule for deletion, so that callbacks
1726 * can safely deregister themselves and even create new serviced
1727 * queries that are identical to this one. */
1728 rbtree_delete(sq->outnet->serviced, sq);
1729 log_assert(rem); /* should have been present */
1730 sq->to_be_deleted = 1;
1731 verbose(VERB_ALGO, "svcd callbacks start");
1732 if(sq->outnet->use_caps_for_id && error == NETEVENT_NOERROR && c &&
1733 !sq->nocaps && sq->qtype != LDNS_RR_TYPE_PTR) {
1734 /* for type PTR do not check perturbed name in answer,
1735 * compatibility with cisco dns guard boxes that mess up
1736 * reverse queries 0x20 contents */
1737 /* noerror and nxdomain must have a qname in reply */
1738 if(sldns_buffer_read_u16_at(c->buffer, 4) == 0 &&
1739 (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer))
1740 == LDNS_RCODE_NOERROR ||
1741 LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer))
1742 == LDNS_RCODE_NXDOMAIN)) {
1743 verbose(VERB_DETAIL, "no qname in reply to check 0x20ID");
1744 log_addr(VERB_DETAIL, "from server",
1745 &sq->addr, sq->addrlen);
1746 log_buf(VERB_DETAIL, "for packet", c->buffer);
1747 error = NETEVENT_CLOSED;
1749 } else if(sldns_buffer_read_u16_at(c->buffer, 4) > 0 &&
1750 !serviced_check_qname(c->buffer, sq->qbuf,
1752 verbose(VERB_DETAIL, "wrong 0x20-ID in reply qname");
1753 log_addr(VERB_DETAIL, "from server",
1754 &sq->addr, sq->addrlen);
1755 log_buf(VERB_DETAIL, "for packet", c->buffer);
1756 error = NETEVENT_CAPSFAIL;
1757 /* and cleanup too */
1758 pkt_dname_tolower(c->buffer,
1759 sldns_buffer_at(c->buffer, 12));
1761 verbose(VERB_ALGO, "good 0x20-ID in reply qname");
1762 /* cleanup caps, prettier cache contents. */
1763 pkt_dname_tolower(c->buffer,
1764 sldns_buffer_at(c->buffer, 12));
1768 /* make a backup of the query, since the querystate processing
1769 * may send outgoing queries that overwrite the buffer.
1770 * use secondary buffer to store the query.
1771 * This is a data copy, but faster than packet to server */
1772 backlen = sldns_buffer_limit(c->buffer);
1773 backup_p = memdup(sldns_buffer_begin(c->buffer), backlen);
1775 log_err("malloc failure in serviced query callbacks");
1776 error = NETEVENT_CLOSED;
1779 sq->outnet->svcd_overhead = backlen;
1781 /* test the actual sq->cblist, because the next elem could be deleted*/
1782 while((p=sq->cblist) != NULL) {
1783 sq->cblist = p->next; /* remove this element */
1785 sldns_buffer_clear(c->buffer);
1786 sldns_buffer_write(c->buffer, backup_p, backlen);
1787 sldns_buffer_flip(c->buffer);
1789 fptr_ok(fptr_whitelist_serviced_query(p->cb));
1790 (void)(*p->cb)(c, p->cb_arg, error, rep);
1795 sq->outnet->svcd_overhead = 0;
1797 verbose(VERB_ALGO, "svcd callbacks end");
1798 log_assert(sq->cblist == NULL);
1799 serviced_delete(sq);
1803 serviced_tcp_callback(struct comm_point* c, void* arg, int error,
1804 struct comm_reply* rep)
1806 struct serviced_query* sq = (struct serviced_query*)arg;
1807 struct comm_reply r2;
1808 sq->pending = NULL; /* removed after this callback */
1809 if(error != NETEVENT_NOERROR)
1810 log_addr(VERB_QUERY, "tcp error for address",
1811 &sq->addr, sq->addrlen);
1812 if(error==NETEVENT_NOERROR)
1813 infra_update_tcp_works(sq->outnet->infra, &sq->addr,
1814 sq->addrlen, sq->zone, sq->zonelen);
1816 if(error==NETEVENT_NOERROR && sq->outnet->dtenv &&
1817 (sq->outnet->dtenv->log_resolver_response_messages ||
1818 sq->outnet->dtenv->log_forwarder_response_messages))
1819 dt_msg_send_outside_response(sq->outnet->dtenv, &sq->addr,
1820 c->type, sq->zone, sq->zonelen, sq->qbuf, sq->qbuflen,
1821 &sq->last_sent_time, sq->outnet->now_tv, c->buffer);
1823 if(error==NETEVENT_NOERROR && sq->status == serviced_query_TCP_EDNS &&
1824 (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) ==
1825 LDNS_RCODE_FORMERR || LDNS_RCODE_WIRE(sldns_buffer_begin(
1826 c->buffer)) == LDNS_RCODE_NOTIMPL) ) {
1827 /* attempt to fallback to nonEDNS */
1828 sq->status = serviced_query_TCP_EDNS_fallback;
1829 serviced_tcp_initiate(sq, c->buffer);
1831 } else if(error==NETEVENT_NOERROR &&
1832 sq->status == serviced_query_TCP_EDNS_fallback &&
1833 (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) ==
1834 LDNS_RCODE_NOERROR || LDNS_RCODE_WIRE(
1835 sldns_buffer_begin(c->buffer)) == LDNS_RCODE_NXDOMAIN
1836 || LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer))
1837 == LDNS_RCODE_YXDOMAIN)) {
1838 /* the fallback produced a result that looks promising, note
1839 * that this server should be approached without EDNS */
1840 /* only store noEDNS in cache if domain is noDNSSEC */
1841 if(!sq->want_dnssec)
1842 if(!infra_edns_update(sq->outnet->infra, &sq->addr,
1843 sq->addrlen, sq->zone, sq->zonelen, -1,
1844 *sq->outnet->now_secs))
1845 log_err("Out of memory caching no edns for host");
1846 sq->status = serviced_query_TCP;
1848 if(sq->tcp_upstream || sq->ssl_upstream) {
1849 struct timeval now = *sq->outnet->now_tv;
1850 if(error!=NETEVENT_NOERROR) {
1851 if(!infra_rtt_update(sq->outnet->infra, &sq->addr,
1852 sq->addrlen, sq->zone, sq->zonelen, sq->qtype,
1853 -1, sq->last_rtt, (time_t)now.tv_sec))
1854 log_err("out of memory in TCP exponential backoff.");
1855 } else if(now.tv_sec > sq->last_sent_time.tv_sec ||
1856 (now.tv_sec == sq->last_sent_time.tv_sec &&
1857 now.tv_usec > sq->last_sent_time.tv_usec)) {
1858 /* convert from microseconds to milliseconds */
1859 int roundtime = ((int)(now.tv_sec - sq->last_sent_time.tv_sec))*1000
1860 + ((int)now.tv_usec - (int)sq->last_sent_time.tv_usec)/1000;
1861 verbose(VERB_ALGO, "measured TCP-time at %d msec", roundtime);
1862 log_assert(roundtime >= 0);
1863 /* only store if less then AUTH_TIMEOUT seconds, it could be
1864 * huge due to system-hibernated and we woke up */
1865 if(roundtime < 60000) {
1866 if(!infra_rtt_update(sq->outnet->infra, &sq->addr,
1867 sq->addrlen, sq->zone, sq->zonelen, sq->qtype,
1868 roundtime, sq->last_rtt, (time_t)now.tv_sec))
1869 log_err("out of memory noting rtt.");
1873 /* insert address into reply info */
1875 /* create one if there isn't (on errors) */
1879 memcpy(&rep->addr, &sq->addr, sq->addrlen);
1880 rep->addrlen = sq->addrlen;
1881 serviced_callbacks(sq, error, c, rep);
1886 serviced_tcp_initiate(struct serviced_query* sq, sldns_buffer* buff)
1888 verbose(VERB_ALGO, "initiate TCP query %s",
1889 sq->status==serviced_query_TCP_EDNS?"EDNS":"");
1890 serviced_encode(sq, buff, sq->status == serviced_query_TCP_EDNS);
1891 sq->last_sent_time = *sq->outnet->now_tv;
1892 sq->pending = pending_tcp_query(sq, buff, TCP_AUTH_QUERY_TIMEOUT,
1893 serviced_tcp_callback, sq);
1895 /* delete from tree so that a retry by above layer does not
1896 * clash with this entry */
1897 verbose(VERB_ALGO, "serviced_tcp_initiate: failed to send tcp query");
1898 serviced_callbacks(sq, NETEVENT_CLOSED, NULL, NULL);
1902 /** Send serviced query over TCP return false on initial failure */
1904 serviced_tcp_send(struct serviced_query* sq, sldns_buffer* buff)
1906 int vs, rtt, timeout;
1907 uint8_t edns_lame_known;
1908 if(!infra_host(sq->outnet->infra, &sq->addr, sq->addrlen, sq->zone,
1909 sq->zonelen, *sq->outnet->now_secs, &vs, &edns_lame_known,
1914 sq->status = serviced_query_TCP_EDNS;
1915 else sq->status = serviced_query_TCP;
1916 serviced_encode(sq, buff, sq->status == serviced_query_TCP_EDNS);
1917 sq->last_sent_time = *sq->outnet->now_tv;
1918 if(sq->tcp_upstream || sq->ssl_upstream) {
1920 if(rtt >= UNKNOWN_SERVER_NICENESS && rtt < TCP_AUTH_QUERY_TIMEOUT)
1921 timeout = TCP_AUTH_QUERY_TIMEOUT;
1923 timeout = TCP_AUTH_QUERY_TIMEOUT;
1925 sq->pending = pending_tcp_query(sq, buff, timeout,
1926 serviced_tcp_callback, sq);
1927 return sq->pending != NULL;
1930 /* see if packet is edns malformed; got zeroes at start.
1931 * This is from servers that return malformed packets to EDNS0 queries,
1932 * but they return good packets for nonEDNS0 queries.
1933 * We try to detect their output; without resorting to a full parse or
1934 * check for too many bytes after the end of the packet. */
1936 packet_edns_malformed(struct sldns_buffer* buf, int qtype)
1939 if(sldns_buffer_limit(buf) < LDNS_HEADER_SIZE)
1940 return 1; /* malformed */
1941 /* they have NOERROR rcode, 1 answer. */
1942 if(LDNS_RCODE_WIRE(sldns_buffer_begin(buf)) != LDNS_RCODE_NOERROR)
1944 /* one query (to skip) and answer records */
1945 if(LDNS_QDCOUNT(sldns_buffer_begin(buf)) != 1 ||
1946 LDNS_ANCOUNT(sldns_buffer_begin(buf)) == 0)
1949 len = dname_valid(sldns_buffer_at(buf, LDNS_HEADER_SIZE),
1950 sldns_buffer_limit(buf)-LDNS_HEADER_SIZE);
1953 if(len == 1 && qtype == 0)
1954 return 0; /* we asked for '.' and type 0 */
1955 /* and then 4 bytes (type and class of query) */
1956 if(sldns_buffer_limit(buf) < LDNS_HEADER_SIZE + len + 4 + 3)
1959 /* and start with 11 zeroes as the answer RR */
1960 /* so check the qtype of the answer record, qname=0, type=0 */
1961 if(sldns_buffer_at(buf, LDNS_HEADER_SIZE+len+4)[0] == 0 &&
1962 sldns_buffer_at(buf, LDNS_HEADER_SIZE+len+4)[1] == 0 &&
1963 sldns_buffer_at(buf, LDNS_HEADER_SIZE+len+4)[2] == 0)
1969 serviced_udp_callback(struct comm_point* c, void* arg, int error,
1970 struct comm_reply* rep)
1972 struct serviced_query* sq = (struct serviced_query*)arg;
1973 struct outside_network* outnet = sq->outnet;
1974 struct timeval now = *sq->outnet->now_tv;
1976 sq->pending = NULL; /* removed after callback */
1977 if(error == NETEVENT_TIMEOUT) {
1978 if(sq->status == serviced_query_UDP_EDNS && sq->last_rtt < 5000) {
1979 /* fallback to 1480/1280 */
1980 sq->status = serviced_query_UDP_EDNS_FRAG;
1981 log_name_addr(VERB_ALGO, "try edns1xx0", sq->qbuf+10,
1982 &sq->addr, sq->addrlen);
1983 if(!serviced_udp_send(sq, c->buffer)) {
1984 serviced_callbacks(sq, NETEVENT_CLOSED, c, rep);
1988 if(sq->status == serviced_query_UDP_EDNS_FRAG) {
1989 /* fragmentation size did not fix it */
1990 sq->status = serviced_query_UDP_EDNS;
1993 if(!infra_rtt_update(outnet->infra, &sq->addr, sq->addrlen,
1994 sq->zone, sq->zonelen, sq->qtype, -1, sq->last_rtt,
1995 (time_t)now.tv_sec))
1996 log_err("out of memory in UDP exponential backoff");
1997 if(sq->retry < OUTBOUND_UDP_RETRY) {
1998 log_name_addr(VERB_ALGO, "retry query", sq->qbuf+10,
1999 &sq->addr, sq->addrlen);
2000 if(!serviced_udp_send(sq, c->buffer)) {
2001 serviced_callbacks(sq, NETEVENT_CLOSED, c, rep);
2006 if(error != NETEVENT_NOERROR) {
2007 /* udp returns error (due to no ID or interface available) */
2008 serviced_callbacks(sq, error, c, rep);
2012 if(error == NETEVENT_NOERROR && outnet->dtenv &&
2013 (outnet->dtenv->log_resolver_response_messages ||
2014 outnet->dtenv->log_forwarder_response_messages))
2015 dt_msg_send_outside_response(outnet->dtenv, &sq->addr, c->type,
2016 sq->zone, sq->zonelen, sq->qbuf, sq->qbuflen,
2017 &sq->last_sent_time, sq->outnet->now_tv, c->buffer);
2019 if( (sq->status == serviced_query_UDP_EDNS
2020 ||sq->status == serviced_query_UDP_EDNS_FRAG)
2021 && (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer))
2022 == LDNS_RCODE_FORMERR || LDNS_RCODE_WIRE(
2023 sldns_buffer_begin(c->buffer)) == LDNS_RCODE_NOTIMPL
2024 || packet_edns_malformed(c->buffer, sq->qtype)
2026 /* try to get an answer by falling back without EDNS */
2027 verbose(VERB_ALGO, "serviced query: attempt without EDNS");
2028 sq->status = serviced_query_UDP_EDNS_fallback;
2030 if(!serviced_udp_send(sq, c->buffer)) {
2031 serviced_callbacks(sq, NETEVENT_CLOSED, c, rep);
2034 } else if(sq->status == serviced_query_UDP_EDNS &&
2035 !sq->edns_lame_known) {
2036 /* now we know that edns queries received answers store that */
2037 log_addr(VERB_ALGO, "serviced query: EDNS works for",
2038 &sq->addr, sq->addrlen);
2039 if(!infra_edns_update(outnet->infra, &sq->addr, sq->addrlen,
2040 sq->zone, sq->zonelen, 0, (time_t)now.tv_sec)) {
2041 log_err("Out of memory caching edns works");
2043 sq->edns_lame_known = 1;
2044 } else if(sq->status == serviced_query_UDP_EDNS_fallback &&
2045 !sq->edns_lame_known && (LDNS_RCODE_WIRE(
2046 sldns_buffer_begin(c->buffer)) == LDNS_RCODE_NOERROR ||
2047 LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) ==
2048 LDNS_RCODE_NXDOMAIN || LDNS_RCODE_WIRE(sldns_buffer_begin(
2049 c->buffer)) == LDNS_RCODE_YXDOMAIN)) {
2050 /* the fallback produced a result that looks promising, note
2051 * that this server should be approached without EDNS */
2052 /* only store noEDNS in cache if domain is noDNSSEC */
2053 if(!sq->want_dnssec) {
2054 log_addr(VERB_ALGO, "serviced query: EDNS fails for",
2055 &sq->addr, sq->addrlen);
2056 if(!infra_edns_update(outnet->infra, &sq->addr, sq->addrlen,
2057 sq->zone, sq->zonelen, -1, (time_t)now.tv_sec)) {
2058 log_err("Out of memory caching no edns for host");
2061 log_addr(VERB_ALGO, "serviced query: EDNS fails, but "
2062 "not stored because need DNSSEC for", &sq->addr,
2065 sq->status = serviced_query_UDP;
2067 if(now.tv_sec > sq->last_sent_time.tv_sec ||
2068 (now.tv_sec == sq->last_sent_time.tv_sec &&
2069 now.tv_usec > sq->last_sent_time.tv_usec)) {
2070 /* convert from microseconds to milliseconds */
2071 int roundtime = ((int)(now.tv_sec - sq->last_sent_time.tv_sec))*1000
2072 + ((int)now.tv_usec - (int)sq->last_sent_time.tv_usec)/1000;
2073 verbose(VERB_ALGO, "measured roundtrip at %d msec", roundtime);
2074 log_assert(roundtime >= 0);
2075 /* in case the system hibernated, do not enter a huge value,
2076 * above this value gives trouble with server selection */
2077 if(roundtime < 60000) {
2078 if(!infra_rtt_update(outnet->infra, &sq->addr, sq->addrlen,
2079 sq->zone, sq->zonelen, sq->qtype, roundtime,
2080 sq->last_rtt, (time_t)now.tv_sec))
2081 log_err("out of memory noting rtt.");
2084 /* perform TC flag check and TCP fallback after updating our
2085 * cache entries for EDNS status and RTT times */
2086 if(LDNS_TC_WIRE(sldns_buffer_begin(c->buffer))) {
2087 /* fallback to TCP */
2088 /* this discards partial UDP contents */
2089 if(sq->status == serviced_query_UDP_EDNS ||
2090 sq->status == serviced_query_UDP_EDNS_FRAG ||
2091 sq->status == serviced_query_UDP_EDNS_fallback)
2092 /* if we have unfinished EDNS_fallback, start again */
2093 sq->status = serviced_query_TCP_EDNS;
2094 else sq->status = serviced_query_TCP;
2095 serviced_tcp_initiate(sq, c->buffer);
2098 /* yay! an answer */
2099 serviced_callbacks(sq, error, c, rep);
2103 struct serviced_query*
2104 outnet_serviced_query(struct outside_network* outnet,
2105 struct query_info* qinfo, uint16_t flags, int dnssec, int want_dnssec,
2106 int nocaps, int tcp_upstream, int ssl_upstream, char* tls_auth_name,
2107 struct sockaddr_storage* addr, socklen_t addrlen, uint8_t* zone,
2108 size_t zonelen, struct module_qstate* qstate,
2109 comm_point_callback_type* callback, void* callback_arg, sldns_buffer* buff,
2110 struct module_env* env)
2112 struct serviced_query* sq;
2113 struct service_callback* cb;
2114 if(!inplace_cb_query_call(env, qinfo, flags, addr, addrlen, zone, zonelen,
2115 qstate, qstate->region))
2117 serviced_gen_query(buff, qinfo->qname, qinfo->qname_len, qinfo->qtype,
2118 qinfo->qclass, flags);
2119 sq = lookup_serviced(outnet, buff, dnssec, addr, addrlen,
2120 qstate->edns_opts_back_out);
2121 /* duplicate entries are included in the callback list, because
2122 * there is a counterpart registration by our caller that needs to
2123 * be doubly-removed (with callbacks perhaps). */
2124 if(!(cb = (struct service_callback*)malloc(sizeof(*cb))))
2127 /* make new serviced query entry */
2128 sq = serviced_create(outnet, buff, dnssec, want_dnssec, nocaps,
2129 tcp_upstream, ssl_upstream, tls_auth_name, addr,
2130 addrlen, zone, zonelen, (int)qinfo->qtype,
2131 qstate->edns_opts_back_out);
2136 /* perform first network action */
2137 if(outnet->do_udp && !(tcp_upstream || ssl_upstream)) {
2138 if(!serviced_udp_send(sq, buff)) {
2139 (void)rbtree_delete(outnet->serviced, sq);
2140 serviced_node_del(&sq->node, NULL);
2145 if(!serviced_tcp_send(sq, buff)) {
2146 (void)rbtree_delete(outnet->serviced, sq);
2147 serviced_node_del(&sq->node, NULL);
2153 /* add callback to list of callbacks */
2155 cb->cb_arg = callback_arg;
2156 cb->next = sq->cblist;
2161 /** remove callback from list */
2163 callback_list_remove(struct serviced_query* sq, void* cb_arg)
2165 struct service_callback** pp = &sq->cblist;
2167 if((*pp)->cb_arg == cb_arg) {
2168 struct service_callback* del = *pp;
2177 void outnet_serviced_query_stop(struct serviced_query* sq, void* cb_arg)
2181 callback_list_remove(sq, cb_arg);
2182 /* if callbacks() routine scheduled deletion, let it do that */
2183 if(!sq->cblist && !sq->to_be_deleted) {
2184 (void)rbtree_delete(sq->outnet->serviced, sq);
2185 serviced_delete(sq);
2189 /** create fd to send to this destination */
2191 fd_for_dest(struct outside_network* outnet, struct sockaddr_storage* to_addr,
2192 socklen_t to_addrlen)
2194 struct sockaddr_storage* addr;
2196 int i, try, pnum, dscp;
2197 struct port_if* pif;
2200 dscp = outnet->ip_dscp;
2201 for(try = 0; try<1000; try++) {
2208 /* select interface */
2209 if(addr_is_ip6(to_addr, to_addrlen)) {
2210 if(outnet->num_ip6 == 0) {
2212 addr_to_str(to_addr, to_addrlen, to, sizeof(to));
2213 verbose(VERB_QUERY, "need ipv6 to send, but no ipv6 outgoing interfaces, for %s", to);
2216 i = ub_random_max(outnet->rnd, outnet->num_ip6);
2217 pif = &outnet->ip6_ifs[i];
2219 if(outnet->num_ip4 == 0) {
2221 addr_to_str(to_addr, to_addrlen, to, sizeof(to));
2222 verbose(VERB_QUERY, "need ipv4 to send, but no ipv4 outgoing interfaces, for %s", to);
2225 i = ub_random_max(outnet->rnd, outnet->num_ip4);
2226 pif = &outnet->ip4_ifs[i];
2229 addrlen = pif->addrlen;
2230 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
2231 pnum = ub_random_max(outnet->rnd, pif->avail_total);
2232 if(pnum < pif->inuse) {
2233 /* port already open */
2234 port = pif->out[pnum]->number;
2236 /* unused ports in start part of array */
2237 port = pif->avail_ports[pnum - pif->inuse];
2242 if(addr_is_ip6(to_addr, to_addrlen)) {
2243 struct sockaddr_in6 sa = *(struct sockaddr_in6*)addr;
2244 sa.sin6_port = (in_port_t)htons((uint16_t)port);
2245 fd = create_udp_sock(AF_INET6, SOCK_DGRAM,
2246 (struct sockaddr*)&sa, addrlen, 1, &inuse, &noproto,
2247 0, 0, 0, NULL, 0, freebind, 0, dscp);
2249 struct sockaddr_in* sa = (struct sockaddr_in*)addr;
2250 sa->sin_port = (in_port_t)htons((uint16_t)port);
2251 fd = create_udp_sock(AF_INET, SOCK_DGRAM,
2252 (struct sockaddr*)addr, addrlen, 1, &inuse, &noproto,
2253 0, 0, 0, NULL, 0, freebind, 0, dscp);
2262 /* too many tries */
2263 log_err("cannot send probe, ports are in use");
2268 outnet_comm_point_for_udp(struct outside_network* outnet,
2269 comm_point_callback_type* cb, void* cb_arg,
2270 struct sockaddr_storage* to_addr, socklen_t to_addrlen)
2272 struct comm_point* cp;
2273 int fd = fd_for_dest(outnet, to_addr, to_addrlen);
2277 cp = comm_point_create_udp(outnet->base, fd, outnet->udp_buff,
2280 log_err("malloc failure");
2287 /** setup SSL for comm point */
2289 setup_comm_ssl(struct comm_point* cp, struct outside_network* outnet,
2292 cp->ssl = outgoing_ssl_fd(outnet->sslctx, fd);
2294 log_err("cannot create SSL object");
2298 comm_point_tcp_win_bio_cb(cp, cp->ssl);
2300 cp->ssl_shake_state = comm_ssl_shake_write;
2301 /* https verification */
2303 if(outnet->tls_use_sni) {
2304 (void)SSL_set_tlsext_host_name(cp->ssl, host);
2307 #ifdef HAVE_SSL_SET1_HOST
2308 if((SSL_CTX_get_verify_mode(outnet->sslctx)&SSL_VERIFY_PEER)) {
2309 /* because we set SSL_VERIFY_PEER, in netevent in
2310 * ssl_handshake, it'll check if the certificate
2311 * verification has succeeded */
2312 /* SSL_VERIFY_PEER is set on the sslctx */
2313 /* and the certificates to verify with are loaded into
2314 * it with SSL_load_verify_locations or
2315 * SSL_CTX_set_default_verify_paths */
2316 /* setting the hostname makes openssl verify the
2317 * host name in the x509 certificate in the
2319 if(!SSL_set1_host(cp->ssl, host)) {
2320 log_err("SSL_set1_host failed");
2324 #elif defined(HAVE_X509_VERIFY_PARAM_SET1_HOST)
2325 /* openssl 1.0.2 has this function that can be used for
2326 * set1_host like verification */
2327 if((SSL_CTX_get_verify_mode(outnet->sslctx)&SSL_VERIFY_PEER)) {
2328 X509_VERIFY_PARAM* param = SSL_get0_param(cp->ssl);
2329 # ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
2330 X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
2332 if(!X509_VERIFY_PARAM_set1_host(param, host, strlen(host))) {
2333 log_err("X509_VERIFY_PARAM_set1_host failed");
2339 #endif /* HAVE_SSL_SET1_HOST */
2344 outnet_comm_point_for_tcp(struct outside_network* outnet,
2345 comm_point_callback_type* cb, void* cb_arg,
2346 struct sockaddr_storage* to_addr, socklen_t to_addrlen,
2347 sldns_buffer* query, int timeout, int ssl, char* host)
2349 struct comm_point* cp;
2350 int fd = outnet_get_tcp_fd(to_addr, to_addrlen, outnet->tcp_mss, outnet->ip_dscp);
2354 fd_set_nonblock(fd);
2355 if(!outnet_tcp_connect(fd, to_addr, to_addrlen)) {
2356 /* outnet_tcp_connect has closed fd on error for us */
2359 cp = comm_point_create_tcp_out(outnet->base, 65552, cb, cb_arg);
2361 log_err("malloc failure");
2365 cp->repinfo.addrlen = to_addrlen;
2366 memcpy(&cp->repinfo.addr, to_addr, to_addrlen);
2368 /* setup for SSL (if needed) */
2370 if(!setup_comm_ssl(cp, outnet, fd, host)) {
2371 log_err("cannot setup XoT");
2372 comm_point_delete(cp);
2377 /* set timeout on TCP connection */
2378 comm_point_start_listening(cp, fd, timeout);
2379 /* copy scratch buffer to cp->buffer */
2380 sldns_buffer_copy(cp->buffer, query);
2384 /** setup http request headers in buffer for sending query to destination */
2386 setup_http_request(sldns_buffer* buf, char* host, char* path)
2388 sldns_buffer_clear(buf);
2389 sldns_buffer_printf(buf, "GET /%s HTTP/1.1\r\n", path);
2390 sldns_buffer_printf(buf, "Host: %s\r\n", host);
2391 sldns_buffer_printf(buf, "User-Agent: unbound/%s\r\n",
2393 /* We do not really do multiple queries per connection,
2394 * but this header setting is also not needed.
2395 * sldns_buffer_printf(buf, "Connection: close\r\n") */
2396 sldns_buffer_printf(buf, "\r\n");
2397 if(sldns_buffer_position(buf)+10 > sldns_buffer_capacity(buf))
2398 return 0; /* somehow buffer too short, but it is about 60K
2399 and the request is only a couple bytes long. */
2400 sldns_buffer_flip(buf);
2405 outnet_comm_point_for_http(struct outside_network* outnet,
2406 comm_point_callback_type* cb, void* cb_arg,
2407 struct sockaddr_storage* to_addr, socklen_t to_addrlen, int timeout,
2408 int ssl, char* host, char* path)
2410 /* cp calls cb with err=NETEVENT_DONE when transfer is done */
2411 struct comm_point* cp;
2412 int fd = outnet_get_tcp_fd(to_addr, to_addrlen, outnet->tcp_mss, outnet->ip_dscp);
2416 fd_set_nonblock(fd);
2417 if(!outnet_tcp_connect(fd, to_addr, to_addrlen)) {
2418 /* outnet_tcp_connect has closed fd on error for us */
2421 cp = comm_point_create_http_out(outnet->base, 65552, cb, cb_arg,
2424 log_err("malloc failure");
2428 cp->repinfo.addrlen = to_addrlen;
2429 memcpy(&cp->repinfo.addr, to_addr, to_addrlen);
2431 /* setup for SSL (if needed) */
2433 if(!setup_comm_ssl(cp, outnet, fd, host)) {
2434 log_err("cannot setup https");
2435 comm_point_delete(cp);
2440 /* set timeout on TCP connection */
2441 comm_point_start_listening(cp, fd, timeout);
2443 /* setup http request in cp->buffer */
2444 if(!setup_http_request(cp->buffer, host, path)) {
2445 log_err("error setting up http request");
2446 comm_point_delete(cp);
2452 /** get memory used by waiting tcp entry (in use or not) */
2454 waiting_tcp_get_mem(struct waiting_tcp* w)
2458 s = sizeof(*w) + w->pkt_len;
2460 s += comm_timer_get_mem(w->timer);
2464 /** get memory used by port if */
2466 if_get_mem(struct port_if* pif)
2471 #ifndef DISABLE_EXPLICIT_PORT_RANDOMISATION
2472 sizeof(int)*pif->avail_total +
2474 sizeof(struct port_comm*)*pif->maxout;
2475 for(i=0; i<pif->inuse; i++)
2476 s += sizeof(*pif->out[i]) +
2477 comm_point_get_mem(pif->out[i]->cp);
2481 /** get memory used by waiting udp */
2483 waiting_udp_get_mem(struct pending* w)
2486 s = sizeof(*w) + comm_timer_get_mem(w->timer) + w->pkt_len;
2490 size_t outnet_get_mem(struct outside_network* outnet)
2494 struct waiting_tcp* w;
2496 struct serviced_query* sq;
2497 struct service_callback* sb;
2498 struct port_comm* pc;
2499 size_t s = sizeof(*outnet) + sizeof(*outnet->base) +
2500 sizeof(*outnet->udp_buff) +
2501 sldns_buffer_capacity(outnet->udp_buff);
2502 /* second buffer is not ours */
2503 for(pc = outnet->unused_fds; pc; pc = pc->next) {
2504 s += sizeof(*pc) + comm_point_get_mem(pc->cp);
2506 for(k=0; k<outnet->num_ip4; k++)
2507 s += if_get_mem(&outnet->ip4_ifs[k]);
2508 for(k=0; k<outnet->num_ip6; k++)
2509 s += if_get_mem(&outnet->ip6_ifs[k]);
2510 for(u=outnet->udp_wait_first; u; u=u->next_waiting)
2511 s += waiting_udp_get_mem(u);
2513 s += sizeof(struct pending_tcp*)*outnet->num_tcp;
2514 for(i=0; i<outnet->num_tcp; i++) {
2515 s += sizeof(struct pending_tcp);
2516 s += comm_point_get_mem(outnet->tcp_conns[i]->c);
2517 if(outnet->tcp_conns[i]->query)
2518 s += waiting_tcp_get_mem(outnet->tcp_conns[i]->query);
2520 for(w=outnet->tcp_wait_first; w; w = w->next_waiting)
2521 s += waiting_tcp_get_mem(w);
2522 s += sizeof(*outnet->pending);
2523 s += (sizeof(struct pending) + comm_timer_get_mem(NULL)) *
2524 outnet->pending->count;
2525 s += sizeof(*outnet->serviced);
2526 s += outnet->svcd_overhead;
2527 RBTREE_FOR(sq, struct serviced_query*, outnet->serviced) {
2528 s += sizeof(*sq) + sq->qbuflen;
2529 for(sb = sq->cblist; sb; sb = sb->next)
2536 serviced_get_mem(struct serviced_query* sq)
2538 struct service_callback* sb;
2540 s = sizeof(*sq) + sq->qbuflen;
2541 for(sb = sq->cblist; sb; sb = sb->next)
2543 if(sq->status == serviced_query_UDP_EDNS ||
2544 sq->status == serviced_query_UDP ||
2545 sq->status == serviced_query_UDP_EDNS_FRAG ||
2546 sq->status == serviced_query_UDP_EDNS_fallback) {
2547 s += sizeof(struct pending);
2548 s += comm_timer_get_mem(NULL);
2550 /* does not have size of the pkt pointer */
2551 /* always has a timer except on malloc failures */
2553 /* these sizes are part of the main outside network mem */
2555 s += sizeof(struct waiting_tcp);
2556 s += comm_timer_get_mem(NULL);