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