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