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 "util/data/msgparse.h"
52 #include "util/data/msgreply.h"
53 #include "util/data/msgencode.h"
54 #include "util/data/dname.h"
55 #include "util/netevent.h"
57 #include "util/net_help.h"
58 #include "util/random.h"
59 #include "util/fptr_wlist.h"
60 #include "sldns/sbuffer.h"
61 #include "dnstap/dnstap.h"
62 #ifdef HAVE_OPENSSL_SSL_H
63 #include <openssl/ssl.h>
71 /** number of times to retry making a random ID that is unique. */
72 #define MAX_ID_RETRY 1000
73 /** number of times to retry finding interface, port that can be opened. */
74 #define MAX_PORT_RETRY 10000
75 /** number of retries on outgoing UDP queries */
76 #define OUTBOUND_UDP_RETRY 1
78 /** initiate TCP transaction for serviced query */
79 static void serviced_tcp_initiate(struct serviced_query* sq, sldns_buffer* buff);
80 /** with a fd available, randomize and send UDP */
81 static int randomize_and_send_udp(struct pending* pend, sldns_buffer* packet,
84 /** remove waiting tcp from the outnet waiting list */
85 static void waiting_list_remove(struct outside_network* outnet,
86 struct waiting_tcp* w);
89 pending_cmp(const void* key1, const void* key2)
91 struct pending *p1 = (struct pending*)key1;
92 struct pending *p2 = (struct pending*)key2;
97 log_assert(p1->id == p2->id);
98 return sockaddr_cmp(&p1->addr, p1->addrlen, &p2->addr, p2->addrlen);
102 serviced_cmp(const void* key1, const void* key2)
104 struct serviced_query* q1 = (struct serviced_query*)key1;
105 struct serviced_query* q2 = (struct serviced_query*)key2;
107 if(q1->qbuflen < q2->qbuflen)
109 if(q1->qbuflen > q2->qbuflen)
111 log_assert(q1->qbuflen == q2->qbuflen);
112 log_assert(q1->qbuflen >= 15 /* 10 header, root, type, class */);
113 /* alternate casing of qname is still the same query */
114 if((r = memcmp(q1->qbuf, q2->qbuf, 10)) != 0)
116 if((r = memcmp(q1->qbuf+q1->qbuflen-4, q2->qbuf+q2->qbuflen-4, 4)) != 0)
118 if(q1->dnssec != q2->dnssec) {
119 if(q1->dnssec < q2->dnssec)
123 if((r = query_dname_compare(q1->qbuf+10, q2->qbuf+10)) != 0)
125 if((r = edns_opt_list_compare(q1->opt_list, q2->opt_list)) != 0)
127 return sockaddr_cmp(&q1->addr, q1->addrlen, &q2->addr, q2->addrlen);
130 /** delete waiting_tcp entry. Does not unlink from waiting list.
131 * @param w: to delete.
134 waiting_tcp_delete(struct waiting_tcp* w)
138 comm_timer_delete(w->timer);
143 * Pick random outgoing-interface of that family, and bind it.
144 * port set to 0 so OS picks a port number for us.
145 * if it is the ANY address, do not bind.
146 * @param w: tcp structure with destination address.
147 * @param s: socket fd.
148 * @return false on error, socket closed.
151 pick_outgoing_tcp(struct waiting_tcp* w, int s)
153 struct port_if* pi = NULL;
156 if(addr_is_ip6(&w->addr, w->addrlen))
157 num = w->outnet->num_ip6;
160 num = w->outnet->num_ip4;
162 log_err("no TCP outgoing interfaces of family");
163 log_addr(VERB_OPS, "for addr", &w->addr, w->addrlen);
172 if(addr_is_ip6(&w->addr, w->addrlen))
173 pi = &w->outnet->ip6_ifs[ub_random_max(w->outnet->rnd, num)];
176 pi = &w->outnet->ip4_ifs[ub_random_max(w->outnet->rnd, num)];
178 if(addr_is_any(&pi->addr, pi->addrlen)) {
179 /* binding to the ANY interface is for listening sockets */
183 if(addr_is_ip6(&pi->addr, pi->addrlen))
184 ((struct sockaddr_in6*)&pi->addr)->sin6_port = 0;
185 else ((struct sockaddr_in*)&pi->addr)->sin_port = 0;
186 if(bind(s, (struct sockaddr*)&pi->addr, pi->addrlen) != 0) {
188 log_err("outgoing tcp: bind: %s", strerror(errno));
191 log_err("outgoing tcp: bind: %s",
192 wsa_strerror(WSAGetLastError()));
197 log_addr(VERB_ALGO, "tcp bound to src", &pi->addr, pi->addrlen);
201 /** get TCP file descriptor for address, returns -1 on failure,
202 * tcp_mss is 0 or maxseg size to set for TCP packets. */
204 outnet_get_tcp_fd(struct sockaddr_storage* addr, socklen_t addrlen, int tcp_mss)
211 if(addr_is_ip6(addr, addrlen))
212 s = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
215 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
218 log_err_addr("outgoing tcp: socket", strerror(errno),
221 log_err_addr("outgoing tcp: socket",
222 wsa_strerror(WSAGetLastError()), addr, addrlen);
228 if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&on,
229 (socklen_t)sizeof(on)) < 0) {
230 verbose(VERB_ALGO, "outgoing tcp:"
231 " setsockopt(.. SO_REUSEADDR ..) failed");
236 #if defined(IPPROTO_TCP) && defined(TCP_MAXSEG)
237 if(setsockopt(s, IPPROTO_TCP, TCP_MAXSEG,
238 (void*)&tcp_mss, (socklen_t)sizeof(tcp_mss)) < 0) {
239 verbose(VERB_ALGO, "outgoing tcp:"
240 " setsockopt(.. TCP_MAXSEG ..) failed");
243 verbose(VERB_ALGO, "outgoing tcp:"
244 " setsockopt(TCP_MAXSEG) unsupported");
245 #endif /* defined(IPPROTO_TCP) && defined(TCP_MAXSEG) */
251 /** connect tcp connection to addr, 0 on failure */
253 outnet_tcp_connect(int s, struct sockaddr_storage* addr, socklen_t addrlen)
255 if(connect(s, (struct sockaddr*)addr, addrlen) == -1) {
258 if(errno != EINPROGRESS) {
260 if(tcp_connect_errno_needs_log(
261 (struct sockaddr*)addr, addrlen))
262 log_err_addr("outgoing tcp: connect",
263 strerror(errno), addr, addrlen);
269 #else /* USE_WINSOCK */
270 if(WSAGetLastError() != WSAEINPROGRESS &&
271 WSAGetLastError() != WSAEWOULDBLOCK) {
280 /** use next free buffer to service a tcp query */
282 outnet_tcp_take_into_use(struct waiting_tcp* w, uint8_t* pkt, size_t pkt_len)
284 struct pending_tcp* pend = w->outnet->tcp_free;
288 log_assert(w->addrlen > 0);
290 s = outnet_get_tcp_fd(&w->addr, w->addrlen, w->outnet->tcp_mss);
292 if(!pick_outgoing_tcp(w, s))
296 #ifdef USE_OSX_MSG_FASTOPEN
297 /* API for fast open is different here. We use a connectx() function and
298 then writes can happen as normal even using SSL.*/
299 /* connectx requires that the len be set in the sockaddr struct*/
300 struct sockaddr_in *addr_in = (struct sockaddr_in *)&w->addr;
301 addr_in->sin_len = w->addrlen;
302 sa_endpoints_t endpoints;
303 endpoints.sae_srcif = 0;
304 endpoints.sae_srcaddr = NULL;
305 endpoints.sae_srcaddrlen = 0;
306 endpoints.sae_dstaddr = (struct sockaddr *)&w->addr;
307 endpoints.sae_dstaddrlen = w->addrlen;
308 if (connectx(s, &endpoints, SAE_ASSOCID_ANY,
309 CONNECT_DATA_IDEMPOTENT | CONNECT_RESUME_ON_READ_WRITE,
310 NULL, 0, NULL, NULL) == -1) {
311 /* if fails, failover to connect for OSX 10.10 */
313 if(errno != EINPROGRESS) {
317 if(connect(s, (struct sockaddr*)&w->addr, w->addrlen) == -1) {
318 #else /* USE_OSX_MSG_FASTOPEN*/
319 #ifdef USE_MSG_FASTOPEN
320 pend->c->tcp_do_fastopen = 1;
321 /* Only do TFO for TCP in which case no connect() is required here.
322 Don't combine client TFO with SSL, since OpenSSL can't
323 currently support doing a handshake on fd that already isn't connected*/
324 if (w->outnet->sslctx && w->ssl_upstream) {
325 if(connect(s, (struct sockaddr*)&w->addr, w->addrlen) == -1) {
326 #else /* USE_MSG_FASTOPEN*/
327 if(connect(s, (struct sockaddr*)&w->addr, w->addrlen) == -1) {
328 #endif /* USE_MSG_FASTOPEN*/
329 #endif /* USE_OSX_MSG_FASTOPEN*/
332 if(errno != EINPROGRESS) {
336 if(tcp_connect_errno_needs_log(
337 (struct sockaddr*)&w->addr, w->addrlen))
338 log_err_addr("outgoing tcp: connect",
339 strerror(errno), &w->addr, w->addrlen);
341 #else /* USE_WINSOCK */
342 if(WSAGetLastError() != WSAEINPROGRESS &&
343 WSAGetLastError() != WSAEWOULDBLOCK) {
349 #ifdef USE_MSG_FASTOPEN
351 #endif /* USE_MSG_FASTOPEN */
352 #ifdef USE_OSX_MSG_FASTOPEN
355 #endif /* USE_OSX_MSG_FASTOPEN */
356 if(w->outnet->sslctx && w->ssl_upstream) {
357 pend->c->ssl = outgoing_ssl_fd(w->outnet->sslctx, s);
360 comm_point_close(pend->c);
364 comm_point_tcp_win_bio_cb(pend->c, pend->c->ssl);
366 pend->c->ssl_shake_state = comm_ssl_shake_write;
367 #ifdef HAVE_SSL_SET1_HOST
368 if(w->tls_auth_name) {
369 SSL_set_verify(pend->c->ssl, SSL_VERIFY_PEER, NULL);
370 /* setting the hostname makes openssl verify the
371 * host name in the x509 certificate in the
373 if(!SSL_set1_host(pend->c->ssl, w->tls_auth_name)) {
374 log_err("SSL_set1_host failed");
376 comm_point_close(pend->c);
380 #endif /* HAVE_SSL_SET1_HOST */
383 w->next_waiting = (void*)pend;
384 pend->id = LDNS_ID_WIRE(pkt);
385 w->outnet->num_tcp_outgoing++;
386 w->outnet->tcp_free = pend->next_free;
387 pend->next_free = NULL;
389 pend->c->repinfo.addrlen = w->addrlen;
390 memcpy(&pend->c->repinfo.addr, &w->addr, w->addrlen);
391 sldns_buffer_clear(pend->c->buffer);
392 sldns_buffer_write(pend->c->buffer, pkt, pkt_len);
393 sldns_buffer_flip(pend->c->buffer);
394 pend->c->tcp_is_reading = 0;
395 pend->c->tcp_byte_count = 0;
396 comm_point_start_listening(pend->c, s, -1);
400 /** see if buffers can be used to service TCP queries */
402 use_free_buffer(struct outside_network* outnet)
404 struct waiting_tcp* w;
405 while(outnet->tcp_free && outnet->tcp_wait_first
406 && !outnet->want_to_quit) {
407 w = outnet->tcp_wait_first;
408 outnet->tcp_wait_first = w->next_waiting;
409 if(outnet->tcp_wait_last == w)
410 outnet->tcp_wait_last = NULL;
411 if(!outnet_tcp_take_into_use(w, w->pkt, w->pkt_len)) {
412 comm_point_callback_type* cb = w->cb;
413 void* cb_arg = w->cb_arg;
414 waiting_tcp_delete(w);
415 fptr_ok(fptr_whitelist_pending_tcp(cb));
416 (void)(*cb)(NULL, cb_arg, NETEVENT_CLOSED, NULL);
421 /** decommission a tcp buffer, closes commpoint and frees waiting_tcp entry */
423 decommission_pending_tcp(struct outside_network* outnet,
424 struct pending_tcp* pend)
428 SSL_shutdown(pend->c->ssl);
429 SSL_free(pend->c->ssl);
433 comm_point_close(pend->c);
434 pend->next_free = outnet->tcp_free;
435 outnet->tcp_free = pend;
436 waiting_tcp_delete(pend->query);
438 use_free_buffer(outnet);
442 outnet_tcp_cb(struct comm_point* c, void* arg, int error,
443 struct comm_reply *reply_info)
445 struct pending_tcp* pend = (struct pending_tcp*)arg;
446 struct outside_network* outnet = pend->query->outnet;
447 verbose(VERB_ALGO, "outnettcp cb");
448 if(error != NETEVENT_NOERROR) {
449 verbose(VERB_QUERY, "outnettcp got tcp error %d", error);
450 /* pass error below and exit */
453 if(sldns_buffer_limit(c->buffer) < sizeof(uint16_t) ||
454 LDNS_ID_WIRE(sldns_buffer_begin(c->buffer))!=pend->id) {
456 "outnettcp: bad ID in reply, from:",
457 &pend->query->addr, pend->query->addrlen);
458 error = NETEVENT_CLOSED;
461 fptr_ok(fptr_whitelist_pending_tcp(pend->query->cb));
462 (void)(*pend->query->cb)(c, pend->query->cb_arg, error, reply_info);
463 decommission_pending_tcp(outnet, pend);
467 /** lower use count on pc, see if it can be closed */
469 portcomm_loweruse(struct outside_network* outnet, struct port_comm* pc)
472 pc->num_outstanding--;
473 if(pc->num_outstanding > 0) {
476 /* close it and replace in unused list */
477 verbose(VERB_ALGO, "close of port %d", pc->number);
478 comm_point_close(pc->cp);
480 log_assert(pif->inuse > 0);
481 pif->avail_ports[pif->avail_total - pif->inuse] = pc->number;
483 pif->out[pc->index] = pif->out[pif->inuse];
484 pif->out[pc->index]->index = pc->index;
485 pc->next = outnet->unused_fds;
486 outnet->unused_fds = pc;
489 /** try to send waiting UDP queries */
491 outnet_send_wait_udp(struct outside_network* outnet)
493 struct pending* pend;
494 /* process waiting queries */
495 while(outnet->udp_wait_first && outnet->unused_fds
496 && !outnet->want_to_quit) {
497 pend = outnet->udp_wait_first;
498 outnet->udp_wait_first = pend->next_waiting;
499 if(!pend->next_waiting) outnet->udp_wait_last = NULL;
500 sldns_buffer_clear(outnet->udp_buff);
501 sldns_buffer_write(outnet->udp_buff, pend->pkt, pend->pkt_len);
502 sldns_buffer_flip(outnet->udp_buff);
503 free(pend->pkt); /* freeing now makes get_mem correct */
506 if(!randomize_and_send_udp(pend, outnet->udp_buff,
508 /* callback error on pending */
510 fptr_ok(fptr_whitelist_pending_udp(pend->cb));
511 (void)(*pend->cb)(outnet->unused_fds->cp, pend->cb_arg,
512 NETEVENT_CLOSED, NULL);
514 pending_delete(outnet, pend);
520 outnet_udp_cb(struct comm_point* c, void* arg, int error,
521 struct comm_reply *reply_info)
523 struct outside_network* outnet = (struct outside_network*)arg;
526 verbose(VERB_ALGO, "answer cb");
528 if(error != NETEVENT_NOERROR) {
529 verbose(VERB_QUERY, "outnetudp got udp error %d", error);
532 if(sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE) {
533 verbose(VERB_QUERY, "outnetudp udp too short");
536 log_assert(reply_info);
538 /* setup lookup key */
539 key.id = (unsigned)LDNS_ID_WIRE(sldns_buffer_begin(c->buffer));
540 memcpy(&key.addr, &reply_info->addr, reply_info->addrlen);
541 key.addrlen = reply_info->addrlen;
542 verbose(VERB_ALGO, "Incoming reply id = %4.4x", key.id);
543 log_addr(VERB_ALGO, "Incoming reply addr =",
544 &reply_info->addr, reply_info->addrlen);
546 /* find it, see if this thing is a valid query response */
547 verbose(VERB_ALGO, "lookup size is %d entries", (int)outnet->pending->count);
548 p = (struct pending*)rbtree_search(outnet->pending, &key);
550 verbose(VERB_QUERY, "received unwanted or unsolicited udp reply dropped.");
551 log_buf(VERB_ALGO, "dropped message", c->buffer);
552 outnet->unwanted_replies++;
553 if(outnet->unwanted_threshold && ++outnet->unwanted_total
554 >= outnet->unwanted_threshold) {
555 log_warn("unwanted reply total reached threshold (%u)"
556 " you may be under attack."
557 " defensive action: clearing the cache",
558 (unsigned)outnet->unwanted_threshold);
559 fptr_ok(fptr_whitelist_alloc_cleanup(
560 outnet->unwanted_action));
561 (*outnet->unwanted_action)(outnet->unwanted_param);
562 outnet->unwanted_total = 0;
567 verbose(VERB_ALGO, "received udp reply.");
568 log_buf(VERB_ALGO, "udp message", c->buffer);
570 verbose(VERB_QUERY, "received reply id,addr on wrong port. "
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;
586 comm_timer_disable(p->timer);
587 verbose(VERB_ALGO, "outnet handle udp reply");
588 /* delete from tree first in case callback creates a retry */
589 (void)rbtree_delete(outnet->pending, p->node.key);
591 fptr_ok(fptr_whitelist_pending_udp(p->cb));
592 (void)(*p->cb)(p->pc->cp, p->cb_arg, NETEVENT_NOERROR, reply_info);
594 portcomm_loweruse(outnet, p->pc);
595 pending_delete(NULL, p);
596 outnet_send_wait_udp(outnet);
600 /** calculate number of ip4 and ip6 interfaces*/
602 calc_num46(char** ifs, int num_ifs, int do_ip4, int do_ip6,
603 int* num_ip4, int* num_ip6)
615 for(i=0; i<num_ifs; i++)
617 if(str_is_ip6(ifs[i])) {
629 pending_udp_timer_delay_cb(void* arg)
631 struct pending* p = (struct pending*)arg;
632 struct outside_network* outnet = p->outnet;
633 verbose(VERB_ALGO, "timeout udp with delay");
634 portcomm_loweruse(outnet, p->pc);
635 pending_delete(outnet, p);
636 outnet_send_wait_udp(outnet);
640 pending_udp_timer_cb(void *arg)
642 struct pending* p = (struct pending*)arg;
643 struct outside_network* outnet = p->outnet;
645 verbose(VERB_ALGO, "timeout udp");
647 fptr_ok(fptr_whitelist_pending_udp(p->cb));
648 (void)(*p->cb)(p->pc->cp, p->cb_arg, NETEVENT_TIMEOUT, NULL);
650 /* if delayclose, keep port open for a longer time.
651 * But if the udpwaitlist exists, then we are struggling to
652 * keep up with demand for sockets, so do not wait, but service
653 * the customer (customer service more important than portICMPs) */
654 if(outnet->delayclose && !outnet->udp_wait_first) {
656 p->timer->callback = &pending_udp_timer_delay_cb;
657 comm_timer_set(p->timer, &outnet->delay_tv);
660 portcomm_loweruse(outnet, p->pc);
661 pending_delete(outnet, p);
662 outnet_send_wait_udp(outnet);
665 /** create pending_tcp buffers */
667 create_pending_tcp(struct outside_network* outnet, size_t bufsize)
670 if(outnet->num_tcp == 0)
671 return 1; /* no tcp needed, nothing to do */
672 if(!(outnet->tcp_conns = (struct pending_tcp **)calloc(
673 outnet->num_tcp, sizeof(struct pending_tcp*))))
675 for(i=0; i<outnet->num_tcp; i++) {
676 if(!(outnet->tcp_conns[i] = (struct pending_tcp*)calloc(1,
677 sizeof(struct pending_tcp))))
679 outnet->tcp_conns[i]->next_free = outnet->tcp_free;
680 outnet->tcp_free = outnet->tcp_conns[i];
681 outnet->tcp_conns[i]->c = comm_point_create_tcp_out(
682 outnet->base, bufsize, outnet_tcp_cb,
683 outnet->tcp_conns[i]);
684 if(!outnet->tcp_conns[i]->c)
690 /** setup an outgoing interface, ready address */
691 static int setup_if(struct port_if* pif, const char* addrstr,
692 int* avail, int numavail, size_t numfd)
694 pif->avail_total = numavail;
695 pif->avail_ports = (int*)memdup(avail, (size_t)numavail*sizeof(int));
696 if(!pif->avail_ports)
698 if(!ipstrtoaddr(addrstr, UNBOUND_DNS_PORT, &pif->addr, &pif->addrlen) &&
699 !netblockstrtoaddr(addrstr, UNBOUND_DNS_PORT,
700 &pif->addr, &pif->addrlen, &pif->pfxlen))
702 pif->maxout = (int)numfd;
704 pif->out = (struct port_comm**)calloc(numfd,
705 sizeof(struct port_comm*));
711 struct outside_network*
712 outside_network_create(struct comm_base *base, size_t bufsize,
713 size_t num_ports, char** ifs, int num_ifs, int do_ip4,
714 int do_ip6, size_t num_tcp, struct infra_cache* infra,
715 struct ub_randstate* rnd, int use_caps_for_id, int* availports,
716 int numavailports, size_t unwanted_threshold, int tcp_mss,
717 void (*unwanted_action)(void*), void* unwanted_param, int do_udp,
718 void* sslctx, int delayclose, struct dt_env* dtenv)
720 struct outside_network* outnet = (struct outside_network*)
721 calloc(1, sizeof(struct outside_network));
724 log_err("malloc failed");
727 comm_base_timept(base, &outnet->now_secs, &outnet->now_tv);
729 outnet->num_tcp = num_tcp;
730 outnet->num_tcp_outgoing = 0;
731 outnet->infra = infra;
733 outnet->sslctx = sslctx;
735 outnet->dtenv = dtenv;
739 outnet->svcd_overhead = 0;
740 outnet->want_to_quit = 0;
741 outnet->unwanted_threshold = unwanted_threshold;
742 outnet->unwanted_action = unwanted_action;
743 outnet->unwanted_param = unwanted_param;
744 outnet->use_caps_for_id = use_caps_for_id;
745 outnet->do_udp = do_udp;
746 outnet->tcp_mss = tcp_mss;
749 outnet->delayclose = 1;
750 outnet->delay_tv.tv_sec = delayclose/1000;
751 outnet->delay_tv.tv_usec = (delayclose%1000)*1000;
754 if(numavailports == 0) {
755 log_err("no outgoing ports available");
756 outside_network_delete(outnet);
762 calc_num46(ifs, num_ifs, do_ip4, do_ip6,
763 &outnet->num_ip4, &outnet->num_ip6);
764 if(outnet->num_ip4 != 0) {
765 if(!(outnet->ip4_ifs = (struct port_if*)calloc(
766 (size_t)outnet->num_ip4, sizeof(struct port_if)))) {
767 log_err("malloc failed");
768 outside_network_delete(outnet);
772 if(outnet->num_ip6 != 0) {
773 if(!(outnet->ip6_ifs = (struct port_if*)calloc(
774 (size_t)outnet->num_ip6, sizeof(struct port_if)))) {
775 log_err("malloc failed");
776 outside_network_delete(outnet);
780 if( !(outnet->udp_buff = sldns_buffer_new(bufsize)) ||
781 !(outnet->pending = rbtree_create(pending_cmp)) ||
782 !(outnet->serviced = rbtree_create(serviced_cmp)) ||
783 !create_pending_tcp(outnet, bufsize)) {
784 log_err("malloc failed");
785 outside_network_delete(outnet);
789 /* allocate commpoints */
790 for(k=0; k<num_ports; k++) {
791 struct port_comm* pc;
792 pc = (struct port_comm*)calloc(1, sizeof(*pc));
794 log_err("malloc failed");
795 outside_network_delete(outnet);
798 pc->cp = comm_point_create_udp(outnet->base, -1,
799 outnet->udp_buff, outnet_udp_cb, outnet);
801 log_err("malloc failed");
803 outside_network_delete(outnet);
806 pc->next = outnet->unused_fds;
807 outnet->unused_fds = pc;
810 /* allocate interfaces */
812 if(do_ip4 && !setup_if(&outnet->ip4_ifs[0], "0.0.0.0",
813 availports, numavailports, num_ports)) {
814 log_err("malloc failed");
815 outside_network_delete(outnet);
818 if(do_ip6 && !setup_if(&outnet->ip6_ifs[0], "::",
819 availports, numavailports, num_ports)) {
820 log_err("malloc failed");
821 outside_network_delete(outnet);
825 size_t done_4 = 0, done_6 = 0;
827 for(i=0; i<num_ifs; i++) {
828 if(str_is_ip6(ifs[i]) && do_ip6) {
829 if(!setup_if(&outnet->ip6_ifs[done_6], ifs[i],
830 availports, numavailports, num_ports)){
831 log_err("malloc failed");
832 outside_network_delete(outnet);
837 if(!str_is_ip6(ifs[i]) && do_ip4) {
838 if(!setup_if(&outnet->ip4_ifs[done_4], ifs[i],
839 availports, numavailports, num_ports)){
840 log_err("malloc failed");
841 outside_network_delete(outnet);
851 /** helper pending delete */
853 pending_node_del(rbnode_type* node, void* arg)
855 struct pending* pend = (struct pending*)node;
856 struct outside_network* outnet = (struct outside_network*)arg;
857 pending_delete(outnet, pend);
860 /** helper serviced delete */
862 serviced_node_del(rbnode_type* node, void* ATTR_UNUSED(arg))
864 struct serviced_query* sq = (struct serviced_query*)node;
865 struct service_callback* p = sq->cblist, *np;
868 free(sq->tls_auth_name);
869 edns_opt_list_free(sq->opt_list);
879 outside_network_quit_prepare(struct outside_network* outnet)
883 /* prevent queued items from being sent */
884 outnet->want_to_quit = 1;
888 outside_network_delete(struct outside_network* outnet)
892 outnet->want_to_quit = 1;
893 /* check every element, since we can be called on malloc error */
894 if(outnet->pending) {
895 /* free pending elements, but do no unlink from tree. */
896 traverse_postorder(outnet->pending, pending_node_del, NULL);
897 free(outnet->pending);
899 if(outnet->serviced) {
900 traverse_postorder(outnet->serviced, serviced_node_del, NULL);
901 free(outnet->serviced);
904 sldns_buffer_free(outnet->udp_buff);
905 if(outnet->unused_fds) {
906 struct port_comm* p = outnet->unused_fds, *np;
909 comm_point_delete(p->cp);
913 outnet->unused_fds = NULL;
915 if(outnet->ip4_ifs) {
917 for(i=0; i<outnet->num_ip4; i++) {
918 for(k=0; k<outnet->ip4_ifs[i].inuse; k++) {
919 struct port_comm* pc = outnet->ip4_ifs[i].
921 comm_point_delete(pc->cp);
924 free(outnet->ip4_ifs[i].avail_ports);
925 free(outnet->ip4_ifs[i].out);
927 free(outnet->ip4_ifs);
929 if(outnet->ip6_ifs) {
931 for(i=0; i<outnet->num_ip6; i++) {
932 for(k=0; k<outnet->ip6_ifs[i].inuse; k++) {
933 struct port_comm* pc = outnet->ip6_ifs[i].
935 comm_point_delete(pc->cp);
938 free(outnet->ip6_ifs[i].avail_ports);
939 free(outnet->ip6_ifs[i].out);
941 free(outnet->ip6_ifs);
943 if(outnet->tcp_conns) {
945 for(i=0; i<outnet->num_tcp; i++)
946 if(outnet->tcp_conns[i]) {
947 comm_point_delete(outnet->tcp_conns[i]->c);
948 waiting_tcp_delete(outnet->tcp_conns[i]->query);
949 free(outnet->tcp_conns[i]);
951 free(outnet->tcp_conns);
953 if(outnet->tcp_wait_first) {
954 struct waiting_tcp* p = outnet->tcp_wait_first, *np;
956 np = p->next_waiting;
957 waiting_tcp_delete(p);
961 if(outnet->udp_wait_first) {
962 struct pending* p = outnet->udp_wait_first, *np;
964 np = p->next_waiting;
965 pending_delete(NULL, p);
973 pending_delete(struct outside_network* outnet, struct pending* p)
977 if(outnet && outnet->udp_wait_first &&
978 (p->next_waiting || p == outnet->udp_wait_last) ) {
979 /* delete from waiting list, if it is in the waiting list */
980 struct pending* prev = NULL, *x = outnet->udp_wait_first;
988 prev->next_waiting = p->next_waiting;
989 else outnet->udp_wait_first = p->next_waiting;
990 if(outnet->udp_wait_last == p)
991 outnet->udp_wait_last = prev;
995 (void)rbtree_delete(outnet->pending, p->node.key);
998 comm_timer_delete(p->timer);
1004 sai6_putrandom(struct sockaddr_in6 *sa, int pfxlen, struct ub_randstate *rnd)
1007 if(!(pfxlen > 0 && pfxlen < 128))
1009 for(i = 0; i < (128 - pfxlen) / 8; i++) {
1010 sa->sin6_addr.s6_addr[15-i] = (uint8_t)ub_random_max(rnd, 256);
1014 sa->sin6_addr.s6_addr[15-i] |=
1015 ((0xFF >> last) & ub_random_max(rnd, 256));
1020 * Try to open a UDP socket for outgoing communication.
1021 * Sets sockets options as needed.
1022 * @param addr: socket address.
1023 * @param addrlen: length of address.
1024 * @param pfxlen: length of network prefix (for address randomisation).
1025 * @param port: port override for addr.
1026 * @param inuse: if -1 is returned, this bool means the port was in use.
1027 * @param rnd: random state (for address randomisation).
1031 udp_sockport(struct sockaddr_storage* addr, socklen_t addrlen, int pfxlen,
1032 int port, int* inuse, struct ub_randstate* rnd)
1035 if(addr_is_ip6(addr, addrlen)) {
1037 struct sockaddr_in6 sa = *(struct sockaddr_in6*)addr;
1038 sa.sin6_port = (in_port_t)htons((uint16_t)port);
1041 sai6_putrandom(&sa, pfxlen, rnd);
1043 fd = create_udp_sock(AF_INET6, SOCK_DGRAM,
1044 (struct sockaddr*)&sa, addrlen, 1, inuse, &noproto,
1045 0, 0, 0, NULL, 0, freebind, 0);
1047 struct sockaddr_in* sa = (struct sockaddr_in*)addr;
1048 sa->sin_port = (in_port_t)htons((uint16_t)port);
1049 fd = create_udp_sock(AF_INET, SOCK_DGRAM,
1050 (struct sockaddr*)addr, addrlen, 1, inuse, &noproto,
1051 0, 0, 0, NULL, 0, 0, 0);
1056 /** Select random ID */
1058 select_id(struct outside_network* outnet, struct pending* pend,
1059 sldns_buffer* packet)
1062 pend->id = ((unsigned)ub_random(outnet->rnd)>>8) & 0xffff;
1063 LDNS_ID_SET(sldns_buffer_begin(packet), pend->id);
1065 /* insert in tree */
1066 pend->node.key = pend;
1067 while(!rbtree_insert(outnet->pending, &pend->node)) {
1068 /* change ID to avoid collision */
1069 pend->id = ((unsigned)ub_random(outnet->rnd)>>8) & 0xffff;
1070 LDNS_ID_SET(sldns_buffer_begin(packet), pend->id);
1072 if(id_tries == MAX_ID_RETRY) {
1073 pend->id=99999; /* non existant ID */
1074 log_err("failed to generate unique ID, drop msg");
1078 verbose(VERB_ALGO, "inserted new pending reply id=%4.4x", pend->id);
1082 /** Select random interface and port */
1084 select_ifport(struct outside_network* outnet, struct pending* pend,
1085 int num_if, struct port_if* ifs)
1087 int my_if, my_port, fd, portno, inuse, tries=0;
1088 struct port_if* pif;
1089 /* randomly select interface and port */
1091 verbose(VERB_QUERY, "Need to send query but have no "
1092 "outgoing interfaces of that family");
1095 log_assert(outnet->unused_fds);
1098 my_if = ub_random_max(outnet->rnd, num_if);
1100 my_port = ub_random_max(outnet->rnd, pif->avail_total);
1101 if(my_port < pif->inuse) {
1102 /* port already open */
1103 pend->pc = pif->out[my_port];
1104 verbose(VERB_ALGO, "using UDP if=%d port=%d",
1105 my_if, pend->pc->number);
1108 /* try to open new port, if fails, loop to try again */
1109 log_assert(pif->inuse < pif->maxout);
1110 portno = pif->avail_ports[my_port - pif->inuse];
1111 fd = udp_sockport(&pif->addr, pif->addrlen, pif->pfxlen,
1112 portno, &inuse, outnet->rnd);
1113 if(fd == -1 && !inuse) {
1114 /* nonrecoverable error making socket */
1118 verbose(VERB_ALGO, "opened UDP if=%d port=%d",
1121 pend->pc = outnet->unused_fds;
1122 outnet->unused_fds = pend->pc->next;
1124 /* setup portcomm */
1125 pend->pc->next = NULL;
1126 pend->pc->number = portno;
1127 pend->pc->pif = pif;
1128 pend->pc->index = pif->inuse;
1129 pend->pc->num_outstanding = 0;
1130 comm_point_start_listening(pend->pc->cp, fd, -1);
1132 /* grab port in interface */
1133 pif->out[pif->inuse] = pend->pc;
1134 pif->avail_ports[my_port - pif->inuse] =
1135 pif->avail_ports[pif->avail_total-pif->inuse-1];
1139 /* failed, already in use */
1140 verbose(VERB_QUERY, "port %d in use, trying another", portno);
1142 if(tries == MAX_PORT_RETRY) {
1143 log_err("failed to find an open port, drop msg");
1147 log_assert(pend->pc);
1148 pend->pc->num_outstanding++;
1154 randomize_and_send_udp(struct pending* pend, sldns_buffer* packet, int timeout)
1157 struct outside_network* outnet = pend->sq->outnet;
1160 if(!select_id(outnet, pend, packet)) {
1164 /* select src_if, port */
1165 if(addr_is_ip6(&pend->addr, pend->addrlen)) {
1166 if(!select_ifport(outnet, pend,
1167 outnet->num_ip6, outnet->ip6_ifs))
1170 if(!select_ifport(outnet, pend,
1171 outnet->num_ip4, outnet->ip4_ifs))
1174 log_assert(pend->pc && pend->pc->cp);
1176 /* send it over the commlink */
1177 if(!comm_point_send_udp_msg(pend->pc->cp, packet,
1178 (struct sockaddr*)&pend->addr, pend->addrlen)) {
1179 portcomm_loweruse(outnet, pend->pc);
1183 /* system calls to set timeout after sending UDP to make roundtrip
1186 tv.tv_sec = timeout/1000;
1187 tv.tv_usec = (timeout%1000)*1000;
1189 comm_timer_set(pend->timer, &tv);
1193 (outnet->dtenv->log_resolver_query_messages ||
1194 outnet->dtenv->log_forwarder_query_messages))
1195 dt_msg_send_outside_query(outnet->dtenv, &pend->addr, comm_udp,
1196 pend->sq->zone, pend->sq->zonelen, packet);
1202 pending_udp_query(struct serviced_query* sq, struct sldns_buffer* packet,
1203 int timeout, comm_point_callback_type* cb, void* cb_arg)
1205 struct pending* pend = (struct pending*)calloc(1, sizeof(*pend));
1206 if(!pend) return NULL;
1207 pend->outnet = sq->outnet;
1209 pend->addrlen = sq->addrlen;
1210 memmove(&pend->addr, &sq->addr, sq->addrlen);
1212 pend->cb_arg = cb_arg;
1213 pend->node.key = pend;
1214 pend->timer = comm_timer_create(sq->outnet->base, pending_udp_timer_cb,
1221 if(sq->outnet->unused_fds == NULL) {
1222 /* no unused fd, cannot create a new port (randomly) */
1223 verbose(VERB_ALGO, "no fds available, udp query waiting");
1224 pend->timeout = timeout;
1225 pend->pkt_len = sldns_buffer_limit(packet);
1226 pend->pkt = (uint8_t*)memdup(sldns_buffer_begin(packet),
1229 comm_timer_delete(pend->timer);
1233 /* put at end of waiting list */
1234 if(sq->outnet->udp_wait_last)
1235 sq->outnet->udp_wait_last->next_waiting = pend;
1237 sq->outnet->udp_wait_first = pend;
1238 sq->outnet->udp_wait_last = pend;
1241 if(!randomize_and_send_udp(pend, packet, timeout)) {
1242 pending_delete(sq->outnet, pend);
1249 outnet_tcptimer(void* arg)
1251 struct waiting_tcp* w = (struct waiting_tcp*)arg;
1252 struct outside_network* outnet = w->outnet;
1253 comm_point_callback_type* cb;
1256 /* it is on the waiting list */
1257 waiting_list_remove(outnet, w);
1260 struct pending_tcp* pend=(struct pending_tcp*)w->next_waiting;
1261 comm_point_close(pend->c);
1263 pend->next_free = outnet->tcp_free;
1264 outnet->tcp_free = pend;
1268 waiting_tcp_delete(w);
1269 fptr_ok(fptr_whitelist_pending_tcp(cb));
1270 (void)(*cb)(NULL, cb_arg, NETEVENT_TIMEOUT, NULL);
1271 use_free_buffer(outnet);
1275 pending_tcp_query(struct serviced_query* sq, sldns_buffer* packet,
1276 int timeout, comm_point_callback_type* callback, void* callback_arg)
1278 struct pending_tcp* pend = sq->outnet->tcp_free;
1279 struct waiting_tcp* w;
1282 /* if no buffer is free allocate space to store query */
1283 w = (struct waiting_tcp*)malloc(sizeof(struct waiting_tcp)
1284 + (pend?0:sldns_buffer_limit(packet)));
1288 if(!(w->timer = comm_timer_create(sq->outnet->base, outnet_tcptimer, w))) {
1294 id = ((unsigned)ub_random(sq->outnet->rnd)>>8) & 0xffff;
1295 LDNS_ID_SET(sldns_buffer_begin(packet), id);
1296 memcpy(&w->addr, &sq->addr, sq->addrlen);
1297 w->addrlen = sq->addrlen;
1298 w->outnet = sq->outnet;
1300 w->cb_arg = callback_arg;
1301 w->ssl_upstream = sq->ssl_upstream;
1302 w->tls_auth_name = sq->tls_auth_name;
1304 tv.tv_sec = timeout;
1307 comm_timer_set(w->timer, &tv);
1309 /* we have a buffer available right now */
1310 if(!outnet_tcp_take_into_use(w, sldns_buffer_begin(packet),
1311 sldns_buffer_limit(packet))) {
1312 waiting_tcp_delete(w);
1316 if(sq->outnet->dtenv &&
1317 (sq->outnet->dtenv->log_resolver_query_messages ||
1318 sq->outnet->dtenv->log_forwarder_query_messages))
1319 dt_msg_send_outside_query(sq->outnet->dtenv, &sq->addr,
1320 comm_tcp, sq->zone, sq->zonelen, packet);
1324 w->pkt = (uint8_t*)w + sizeof(struct waiting_tcp);
1325 w->pkt_len = sldns_buffer_limit(packet);
1326 memmove(w->pkt, sldns_buffer_begin(packet), w->pkt_len);
1327 w->next_waiting = NULL;
1328 if(sq->outnet->tcp_wait_last)
1329 sq->outnet->tcp_wait_last->next_waiting = w;
1330 else sq->outnet->tcp_wait_first = w;
1331 sq->outnet->tcp_wait_last = w;
1336 /** create query for serviced queries */
1338 serviced_gen_query(sldns_buffer* buff, uint8_t* qname, size_t qnamelen,
1339 uint16_t qtype, uint16_t qclass, uint16_t flags)
1341 sldns_buffer_clear(buff);
1343 sldns_buffer_write_u16(buff, flags);
1344 sldns_buffer_write_u16(buff, 1); /* qdcount */
1345 sldns_buffer_write_u16(buff, 0); /* ancount */
1346 sldns_buffer_write_u16(buff, 0); /* nscount */
1347 sldns_buffer_write_u16(buff, 0); /* arcount */
1348 sldns_buffer_write(buff, qname, qnamelen);
1349 sldns_buffer_write_u16(buff, qtype);
1350 sldns_buffer_write_u16(buff, qclass);
1351 sldns_buffer_flip(buff);
1354 /** lookup serviced query in serviced query rbtree */
1355 static struct serviced_query*
1356 lookup_serviced(struct outside_network* outnet, sldns_buffer* buff, int dnssec,
1357 struct sockaddr_storage* addr, socklen_t addrlen,
1358 struct edns_option* opt_list)
1360 struct serviced_query key;
1361 key.node.key = &key;
1362 key.qbuf = sldns_buffer_begin(buff);
1363 key.qbuflen = sldns_buffer_limit(buff);
1364 key.dnssec = dnssec;
1365 memcpy(&key.addr, addr, addrlen);
1366 key.addrlen = addrlen;
1367 key.outnet = outnet;
1368 key.opt_list = opt_list;
1369 return (struct serviced_query*)rbtree_search(outnet->serviced, &key);
1372 /** Create new serviced entry */
1373 static struct serviced_query*
1374 serviced_create(struct outside_network* outnet, sldns_buffer* buff, int dnssec,
1375 int want_dnssec, int nocaps, int tcp_upstream, int ssl_upstream,
1376 char* tls_auth_name, struct sockaddr_storage* addr, socklen_t addrlen,
1377 uint8_t* zone, size_t zonelen, int qtype, struct edns_option* opt_list)
1379 struct serviced_query* sq = (struct serviced_query*)malloc(sizeof(*sq));
1380 #ifdef UNBOUND_DEBUG
1386 sq->qbuf = memdup(sldns_buffer_begin(buff), sldns_buffer_limit(buff));
1391 sq->qbuflen = sldns_buffer_limit(buff);
1392 sq->zone = memdup(zone, zonelen);
1398 sq->zonelen = zonelen;
1400 sq->dnssec = dnssec;
1401 sq->want_dnssec = want_dnssec;
1402 sq->nocaps = nocaps;
1403 sq->tcp_upstream = tcp_upstream;
1404 sq->ssl_upstream = ssl_upstream;
1406 sq->tls_auth_name = strdup(tls_auth_name);
1407 if(!sq->tls_auth_name) {
1414 sq->tls_auth_name = NULL;
1416 memcpy(&sq->addr, addr, addrlen);
1417 sq->addrlen = addrlen;
1418 sq->opt_list = NULL;
1420 sq->opt_list = edns_opt_copy_alloc(opt_list);
1422 free(sq->tls_auth_name);
1429 sq->outnet = outnet;
1432 sq->status = serviced_initial;
1434 sq->to_be_deleted = 0;
1435 #ifdef UNBOUND_DEBUG
1440 rbtree_insert(outnet->serviced, &sq->node);
1441 log_assert(ins != NULL); /* must not be already present */
1445 /** remove waiting tcp from the outnet waiting list */
1447 waiting_list_remove(struct outside_network* outnet, struct waiting_tcp* w)
1449 struct waiting_tcp* p = outnet->tcp_wait_first, *prev = NULL;
1454 prev->next_waiting = w->next_waiting;
1455 else outnet->tcp_wait_first = w->next_waiting;
1456 if(outnet->tcp_wait_last == w)
1457 outnet->tcp_wait_last = prev;
1461 p = p->next_waiting;
1465 /** cleanup serviced query entry */
1467 serviced_delete(struct serviced_query* sq)
1470 /* clear up the pending query */
1471 if(sq->status == serviced_query_UDP_EDNS ||
1472 sq->status == serviced_query_UDP ||
1473 sq->status == serviced_query_PROBE_EDNS ||
1474 sq->status == serviced_query_UDP_EDNS_FRAG ||
1475 sq->status == serviced_query_UDP_EDNS_fallback) {
1476 struct pending* p = (struct pending*)sq->pending;
1478 portcomm_loweruse(sq->outnet, p->pc);
1479 pending_delete(sq->outnet, p);
1480 /* this call can cause reentrant calls back into the
1482 outnet_send_wait_udp(sq->outnet);
1484 struct waiting_tcp* p = (struct waiting_tcp*)
1486 if(p->pkt == NULL) {
1487 decommission_pending_tcp(sq->outnet,
1488 (struct pending_tcp*)p->next_waiting);
1490 waiting_list_remove(sq->outnet, p);
1491 waiting_tcp_delete(p);
1495 /* does not delete from tree, caller has to do that */
1496 serviced_node_del(&sq->node, NULL);
1499 /** perturb a dname capitalization randomly */
1501 serviced_perturb_qname(struct ub_randstate* rnd, uint8_t* qbuf, size_t len)
1504 uint8_t* d = qbuf + 10;
1505 long int random = 0;
1507 log_assert(len >= 10 + 5 /* offset qname, root, qtype, qclass */);
1512 /* only perturb A-Z, a-z */
1513 if(isalpha((unsigned char)*d)) {
1514 /* get a random bit */
1516 random = ub_random(rnd);
1520 *d = (uint8_t)toupper((unsigned char)*d);
1522 *d = (uint8_t)tolower((unsigned char)*d);
1531 if(verbosity >= VERB_ALGO) {
1532 char buf[LDNS_MAX_DOMAINLEN+1];
1533 dname_str(qbuf+10, buf);
1534 verbose(VERB_ALGO, "qname perturbed to %s", buf);
1538 /** put serviced query into a buffer */
1540 serviced_encode(struct serviced_query* sq, sldns_buffer* buff, int with_edns)
1542 /* if we are using 0x20 bits for ID randomness, perturb them */
1543 if(sq->outnet->use_caps_for_id && !sq->nocaps) {
1544 serviced_perturb_qname(sq->outnet->rnd, sq->qbuf, sq->qbuflen);
1546 /* generate query */
1547 sldns_buffer_clear(buff);
1548 sldns_buffer_write_u16(buff, 0); /* id placeholder */
1549 sldns_buffer_write(buff, sq->qbuf, sq->qbuflen);
1550 sldns_buffer_flip(buff);
1552 /* add edns section */
1553 struct edns_data edns;
1554 edns.edns_present = 1;
1556 edns.edns_version = EDNS_ADVERTISED_VERSION;
1557 edns.opt_list = sq->opt_list;
1558 if(sq->status == serviced_query_UDP_EDNS_FRAG) {
1559 if(addr_is_ip6(&sq->addr, sq->addrlen)) {
1560 if(EDNS_FRAG_SIZE_IP6 < EDNS_ADVERTISED_SIZE)
1561 edns.udp_size = EDNS_FRAG_SIZE_IP6;
1562 else edns.udp_size = EDNS_ADVERTISED_SIZE;
1564 if(EDNS_FRAG_SIZE_IP4 < EDNS_ADVERTISED_SIZE)
1565 edns.udp_size = EDNS_FRAG_SIZE_IP4;
1566 else edns.udp_size = EDNS_ADVERTISED_SIZE;
1569 edns.udp_size = EDNS_ADVERTISED_SIZE;
1572 if(sq->dnssec & EDNS_DO)
1573 edns.bits = EDNS_DO;
1574 if(sq->dnssec & BIT_CD)
1575 LDNS_CD_SET(sldns_buffer_begin(buff));
1576 attach_edns_record(buff, &edns);
1581 * Perform serviced query UDP sending operation.
1582 * Sends UDP with EDNS, unless infra host marked non EDNS.
1583 * @param sq: query to send.
1584 * @param buff: buffer scratch space.
1585 * @return 0 on error.
1588 serviced_udp_send(struct serviced_query* sq, sldns_buffer* buff)
1591 uint8_t edns_lame_known;
1592 time_t now = *sq->outnet->now_secs;
1594 if(!infra_host(sq->outnet->infra, &sq->addr, sq->addrlen, sq->zone,
1595 sq->zonelen, now, &vs, &edns_lame_known, &rtt))
1598 verbose(VERB_ALGO, "EDNS lookup known=%d vs=%d", edns_lame_known, vs);
1599 if(sq->status == serviced_initial) {
1600 if(edns_lame_known == 0 && rtt > 5000 && rtt < 10001) {
1601 /* perform EDNS lame probe - check if server is
1602 * EDNS lame (EDNS queries to it are dropped) */
1603 verbose(VERB_ALGO, "serviced query: send probe to see "
1604 " if use of EDNS causes timeouts");
1605 /* even 700 msec may be too small */
1607 sq->status = serviced_query_PROBE_EDNS;
1608 } else if(vs != -1) {
1609 sq->status = serviced_query_UDP_EDNS;
1611 sq->status = serviced_query_UDP;
1614 serviced_encode(sq, buff, (sq->status == serviced_query_UDP_EDNS) ||
1615 (sq->status == serviced_query_UDP_EDNS_FRAG));
1616 sq->last_sent_time = *sq->outnet->now_tv;
1617 sq->edns_lame_known = (int)edns_lame_known;
1618 verbose(VERB_ALGO, "serviced query UDP timeout=%d msec", rtt);
1619 sq->pending = pending_udp_query(sq, buff, rtt,
1620 serviced_udp_callback, sq);
1626 /** check that perturbed qname is identical */
1628 serviced_check_qname(sldns_buffer* pkt, uint8_t* qbuf, size_t qbuflen)
1630 uint8_t* d1 = sldns_buffer_begin(pkt)+12;
1631 uint8_t* d2 = qbuf+10;
1634 if(sldns_buffer_limit(pkt) < 12+1+4) /* packet too small for qname */
1636 log_assert(qbuflen >= 15 /* 10 header, root, type, class */);
1639 while(len1 != 0 || len2 != 0) {
1640 if(LABEL_IS_PTR(len1)) {
1641 /* check if we can read *d1 with compression ptr rest */
1642 if(d1 >= sldns_buffer_at(pkt, sldns_buffer_limit(pkt)))
1644 d1 = sldns_buffer_begin(pkt)+PTR_OFFSET(len1, *d1);
1645 /* check if we can read the destination *d1 */
1646 if(d1 >= sldns_buffer_at(pkt, sldns_buffer_limit(pkt)))
1649 if(count++ > MAX_COMPRESS_PTRS)
1653 if(d2 > qbuf+qbuflen)
1657 if(len1 > LDNS_MAX_LABELLEN)
1659 /* check len1 + 1(next length) are okay to read */
1660 if(d1+len1 >= sldns_buffer_at(pkt, sldns_buffer_limit(pkt)))
1662 log_assert(len1 <= LDNS_MAX_LABELLEN);
1663 log_assert(len2 <= LDNS_MAX_LABELLEN);
1664 log_assert(len1 == len2 && len1 != 0);
1665 /* compare the labels - bitwise identical */
1666 if(memcmp(d1, d2, len1) != 0)
1676 /** call the callbacks for a serviced query */
1678 serviced_callbacks(struct serviced_query* sq, int error, struct comm_point* c,
1679 struct comm_reply* rep)
1681 struct service_callback* p;
1682 int dobackup = (sq->cblist && sq->cblist->next); /* >1 cb*/
1683 uint8_t *backup_p = NULL;
1685 #ifdef UNBOUND_DEBUG
1690 /* remove from tree, and schedule for deletion, so that callbacks
1691 * can safely deregister themselves and even create new serviced
1692 * queries that are identical to this one. */
1693 rbtree_delete(sq->outnet->serviced, sq);
1694 log_assert(rem); /* should have been present */
1695 sq->to_be_deleted = 1;
1696 verbose(VERB_ALGO, "svcd callbacks start");
1697 if(sq->outnet->use_caps_for_id && error == NETEVENT_NOERROR && c &&
1698 !sq->nocaps && sq->qtype != LDNS_RR_TYPE_PTR) {
1699 /* for type PTR do not check perturbed name in answer,
1700 * compatibility with cisco dns guard boxes that mess up
1701 * reverse queries 0x20 contents */
1702 /* noerror and nxdomain must have a qname in reply */
1703 if(sldns_buffer_read_u16_at(c->buffer, 4) == 0 &&
1704 (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer))
1705 == LDNS_RCODE_NOERROR ||
1706 LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer))
1707 == LDNS_RCODE_NXDOMAIN)) {
1708 verbose(VERB_DETAIL, "no qname in reply to check 0x20ID");
1709 log_addr(VERB_DETAIL, "from server",
1710 &sq->addr, sq->addrlen);
1711 log_buf(VERB_DETAIL, "for packet", c->buffer);
1712 error = NETEVENT_CLOSED;
1714 } else if(sldns_buffer_read_u16_at(c->buffer, 4) > 0 &&
1715 !serviced_check_qname(c->buffer, sq->qbuf,
1717 verbose(VERB_DETAIL, "wrong 0x20-ID in reply qname");
1718 log_addr(VERB_DETAIL, "from server",
1719 &sq->addr, sq->addrlen);
1720 log_buf(VERB_DETAIL, "for packet", c->buffer);
1721 error = NETEVENT_CAPSFAIL;
1722 /* and cleanup too */
1723 pkt_dname_tolower(c->buffer,
1724 sldns_buffer_at(c->buffer, 12));
1726 verbose(VERB_ALGO, "good 0x20-ID in reply qname");
1727 /* cleanup caps, prettier cache contents. */
1728 pkt_dname_tolower(c->buffer,
1729 sldns_buffer_at(c->buffer, 12));
1733 /* make a backup of the query, since the querystate processing
1734 * may send outgoing queries that overwrite the buffer.
1735 * use secondary buffer to store the query.
1736 * This is a data copy, but faster than packet to server */
1737 backlen = sldns_buffer_limit(c->buffer);
1738 backup_p = memdup(sldns_buffer_begin(c->buffer), backlen);
1740 log_err("malloc failure in serviced query callbacks");
1741 error = NETEVENT_CLOSED;
1744 sq->outnet->svcd_overhead = backlen;
1746 /* test the actual sq->cblist, because the next elem could be deleted*/
1747 while((p=sq->cblist) != NULL) {
1748 sq->cblist = p->next; /* remove this element */
1750 sldns_buffer_clear(c->buffer);
1751 sldns_buffer_write(c->buffer, backup_p, backlen);
1752 sldns_buffer_flip(c->buffer);
1754 fptr_ok(fptr_whitelist_serviced_query(p->cb));
1755 (void)(*p->cb)(c, p->cb_arg, error, rep);
1760 sq->outnet->svcd_overhead = 0;
1762 verbose(VERB_ALGO, "svcd callbacks end");
1763 log_assert(sq->cblist == NULL);
1764 serviced_delete(sq);
1768 serviced_tcp_callback(struct comm_point* c, void* arg, int error,
1769 struct comm_reply* rep)
1771 struct serviced_query* sq = (struct serviced_query*)arg;
1772 struct comm_reply r2;
1773 sq->pending = NULL; /* removed after this callback */
1774 if(error != NETEVENT_NOERROR)
1775 log_addr(VERB_QUERY, "tcp error for address",
1776 &sq->addr, sq->addrlen);
1777 if(error==NETEVENT_NOERROR)
1778 infra_update_tcp_works(sq->outnet->infra, &sq->addr,
1779 sq->addrlen, sq->zone, sq->zonelen);
1781 if(error==NETEVENT_NOERROR && sq->outnet->dtenv &&
1782 (sq->outnet->dtenv->log_resolver_response_messages ||
1783 sq->outnet->dtenv->log_forwarder_response_messages))
1784 dt_msg_send_outside_response(sq->outnet->dtenv, &sq->addr,
1785 c->type, sq->zone, sq->zonelen, sq->qbuf, sq->qbuflen,
1786 &sq->last_sent_time, sq->outnet->now_tv, c->buffer);
1788 if(error==NETEVENT_NOERROR && sq->status == serviced_query_TCP_EDNS &&
1789 (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) ==
1790 LDNS_RCODE_FORMERR || LDNS_RCODE_WIRE(sldns_buffer_begin(
1791 c->buffer)) == LDNS_RCODE_NOTIMPL) ) {
1792 /* attempt to fallback to nonEDNS */
1793 sq->status = serviced_query_TCP_EDNS_fallback;
1794 serviced_tcp_initiate(sq, c->buffer);
1796 } else if(error==NETEVENT_NOERROR &&
1797 sq->status == serviced_query_TCP_EDNS_fallback &&
1798 (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) ==
1799 LDNS_RCODE_NOERROR || LDNS_RCODE_WIRE(
1800 sldns_buffer_begin(c->buffer)) == LDNS_RCODE_NXDOMAIN
1801 || LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer))
1802 == LDNS_RCODE_YXDOMAIN)) {
1803 /* the fallback produced a result that looks promising, note
1804 * that this server should be approached without EDNS */
1805 /* only store noEDNS in cache if domain is noDNSSEC */
1806 if(!sq->want_dnssec)
1807 if(!infra_edns_update(sq->outnet->infra, &sq->addr,
1808 sq->addrlen, sq->zone, sq->zonelen, -1,
1809 *sq->outnet->now_secs))
1810 log_err("Out of memory caching no edns for host");
1811 sq->status = serviced_query_TCP;
1813 if(sq->tcp_upstream || sq->ssl_upstream) {
1814 struct timeval now = *sq->outnet->now_tv;
1815 if(now.tv_sec > sq->last_sent_time.tv_sec ||
1816 (now.tv_sec == sq->last_sent_time.tv_sec &&
1817 now.tv_usec > sq->last_sent_time.tv_usec)) {
1818 /* convert from microseconds to milliseconds */
1819 int roundtime = ((int)(now.tv_sec - sq->last_sent_time.tv_sec))*1000
1820 + ((int)now.tv_usec - (int)sq->last_sent_time.tv_usec)/1000;
1821 verbose(VERB_ALGO, "measured TCP-time at %d msec", roundtime);
1822 log_assert(roundtime >= 0);
1823 /* only store if less then AUTH_TIMEOUT seconds, it could be
1824 * huge due to system-hibernated and we woke up */
1825 if(roundtime < TCP_AUTH_QUERY_TIMEOUT*1000) {
1826 if(!infra_rtt_update(sq->outnet->infra, &sq->addr,
1827 sq->addrlen, sq->zone, sq->zonelen, sq->qtype,
1828 roundtime, sq->last_rtt, (time_t)now.tv_sec))
1829 log_err("out of memory noting rtt.");
1833 /* insert address into reply info */
1835 /* create one if there isn't (on errors) */
1839 memcpy(&rep->addr, &sq->addr, sq->addrlen);
1840 rep->addrlen = sq->addrlen;
1841 serviced_callbacks(sq, error, c, rep);
1846 serviced_tcp_initiate(struct serviced_query* sq, sldns_buffer* buff)
1848 verbose(VERB_ALGO, "initiate TCP query %s",
1849 sq->status==serviced_query_TCP_EDNS?"EDNS":"");
1850 serviced_encode(sq, buff, sq->status == serviced_query_TCP_EDNS);
1851 sq->last_sent_time = *sq->outnet->now_tv;
1852 sq->pending = pending_tcp_query(sq, buff, TCP_AUTH_QUERY_TIMEOUT,
1853 serviced_tcp_callback, sq);
1855 /* delete from tree so that a retry by above layer does not
1856 * clash with this entry */
1857 log_err("serviced_tcp_initiate: failed to send tcp query");
1858 serviced_callbacks(sq, NETEVENT_CLOSED, NULL, NULL);
1862 /** Send serviced query over TCP return false on initial failure */
1864 serviced_tcp_send(struct serviced_query* sq, sldns_buffer* buff)
1867 uint8_t edns_lame_known;
1868 if(!infra_host(sq->outnet->infra, &sq->addr, sq->addrlen, sq->zone,
1869 sq->zonelen, *sq->outnet->now_secs, &vs, &edns_lame_known,
1873 sq->status = serviced_query_TCP_EDNS;
1874 else sq->status = serviced_query_TCP;
1875 serviced_encode(sq, buff, sq->status == serviced_query_TCP_EDNS);
1876 sq->last_sent_time = *sq->outnet->now_tv;
1877 sq->pending = pending_tcp_query(sq, buff, TCP_AUTH_QUERY_TIMEOUT,
1878 serviced_tcp_callback, sq);
1879 return sq->pending != NULL;
1882 /* see if packet is edns malformed; got zeroes at start.
1883 * This is from servers that return malformed packets to EDNS0 queries,
1884 * but they return good packets for nonEDNS0 queries.
1885 * We try to detect their output; without resorting to a full parse or
1886 * check for too many bytes after the end of the packet. */
1888 packet_edns_malformed(struct sldns_buffer* buf, int qtype)
1891 if(sldns_buffer_limit(buf) < LDNS_HEADER_SIZE)
1892 return 1; /* malformed */
1893 /* they have NOERROR rcode, 1 answer. */
1894 if(LDNS_RCODE_WIRE(sldns_buffer_begin(buf)) != LDNS_RCODE_NOERROR)
1896 /* one query (to skip) and answer records */
1897 if(LDNS_QDCOUNT(sldns_buffer_begin(buf)) != 1 ||
1898 LDNS_ANCOUNT(sldns_buffer_begin(buf)) == 0)
1901 len = dname_valid(sldns_buffer_at(buf, LDNS_HEADER_SIZE),
1902 sldns_buffer_limit(buf)-LDNS_HEADER_SIZE);
1905 if(len == 1 && qtype == 0)
1906 return 0; /* we asked for '.' and type 0 */
1907 /* and then 4 bytes (type and class of query) */
1908 if(sldns_buffer_limit(buf) < LDNS_HEADER_SIZE + len + 4 + 3)
1911 /* and start with 11 zeroes as the answer RR */
1912 /* so check the qtype of the answer record, qname=0, type=0 */
1913 if(sldns_buffer_at(buf, LDNS_HEADER_SIZE+len+4)[0] == 0 &&
1914 sldns_buffer_at(buf, LDNS_HEADER_SIZE+len+4)[1] == 0 &&
1915 sldns_buffer_at(buf, LDNS_HEADER_SIZE+len+4)[2] == 0)
1921 serviced_udp_callback(struct comm_point* c, void* arg, int error,
1922 struct comm_reply* rep)
1924 struct serviced_query* sq = (struct serviced_query*)arg;
1925 struct outside_network* outnet = sq->outnet;
1926 struct timeval now = *sq->outnet->now_tv;
1927 int fallback_tcp = 0;
1929 sq->pending = NULL; /* removed after callback */
1930 if(error == NETEVENT_TIMEOUT) {
1932 if(sq->status == serviced_query_PROBE_EDNS) {
1933 /* non-EDNS probe failed; we do not know its status,
1934 * keep trying with EDNS, timeout may not be caused
1936 sq->status = serviced_query_UDP_EDNS;
1938 if(sq->status == serviced_query_UDP_EDNS && sq->last_rtt < 5000) {
1939 /* fallback to 1480/1280 */
1940 sq->status = serviced_query_UDP_EDNS_FRAG;
1941 log_name_addr(VERB_ALGO, "try edns1xx0", sq->qbuf+10,
1942 &sq->addr, sq->addrlen);
1943 if(!serviced_udp_send(sq, c->buffer)) {
1944 serviced_callbacks(sq, NETEVENT_CLOSED, c, rep);
1948 if(sq->status == serviced_query_UDP_EDNS_FRAG) {
1949 /* fragmentation size did not fix it */
1950 sq->status = serviced_query_UDP_EDNS;
1953 if(!(rto=infra_rtt_update(outnet->infra, &sq->addr, sq->addrlen,
1954 sq->zone, sq->zonelen, sq->qtype, -1, sq->last_rtt,
1955 (time_t)now.tv_sec)))
1956 log_err("out of memory in UDP exponential backoff");
1957 if(sq->retry < OUTBOUND_UDP_RETRY) {
1958 log_name_addr(VERB_ALGO, "retry query", sq->qbuf+10,
1959 &sq->addr, sq->addrlen);
1960 if(!serviced_udp_send(sq, c->buffer)) {
1961 serviced_callbacks(sq, NETEVENT_CLOSED, c, rep);
1965 if(rto >= RTT_MAX_TIMEOUT) {
1967 /* UDP does not work, fallback to TCP below */
1969 serviced_callbacks(sq, NETEVENT_TIMEOUT, c, rep);
1972 } else if(error != NETEVENT_NOERROR) {
1973 /* udp returns error (due to no ID or interface available) */
1974 serviced_callbacks(sq, error, c, rep);
1978 if(error == NETEVENT_NOERROR && outnet->dtenv &&
1979 (outnet->dtenv->log_resolver_response_messages ||
1980 outnet->dtenv->log_forwarder_response_messages))
1981 dt_msg_send_outside_response(outnet->dtenv, &sq->addr, c->type,
1982 sq->zone, sq->zonelen, sq->qbuf, sq->qbuflen,
1983 &sq->last_sent_time, sq->outnet->now_tv, c->buffer);
1986 if( (sq->status == serviced_query_UDP_EDNS
1987 ||sq->status == serviced_query_UDP_EDNS_FRAG)
1988 && (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer))
1989 == LDNS_RCODE_FORMERR || LDNS_RCODE_WIRE(
1990 sldns_buffer_begin(c->buffer)) == LDNS_RCODE_NOTIMPL
1991 || packet_edns_malformed(c->buffer, sq->qtype)
1993 /* try to get an answer by falling back without EDNS */
1994 verbose(VERB_ALGO, "serviced query: attempt without EDNS");
1995 sq->status = serviced_query_UDP_EDNS_fallback;
1997 if(!serviced_udp_send(sq, c->buffer)) {
1998 serviced_callbacks(sq, NETEVENT_CLOSED, c, rep);
2001 } else if(sq->status == serviced_query_PROBE_EDNS) {
2002 /* probe without EDNS succeeds, so we conclude that this
2003 * host likely has EDNS packets dropped */
2004 log_addr(VERB_DETAIL, "timeouts, concluded that connection to "
2005 "host drops EDNS packets", &sq->addr, sq->addrlen);
2006 /* only store noEDNS in cache if domain is noDNSSEC */
2007 if(!sq->want_dnssec)
2008 if(!infra_edns_update(outnet->infra, &sq->addr, sq->addrlen,
2009 sq->zone, sq->zonelen, -1, (time_t)now.tv_sec)) {
2010 log_err("Out of memory caching no edns for host");
2012 sq->status = serviced_query_UDP;
2013 } else if(sq->status == serviced_query_UDP_EDNS &&
2014 !sq->edns_lame_known) {
2015 /* now we know that edns queries received answers store that */
2016 log_addr(VERB_ALGO, "serviced query: EDNS works for",
2017 &sq->addr, sq->addrlen);
2018 if(!infra_edns_update(outnet->infra, &sq->addr, sq->addrlen,
2019 sq->zone, sq->zonelen, 0, (time_t)now.tv_sec)) {
2020 log_err("Out of memory caching edns works");
2022 sq->edns_lame_known = 1;
2023 } else if(sq->status == serviced_query_UDP_EDNS_fallback &&
2024 !sq->edns_lame_known && (LDNS_RCODE_WIRE(
2025 sldns_buffer_begin(c->buffer)) == LDNS_RCODE_NOERROR ||
2026 LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) ==
2027 LDNS_RCODE_NXDOMAIN || LDNS_RCODE_WIRE(sldns_buffer_begin(
2028 c->buffer)) == LDNS_RCODE_YXDOMAIN)) {
2029 /* the fallback produced a result that looks promising, note
2030 * that this server should be approached without EDNS */
2031 /* only store noEDNS in cache if domain is noDNSSEC */
2032 if(!sq->want_dnssec) {
2033 log_addr(VERB_ALGO, "serviced query: EDNS fails for",
2034 &sq->addr, sq->addrlen);
2035 if(!infra_edns_update(outnet->infra, &sq->addr, sq->addrlen,
2036 sq->zone, sq->zonelen, -1, (time_t)now.tv_sec)) {
2037 log_err("Out of memory caching no edns for host");
2040 log_addr(VERB_ALGO, "serviced query: EDNS fails, but "
2041 "not stored because need DNSSEC for", &sq->addr,
2044 sq->status = serviced_query_UDP;
2046 if(now.tv_sec > sq->last_sent_time.tv_sec ||
2047 (now.tv_sec == sq->last_sent_time.tv_sec &&
2048 now.tv_usec > sq->last_sent_time.tv_usec)) {
2049 /* convert from microseconds to milliseconds */
2050 int roundtime = ((int)(now.tv_sec - sq->last_sent_time.tv_sec))*1000
2051 + ((int)now.tv_usec - (int)sq->last_sent_time.tv_usec)/1000;
2052 verbose(VERB_ALGO, "measured roundtrip at %d msec", roundtime);
2053 log_assert(roundtime >= 0);
2054 /* in case the system hibernated, do not enter a huge value,
2055 * above this value gives trouble with server selection */
2056 if(roundtime < 60000) {
2057 if(!infra_rtt_update(outnet->infra, &sq->addr, sq->addrlen,
2058 sq->zone, sq->zonelen, sq->qtype, roundtime,
2059 sq->last_rtt, (time_t)now.tv_sec))
2060 log_err("out of memory noting rtt.");
2063 } /* end of if_!fallback_tcp */
2064 /* perform TC flag check and TCP fallback after updating our
2065 * cache entries for EDNS status and RTT times */
2066 if(LDNS_TC_WIRE(sldns_buffer_begin(c->buffer)) || fallback_tcp) {
2067 /* fallback to TCP */
2068 /* this discards partial UDP contents */
2069 if(sq->status == serviced_query_UDP_EDNS ||
2070 sq->status == serviced_query_UDP_EDNS_FRAG ||
2071 sq->status == serviced_query_UDP_EDNS_fallback)
2072 /* if we have unfinished EDNS_fallback, start again */
2073 sq->status = serviced_query_TCP_EDNS;
2074 else sq->status = serviced_query_TCP;
2075 serviced_tcp_initiate(sq, c->buffer);
2078 /* yay! an answer */
2079 serviced_callbacks(sq, error, c, rep);
2083 struct serviced_query*
2084 outnet_serviced_query(struct outside_network* outnet,
2085 struct query_info* qinfo, uint16_t flags, int dnssec, int want_dnssec,
2086 int nocaps, int tcp_upstream, int ssl_upstream, char* tls_auth_name,
2087 struct sockaddr_storage* addr, socklen_t addrlen, uint8_t* zone,
2088 size_t zonelen, struct module_qstate* qstate,
2089 comm_point_callback_type* callback, void* callback_arg, sldns_buffer* buff,
2090 struct module_env* env)
2092 struct serviced_query* sq;
2093 struct service_callback* cb;
2094 if(!inplace_cb_query_call(env, qinfo, flags, addr, addrlen, zone, zonelen,
2095 qstate, qstate->region))
2097 serviced_gen_query(buff, qinfo->qname, qinfo->qname_len, qinfo->qtype,
2098 qinfo->qclass, flags);
2099 sq = lookup_serviced(outnet, buff, dnssec, addr, addrlen,
2100 qstate->edns_opts_back_out);
2101 /* duplicate entries are included in the callback list, because
2102 * there is a counterpart registration by our caller that needs to
2103 * be doubly-removed (with callbacks perhaps). */
2104 if(!(cb = (struct service_callback*)malloc(sizeof(*cb))))
2107 /* make new serviced query entry */
2108 sq = serviced_create(outnet, buff, dnssec, want_dnssec, nocaps,
2109 tcp_upstream, ssl_upstream, tls_auth_name, addr,
2110 addrlen, zone, zonelen, (int)qinfo->qtype,
2111 qstate->edns_opts_back_out);
2116 /* perform first network action */
2117 if(outnet->do_udp && !(tcp_upstream || ssl_upstream)) {
2118 if(!serviced_udp_send(sq, buff)) {
2119 (void)rbtree_delete(outnet->serviced, sq);
2127 if(!serviced_tcp_send(sq, buff)) {
2128 (void)rbtree_delete(outnet->serviced, sq);
2137 /* add callback to list of callbacks */
2139 cb->cb_arg = callback_arg;
2140 cb->next = sq->cblist;
2145 /** remove callback from list */
2147 callback_list_remove(struct serviced_query* sq, void* cb_arg)
2149 struct service_callback** pp = &sq->cblist;
2151 if((*pp)->cb_arg == cb_arg) {
2152 struct service_callback* del = *pp;
2161 void outnet_serviced_query_stop(struct serviced_query* sq, void* cb_arg)
2165 callback_list_remove(sq, cb_arg);
2166 /* if callbacks() routine scheduled deletion, let it do that */
2167 if(!sq->cblist && !sq->to_be_deleted) {
2168 (void)rbtree_delete(sq->outnet->serviced, sq);
2169 serviced_delete(sq);
2173 /** create fd to send to this destination */
2175 fd_for_dest(struct outside_network* outnet, struct sockaddr_storage* to_addr,
2176 socklen_t to_addrlen)
2178 struct sockaddr_storage* addr;
2183 /* select interface */
2184 if(addr_is_ip6(to_addr, to_addrlen)) {
2185 if(outnet->num_ip6 == 0) {
2187 addr_to_str(to_addr, to_addrlen, to, sizeof(to));
2188 verbose(VERB_QUERY, "need ipv6 to send, but no ipv6 outgoing interfaces, for %s", to);
2191 i = ub_random_max(outnet->rnd, outnet->num_ip6);
2192 addr = &outnet->ip6_ifs[i].addr;
2193 addrlen = outnet->ip6_ifs[i].addrlen;
2195 if(outnet->num_ip4 == 0) {
2197 addr_to_str(to_addr, to_addrlen, to, sizeof(to));
2198 verbose(VERB_QUERY, "need ipv4 to send, but no ipv4 outgoing interfaces, for %s", to);
2201 i = ub_random_max(outnet->rnd, outnet->num_ip4);
2202 addr = &outnet->ip4_ifs[i].addr;
2203 addrlen = outnet->ip4_ifs[i].addrlen;
2207 for(try = 0; try<1000; try++) {
2211 int port = ub_random(outnet->rnd)&0xffff;
2213 if(addr_is_ip6(to_addr, to_addrlen)) {
2214 struct sockaddr_in6 sa = *(struct sockaddr_in6*)addr;
2215 sa.sin6_port = (in_port_t)htons((uint16_t)port);
2216 fd = create_udp_sock(AF_INET6, SOCK_DGRAM,
2217 (struct sockaddr*)&sa, addrlen, 1, &inuse, &noproto,
2218 0, 0, 0, NULL, 0, freebind, 0);
2220 struct sockaddr_in* sa = (struct sockaddr_in*)addr;
2221 sa->sin_port = (in_port_t)htons((uint16_t)port);
2222 fd = create_udp_sock(AF_INET, SOCK_DGRAM,
2223 (struct sockaddr*)addr, addrlen, 1, &inuse, &noproto,
2224 0, 0, 0, NULL, 0, freebind, 0);
2233 /* too many tries */
2234 log_err("cannot send probe, ports are in use");
2239 outnet_comm_point_for_udp(struct outside_network* outnet,
2240 comm_point_callback_type* cb, void* cb_arg,
2241 struct sockaddr_storage* to_addr, socklen_t to_addrlen)
2243 struct comm_point* cp;
2244 int fd = fd_for_dest(outnet, to_addr, to_addrlen);
2248 cp = comm_point_create_udp(outnet->base, fd, outnet->udp_buff,
2251 log_err("malloc failure");
2259 outnet_comm_point_for_tcp(struct outside_network* outnet,
2260 comm_point_callback_type* cb, void* cb_arg,
2261 struct sockaddr_storage* to_addr, socklen_t to_addrlen,
2262 sldns_buffer* query, int timeout)
2264 struct comm_point* cp;
2265 int fd = outnet_get_tcp_fd(to_addr, to_addrlen, outnet->tcp_mss);
2269 fd_set_nonblock(fd);
2270 if(!outnet_tcp_connect(fd, to_addr, to_addrlen)) {
2271 /* outnet_tcp_connect has closed fd on error for us */
2274 cp = comm_point_create_tcp_out(outnet->base, 65552, cb, cb_arg);
2276 log_err("malloc failure");
2280 cp->repinfo.addrlen = to_addrlen;
2281 memcpy(&cp->repinfo.addr, to_addr, to_addrlen);
2282 /* set timeout on TCP connection */
2283 comm_point_start_listening(cp, fd, timeout);
2284 /* copy scratch buffer to cp->buffer */
2285 sldns_buffer_copy(cp->buffer, query);
2289 /** setup http request headers in buffer for sending query to destination */
2291 setup_http_request(sldns_buffer* buf, char* host, char* path)
2293 sldns_buffer_clear(buf);
2294 sldns_buffer_printf(buf, "GET /%s HTTP/1.1\r\n", path);
2295 sldns_buffer_printf(buf, "Host: %s\r\n", host);
2296 sldns_buffer_printf(buf, "User-Agent: unbound/%s\r\n",
2298 /* We do not really do multiple queries per connection,
2299 * but this header setting is also not needed.
2300 * sldns_buffer_printf(buf, "Connection: close\r\n") */
2301 sldns_buffer_printf(buf, "\r\n");
2302 if(sldns_buffer_position(buf)+10 > sldns_buffer_capacity(buf))
2303 return 0; /* somehow buffer too short, but it is about 60K
2304 and the request is only a couple bytes long. */
2305 sldns_buffer_flip(buf);
2310 outnet_comm_point_for_http(struct outside_network* outnet,
2311 comm_point_callback_type* cb, void* cb_arg,
2312 struct sockaddr_storage* to_addr, socklen_t to_addrlen, int timeout,
2313 int ssl, char* host, char* path)
2315 /* cp calls cb with err=NETEVENT_DONE when transfer is done */
2316 struct comm_point* cp;
2317 int fd = outnet_get_tcp_fd(to_addr, to_addrlen, outnet->tcp_mss);
2321 fd_set_nonblock(fd);
2322 if(!outnet_tcp_connect(fd, to_addr, to_addrlen)) {
2323 /* outnet_tcp_connect has closed fd on error for us */
2326 cp = comm_point_create_http_out(outnet->base, 65552, cb, cb_arg,
2329 log_err("malloc failure");
2333 cp->repinfo.addrlen = to_addrlen;
2334 memcpy(&cp->repinfo.addr, to_addr, to_addrlen);
2336 /* setup for SSL (if needed) */
2338 cp->ssl = outgoing_ssl_fd(outnet->sslctx, fd);
2340 log_err("cannot setup https");
2341 comm_point_delete(cp);
2345 comm_point_tcp_win_bio_cb(cp, cp->ssl);
2347 cp->ssl_shake_state = comm_ssl_shake_write;
2348 /* https verification */
2349 #ifdef HAVE_SSL_SET1_HOST
2350 if((SSL_CTX_get_verify_mode(outnet->sslctx)&SSL_VERIFY_PEER)) {
2351 /* because we set SSL_VERIFY_PEER, in netevent in
2352 * ssl_handshake, it'll check if the certificate
2353 * verification has succeeded */
2354 /* SSL_VERIFY_PEER is set on the sslctx */
2355 /* and the certificates to verify with are loaded into
2356 * it with SSL_load_verify_locations or
2357 * SSL_CTX_set_default_verify_paths */
2358 /* setting the hostname makes openssl verify the
2359 * host name in the x509 certificate in the
2361 if(!SSL_set1_host(cp->ssl, host)) {
2362 log_err("SSL_set1_host failed");
2363 comm_point_delete(cp);
2367 #endif /* HAVE_SSL_SET1_HOST */
2370 /* set timeout on TCP connection */
2371 comm_point_start_listening(cp, fd, timeout);
2373 /* setup http request in cp->buffer */
2374 if(!setup_http_request(cp->buffer, host, path)) {
2375 log_err("error setting up http request");
2376 comm_point_delete(cp);
2382 /** get memory used by waiting tcp entry (in use or not) */
2384 waiting_tcp_get_mem(struct waiting_tcp* w)
2388 s = sizeof(*w) + w->pkt_len;
2390 s += comm_timer_get_mem(w->timer);
2394 /** get memory used by port if */
2396 if_get_mem(struct port_if* pif)
2400 s = sizeof(*pif) + sizeof(int)*pif->avail_total +
2401 sizeof(struct port_comm*)*pif->maxout;
2402 for(i=0; i<pif->inuse; i++)
2403 s += sizeof(*pif->out[i]) +
2404 comm_point_get_mem(pif->out[i]->cp);
2408 /** get memory used by waiting udp */
2410 waiting_udp_get_mem(struct pending* w)
2413 s = sizeof(*w) + comm_timer_get_mem(w->timer) + w->pkt_len;
2417 size_t outnet_get_mem(struct outside_network* outnet)
2421 struct waiting_tcp* w;
2423 struct serviced_query* sq;
2424 struct service_callback* sb;
2425 struct port_comm* pc;
2426 size_t s = sizeof(*outnet) + sizeof(*outnet->base) +
2427 sizeof(*outnet->udp_buff) +
2428 sldns_buffer_capacity(outnet->udp_buff);
2429 /* second buffer is not ours */
2430 for(pc = outnet->unused_fds; pc; pc = pc->next) {
2431 s += sizeof(*pc) + comm_point_get_mem(pc->cp);
2433 for(k=0; k<outnet->num_ip4; k++)
2434 s += if_get_mem(&outnet->ip4_ifs[k]);
2435 for(k=0; k<outnet->num_ip6; k++)
2436 s += if_get_mem(&outnet->ip6_ifs[k]);
2437 for(u=outnet->udp_wait_first; u; u=u->next_waiting)
2438 s += waiting_udp_get_mem(u);
2440 s += sizeof(struct pending_tcp*)*outnet->num_tcp;
2441 for(i=0; i<outnet->num_tcp; i++) {
2442 s += sizeof(struct pending_tcp);
2443 s += comm_point_get_mem(outnet->tcp_conns[i]->c);
2444 if(outnet->tcp_conns[i]->query)
2445 s += waiting_tcp_get_mem(outnet->tcp_conns[i]->query);
2447 for(w=outnet->tcp_wait_first; w; w = w->next_waiting)
2448 s += waiting_tcp_get_mem(w);
2449 s += sizeof(*outnet->pending);
2450 s += (sizeof(struct pending) + comm_timer_get_mem(NULL)) *
2451 outnet->pending->count;
2452 s += sizeof(*outnet->serviced);
2453 s += outnet->svcd_overhead;
2454 RBTREE_FOR(sq, struct serviced_query*, outnet->serviced) {
2455 s += sizeof(*sq) + sq->qbuflen;
2456 for(sb = sq->cblist; sb; sb = sb->next)
2463 serviced_get_mem(struct serviced_query* sq)
2465 struct service_callback* sb;
2467 s = sizeof(*sq) + sq->qbuflen;
2468 for(sb = sq->cblist; sb; sb = sb->next)
2470 if(sq->status == serviced_query_UDP_EDNS ||
2471 sq->status == serviced_query_UDP ||
2472 sq->status == serviced_query_PROBE_EDNS ||
2473 sq->status == serviced_query_UDP_EDNS_FRAG ||
2474 sq->status == serviced_query_UDP_EDNS_fallback) {
2475 s += sizeof(struct pending);
2476 s += comm_timer_get_mem(NULL);
2478 /* does not have size of the pkt pointer */
2479 /* always has a timer except on malloc failures */
2481 /* these sizes are part of the main outside network mem */
2483 s += sizeof(struct waiting_tcp);
2484 s += comm_timer_get_mem(NULL);