]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - services/outside_network.c
Vendor import of Unbound 1.9.1.
[FreeBSD/FreeBSD.git] / services / outside_network.c
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 "sldns/sbuffer.h"
62 #include "dnstap/dnstap.h"
63 #ifdef HAVE_OPENSSL_SSL_H
64 #include <openssl/ssl.h>
65 #endif
66 #ifdef HAVE_X509_VERIFY_PARAM_SET1_HOST
67 #include <openssl/x509v3.h>
68 #endif
69
70 #ifdef HAVE_NETDB_H
71 #include <netdb.h>
72 #endif
73 #include <fcntl.h>
74
75 /** number of times to retry making a random ID that is unique. */
76 #define MAX_ID_RETRY 1000
77 /** number of times to retry finding interface, port that can be opened. */
78 #define MAX_PORT_RETRY 10000
79 /** number of retries on outgoing UDP queries */
80 #define OUTBOUND_UDP_RETRY 1
81
82 /** initiate TCP transaction for serviced query */
83 static void serviced_tcp_initiate(struct serviced_query* sq, sldns_buffer* buff);
84 /** with a fd available, randomize and send UDP */
85 static int randomize_and_send_udp(struct pending* pend, sldns_buffer* packet,
86         int timeout);
87
88 /** remove waiting tcp from the outnet waiting list */
89 static void waiting_list_remove(struct outside_network* outnet,
90         struct waiting_tcp* w);
91
92 int 
93 pending_cmp(const void* key1, const void* key2)
94 {
95         struct pending *p1 = (struct pending*)key1;
96         struct pending *p2 = (struct pending*)key2;
97         if(p1->id < p2->id)
98                 return -1;
99         if(p1->id > p2->id)
100                 return 1;
101         log_assert(p1->id == p2->id);
102         return sockaddr_cmp(&p1->addr, p1->addrlen, &p2->addr, p2->addrlen);
103 }
104
105 int 
106 serviced_cmp(const void* key1, const void* key2)
107 {
108         struct serviced_query* q1 = (struct serviced_query*)key1;
109         struct serviced_query* q2 = (struct serviced_query*)key2;
110         int r;
111         if(q1->qbuflen < q2->qbuflen)
112                 return -1;
113         if(q1->qbuflen > q2->qbuflen)
114                 return 1;
115         log_assert(q1->qbuflen == q2->qbuflen);
116         log_assert(q1->qbuflen >= 15 /* 10 header, root, type, class */);
117         /* alternate casing of qname is still the same query */
118         if((r = memcmp(q1->qbuf, q2->qbuf, 10)) != 0)
119                 return r;
120         if((r = memcmp(q1->qbuf+q1->qbuflen-4, q2->qbuf+q2->qbuflen-4, 4)) != 0)
121                 return r;
122         if(q1->dnssec != q2->dnssec) {
123                 if(q1->dnssec < q2->dnssec)
124                         return -1;
125                 return 1;
126         }
127         if((r = query_dname_compare(q1->qbuf+10, q2->qbuf+10)) != 0)
128                 return r;
129         if((r = edns_opt_list_compare(q1->opt_list, q2->opt_list)) != 0)
130                 return r;
131         return sockaddr_cmp(&q1->addr, q1->addrlen, &q2->addr, q2->addrlen);
132 }
133
134 /** delete waiting_tcp entry. Does not unlink from waiting list. 
135  * @param w: to delete.
136  */
137 static void
138 waiting_tcp_delete(struct waiting_tcp* w)
139 {
140         if(!w) return;
141         if(w->timer)
142                 comm_timer_delete(w->timer);
143         free(w);
144 }
145
146 /** 
147  * Pick random outgoing-interface of that family, and bind it.
148  * port set to 0 so OS picks a port number for us.
149  * if it is the ANY address, do not bind.
150  * @param w: tcp structure with destination address.
151  * @param s: socket fd.
152  * @return false on error, socket closed.
153  */
154 static int
155 pick_outgoing_tcp(struct waiting_tcp* w, int s)
156 {
157         struct port_if* pi = NULL;
158         int num;
159 #ifdef INET6
160         if(addr_is_ip6(&w->addr, w->addrlen))
161                 num = w->outnet->num_ip6;
162         else
163 #endif
164                 num = w->outnet->num_ip4;
165         if(num == 0) {
166                 log_err("no TCP outgoing interfaces of family");
167                 log_addr(VERB_OPS, "for addr", &w->addr, w->addrlen);
168 #ifndef USE_WINSOCK
169                 close(s);
170 #else
171                 closesocket(s);
172 #endif
173                 return 0;
174         }
175 #ifdef INET6
176         if(addr_is_ip6(&w->addr, w->addrlen))
177                 pi = &w->outnet->ip6_ifs[ub_random_max(w->outnet->rnd, num)];
178         else
179 #endif
180                 pi = &w->outnet->ip4_ifs[ub_random_max(w->outnet->rnd, num)];
181         log_assert(pi);
182         if(addr_is_any(&pi->addr, pi->addrlen)) {
183                 /* binding to the ANY interface is for listening sockets */
184                 return 1;
185         }
186         /* set port to 0 */
187         if(addr_is_ip6(&pi->addr, pi->addrlen))
188                 ((struct sockaddr_in6*)&pi->addr)->sin6_port = 0;
189         else    ((struct sockaddr_in*)&pi->addr)->sin_port = 0;
190         if(bind(s, (struct sockaddr*)&pi->addr, pi->addrlen) != 0) {
191 #ifndef USE_WINSOCK
192                 log_err("outgoing tcp: bind: %s", strerror(errno));
193                 close(s);
194 #else
195                 log_err("outgoing tcp: bind: %s", 
196                         wsa_strerror(WSAGetLastError()));
197                 closesocket(s);
198 #endif
199                 return 0;
200         }
201         log_addr(VERB_ALGO, "tcp bound to src", &pi->addr, pi->addrlen);
202         return 1;
203 }
204
205 /** get TCP file descriptor for address, returns -1 on failure,
206  * tcp_mss is 0 or maxseg size to set for TCP packets. */
207 int
208 outnet_get_tcp_fd(struct sockaddr_storage* addr, socklen_t addrlen, int tcp_mss)
209 {
210         int s;
211 #ifdef SO_REUSEADDR
212         int on = 1;
213 #endif
214 #ifdef INET6
215         if(addr_is_ip6(addr, addrlen))
216                 s = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
217         else
218 #endif
219                 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
220         if(s == -1) {
221 #ifndef USE_WINSOCK
222                 log_err_addr("outgoing tcp: socket", strerror(errno),
223                         addr, addrlen);
224 #else
225                 log_err_addr("outgoing tcp: socket", 
226                         wsa_strerror(WSAGetLastError()), addr, addrlen);
227 #endif
228                 return -1;
229         }
230
231 #ifdef SO_REUSEADDR
232         if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&on,
233                 (socklen_t)sizeof(on)) < 0) {
234                 verbose(VERB_ALGO, "outgoing tcp:"
235                         " setsockopt(.. SO_REUSEADDR ..) failed");
236         }
237 #endif
238
239         if(tcp_mss > 0) {
240 #if defined(IPPROTO_TCP) && defined(TCP_MAXSEG)
241                 if(setsockopt(s, IPPROTO_TCP, TCP_MAXSEG,
242                         (void*)&tcp_mss, (socklen_t)sizeof(tcp_mss)) < 0) {
243                         verbose(VERB_ALGO, "outgoing tcp:"
244                                 " setsockopt(.. TCP_MAXSEG ..) failed");
245                 }
246 #else
247                 verbose(VERB_ALGO, "outgoing tcp:"
248                         " setsockopt(TCP_MAXSEG) unsupported");
249 #endif /* defined(IPPROTO_TCP) && defined(TCP_MAXSEG) */
250         }
251
252         return s;
253 }
254
255 /** connect tcp connection to addr, 0 on failure */
256 int
257 outnet_tcp_connect(int s, struct sockaddr_storage* addr, socklen_t addrlen)
258 {
259         if(connect(s, (struct sockaddr*)addr, addrlen) == -1) {
260 #ifndef USE_WINSOCK
261 #ifdef EINPROGRESS
262                 if(errno != EINPROGRESS) {
263 #endif
264                         if(tcp_connect_errno_needs_log(
265                                 (struct sockaddr*)addr, addrlen))
266                                 log_err_addr("outgoing tcp: connect",
267                                         strerror(errno), addr, addrlen);
268                         close(s);
269                         return 0;
270 #ifdef EINPROGRESS
271                 }
272 #endif
273 #else /* USE_WINSOCK */
274                 if(WSAGetLastError() != WSAEINPROGRESS &&
275                         WSAGetLastError() != WSAEWOULDBLOCK) {
276                         closesocket(s);
277                         return 0;
278                 }
279 #endif
280         }
281         return 1;
282 }
283
284 /** use next free buffer to service a tcp query */
285 static int
286 outnet_tcp_take_into_use(struct waiting_tcp* w, uint8_t* pkt, size_t pkt_len)
287 {
288         struct pending_tcp* pend = w->outnet->tcp_free;
289         int s;
290         log_assert(pend);
291         log_assert(pkt);
292         log_assert(w->addrlen > 0);
293         /* open socket */
294         s = outnet_get_tcp_fd(&w->addr, w->addrlen, w->outnet->tcp_mss);
295
296         if(!pick_outgoing_tcp(w, s))
297                 return 0;
298
299         fd_set_nonblock(s);
300 #ifdef USE_OSX_MSG_FASTOPEN
301         /* API for fast open is different here. We use a connectx() function and 
302            then writes can happen as normal even using SSL.*/
303         /* connectx requires that the len be set in the sockaddr struct*/
304         struct sockaddr_in *addr_in = (struct sockaddr_in *)&w->addr;
305         addr_in->sin_len = w->addrlen;
306         sa_endpoints_t endpoints;
307         endpoints.sae_srcif = 0;
308         endpoints.sae_srcaddr = NULL;
309         endpoints.sae_srcaddrlen = 0;
310         endpoints.sae_dstaddr = (struct sockaddr *)&w->addr;
311         endpoints.sae_dstaddrlen = w->addrlen;
312         if (connectx(s, &endpoints, SAE_ASSOCID_ANY,  
313                      CONNECT_DATA_IDEMPOTENT | CONNECT_RESUME_ON_READ_WRITE,
314                      NULL, 0, NULL, NULL) == -1) {
315                 /* if fails, failover to connect for OSX 10.10 */
316 #ifdef EINPROGRESS
317                 if(errno != EINPROGRESS) {
318 #else
319                 if(1) {
320 #endif
321                         if(connect(s, (struct sockaddr*)&w->addr, w->addrlen) == -1) {
322 #else /* USE_OSX_MSG_FASTOPEN*/
323 #ifdef USE_MSG_FASTOPEN
324         pend->c->tcp_do_fastopen = 1;
325         /* Only do TFO for TCP in which case no connect() is required here.
326            Don't combine client TFO with SSL, since OpenSSL can't 
327            currently support doing a handshake on fd that already isn't connected*/
328         if (w->outnet->sslctx && w->ssl_upstream) {
329                 if(connect(s, (struct sockaddr*)&w->addr, w->addrlen) == -1) {
330 #else /* USE_MSG_FASTOPEN*/
331         if(connect(s, (struct sockaddr*)&w->addr, w->addrlen) == -1) {
332 #endif /* USE_MSG_FASTOPEN*/
333 #endif /* USE_OSX_MSG_FASTOPEN*/
334 #ifndef USE_WINSOCK
335 #ifdef EINPROGRESS
336                 if(errno != EINPROGRESS) {
337 #else
338                 if(1) {
339 #endif
340                         if(tcp_connect_errno_needs_log(
341                                 (struct sockaddr*)&w->addr, w->addrlen))
342                                 log_err_addr("outgoing tcp: connect",
343                                         strerror(errno), &w->addr, w->addrlen);
344                         close(s);
345 #else /* USE_WINSOCK */
346                 if(WSAGetLastError() != WSAEINPROGRESS &&
347                         WSAGetLastError() != WSAEWOULDBLOCK) {
348                         closesocket(s);
349 #endif
350                         return 0;
351                 }
352         }
353 #ifdef USE_MSG_FASTOPEN
354         }
355 #endif /* USE_MSG_FASTOPEN */
356 #ifdef USE_OSX_MSG_FASTOPEN
357                 }
358         }
359 #endif /* USE_OSX_MSG_FASTOPEN */
360         if(w->outnet->sslctx && w->ssl_upstream) {
361                 pend->c->ssl = outgoing_ssl_fd(w->outnet->sslctx, s);
362                 if(!pend->c->ssl) {
363                         pend->c->fd = s;
364                         comm_point_close(pend->c);
365                         return 0;
366                 }
367 #ifdef USE_WINSOCK
368                 comm_point_tcp_win_bio_cb(pend->c, pend->c->ssl);
369 #endif
370                 pend->c->ssl_shake_state = comm_ssl_shake_write;
371                 if(w->tls_auth_name) {
372 #ifdef HAVE_SSL
373                         (void)SSL_set_tlsext_host_name(pend->c->ssl, w->tls_auth_name);
374 #endif
375                 }
376 #ifdef HAVE_SSL_SET1_HOST
377                 if(w->tls_auth_name) {
378                         SSL_set_verify(pend->c->ssl, SSL_VERIFY_PEER, NULL);
379                         /* setting the hostname makes openssl verify the
380                          * host name in the x509 certificate in the
381                          * SSL connection*/
382                         if(!SSL_set1_host(pend->c->ssl, w->tls_auth_name)) {
383                                 log_err("SSL_set1_host failed");
384                                 pend->c->fd = s;
385                                 SSL_free(pend->c->ssl);
386                                 pend->c->ssl = NULL;
387                                 comm_point_close(pend->c);
388                                 return 0;
389                         }
390                 }
391 #elif defined(HAVE_X509_VERIFY_PARAM_SET1_HOST)
392                 /* openssl 1.0.2 has this function that can be used for
393                  * set1_host like verification */
394                 if(w->tls_auth_name) {
395                         X509_VERIFY_PARAM* param = SSL_get0_param(pend->c->ssl);
396                         X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
397                         if(!X509_VERIFY_PARAM_set1_host(param, w->tls_auth_name, strlen(w->tls_auth_name))) {
398                                 log_err("X509_VERIFY_PARAM_set1_host failed");
399                                 pend->c->fd = s;
400                                 SSL_free(pend->c->ssl);
401                                 pend->c->ssl = NULL;
402                                 comm_point_close(pend->c);
403                                 return 0;
404                         }
405                         SSL_set_verify(pend->c->ssl, SSL_VERIFY_PEER, NULL);
406                 }
407 #endif /* HAVE_SSL_SET1_HOST */
408         }
409         w->pkt = NULL;
410         w->next_waiting = (void*)pend;
411         pend->id = LDNS_ID_WIRE(pkt);
412         w->outnet->num_tcp_outgoing++;
413         w->outnet->tcp_free = pend->next_free;
414         pend->next_free = NULL;
415         pend->query = w;
416         pend->c->repinfo.addrlen = w->addrlen;
417         memcpy(&pend->c->repinfo.addr, &w->addr, w->addrlen);
418         sldns_buffer_clear(pend->c->buffer);
419         sldns_buffer_write(pend->c->buffer, pkt, pkt_len);
420         sldns_buffer_flip(pend->c->buffer);
421         pend->c->tcp_is_reading = 0;
422         pend->c->tcp_byte_count = 0;
423         comm_point_start_listening(pend->c, s, -1);
424         return 1;
425 }
426
427 /** see if buffers can be used to service TCP queries */
428 static void
429 use_free_buffer(struct outside_network* outnet)
430 {
431         struct waiting_tcp* w;
432         while(outnet->tcp_free && outnet->tcp_wait_first 
433                 && !outnet->want_to_quit) {
434                 w = outnet->tcp_wait_first;
435                 outnet->tcp_wait_first = w->next_waiting;
436                 if(outnet->tcp_wait_last == w)
437                         outnet->tcp_wait_last = NULL;
438                 if(!outnet_tcp_take_into_use(w, w->pkt, w->pkt_len)) {
439                         comm_point_callback_type* cb = w->cb;
440                         void* cb_arg = w->cb_arg;
441                         waiting_tcp_delete(w);
442                         fptr_ok(fptr_whitelist_pending_tcp(cb));
443                         (void)(*cb)(NULL, cb_arg, NETEVENT_CLOSED, NULL);
444                 }
445         }
446 }
447
448 /** decommission a tcp buffer, closes commpoint and frees waiting_tcp entry */
449 static void
450 decommission_pending_tcp(struct outside_network* outnet, 
451         struct pending_tcp* pend)
452 {
453         if(pend->c->ssl) {
454 #ifdef HAVE_SSL
455                 SSL_shutdown(pend->c->ssl);
456                 SSL_free(pend->c->ssl);
457                 pend->c->ssl = NULL;
458 #endif
459         }
460         comm_point_close(pend->c);
461         pend->next_free = outnet->tcp_free;
462         outnet->tcp_free = pend;
463         waiting_tcp_delete(pend->query);
464         pend->query = NULL;
465         use_free_buffer(outnet);
466 }
467
468 int 
469 outnet_tcp_cb(struct comm_point* c, void* arg, int error,
470         struct comm_reply *reply_info)
471 {
472         struct pending_tcp* pend = (struct pending_tcp*)arg;
473         struct outside_network* outnet = pend->query->outnet;
474         verbose(VERB_ALGO, "outnettcp cb");
475         if(error != NETEVENT_NOERROR) {
476                 verbose(VERB_QUERY, "outnettcp got tcp error %d", error);
477                 /* pass error below and exit */
478         } else {
479                 /* check ID */
480                 if(sldns_buffer_limit(c->buffer) < sizeof(uint16_t) ||
481                         LDNS_ID_WIRE(sldns_buffer_begin(c->buffer))!=pend->id) {
482                         log_addr(VERB_QUERY, 
483                                 "outnettcp: bad ID in reply, from:",
484                                 &pend->query->addr, pend->query->addrlen);
485                         error = NETEVENT_CLOSED;
486                 }
487         }
488         fptr_ok(fptr_whitelist_pending_tcp(pend->query->cb));
489         (void)(*pend->query->cb)(c, pend->query->cb_arg, error, reply_info);
490         decommission_pending_tcp(outnet, pend);
491         return 0;
492 }
493
494 /** lower use count on pc, see if it can be closed */
495 static void
496 portcomm_loweruse(struct outside_network* outnet, struct port_comm* pc)
497 {
498         struct port_if* pif;
499         pc->num_outstanding--;
500         if(pc->num_outstanding > 0) {
501                 return;
502         }
503         /* close it and replace in unused list */
504         verbose(VERB_ALGO, "close of port %d", pc->number);
505         comm_point_close(pc->cp);
506         pif = pc->pif;
507         log_assert(pif->inuse > 0);
508         pif->avail_ports[pif->avail_total - pif->inuse] = pc->number;
509         pif->inuse--;
510         pif->out[pc->index] = pif->out[pif->inuse];
511         pif->out[pc->index]->index = pc->index;
512         pc->next = outnet->unused_fds;
513         outnet->unused_fds = pc;
514 }
515
516 /** try to send waiting UDP queries */
517 static void
518 outnet_send_wait_udp(struct outside_network* outnet)
519 {
520         struct pending* pend;
521         /* process waiting queries */
522         while(outnet->udp_wait_first && outnet->unused_fds 
523                 && !outnet->want_to_quit) {
524                 pend = outnet->udp_wait_first;
525                 outnet->udp_wait_first = pend->next_waiting;
526                 if(!pend->next_waiting) outnet->udp_wait_last = NULL;
527                 sldns_buffer_clear(outnet->udp_buff);
528                 sldns_buffer_write(outnet->udp_buff, pend->pkt, pend->pkt_len);
529                 sldns_buffer_flip(outnet->udp_buff);
530                 free(pend->pkt); /* freeing now makes get_mem correct */
531                 pend->pkt = NULL; 
532                 pend->pkt_len = 0;
533                 if(!randomize_and_send_udp(pend, outnet->udp_buff,
534                         pend->timeout)) {
535                         /* callback error on pending */
536                         if(pend->cb) {
537                                 fptr_ok(fptr_whitelist_pending_udp(pend->cb));
538                                 (void)(*pend->cb)(outnet->unused_fds->cp, pend->cb_arg, 
539                                         NETEVENT_CLOSED, NULL);
540                         }
541                         pending_delete(outnet, pend);
542                 }
543         }
544 }
545
546 int 
547 outnet_udp_cb(struct comm_point* c, void* arg, int error,
548         struct comm_reply *reply_info)
549 {
550         struct outside_network* outnet = (struct outside_network*)arg;
551         struct pending key;
552         struct pending* p;
553         verbose(VERB_ALGO, "answer cb");
554
555         if(error != NETEVENT_NOERROR) {
556                 verbose(VERB_QUERY, "outnetudp got udp error %d", error);
557                 return 0;
558         }
559         if(sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE) {
560                 verbose(VERB_QUERY, "outnetudp udp too short");
561                 return 0;
562         }
563         log_assert(reply_info);
564
565         /* setup lookup key */
566         key.id = (unsigned)LDNS_ID_WIRE(sldns_buffer_begin(c->buffer));
567         memcpy(&key.addr, &reply_info->addr, reply_info->addrlen);
568         key.addrlen = reply_info->addrlen;
569         verbose(VERB_ALGO, "Incoming reply id = %4.4x", key.id);
570         log_addr(VERB_ALGO, "Incoming reply addr =", 
571                 &reply_info->addr, reply_info->addrlen);
572
573         /* find it, see if this thing is a valid query response */
574         verbose(VERB_ALGO, "lookup size is %d entries", (int)outnet->pending->count);
575         p = (struct pending*)rbtree_search(outnet->pending, &key);
576         if(!p) {
577                 verbose(VERB_QUERY, "received unwanted or unsolicited udp reply dropped.");
578                 log_buf(VERB_ALGO, "dropped message", c->buffer);
579                 outnet->unwanted_replies++;
580                 if(outnet->unwanted_threshold && ++outnet->unwanted_total 
581                         >= outnet->unwanted_threshold) {
582                         log_warn("unwanted reply total reached threshold (%u)"
583                                 " you may be under attack."
584                                 " defensive action: clearing the cache",
585                                 (unsigned)outnet->unwanted_threshold);
586                         fptr_ok(fptr_whitelist_alloc_cleanup(
587                                 outnet->unwanted_action));
588                         (*outnet->unwanted_action)(outnet->unwanted_param);
589                         outnet->unwanted_total = 0;
590                 }
591                 return 0;
592         }
593
594         verbose(VERB_ALGO, "received udp reply.");
595         log_buf(VERB_ALGO, "udp message", c->buffer);
596         if(p->pc->cp != c) {
597                 verbose(VERB_QUERY, "received reply id,addr on wrong port. "
598                         "dropped.");
599                 outnet->unwanted_replies++;
600                 if(outnet->unwanted_threshold && ++outnet->unwanted_total 
601                         >= outnet->unwanted_threshold) {
602                         log_warn("unwanted reply total reached threshold (%u)"
603                                 " you may be under attack."
604                                 " defensive action: clearing the cache",
605                                 (unsigned)outnet->unwanted_threshold);
606                         fptr_ok(fptr_whitelist_alloc_cleanup(
607                                 outnet->unwanted_action));
608                         (*outnet->unwanted_action)(outnet->unwanted_param);
609                         outnet->unwanted_total = 0;
610                 }
611                 return 0;
612         }
613         comm_timer_disable(p->timer);
614         verbose(VERB_ALGO, "outnet handle udp reply");
615         /* delete from tree first in case callback creates a retry */
616         (void)rbtree_delete(outnet->pending, p->node.key);
617         if(p->cb) {
618                 fptr_ok(fptr_whitelist_pending_udp(p->cb));
619                 (void)(*p->cb)(p->pc->cp, p->cb_arg, NETEVENT_NOERROR, reply_info);
620         }
621         portcomm_loweruse(outnet, p->pc);
622         pending_delete(NULL, p);
623         outnet_send_wait_udp(outnet);
624         return 0;
625 }
626
627 /** calculate number of ip4 and ip6 interfaces*/
628 static void 
629 calc_num46(char** ifs, int num_ifs, int do_ip4, int do_ip6, 
630         int* num_ip4, int* num_ip6)
631 {
632         int i;
633         *num_ip4 = 0;
634         *num_ip6 = 0;
635         if(num_ifs <= 0) {
636                 if(do_ip4)
637                         *num_ip4 = 1;
638                 if(do_ip6)
639                         *num_ip6 = 1;
640                 return;
641         }
642         for(i=0; i<num_ifs; i++)
643         {
644                 if(str_is_ip6(ifs[i])) {
645                         if(do_ip6)
646                                 (*num_ip6)++;
647                 } else {
648                         if(do_ip4)
649                                 (*num_ip4)++;
650                 }
651         }
652
653 }
654
655 void
656 pending_udp_timer_delay_cb(void* arg)
657 {
658         struct pending* p = (struct pending*)arg;
659         struct outside_network* outnet = p->outnet;
660         verbose(VERB_ALGO, "timeout udp with delay");
661         portcomm_loweruse(outnet, p->pc);
662         pending_delete(outnet, p);
663         outnet_send_wait_udp(outnet);
664 }
665
666 void 
667 pending_udp_timer_cb(void *arg)
668 {
669         struct pending* p = (struct pending*)arg;
670         struct outside_network* outnet = p->outnet;
671         /* it timed out */
672         verbose(VERB_ALGO, "timeout udp");
673         if(p->cb) {
674                 fptr_ok(fptr_whitelist_pending_udp(p->cb));
675                 (void)(*p->cb)(p->pc->cp, p->cb_arg, NETEVENT_TIMEOUT, NULL);
676         }
677         /* if delayclose, keep port open for a longer time.
678          * But if the udpwaitlist exists, then we are struggling to
679          * keep up with demand for sockets, so do not wait, but service
680          * the customer (customer service more important than portICMPs) */
681         if(outnet->delayclose && !outnet->udp_wait_first) {
682                 p->cb = NULL;
683                 p->timer->callback = &pending_udp_timer_delay_cb;
684                 comm_timer_set(p->timer, &outnet->delay_tv);
685                 return;
686         }
687         portcomm_loweruse(outnet, p->pc);
688         pending_delete(outnet, p);
689         outnet_send_wait_udp(outnet);
690 }
691
692 /** create pending_tcp buffers */
693 static int
694 create_pending_tcp(struct outside_network* outnet, size_t bufsize)
695 {
696         size_t i;
697         if(outnet->num_tcp == 0)
698                 return 1; /* no tcp needed, nothing to do */
699         if(!(outnet->tcp_conns = (struct pending_tcp **)calloc(
700                         outnet->num_tcp, sizeof(struct pending_tcp*))))
701                 return 0;
702         for(i=0; i<outnet->num_tcp; i++) {
703                 if(!(outnet->tcp_conns[i] = (struct pending_tcp*)calloc(1, 
704                         sizeof(struct pending_tcp))))
705                         return 0;
706                 outnet->tcp_conns[i]->next_free = outnet->tcp_free;
707                 outnet->tcp_free = outnet->tcp_conns[i];
708                 outnet->tcp_conns[i]->c = comm_point_create_tcp_out(
709                         outnet->base, bufsize, outnet_tcp_cb, 
710                         outnet->tcp_conns[i]);
711                 if(!outnet->tcp_conns[i]->c)
712                         return 0;
713         }
714         return 1;
715 }
716
717 /** setup an outgoing interface, ready address */
718 static int setup_if(struct port_if* pif, const char* addrstr, 
719         int* avail, int numavail, size_t numfd)
720 {
721         pif->avail_total = numavail;
722         pif->avail_ports = (int*)memdup(avail, (size_t)numavail*sizeof(int));
723         if(!pif->avail_ports)
724                 return 0;
725         if(!ipstrtoaddr(addrstr, UNBOUND_DNS_PORT, &pif->addr, &pif->addrlen) &&
726            !netblockstrtoaddr(addrstr, UNBOUND_DNS_PORT,
727                               &pif->addr, &pif->addrlen, &pif->pfxlen))
728                 return 0;
729         pif->maxout = (int)numfd;
730         pif->inuse = 0;
731         pif->out = (struct port_comm**)calloc(numfd, 
732                 sizeof(struct port_comm*));
733         if(!pif->out)
734                 return 0;
735         return 1;
736 }
737
738 struct outside_network* 
739 outside_network_create(struct comm_base *base, size_t bufsize, 
740         size_t num_ports, char** ifs, int num_ifs, int do_ip4, 
741         int do_ip6, size_t num_tcp, struct infra_cache* infra,
742         struct ub_randstate* rnd, int use_caps_for_id, int* availports, 
743         int numavailports, size_t unwanted_threshold, int tcp_mss,
744         void (*unwanted_action)(void*), void* unwanted_param, int do_udp,
745         void* sslctx, int delayclose, struct dt_env* dtenv)
746 {
747         struct outside_network* outnet = (struct outside_network*)
748                 calloc(1, sizeof(struct outside_network));
749         size_t k;
750         if(!outnet) {
751                 log_err("malloc failed");
752                 return NULL;
753         }
754         comm_base_timept(base, &outnet->now_secs, &outnet->now_tv);
755         outnet->base = base;
756         outnet->num_tcp = num_tcp;
757         outnet->num_tcp_outgoing = 0;
758         outnet->infra = infra;
759         outnet->rnd = rnd;
760         outnet->sslctx = sslctx;
761 #ifdef USE_DNSTAP
762         outnet->dtenv = dtenv;
763 #else
764         (void)dtenv;
765 #endif
766         outnet->svcd_overhead = 0;
767         outnet->want_to_quit = 0;
768         outnet->unwanted_threshold = unwanted_threshold;
769         outnet->unwanted_action = unwanted_action;
770         outnet->unwanted_param = unwanted_param;
771         outnet->use_caps_for_id = use_caps_for_id;
772         outnet->do_udp = do_udp;
773         outnet->tcp_mss = tcp_mss;
774 #ifndef S_SPLINT_S
775         if(delayclose) {
776                 outnet->delayclose = 1;
777                 outnet->delay_tv.tv_sec = delayclose/1000;
778                 outnet->delay_tv.tv_usec = (delayclose%1000)*1000;
779         }
780 #endif
781         if(numavailports == 0 || num_ports == 0) {
782                 log_err("no outgoing ports available");
783                 outside_network_delete(outnet);
784                 return NULL;
785         }
786 #ifndef INET6
787         do_ip6 = 0;
788 #endif
789         calc_num46(ifs, num_ifs, do_ip4, do_ip6, 
790                 &outnet->num_ip4, &outnet->num_ip6);
791         if(outnet->num_ip4 != 0) {
792                 if(!(outnet->ip4_ifs = (struct port_if*)calloc(
793                         (size_t)outnet->num_ip4, sizeof(struct port_if)))) {
794                         log_err("malloc failed");
795                         outside_network_delete(outnet);
796                         return NULL;
797                 }
798         }
799         if(outnet->num_ip6 != 0) {
800                 if(!(outnet->ip6_ifs = (struct port_if*)calloc(
801                         (size_t)outnet->num_ip6, sizeof(struct port_if)))) {
802                         log_err("malloc failed");
803                         outside_network_delete(outnet);
804                         return NULL;
805                 }
806         }
807         if(     !(outnet->udp_buff = sldns_buffer_new(bufsize)) ||
808                 !(outnet->pending = rbtree_create(pending_cmp)) ||
809                 !(outnet->serviced = rbtree_create(serviced_cmp)) ||
810                 !create_pending_tcp(outnet, bufsize)) {
811                 log_err("malloc failed");
812                 outside_network_delete(outnet);
813                 return NULL;
814         }
815
816         /* allocate commpoints */
817         for(k=0; k<num_ports; k++) {
818                 struct port_comm* pc;
819                 pc = (struct port_comm*)calloc(1, sizeof(*pc));
820                 if(!pc) {
821                         log_err("malloc failed");
822                         outside_network_delete(outnet);
823                         return NULL;
824                 }
825                 pc->cp = comm_point_create_udp(outnet->base, -1, 
826                         outnet->udp_buff, outnet_udp_cb, outnet);
827                 if(!pc->cp) {
828                         log_err("malloc failed");
829                         free(pc);
830                         outside_network_delete(outnet);
831                         return NULL;
832                 }
833                 pc->next = outnet->unused_fds;
834                 outnet->unused_fds = pc;
835         }
836
837         /* allocate interfaces */
838         if(num_ifs == 0) {
839                 if(do_ip4 && !setup_if(&outnet->ip4_ifs[0], "0.0.0.0", 
840                         availports, numavailports, num_ports)) {
841                         log_err("malloc failed");
842                         outside_network_delete(outnet);
843                         return NULL;
844                 }
845                 if(do_ip6 && !setup_if(&outnet->ip6_ifs[0], "::", 
846                         availports, numavailports, num_ports)) {
847                         log_err("malloc failed");
848                         outside_network_delete(outnet);
849                         return NULL;
850                 }
851         } else {
852                 size_t done_4 = 0, done_6 = 0;
853                 int i;
854                 for(i=0; i<num_ifs; i++) {
855                         if(str_is_ip6(ifs[i]) && do_ip6) {
856                                 if(!setup_if(&outnet->ip6_ifs[done_6], ifs[i],
857                                         availports, numavailports, num_ports)){
858                                         log_err("malloc failed");
859                                         outside_network_delete(outnet);
860                                         return NULL;
861                                 }
862                                 done_6++;
863                         }
864                         if(!str_is_ip6(ifs[i]) && do_ip4) {
865                                 if(!setup_if(&outnet->ip4_ifs[done_4], ifs[i],
866                                         availports, numavailports, num_ports)){
867                                         log_err("malloc failed");
868                                         outside_network_delete(outnet);
869                                         return NULL;
870                                 }
871                                 done_4++;
872                         }
873                 }
874         }
875         return outnet;
876 }
877
878 /** helper pending delete */
879 static void
880 pending_node_del(rbnode_type* node, void* arg)
881 {
882         struct pending* pend = (struct pending*)node;
883         struct outside_network* outnet = (struct outside_network*)arg;
884         pending_delete(outnet, pend);
885 }
886
887 /** helper serviced delete */
888 static void
889 serviced_node_del(rbnode_type* node, void* ATTR_UNUSED(arg))
890 {
891         struct serviced_query* sq = (struct serviced_query*)node;
892         struct service_callback* p = sq->cblist, *np;
893         free(sq->qbuf);
894         free(sq->zone);
895         free(sq->tls_auth_name);
896         edns_opt_list_free(sq->opt_list);
897         while(p) {
898                 np = p->next;
899                 free(p);
900                 p = np;
901         }
902         free(sq);
903 }
904
905 void 
906 outside_network_quit_prepare(struct outside_network* outnet)
907 {
908         if(!outnet)
909                 return;
910         /* prevent queued items from being sent */
911         outnet->want_to_quit = 1; 
912 }
913
914 void 
915 outside_network_delete(struct outside_network* outnet)
916 {
917         if(!outnet)
918                 return;
919         outnet->want_to_quit = 1;
920         /* check every element, since we can be called on malloc error */
921         if(outnet->pending) {
922                 /* free pending elements, but do no unlink from tree. */
923                 traverse_postorder(outnet->pending, pending_node_del, NULL);
924                 free(outnet->pending);
925         }
926         if(outnet->serviced) {
927                 traverse_postorder(outnet->serviced, serviced_node_del, NULL);
928                 free(outnet->serviced);
929         }
930         if(outnet->udp_buff)
931                 sldns_buffer_free(outnet->udp_buff);
932         if(outnet->unused_fds) {
933                 struct port_comm* p = outnet->unused_fds, *np;
934                 while(p) {
935                         np = p->next;
936                         comm_point_delete(p->cp);
937                         free(p);
938                         p = np;
939                 }
940                 outnet->unused_fds = NULL;
941         }
942         if(outnet->ip4_ifs) {
943                 int i, k;
944                 for(i=0; i<outnet->num_ip4; i++) {
945                         for(k=0; k<outnet->ip4_ifs[i].inuse; k++) {
946                                 struct port_comm* pc = outnet->ip4_ifs[i].
947                                         out[k];
948                                 comm_point_delete(pc->cp);
949                                 free(pc);
950                         }
951                         free(outnet->ip4_ifs[i].avail_ports);
952                         free(outnet->ip4_ifs[i].out);
953                 }
954                 free(outnet->ip4_ifs);
955         }
956         if(outnet->ip6_ifs) {
957                 int i, k;
958                 for(i=0; i<outnet->num_ip6; i++) {
959                         for(k=0; k<outnet->ip6_ifs[i].inuse; k++) {
960                                 struct port_comm* pc = outnet->ip6_ifs[i].
961                                         out[k];
962                                 comm_point_delete(pc->cp);
963                                 free(pc);
964                         }
965                         free(outnet->ip6_ifs[i].avail_ports);
966                         free(outnet->ip6_ifs[i].out);
967                 }
968                 free(outnet->ip6_ifs);
969         }
970         if(outnet->tcp_conns) {
971                 size_t i;
972                 for(i=0; i<outnet->num_tcp; i++)
973                         if(outnet->tcp_conns[i]) {
974                                 comm_point_delete(outnet->tcp_conns[i]->c);
975                                 waiting_tcp_delete(outnet->tcp_conns[i]->query);
976                                 free(outnet->tcp_conns[i]);
977                         }
978                 free(outnet->tcp_conns);
979         }
980         if(outnet->tcp_wait_first) {
981                 struct waiting_tcp* p = outnet->tcp_wait_first, *np;
982                 while(p) {
983                         np = p->next_waiting;
984                         waiting_tcp_delete(p);
985                         p = np;
986                 }
987         }
988         if(outnet->udp_wait_first) {
989                 struct pending* p = outnet->udp_wait_first, *np;
990                 while(p) {
991                         np = p->next_waiting;
992                         pending_delete(NULL, p);
993                         p = np;
994                 }
995         }
996         free(outnet);
997 }
998
999 void 
1000 pending_delete(struct outside_network* outnet, struct pending* p)
1001 {
1002         if(!p)
1003                 return;
1004         if(outnet && outnet->udp_wait_first &&
1005                 (p->next_waiting || p == outnet->udp_wait_last) ) {
1006                 /* delete from waiting list, if it is in the waiting list */
1007                 struct pending* prev = NULL, *x = outnet->udp_wait_first;
1008                 while(x && x != p) {
1009                         prev = x;
1010                         x = x->next_waiting;
1011                 }
1012                 if(x) {
1013                         log_assert(x == p);
1014                         if(prev)
1015                                 prev->next_waiting = p->next_waiting;
1016                         else    outnet->udp_wait_first = p->next_waiting;
1017                         if(outnet->udp_wait_last == p)
1018                                 outnet->udp_wait_last = prev;
1019                 }
1020         }
1021         if(outnet) {
1022                 (void)rbtree_delete(outnet->pending, p->node.key);
1023         }
1024         if(p->timer)
1025                 comm_timer_delete(p->timer);
1026         free(p->pkt);
1027         free(p);
1028 }
1029
1030 static void
1031 sai6_putrandom(struct sockaddr_in6 *sa, int pfxlen, struct ub_randstate *rnd)
1032 {
1033         int i, last;
1034         if(!(pfxlen > 0 && pfxlen < 128))
1035                 return;
1036         for(i = 0; i < (128 - pfxlen) / 8; i++) {
1037                 sa->sin6_addr.s6_addr[15-i] = (uint8_t)ub_random_max(rnd, 256);
1038         }
1039         last = pfxlen & 7;
1040         if(last != 0) {
1041                 sa->sin6_addr.s6_addr[15-i] |=
1042                         ((0xFF >> last) & ub_random_max(rnd, 256));
1043         }
1044 }
1045
1046 /**
1047  * Try to open a UDP socket for outgoing communication.
1048  * Sets sockets options as needed.
1049  * @param addr: socket address.
1050  * @param addrlen: length of address.
1051  * @param pfxlen: length of network prefix (for address randomisation).
1052  * @param port: port override for addr.
1053  * @param inuse: if -1 is returned, this bool means the port was in use.
1054  * @param rnd: random state (for address randomisation).
1055  * @return fd or -1
1056  */
1057 static int
1058 udp_sockport(struct sockaddr_storage* addr, socklen_t addrlen, int pfxlen,
1059         int port, int* inuse, struct ub_randstate* rnd)
1060 {
1061         int fd, noproto;
1062         if(addr_is_ip6(addr, addrlen)) {
1063                 int freebind = 0;
1064                 struct sockaddr_in6 sa = *(struct sockaddr_in6*)addr;
1065                 sa.sin6_port = (in_port_t)htons((uint16_t)port);
1066                 sa.sin6_flowinfo = 0;
1067                 sa.sin6_scope_id = 0;
1068                 if(pfxlen != 0) {
1069                         freebind = 1;
1070                         sai6_putrandom(&sa, pfxlen, rnd);
1071                 }
1072                 fd = create_udp_sock(AF_INET6, SOCK_DGRAM, 
1073                         (struct sockaddr*)&sa, addrlen, 1, inuse, &noproto,
1074                         0, 0, 0, NULL, 0, freebind, 0);
1075         } else {
1076                 struct sockaddr_in* sa = (struct sockaddr_in*)addr;
1077                 sa->sin_port = (in_port_t)htons((uint16_t)port);
1078                 fd = create_udp_sock(AF_INET, SOCK_DGRAM, 
1079                         (struct sockaddr*)addr, addrlen, 1, inuse, &noproto,
1080                         0, 0, 0, NULL, 0, 0, 0);
1081         }
1082         return fd;
1083 }
1084
1085 /** Select random ID */
1086 static int
1087 select_id(struct outside_network* outnet, struct pending* pend,
1088         sldns_buffer* packet)
1089 {
1090         int id_tries = 0;
1091         pend->id = ((unsigned)ub_random(outnet->rnd)>>8) & 0xffff;
1092         LDNS_ID_SET(sldns_buffer_begin(packet), pend->id);
1093
1094         /* insert in tree */
1095         pend->node.key = pend;
1096         while(!rbtree_insert(outnet->pending, &pend->node)) {
1097                 /* change ID to avoid collision */
1098                 pend->id = ((unsigned)ub_random(outnet->rnd)>>8) & 0xffff;
1099                 LDNS_ID_SET(sldns_buffer_begin(packet), pend->id);
1100                 id_tries++;
1101                 if(id_tries == MAX_ID_RETRY) {
1102                         pend->id=99999; /* non existant ID */
1103                         log_err("failed to generate unique ID, drop msg");
1104                         return 0;
1105                 }
1106         }
1107         verbose(VERB_ALGO, "inserted new pending reply id=%4.4x", pend->id);
1108         return 1;
1109 }
1110
1111 /** Select random interface and port */
1112 static int
1113 select_ifport(struct outside_network* outnet, struct pending* pend,
1114         int num_if, struct port_if* ifs)
1115 {
1116         int my_if, my_port, fd, portno, inuse, tries=0;
1117         struct port_if* pif;
1118         /* randomly select interface and port */
1119         if(num_if == 0) {
1120                 verbose(VERB_QUERY, "Need to send query but have no "
1121                         "outgoing interfaces of that family");
1122                 return 0;
1123         }
1124         log_assert(outnet->unused_fds);
1125         tries = 0;
1126         while(1) {
1127                 my_if = ub_random_max(outnet->rnd, num_if);
1128                 pif = &ifs[my_if];
1129                 my_port = ub_random_max(outnet->rnd, pif->avail_total);
1130                 if(my_port < pif->inuse) {
1131                         /* port already open */
1132                         pend->pc = pif->out[my_port];
1133                         verbose(VERB_ALGO, "using UDP if=%d port=%d", 
1134                                 my_if, pend->pc->number);
1135                         break;
1136                 }
1137                 /* try to open new port, if fails, loop to try again */
1138                 log_assert(pif->inuse < pif->maxout);
1139                 portno = pif->avail_ports[my_port - pif->inuse];
1140                 fd = udp_sockport(&pif->addr, pif->addrlen, pif->pfxlen,
1141                         portno, &inuse, outnet->rnd);
1142                 if(fd == -1 && !inuse) {
1143                         /* nonrecoverable error making socket */
1144                         return 0;
1145                 }
1146                 if(fd != -1) {
1147                         verbose(VERB_ALGO, "opened UDP if=%d port=%d", 
1148                                 my_if, portno);
1149                         /* grab fd */
1150                         pend->pc = outnet->unused_fds;
1151                         outnet->unused_fds = pend->pc->next;
1152
1153                         /* setup portcomm */
1154                         pend->pc->next = NULL;
1155                         pend->pc->number = portno;
1156                         pend->pc->pif = pif;
1157                         pend->pc->index = pif->inuse;
1158                         pend->pc->num_outstanding = 0;
1159                         comm_point_start_listening(pend->pc->cp, fd, -1);
1160
1161                         /* grab port in interface */
1162                         pif->out[pif->inuse] = pend->pc;
1163                         pif->avail_ports[my_port - pif->inuse] =
1164                                 pif->avail_ports[pif->avail_total-pif->inuse-1];
1165                         pif->inuse++;
1166                         break;
1167                 }
1168                 /* failed, already in use */
1169                 verbose(VERB_QUERY, "port %d in use, trying another", portno);
1170                 tries++;
1171                 if(tries == MAX_PORT_RETRY) {
1172                         log_err("failed to find an open port, drop msg");
1173                         return 0;
1174                 }
1175         }
1176         log_assert(pend->pc);
1177         pend->pc->num_outstanding++;
1178
1179         return 1;
1180 }
1181
1182 static int
1183 randomize_and_send_udp(struct pending* pend, sldns_buffer* packet, int timeout)
1184 {
1185         struct timeval tv;
1186         struct outside_network* outnet = pend->sq->outnet;
1187
1188         /* select id */
1189         if(!select_id(outnet, pend, packet)) {
1190                 return 0;
1191         }
1192
1193         /* select src_if, port */
1194         if(addr_is_ip6(&pend->addr, pend->addrlen)) {
1195                 if(!select_ifport(outnet, pend, 
1196                         outnet->num_ip6, outnet->ip6_ifs))
1197                         return 0;
1198         } else {
1199                 if(!select_ifport(outnet, pend, 
1200                         outnet->num_ip4, outnet->ip4_ifs))
1201                         return 0;
1202         }
1203         log_assert(pend->pc && pend->pc->cp);
1204
1205         /* send it over the commlink */
1206         if(!comm_point_send_udp_msg(pend->pc->cp, packet, 
1207                 (struct sockaddr*)&pend->addr, pend->addrlen)) {
1208                 portcomm_loweruse(outnet, pend->pc);
1209                 return 0;
1210         }
1211
1212         /* system calls to set timeout after sending UDP to make roundtrip
1213            smaller. */
1214 #ifndef S_SPLINT_S
1215         tv.tv_sec = timeout/1000;
1216         tv.tv_usec = (timeout%1000)*1000;
1217 #endif
1218         comm_timer_set(pend->timer, &tv);
1219
1220 #ifdef USE_DNSTAP
1221         if(outnet->dtenv &&
1222            (outnet->dtenv->log_resolver_query_messages ||
1223             outnet->dtenv->log_forwarder_query_messages))
1224                 dt_msg_send_outside_query(outnet->dtenv, &pend->addr, comm_udp,
1225                 pend->sq->zone, pend->sq->zonelen, packet);
1226 #endif
1227         return 1;
1228 }
1229
1230 struct pending* 
1231 pending_udp_query(struct serviced_query* sq, struct sldns_buffer* packet,
1232         int timeout, comm_point_callback_type* cb, void* cb_arg)
1233 {
1234         struct pending* pend = (struct pending*)calloc(1, sizeof(*pend));
1235         if(!pend) return NULL;
1236         pend->outnet = sq->outnet;
1237         pend->sq = sq;
1238         pend->addrlen = sq->addrlen;
1239         memmove(&pend->addr, &sq->addr, sq->addrlen);
1240         pend->cb = cb;
1241         pend->cb_arg = cb_arg;
1242         pend->node.key = pend;
1243         pend->timer = comm_timer_create(sq->outnet->base, pending_udp_timer_cb,
1244                 pend);
1245         if(!pend->timer) {
1246                 free(pend);
1247                 return NULL;
1248         }
1249
1250         if(sq->outnet->unused_fds == NULL) {
1251                 /* no unused fd, cannot create a new port (randomly) */
1252                 verbose(VERB_ALGO, "no fds available, udp query waiting");
1253                 pend->timeout = timeout;
1254                 pend->pkt_len = sldns_buffer_limit(packet);
1255                 pend->pkt = (uint8_t*)memdup(sldns_buffer_begin(packet),
1256                         pend->pkt_len);
1257                 if(!pend->pkt) {
1258                         comm_timer_delete(pend->timer);
1259                         free(pend);
1260                         return NULL;
1261                 }
1262                 /* put at end of waiting list */
1263                 if(sq->outnet->udp_wait_last)
1264                         sq->outnet->udp_wait_last->next_waiting = pend;
1265                 else 
1266                         sq->outnet->udp_wait_first = pend;
1267                 sq->outnet->udp_wait_last = pend;
1268                 return pend;
1269         }
1270         if(!randomize_and_send_udp(pend, packet, timeout)) {
1271                 pending_delete(sq->outnet, pend);
1272                 return NULL;
1273         }
1274         return pend;
1275 }
1276
1277 void
1278 outnet_tcptimer(void* arg)
1279 {
1280         struct waiting_tcp* w = (struct waiting_tcp*)arg;
1281         struct outside_network* outnet = w->outnet;
1282         comm_point_callback_type* cb;
1283         void* cb_arg;
1284         if(w->pkt) {
1285                 /* it is on the waiting list */
1286                 waiting_list_remove(outnet, w);
1287         } else {
1288                 /* it was in use */
1289                 struct pending_tcp* pend=(struct pending_tcp*)w->next_waiting;
1290                 if(pend->c->ssl) {
1291 #ifdef HAVE_SSL
1292                         SSL_shutdown(pend->c->ssl);
1293                         SSL_free(pend->c->ssl);
1294                         pend->c->ssl = NULL;
1295 #endif
1296                 }
1297                 comm_point_close(pend->c);
1298                 pend->query = NULL;
1299                 pend->next_free = outnet->tcp_free;
1300                 outnet->tcp_free = pend;
1301         }
1302         cb = w->cb;
1303         cb_arg = w->cb_arg;
1304         waiting_tcp_delete(w);
1305         fptr_ok(fptr_whitelist_pending_tcp(cb));
1306         (void)(*cb)(NULL, cb_arg, NETEVENT_TIMEOUT, NULL);
1307         use_free_buffer(outnet);
1308 }
1309
1310 struct waiting_tcp*
1311 pending_tcp_query(struct serviced_query* sq, sldns_buffer* packet,
1312         int timeout, comm_point_callback_type* callback, void* callback_arg)
1313 {
1314         struct pending_tcp* pend = sq->outnet->tcp_free;
1315         struct waiting_tcp* w;
1316         struct timeval tv;
1317         uint16_t id;
1318         /* if no buffer is free allocate space to store query */
1319         w = (struct waiting_tcp*)malloc(sizeof(struct waiting_tcp) 
1320                 + (pend?0:sldns_buffer_limit(packet)));
1321         if(!w) {
1322                 return NULL;
1323         }
1324         if(!(w->timer = comm_timer_create(sq->outnet->base, outnet_tcptimer, w))) {
1325                 free(w);
1326                 return NULL;
1327         }
1328         w->pkt = NULL;
1329         w->pkt_len = 0;
1330         id = ((unsigned)ub_random(sq->outnet->rnd)>>8) & 0xffff;
1331         LDNS_ID_SET(sldns_buffer_begin(packet), id);
1332         memcpy(&w->addr, &sq->addr, sq->addrlen);
1333         w->addrlen = sq->addrlen;
1334         w->outnet = sq->outnet;
1335         w->cb = callback;
1336         w->cb_arg = callback_arg;
1337         w->ssl_upstream = sq->ssl_upstream;
1338         w->tls_auth_name = sq->tls_auth_name;
1339 #ifndef S_SPLINT_S
1340         tv.tv_sec = timeout/1000;
1341         tv.tv_usec = (timeout%1000)*1000;
1342 #endif
1343         comm_timer_set(w->timer, &tv);
1344         if(pend) {
1345                 /* we have a buffer available right now */
1346                 if(!outnet_tcp_take_into_use(w, sldns_buffer_begin(packet),
1347                         sldns_buffer_limit(packet))) {
1348                         waiting_tcp_delete(w);
1349                         return NULL;
1350                 }
1351 #ifdef USE_DNSTAP
1352                 if(sq->outnet->dtenv &&
1353                    (sq->outnet->dtenv->log_resolver_query_messages ||
1354                     sq->outnet->dtenv->log_forwarder_query_messages))
1355                 dt_msg_send_outside_query(sq->outnet->dtenv, &sq->addr,
1356                 comm_tcp, sq->zone, sq->zonelen, packet);
1357 #endif
1358         } else {
1359                 /* queue up */
1360                 w->pkt = (uint8_t*)w + sizeof(struct waiting_tcp);
1361                 w->pkt_len = sldns_buffer_limit(packet);
1362                 memmove(w->pkt, sldns_buffer_begin(packet), w->pkt_len);
1363                 w->next_waiting = NULL;
1364                 if(sq->outnet->tcp_wait_last)
1365                         sq->outnet->tcp_wait_last->next_waiting = w;
1366                 else    sq->outnet->tcp_wait_first = w;
1367                 sq->outnet->tcp_wait_last = w;
1368         }
1369         return w;
1370 }
1371
1372 /** create query for serviced queries */
1373 static void
1374 serviced_gen_query(sldns_buffer* buff, uint8_t* qname, size_t qnamelen, 
1375         uint16_t qtype, uint16_t qclass, uint16_t flags)
1376 {
1377         sldns_buffer_clear(buff);
1378         /* skip id */
1379         sldns_buffer_write_u16(buff, flags);
1380         sldns_buffer_write_u16(buff, 1); /* qdcount */
1381         sldns_buffer_write_u16(buff, 0); /* ancount */
1382         sldns_buffer_write_u16(buff, 0); /* nscount */
1383         sldns_buffer_write_u16(buff, 0); /* arcount */
1384         sldns_buffer_write(buff, qname, qnamelen);
1385         sldns_buffer_write_u16(buff, qtype);
1386         sldns_buffer_write_u16(buff, qclass);
1387         sldns_buffer_flip(buff);
1388 }
1389
1390 /** lookup serviced query in serviced query rbtree */
1391 static struct serviced_query*
1392 lookup_serviced(struct outside_network* outnet, sldns_buffer* buff, int dnssec,
1393         struct sockaddr_storage* addr, socklen_t addrlen,
1394         struct edns_option* opt_list)
1395 {
1396         struct serviced_query key;
1397         key.node.key = &key;
1398         key.qbuf = sldns_buffer_begin(buff);
1399         key.qbuflen = sldns_buffer_limit(buff);
1400         key.dnssec = dnssec;
1401         memcpy(&key.addr, addr, addrlen);
1402         key.addrlen = addrlen;
1403         key.outnet = outnet;
1404         key.opt_list = opt_list;
1405         return (struct serviced_query*)rbtree_search(outnet->serviced, &key);
1406 }
1407
1408 /** Create new serviced entry */
1409 static struct serviced_query*
1410 serviced_create(struct outside_network* outnet, sldns_buffer* buff, int dnssec,
1411         int want_dnssec, int nocaps, int tcp_upstream, int ssl_upstream,
1412         char* tls_auth_name, struct sockaddr_storage* addr, socklen_t addrlen,
1413         uint8_t* zone, size_t zonelen, int qtype, struct edns_option* opt_list)
1414 {
1415         struct serviced_query* sq = (struct serviced_query*)malloc(sizeof(*sq));
1416 #ifdef UNBOUND_DEBUG
1417         rbnode_type* ins;
1418 #endif
1419         if(!sq) 
1420                 return NULL;
1421         sq->node.key = sq;
1422         sq->qbuf = memdup(sldns_buffer_begin(buff), sldns_buffer_limit(buff));
1423         if(!sq->qbuf) {
1424                 free(sq);
1425                 return NULL;
1426         }
1427         sq->qbuflen = sldns_buffer_limit(buff);
1428         sq->zone = memdup(zone, zonelen);
1429         if(!sq->zone) {
1430                 free(sq->qbuf);
1431                 free(sq);
1432                 return NULL;
1433         }
1434         sq->zonelen = zonelen;
1435         sq->qtype = qtype;
1436         sq->dnssec = dnssec;
1437         sq->want_dnssec = want_dnssec;
1438         sq->nocaps = nocaps;
1439         sq->tcp_upstream = tcp_upstream;
1440         sq->ssl_upstream = ssl_upstream;
1441         if(tls_auth_name) {
1442                 sq->tls_auth_name = strdup(tls_auth_name);
1443                 if(!sq->tls_auth_name) {
1444                         free(sq->zone);
1445                         free(sq->qbuf);
1446                         free(sq);
1447                         return NULL;
1448                 }
1449         } else {
1450                 sq->tls_auth_name = NULL;
1451         }
1452         memcpy(&sq->addr, addr, addrlen);
1453         sq->addrlen = addrlen;
1454         sq->opt_list = NULL;
1455         if(opt_list) {
1456                 sq->opt_list = edns_opt_copy_alloc(opt_list);
1457                 if(!sq->opt_list) {
1458                         free(sq->tls_auth_name);
1459                         free(sq->zone);
1460                         free(sq->qbuf);
1461                         free(sq);
1462                         return NULL;
1463                 }
1464         }
1465         sq->outnet = outnet;
1466         sq->cblist = NULL;
1467         sq->pending = NULL;
1468         sq->status = serviced_initial;
1469         sq->retry = 0;
1470         sq->to_be_deleted = 0;
1471 #ifdef UNBOUND_DEBUG
1472         ins = 
1473 #else
1474         (void)
1475 #endif
1476         rbtree_insert(outnet->serviced, &sq->node);
1477         log_assert(ins != NULL); /* must not be already present */
1478         return sq;
1479 }
1480
1481 /** remove waiting tcp from the outnet waiting list */
1482 static void
1483 waiting_list_remove(struct outside_network* outnet, struct waiting_tcp* w)
1484 {
1485         struct waiting_tcp* p = outnet->tcp_wait_first, *prev = NULL;
1486         while(p) {
1487                 if(p == w) {
1488                         /* remove w */
1489                         if(prev)
1490                                 prev->next_waiting = w->next_waiting;
1491                         else    outnet->tcp_wait_first = w->next_waiting;
1492                         if(outnet->tcp_wait_last == w)
1493                                 outnet->tcp_wait_last = prev;
1494                         return;
1495                 }
1496                 prev = p;
1497                 p = p->next_waiting;
1498         }
1499 }
1500
1501 /** cleanup serviced query entry */
1502 static void
1503 serviced_delete(struct serviced_query* sq)
1504 {
1505         if(sq->pending) {
1506                 /* clear up the pending query */
1507                 if(sq->status == serviced_query_UDP_EDNS ||
1508                         sq->status == serviced_query_UDP ||
1509                         sq->status == serviced_query_UDP_EDNS_FRAG ||
1510                         sq->status == serviced_query_UDP_EDNS_fallback) {
1511                         struct pending* p = (struct pending*)sq->pending;
1512                         if(p->pc)
1513                                 portcomm_loweruse(sq->outnet, p->pc);
1514                         pending_delete(sq->outnet, p);
1515                         /* this call can cause reentrant calls back into the
1516                          * mesh */
1517                         outnet_send_wait_udp(sq->outnet);
1518                 } else {
1519                         struct waiting_tcp* p = (struct waiting_tcp*)
1520                                 sq->pending;
1521                         if(p->pkt == NULL) {
1522                                 decommission_pending_tcp(sq->outnet, 
1523                                         (struct pending_tcp*)p->next_waiting);
1524                         } else {
1525                                 waiting_list_remove(sq->outnet, p);
1526                                 waiting_tcp_delete(p);
1527                         }
1528                 }
1529         }
1530         /* does not delete from tree, caller has to do that */
1531         serviced_node_del(&sq->node, NULL);
1532 }
1533
1534 /** perturb a dname capitalization randomly */
1535 static void
1536 serviced_perturb_qname(struct ub_randstate* rnd, uint8_t* qbuf, size_t len)
1537 {
1538         uint8_t lablen;
1539         uint8_t* d = qbuf + 10;
1540         long int random = 0;
1541         int bits = 0;
1542         log_assert(len >= 10 + 5 /* offset qname, root, qtype, qclass */);
1543         (void)len;
1544         lablen = *d++;
1545         while(lablen) {
1546                 while(lablen--) {
1547                         /* only perturb A-Z, a-z */
1548                         if(isalpha((unsigned char)*d)) {
1549                                 /* get a random bit */  
1550                                 if(bits == 0) {
1551                                         random = ub_random(rnd);
1552                                         bits = 30;
1553                                 }
1554                                 if(random & 0x1) {
1555                                         *d = (uint8_t)toupper((unsigned char)*d);
1556                                 } else {
1557                                         *d = (uint8_t)tolower((unsigned char)*d);
1558                                 }
1559                                 random >>= 1;
1560                                 bits--;
1561                         }
1562                         d++;
1563                 }
1564                 lablen = *d++;
1565         }
1566         if(verbosity >= VERB_ALGO) {
1567                 char buf[LDNS_MAX_DOMAINLEN+1];
1568                 dname_str(qbuf+10, buf);
1569                 verbose(VERB_ALGO, "qname perturbed to %s", buf);
1570         }
1571 }
1572
1573 /** put serviced query into a buffer */
1574 static void
1575 serviced_encode(struct serviced_query* sq, sldns_buffer* buff, int with_edns)
1576 {
1577         /* if we are using 0x20 bits for ID randomness, perturb them */
1578         if(sq->outnet->use_caps_for_id && !sq->nocaps) {
1579                 serviced_perturb_qname(sq->outnet->rnd, sq->qbuf, sq->qbuflen);
1580         }
1581         /* generate query */
1582         sldns_buffer_clear(buff);
1583         sldns_buffer_write_u16(buff, 0); /* id placeholder */
1584         sldns_buffer_write(buff, sq->qbuf, sq->qbuflen);
1585         sldns_buffer_flip(buff);
1586         if(with_edns) {
1587                 /* add edns section */
1588                 struct edns_data edns;
1589                 edns.edns_present = 1;
1590                 edns.ext_rcode = 0;
1591                 edns.edns_version = EDNS_ADVERTISED_VERSION;
1592                 edns.opt_list = sq->opt_list;
1593                 if(sq->status == serviced_query_UDP_EDNS_FRAG) {
1594                         if(addr_is_ip6(&sq->addr, sq->addrlen)) {
1595                                 if(EDNS_FRAG_SIZE_IP6 < EDNS_ADVERTISED_SIZE)
1596                                         edns.udp_size = EDNS_FRAG_SIZE_IP6;
1597                                 else    edns.udp_size = EDNS_ADVERTISED_SIZE;
1598                         } else {
1599                                 if(EDNS_FRAG_SIZE_IP4 < EDNS_ADVERTISED_SIZE)
1600                                         edns.udp_size = EDNS_FRAG_SIZE_IP4;
1601                                 else    edns.udp_size = EDNS_ADVERTISED_SIZE;
1602                         }
1603                 } else {
1604                         edns.udp_size = EDNS_ADVERTISED_SIZE;
1605                 }
1606                 edns.bits = 0;
1607                 if(sq->dnssec & EDNS_DO)
1608                         edns.bits = EDNS_DO;
1609                 if(sq->dnssec & BIT_CD)
1610                         LDNS_CD_SET(sldns_buffer_begin(buff));
1611                 attach_edns_record(buff, &edns);
1612         }
1613 }
1614
1615 /**
1616  * Perform serviced query UDP sending operation.
1617  * Sends UDP with EDNS, unless infra host marked non EDNS.
1618  * @param sq: query to send.
1619  * @param buff: buffer scratch space.
1620  * @return 0 on error.
1621  */
1622 static int
1623 serviced_udp_send(struct serviced_query* sq, sldns_buffer* buff)
1624 {
1625         int rtt, vs;
1626         uint8_t edns_lame_known;
1627         time_t now = *sq->outnet->now_secs;
1628
1629         if(!infra_host(sq->outnet->infra, &sq->addr, sq->addrlen, sq->zone,
1630                 sq->zonelen, now, &vs, &edns_lame_known, &rtt))
1631                 return 0;
1632         sq->last_rtt = rtt;
1633         verbose(VERB_ALGO, "EDNS lookup known=%d vs=%d", edns_lame_known, vs);
1634         if(sq->status == serviced_initial) {
1635                 if(vs != -1) {
1636                         sq->status = serviced_query_UDP_EDNS;
1637                 } else {        
1638                         sq->status = serviced_query_UDP; 
1639                 }
1640         }
1641         serviced_encode(sq, buff, (sq->status == serviced_query_UDP_EDNS) ||
1642                 (sq->status == serviced_query_UDP_EDNS_FRAG));
1643         sq->last_sent_time = *sq->outnet->now_tv;
1644         sq->edns_lame_known = (int)edns_lame_known;
1645         verbose(VERB_ALGO, "serviced query UDP timeout=%d msec", rtt);
1646         sq->pending = pending_udp_query(sq, buff, rtt,
1647                 serviced_udp_callback, sq);
1648         if(!sq->pending)
1649                 return 0;
1650         return 1;
1651 }
1652
1653 /** check that perturbed qname is identical */
1654 static int
1655 serviced_check_qname(sldns_buffer* pkt, uint8_t* qbuf, size_t qbuflen)
1656 {
1657         uint8_t* d1 = sldns_buffer_begin(pkt)+12;
1658         uint8_t* d2 = qbuf+10;
1659         uint8_t len1, len2;
1660         int count = 0;
1661         if(sldns_buffer_limit(pkt) < 12+1+4) /* packet too small for qname */
1662                 return 0;
1663         log_assert(qbuflen >= 15 /* 10 header, root, type, class */);
1664         len1 = *d1++;
1665         len2 = *d2++;
1666         while(len1 != 0 || len2 != 0) {
1667                 if(LABEL_IS_PTR(len1)) {
1668                         /* check if we can read *d1 with compression ptr rest */
1669                         if(d1 >= sldns_buffer_at(pkt, sldns_buffer_limit(pkt)))
1670                                 return 0;
1671                         d1 = sldns_buffer_begin(pkt)+PTR_OFFSET(len1, *d1);
1672                         /* check if we can read the destination *d1 */
1673                         if(d1 >= sldns_buffer_at(pkt, sldns_buffer_limit(pkt)))
1674                                 return 0;
1675                         len1 = *d1++;
1676                         if(count++ > MAX_COMPRESS_PTRS)
1677                                 return 0;
1678                         continue;
1679                 }
1680                 if(d2 > qbuf+qbuflen)
1681                         return 0;
1682                 if(len1 != len2)
1683                         return 0;
1684                 if(len1 > LDNS_MAX_LABELLEN)
1685                         return 0;
1686                 /* check len1 + 1(next length) are okay to read */
1687                 if(d1+len1 >= sldns_buffer_at(pkt, sldns_buffer_limit(pkt)))
1688                         return 0;
1689                 log_assert(len1 <= LDNS_MAX_LABELLEN);
1690                 log_assert(len2 <= LDNS_MAX_LABELLEN);
1691                 log_assert(len1 == len2 && len1 != 0);
1692                 /* compare the labels - bitwise identical */
1693                 if(memcmp(d1, d2, len1) != 0)
1694                         return 0;
1695                 d1 += len1;
1696                 d2 += len2;
1697                 len1 = *d1++;
1698                 len2 = *d2++;
1699         }
1700         return 1;
1701 }
1702
1703 /** call the callbacks for a serviced query */
1704 static void
1705 serviced_callbacks(struct serviced_query* sq, int error, struct comm_point* c,
1706         struct comm_reply* rep)
1707 {
1708         struct service_callback* p;
1709         int dobackup = (sq->cblist && sq->cblist->next); /* >1 cb*/
1710         uint8_t *backup_p = NULL;
1711         size_t backlen = 0;
1712 #ifdef UNBOUND_DEBUG
1713         rbnode_type* rem =
1714 #else
1715         (void)
1716 #endif
1717         /* remove from tree, and schedule for deletion, so that callbacks
1718          * can safely deregister themselves and even create new serviced
1719          * queries that are identical to this one. */
1720         rbtree_delete(sq->outnet->serviced, sq);
1721         log_assert(rem); /* should have been present */
1722         sq->to_be_deleted = 1; 
1723         verbose(VERB_ALGO, "svcd callbacks start");
1724         if(sq->outnet->use_caps_for_id && error == NETEVENT_NOERROR && c &&
1725                 !sq->nocaps && sq->qtype != LDNS_RR_TYPE_PTR) {
1726                 /* for type PTR do not check perturbed name in answer,
1727                  * compatibility with cisco dns guard boxes that mess up
1728                  * reverse queries 0x20 contents */
1729                 /* noerror and nxdomain must have a qname in reply */
1730                 if(sldns_buffer_read_u16_at(c->buffer, 4) == 0 &&
1731                         (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer))
1732                                 == LDNS_RCODE_NOERROR || 
1733                          LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer))
1734                                 == LDNS_RCODE_NXDOMAIN)) {
1735                         verbose(VERB_DETAIL, "no qname in reply to check 0x20ID");
1736                         log_addr(VERB_DETAIL, "from server", 
1737                                 &sq->addr, sq->addrlen);
1738                         log_buf(VERB_DETAIL, "for packet", c->buffer);
1739                         error = NETEVENT_CLOSED;
1740                         c = NULL;
1741                 } else if(sldns_buffer_read_u16_at(c->buffer, 4) > 0 &&
1742                         !serviced_check_qname(c->buffer, sq->qbuf, 
1743                         sq->qbuflen)) {
1744                         verbose(VERB_DETAIL, "wrong 0x20-ID in reply qname");
1745                         log_addr(VERB_DETAIL, "from server", 
1746                                 &sq->addr, sq->addrlen);
1747                         log_buf(VERB_DETAIL, "for packet", c->buffer);
1748                         error = NETEVENT_CAPSFAIL;
1749                         /* and cleanup too */
1750                         pkt_dname_tolower(c->buffer, 
1751                                 sldns_buffer_at(c->buffer, 12));
1752                 } else {
1753                         verbose(VERB_ALGO, "good 0x20-ID in reply qname");
1754                         /* cleanup caps, prettier cache contents. */
1755                         pkt_dname_tolower(c->buffer, 
1756                                 sldns_buffer_at(c->buffer, 12));
1757                 }
1758         }
1759         if(dobackup && c) {
1760                 /* make a backup of the query, since the querystate processing
1761                  * may send outgoing queries that overwrite the buffer.
1762                  * use secondary buffer to store the query.
1763                  * This is a data copy, but faster than packet to server */
1764                 backlen = sldns_buffer_limit(c->buffer);
1765                 backup_p = memdup(sldns_buffer_begin(c->buffer), backlen);
1766                 if(!backup_p) {
1767                         log_err("malloc failure in serviced query callbacks");
1768                         error = NETEVENT_CLOSED;
1769                         c = NULL;
1770                 }
1771                 sq->outnet->svcd_overhead = backlen;
1772         }
1773         /* test the actual sq->cblist, because the next elem could be deleted*/
1774         while((p=sq->cblist) != NULL) {
1775                 sq->cblist = p->next; /* remove this element */
1776                 if(dobackup && c) {
1777                         sldns_buffer_clear(c->buffer);
1778                         sldns_buffer_write(c->buffer, backup_p, backlen);
1779                         sldns_buffer_flip(c->buffer);
1780                 }
1781                 fptr_ok(fptr_whitelist_serviced_query(p->cb));
1782                 (void)(*p->cb)(c, p->cb_arg, error, rep);
1783                 free(p);
1784         }
1785         if(backup_p) {
1786                 free(backup_p);
1787                 sq->outnet->svcd_overhead = 0;
1788         }
1789         verbose(VERB_ALGO, "svcd callbacks end");
1790         log_assert(sq->cblist == NULL);
1791         serviced_delete(sq);
1792 }
1793
1794 int 
1795 serviced_tcp_callback(struct comm_point* c, void* arg, int error,
1796         struct comm_reply* rep)
1797 {
1798         struct serviced_query* sq = (struct serviced_query*)arg;
1799         struct comm_reply r2;
1800         sq->pending = NULL; /* removed after this callback */
1801         if(error != NETEVENT_NOERROR)
1802                 log_addr(VERB_QUERY, "tcp error for address", 
1803                         &sq->addr, sq->addrlen);
1804         if(error==NETEVENT_NOERROR)
1805                 infra_update_tcp_works(sq->outnet->infra, &sq->addr,
1806                         sq->addrlen, sq->zone, sq->zonelen);
1807 #ifdef USE_DNSTAP
1808         if(error==NETEVENT_NOERROR && sq->outnet->dtenv &&
1809            (sq->outnet->dtenv->log_resolver_response_messages ||
1810             sq->outnet->dtenv->log_forwarder_response_messages))
1811                 dt_msg_send_outside_response(sq->outnet->dtenv, &sq->addr,
1812                 c->type, sq->zone, sq->zonelen, sq->qbuf, sq->qbuflen,
1813                 &sq->last_sent_time, sq->outnet->now_tv, c->buffer);
1814 #endif
1815         if(error==NETEVENT_NOERROR && sq->status == serviced_query_TCP_EDNS &&
1816                 (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) == 
1817                 LDNS_RCODE_FORMERR || LDNS_RCODE_WIRE(sldns_buffer_begin(
1818                 c->buffer)) == LDNS_RCODE_NOTIMPL) ) {
1819                 /* attempt to fallback to nonEDNS */
1820                 sq->status = serviced_query_TCP_EDNS_fallback;
1821                 serviced_tcp_initiate(sq, c->buffer);
1822                 return 0;
1823         } else if(error==NETEVENT_NOERROR && 
1824                 sq->status == serviced_query_TCP_EDNS_fallback &&
1825                         (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) == 
1826                         LDNS_RCODE_NOERROR || LDNS_RCODE_WIRE(
1827                         sldns_buffer_begin(c->buffer)) == LDNS_RCODE_NXDOMAIN 
1828                         || LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) 
1829                         == LDNS_RCODE_YXDOMAIN)) {
1830                 /* the fallback produced a result that looks promising, note
1831                  * that this server should be approached without EDNS */
1832                 /* only store noEDNS in cache if domain is noDNSSEC */
1833                 if(!sq->want_dnssec)
1834                   if(!infra_edns_update(sq->outnet->infra, &sq->addr, 
1835                         sq->addrlen, sq->zone, sq->zonelen, -1,
1836                         *sq->outnet->now_secs))
1837                         log_err("Out of memory caching no edns for host");
1838                 sq->status = serviced_query_TCP;
1839         }
1840         if(sq->tcp_upstream || sq->ssl_upstream) {
1841             struct timeval now = *sq->outnet->now_tv;
1842             if(error!=NETEVENT_NOERROR) {
1843                 if(!infra_rtt_update(sq->outnet->infra, &sq->addr,
1844                     sq->addrlen, sq->zone, sq->zonelen, sq->qtype,
1845                     -1, sq->last_rtt, (time_t)now.tv_sec))
1846                     log_err("out of memory in TCP exponential backoff.");
1847             } else if(now.tv_sec > sq->last_sent_time.tv_sec ||
1848                 (now.tv_sec == sq->last_sent_time.tv_sec &&
1849                 now.tv_usec > sq->last_sent_time.tv_usec)) {
1850                 /* convert from microseconds to milliseconds */
1851                 int roundtime = ((int)(now.tv_sec - sq->last_sent_time.tv_sec))*1000
1852                   + ((int)now.tv_usec - (int)sq->last_sent_time.tv_usec)/1000;
1853                 verbose(VERB_ALGO, "measured TCP-time at %d msec", roundtime);
1854                 log_assert(roundtime >= 0);
1855                 /* only store if less then AUTH_TIMEOUT seconds, it could be
1856                  * huge due to system-hibernated and we woke up */
1857                 if(roundtime < 60000) {
1858                     if(!infra_rtt_update(sq->outnet->infra, &sq->addr,
1859                         sq->addrlen, sq->zone, sq->zonelen, sq->qtype,
1860                         roundtime, sq->last_rtt, (time_t)now.tv_sec))
1861                         log_err("out of memory noting rtt.");
1862                 }
1863             }
1864         }
1865         /* insert address into reply info */
1866         if(!rep) {
1867                 /* create one if there isn't (on errors) */
1868                 rep = &r2;
1869                 r2.c = c;
1870         }
1871         memcpy(&rep->addr, &sq->addr, sq->addrlen);
1872         rep->addrlen = sq->addrlen;
1873         serviced_callbacks(sq, error, c, rep);
1874         return 0;
1875 }
1876
1877 static void
1878 serviced_tcp_initiate(struct serviced_query* sq, sldns_buffer* buff)
1879 {
1880         verbose(VERB_ALGO, "initiate TCP query %s", 
1881                 sq->status==serviced_query_TCP_EDNS?"EDNS":"");
1882         serviced_encode(sq, buff, sq->status == serviced_query_TCP_EDNS);
1883         sq->last_sent_time = *sq->outnet->now_tv;
1884         sq->pending = pending_tcp_query(sq, buff, TCP_AUTH_QUERY_TIMEOUT,
1885                 serviced_tcp_callback, sq);
1886         if(!sq->pending) {
1887                 /* delete from tree so that a retry by above layer does not
1888                  * clash with this entry */
1889                 verbose(VERB_ALGO, "serviced_tcp_initiate: failed to send tcp query");
1890                 serviced_callbacks(sq, NETEVENT_CLOSED, NULL, NULL);
1891         }
1892 }
1893
1894 /** Send serviced query over TCP return false on initial failure */
1895 static int
1896 serviced_tcp_send(struct serviced_query* sq, sldns_buffer* buff)
1897 {
1898         int vs, rtt, timeout;
1899         uint8_t edns_lame_known;
1900         if(!infra_host(sq->outnet->infra, &sq->addr, sq->addrlen, sq->zone,
1901                 sq->zonelen, *sq->outnet->now_secs, &vs, &edns_lame_known,
1902                 &rtt))
1903                 return 0;
1904         sq->last_rtt = rtt;
1905         if(vs != -1)
1906                 sq->status = serviced_query_TCP_EDNS;
1907         else    sq->status = serviced_query_TCP;
1908         serviced_encode(sq, buff, sq->status == serviced_query_TCP_EDNS);
1909         sq->last_sent_time = *sq->outnet->now_tv;
1910         if(sq->tcp_upstream || sq->ssl_upstream) {
1911                 timeout = rtt;
1912                 if(rtt >= UNKNOWN_SERVER_NICENESS && rtt < TCP_AUTH_QUERY_TIMEOUT)
1913                         timeout = TCP_AUTH_QUERY_TIMEOUT;
1914         } else {
1915                 timeout = TCP_AUTH_QUERY_TIMEOUT;
1916         }
1917         sq->pending = pending_tcp_query(sq, buff, timeout,
1918                 serviced_tcp_callback, sq);
1919         return sq->pending != NULL;
1920 }
1921
1922 /* see if packet is edns malformed; got zeroes at start.
1923  * This is from servers that return malformed packets to EDNS0 queries,
1924  * but they return good packets for nonEDNS0 queries.
1925  * We try to detect their output; without resorting to a full parse or
1926  * check for too many bytes after the end of the packet. */
1927 static int
1928 packet_edns_malformed(struct sldns_buffer* buf, int qtype)
1929 {
1930         size_t len;
1931         if(sldns_buffer_limit(buf) < LDNS_HEADER_SIZE)
1932                 return 1; /* malformed */
1933         /* they have NOERROR rcode, 1 answer. */
1934         if(LDNS_RCODE_WIRE(sldns_buffer_begin(buf)) != LDNS_RCODE_NOERROR)
1935                 return 0;
1936         /* one query (to skip) and answer records */
1937         if(LDNS_QDCOUNT(sldns_buffer_begin(buf)) != 1 ||
1938                 LDNS_ANCOUNT(sldns_buffer_begin(buf)) == 0)
1939                 return 0;
1940         /* skip qname */
1941         len = dname_valid(sldns_buffer_at(buf, LDNS_HEADER_SIZE),
1942                 sldns_buffer_limit(buf)-LDNS_HEADER_SIZE);
1943         if(len == 0)
1944                 return 0;
1945         if(len == 1 && qtype == 0)
1946                 return 0; /* we asked for '.' and type 0 */
1947         /* and then 4 bytes (type and class of query) */
1948         if(sldns_buffer_limit(buf) < LDNS_HEADER_SIZE + len + 4 + 3)
1949                 return 0;
1950
1951         /* and start with 11 zeroes as the answer RR */
1952         /* so check the qtype of the answer record, qname=0, type=0 */
1953         if(sldns_buffer_at(buf, LDNS_HEADER_SIZE+len+4)[0] == 0 &&
1954            sldns_buffer_at(buf, LDNS_HEADER_SIZE+len+4)[1] == 0 &&
1955            sldns_buffer_at(buf, LDNS_HEADER_SIZE+len+4)[2] == 0)
1956                 return 1;
1957         return 0;
1958 }
1959
1960 int 
1961 serviced_udp_callback(struct comm_point* c, void* arg, int error,
1962         struct comm_reply* rep)
1963 {
1964         struct serviced_query* sq = (struct serviced_query*)arg;
1965         struct outside_network* outnet = sq->outnet;
1966         struct timeval now = *sq->outnet->now_tv;
1967
1968         sq->pending = NULL; /* removed after callback */
1969         if(error == NETEVENT_TIMEOUT) {
1970                 int rto = 0;
1971                 if(sq->status == serviced_query_UDP_EDNS && sq->last_rtt < 5000) {
1972                         /* fallback to 1480/1280 */
1973                         sq->status = serviced_query_UDP_EDNS_FRAG;
1974                         log_name_addr(VERB_ALGO, "try edns1xx0", sq->qbuf+10,
1975                                 &sq->addr, sq->addrlen);
1976                         if(!serviced_udp_send(sq, c->buffer)) {
1977                                 serviced_callbacks(sq, NETEVENT_CLOSED, c, rep);
1978                         }
1979                         return 0;
1980                 }
1981                 if(sq->status == serviced_query_UDP_EDNS_FRAG) {
1982                         /* fragmentation size did not fix it */
1983                         sq->status = serviced_query_UDP_EDNS;
1984                 }
1985                 sq->retry++;
1986                 if(!(rto=infra_rtt_update(outnet->infra, &sq->addr, sq->addrlen,
1987                         sq->zone, sq->zonelen, sq->qtype, -1, sq->last_rtt,
1988                         (time_t)now.tv_sec)))
1989                         log_err("out of memory in UDP exponential backoff");
1990                 if(sq->retry < OUTBOUND_UDP_RETRY) {
1991                         log_name_addr(VERB_ALGO, "retry query", sq->qbuf+10,
1992                                 &sq->addr, sq->addrlen);
1993                         if(!serviced_udp_send(sq, c->buffer)) {
1994                                 serviced_callbacks(sq, NETEVENT_CLOSED, c, rep);
1995                         }
1996                         return 0;
1997                 }
1998         }
1999         if(error != NETEVENT_NOERROR) {
2000                 /* udp returns error (due to no ID or interface available) */
2001                 serviced_callbacks(sq, error, c, rep);
2002                 return 0;
2003         }
2004 #ifdef USE_DNSTAP
2005         if(error == NETEVENT_NOERROR && outnet->dtenv &&
2006            (outnet->dtenv->log_resolver_response_messages ||
2007             outnet->dtenv->log_forwarder_response_messages))
2008                 dt_msg_send_outside_response(outnet->dtenv, &sq->addr, c->type,
2009                 sq->zone, sq->zonelen, sq->qbuf, sq->qbuflen,
2010                 &sq->last_sent_time, sq->outnet->now_tv, c->buffer);
2011 #endif
2012         if( (sq->status == serviced_query_UDP_EDNS 
2013                 ||sq->status == serviced_query_UDP_EDNS_FRAG)
2014                 && (LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) 
2015                         == LDNS_RCODE_FORMERR || LDNS_RCODE_WIRE(
2016                         sldns_buffer_begin(c->buffer)) == LDNS_RCODE_NOTIMPL
2017                     || packet_edns_malformed(c->buffer, sq->qtype)
2018                         )) {
2019                 /* try to get an answer by falling back without EDNS */
2020                 verbose(VERB_ALGO, "serviced query: attempt without EDNS");
2021                 sq->status = serviced_query_UDP_EDNS_fallback;
2022                 sq->retry = 0;
2023                 if(!serviced_udp_send(sq, c->buffer)) {
2024                         serviced_callbacks(sq, NETEVENT_CLOSED, c, rep);
2025                 }
2026                 return 0;
2027         } else if(sq->status == serviced_query_UDP_EDNS && 
2028                 !sq->edns_lame_known) {
2029                 /* now we know that edns queries received answers store that */
2030                 log_addr(VERB_ALGO, "serviced query: EDNS works for",
2031                         &sq->addr, sq->addrlen);
2032                 if(!infra_edns_update(outnet->infra, &sq->addr, sq->addrlen, 
2033                         sq->zone, sq->zonelen, 0, (time_t)now.tv_sec)) {
2034                         log_err("Out of memory caching edns works");
2035                 }
2036                 sq->edns_lame_known = 1;
2037         } else if(sq->status == serviced_query_UDP_EDNS_fallback &&
2038                 !sq->edns_lame_known && (LDNS_RCODE_WIRE(
2039                 sldns_buffer_begin(c->buffer)) == LDNS_RCODE_NOERROR || 
2040                 LDNS_RCODE_WIRE(sldns_buffer_begin(c->buffer)) == 
2041                 LDNS_RCODE_NXDOMAIN || LDNS_RCODE_WIRE(sldns_buffer_begin(
2042                 c->buffer)) == LDNS_RCODE_YXDOMAIN)) {
2043                 /* the fallback produced a result that looks promising, note
2044                  * that this server should be approached without EDNS */
2045                 /* only store noEDNS in cache if domain is noDNSSEC */
2046                 if(!sq->want_dnssec) {
2047                   log_addr(VERB_ALGO, "serviced query: EDNS fails for",
2048                         &sq->addr, sq->addrlen);
2049                   if(!infra_edns_update(outnet->infra, &sq->addr, sq->addrlen,
2050                         sq->zone, sq->zonelen, -1, (time_t)now.tv_sec)) {
2051                         log_err("Out of memory caching no edns for host");
2052                   }
2053                 } else {
2054                   log_addr(VERB_ALGO, "serviced query: EDNS fails, but "
2055                         "not stored because need DNSSEC for", &sq->addr,
2056                         sq->addrlen);
2057                 }
2058                 sq->status = serviced_query_UDP;
2059         }
2060         if(now.tv_sec > sq->last_sent_time.tv_sec ||
2061                 (now.tv_sec == sq->last_sent_time.tv_sec &&
2062                 now.tv_usec > sq->last_sent_time.tv_usec)) {
2063                 /* convert from microseconds to milliseconds */
2064                 int roundtime = ((int)(now.tv_sec - sq->last_sent_time.tv_sec))*1000
2065                   + ((int)now.tv_usec - (int)sq->last_sent_time.tv_usec)/1000;
2066                 verbose(VERB_ALGO, "measured roundtrip at %d msec", roundtime);
2067                 log_assert(roundtime >= 0);
2068                 /* in case the system hibernated, do not enter a huge value,
2069                  * above this value gives trouble with server selection */
2070                 if(roundtime < 60000) {
2071                     if(!infra_rtt_update(outnet->infra, &sq->addr, sq->addrlen, 
2072                         sq->zone, sq->zonelen, sq->qtype, roundtime,
2073                         sq->last_rtt, (time_t)now.tv_sec))
2074                         log_err("out of memory noting rtt.");
2075                 }
2076         }
2077         /* perform TC flag check and TCP fallback after updating our
2078          * cache entries for EDNS status and RTT times */
2079         if(LDNS_TC_WIRE(sldns_buffer_begin(c->buffer))) {
2080                 /* fallback to TCP */
2081                 /* this discards partial UDP contents */
2082                 if(sq->status == serviced_query_UDP_EDNS ||
2083                         sq->status == serviced_query_UDP_EDNS_FRAG ||
2084                         sq->status == serviced_query_UDP_EDNS_fallback)
2085                         /* if we have unfinished EDNS_fallback, start again */
2086                         sq->status = serviced_query_TCP_EDNS;
2087                 else    sq->status = serviced_query_TCP;
2088                 serviced_tcp_initiate(sq, c->buffer);
2089                 return 0;
2090         }
2091         /* yay! an answer */
2092         serviced_callbacks(sq, error, c, rep);
2093         return 0;
2094 }
2095
2096 struct serviced_query* 
2097 outnet_serviced_query(struct outside_network* outnet,
2098         struct query_info* qinfo, uint16_t flags, int dnssec, int want_dnssec,
2099         int nocaps, int tcp_upstream, int ssl_upstream, char* tls_auth_name,
2100         struct sockaddr_storage* addr, socklen_t addrlen, uint8_t* zone,
2101         size_t zonelen, struct module_qstate* qstate,
2102         comm_point_callback_type* callback, void* callback_arg, sldns_buffer* buff,
2103         struct module_env* env)
2104 {
2105         struct serviced_query* sq;
2106         struct service_callback* cb;
2107         if(!inplace_cb_query_call(env, qinfo, flags, addr, addrlen, zone, zonelen,
2108                 qstate, qstate->region))
2109                         return NULL;
2110         serviced_gen_query(buff, qinfo->qname, qinfo->qname_len, qinfo->qtype,
2111                 qinfo->qclass, flags);
2112         sq = lookup_serviced(outnet, buff, dnssec, addr, addrlen,
2113                 qstate->edns_opts_back_out);
2114         /* duplicate entries are included in the callback list, because
2115          * there is a counterpart registration by our caller that needs to
2116          * be doubly-removed (with callbacks perhaps). */
2117         if(!(cb = (struct service_callback*)malloc(sizeof(*cb))))
2118                 return NULL;
2119         if(!sq) {
2120                 /* make new serviced query entry */
2121                 sq = serviced_create(outnet, buff, dnssec, want_dnssec, nocaps,
2122                         tcp_upstream, ssl_upstream, tls_auth_name, addr,
2123                         addrlen, zone, zonelen, (int)qinfo->qtype,
2124                         qstate->edns_opts_back_out);
2125                 if(!sq) {
2126                         free(cb);
2127                         return NULL;
2128                 }
2129                 /* perform first network action */
2130                 if(outnet->do_udp && !(tcp_upstream || ssl_upstream)) {
2131                         if(!serviced_udp_send(sq, buff)) {
2132                                 (void)rbtree_delete(outnet->serviced, sq);
2133                                 free(sq->qbuf);
2134                                 free(sq->zone);
2135                                 free(sq);
2136                                 free(cb);
2137                                 return NULL;
2138                         }
2139                 } else {
2140                         if(!serviced_tcp_send(sq, buff)) {
2141                                 (void)rbtree_delete(outnet->serviced, sq);
2142                                 free(sq->qbuf);
2143                                 free(sq->zone);
2144                                 free(sq);
2145                                 free(cb);
2146                                 return NULL;
2147                         }
2148                 }
2149         }
2150         /* add callback to list of callbacks */
2151         cb->cb = callback;
2152         cb->cb_arg = callback_arg;
2153         cb->next = sq->cblist;
2154         sq->cblist = cb;
2155         return sq;
2156 }
2157
2158 /** remove callback from list */
2159 static void
2160 callback_list_remove(struct serviced_query* sq, void* cb_arg)
2161 {
2162         struct service_callback** pp = &sq->cblist;
2163         while(*pp) {
2164                 if((*pp)->cb_arg == cb_arg) {
2165                         struct service_callback* del = *pp;
2166                         *pp = del->next;
2167                         free(del);
2168                         return;
2169                 }
2170                 pp = &(*pp)->next;
2171         }
2172 }
2173
2174 void outnet_serviced_query_stop(struct serviced_query* sq, void* cb_arg)
2175 {
2176         if(!sq) 
2177                 return;
2178         callback_list_remove(sq, cb_arg);
2179         /* if callbacks() routine scheduled deletion, let it do that */
2180         if(!sq->cblist && !sq->to_be_deleted) {
2181                 (void)rbtree_delete(sq->outnet->serviced, sq);
2182                 serviced_delete(sq); 
2183         }
2184 }
2185
2186 /** create fd to send to this destination */
2187 static int
2188 fd_for_dest(struct outside_network* outnet, struct sockaddr_storage* to_addr,
2189         socklen_t to_addrlen)
2190 {
2191         struct sockaddr_storage* addr;
2192         socklen_t addrlen;
2193         int i, try, pnum;
2194         struct port_if* pif;
2195
2196         /* create fd */
2197         for(try = 0; try<1000; try++) {
2198                 int port = 0;
2199                 int freebind = 0;
2200                 int noproto = 0;
2201                 int inuse = 0;
2202                 int fd = -1;
2203
2204                 /* select interface */
2205                 if(addr_is_ip6(to_addr, to_addrlen)) {
2206                         if(outnet->num_ip6 == 0) {
2207                                 char to[64];
2208                                 addr_to_str(to_addr, to_addrlen, to, sizeof(to));
2209                                 verbose(VERB_QUERY, "need ipv6 to send, but no ipv6 outgoing interfaces, for %s", to);
2210                                 return -1;
2211                         }
2212                         i = ub_random_max(outnet->rnd, outnet->num_ip6);
2213                         pif = &outnet->ip6_ifs[i];
2214                 } else {
2215                         if(outnet->num_ip4 == 0) {
2216                                 char to[64];
2217                                 addr_to_str(to_addr, to_addrlen, to, sizeof(to));
2218                                 verbose(VERB_QUERY, "need ipv4 to send, but no ipv4 outgoing interfaces, for %s", to);
2219                                 return -1;
2220                         }
2221                         i = ub_random_max(outnet->rnd, outnet->num_ip4);
2222                         pif = &outnet->ip4_ifs[i];
2223                 }
2224                 addr = &pif->addr;
2225                 addrlen = pif->addrlen;
2226                 pnum = ub_random_max(outnet->rnd, pif->avail_total);
2227                 if(pnum < pif->inuse) {
2228                         /* port already open */
2229                         port = pif->out[pnum]->number;
2230                 } else {
2231                         /* unused ports in start part of array */
2232                         port = pif->avail_ports[pnum - pif->inuse];
2233                 }
2234
2235                 if(addr_is_ip6(to_addr, to_addrlen)) {
2236                         struct sockaddr_in6 sa = *(struct sockaddr_in6*)addr;
2237                         sa.sin6_port = (in_port_t)htons((uint16_t)port);
2238                         fd = create_udp_sock(AF_INET6, SOCK_DGRAM,
2239                                 (struct sockaddr*)&sa, addrlen, 1, &inuse, &noproto,
2240                                 0, 0, 0, NULL, 0, freebind, 0);
2241                 } else {
2242                         struct sockaddr_in* sa = (struct sockaddr_in*)addr;
2243                         sa->sin_port = (in_port_t)htons((uint16_t)port);
2244                         fd = create_udp_sock(AF_INET, SOCK_DGRAM, 
2245                                 (struct sockaddr*)addr, addrlen, 1, &inuse, &noproto,
2246                                 0, 0, 0, NULL, 0, freebind, 0);
2247                 }
2248                 if(fd != -1) {
2249                         return fd;
2250                 }
2251                 if(!inuse) {
2252                         return -1;
2253                 }
2254         }
2255         /* too many tries */
2256         log_err("cannot send probe, ports are in use");
2257         return -1;
2258 }
2259
2260 struct comm_point*
2261 outnet_comm_point_for_udp(struct outside_network* outnet,
2262         comm_point_callback_type* cb, void* cb_arg,
2263         struct sockaddr_storage* to_addr, socklen_t to_addrlen)
2264 {
2265         struct comm_point* cp;
2266         int fd = fd_for_dest(outnet, to_addr, to_addrlen);
2267         if(fd == -1) {
2268                 return NULL;
2269         }
2270         cp = comm_point_create_udp(outnet->base, fd, outnet->udp_buff,
2271                 cb, cb_arg);
2272         if(!cp) {
2273                 log_err("malloc failure");
2274                 close(fd);
2275                 return NULL;
2276         }
2277         return cp;
2278 }
2279
2280 struct comm_point*
2281 outnet_comm_point_for_tcp(struct outside_network* outnet,
2282         comm_point_callback_type* cb, void* cb_arg,
2283         struct sockaddr_storage* to_addr, socklen_t to_addrlen,
2284         sldns_buffer* query, int timeout)
2285 {
2286         struct comm_point* cp;
2287         int fd = outnet_get_tcp_fd(to_addr, to_addrlen, outnet->tcp_mss);
2288         if(fd == -1) {
2289                 return 0;
2290         }
2291         fd_set_nonblock(fd);
2292         if(!outnet_tcp_connect(fd, to_addr, to_addrlen)) {
2293                 /* outnet_tcp_connect has closed fd on error for us */
2294                 return 0;
2295         }
2296         cp = comm_point_create_tcp_out(outnet->base, 65552, cb, cb_arg);
2297         if(!cp) {
2298                 log_err("malloc failure");
2299                 close(fd);
2300                 return 0;
2301         }
2302         cp->repinfo.addrlen = to_addrlen;
2303         memcpy(&cp->repinfo.addr, to_addr, to_addrlen);
2304         /* set timeout on TCP connection */
2305         comm_point_start_listening(cp, fd, timeout);
2306         /* copy scratch buffer to cp->buffer */
2307         sldns_buffer_copy(cp->buffer, query);
2308         return cp;
2309 }
2310
2311 /** setup http request headers in buffer for sending query to destination */
2312 static int
2313 setup_http_request(sldns_buffer* buf, char* host, char* path)
2314 {
2315         sldns_buffer_clear(buf);
2316         sldns_buffer_printf(buf, "GET /%s HTTP/1.1\r\n", path);
2317         sldns_buffer_printf(buf, "Host: %s\r\n", host);
2318         sldns_buffer_printf(buf, "User-Agent: unbound/%s\r\n",
2319                 PACKAGE_VERSION);
2320         /* We do not really do multiple queries per connection,
2321          * but this header setting is also not needed.
2322          * sldns_buffer_printf(buf, "Connection: close\r\n") */
2323         sldns_buffer_printf(buf, "\r\n");
2324         if(sldns_buffer_position(buf)+10 > sldns_buffer_capacity(buf))
2325                 return 0; /* somehow buffer too short, but it is about 60K
2326                 and the request is only a couple bytes long. */
2327         sldns_buffer_flip(buf);
2328         return 1;
2329 }
2330
2331 struct comm_point*
2332 outnet_comm_point_for_http(struct outside_network* outnet,
2333         comm_point_callback_type* cb, void* cb_arg,
2334         struct sockaddr_storage* to_addr, socklen_t to_addrlen, int timeout,
2335         int ssl, char* host, char* path)
2336 {
2337         /* cp calls cb with err=NETEVENT_DONE when transfer is done */
2338         struct comm_point* cp;
2339         int fd = outnet_get_tcp_fd(to_addr, to_addrlen, outnet->tcp_mss);
2340         if(fd == -1) {
2341                 return 0;
2342         }
2343         fd_set_nonblock(fd);
2344         if(!outnet_tcp_connect(fd, to_addr, to_addrlen)) {
2345                 /* outnet_tcp_connect has closed fd on error for us */
2346                 return 0;
2347         }
2348         cp = comm_point_create_http_out(outnet->base, 65552, cb, cb_arg,
2349                 outnet->udp_buff);
2350         if(!cp) {
2351                 log_err("malloc failure");
2352                 close(fd);
2353                 return 0;
2354         }
2355         cp->repinfo.addrlen = to_addrlen;
2356         memcpy(&cp->repinfo.addr, to_addr, to_addrlen);
2357
2358         /* setup for SSL (if needed) */
2359         if(ssl) {
2360                 cp->ssl = outgoing_ssl_fd(outnet->sslctx, fd);
2361                 if(!cp->ssl) {
2362                         log_err("cannot setup https");
2363                         comm_point_delete(cp);
2364                         return NULL;
2365                 }
2366 #ifdef USE_WINSOCK
2367                 comm_point_tcp_win_bio_cb(cp, cp->ssl);
2368 #endif
2369                 cp->ssl_shake_state = comm_ssl_shake_write;
2370                 /* https verification */
2371 #ifdef HAVE_SSL_SET1_HOST
2372                 if((SSL_CTX_get_verify_mode(outnet->sslctx)&SSL_VERIFY_PEER)) {
2373                         /* because we set SSL_VERIFY_PEER, in netevent in
2374                          * ssl_handshake, it'll check if the certificate
2375                          * verification has succeeded */
2376                         /* SSL_VERIFY_PEER is set on the sslctx */
2377                         /* and the certificates to verify with are loaded into
2378                          * it with SSL_load_verify_locations or
2379                          * SSL_CTX_set_default_verify_paths */
2380                         /* setting the hostname makes openssl verify the
2381                          * host name in the x509 certificate in the
2382                          * SSL connection*/
2383                         if(!SSL_set1_host(cp->ssl, host)) {
2384                                 log_err("SSL_set1_host failed");
2385                                 comm_point_delete(cp);
2386                                 return NULL;
2387                         }
2388                 }
2389 #elif defined(HAVE_X509_VERIFY_PARAM_SET1_HOST)
2390                 /* openssl 1.0.2 has this function that can be used for
2391                  * set1_host like verification */
2392                 if((SSL_CTX_get_verify_mode(outnet->sslctx)&SSL_VERIFY_PEER)) {
2393                         X509_VERIFY_PARAM* param = SSL_get0_param(cp->ssl);
2394                         X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
2395                         if(!X509_VERIFY_PARAM_set1_host(param, host, strlen(host))) {
2396                                 log_err("X509_VERIFY_PARAM_set1_host failed");
2397                                 comm_point_delete(cp);
2398                                 return NULL;
2399                         }
2400                 }
2401 #endif /* HAVE_SSL_SET1_HOST */
2402         }
2403
2404         /* set timeout on TCP connection */
2405         comm_point_start_listening(cp, fd, timeout);
2406
2407         /* setup http request in cp->buffer */
2408         if(!setup_http_request(cp->buffer, host, path)) {
2409                 log_err("error setting up http request");
2410                 comm_point_delete(cp);
2411                 return NULL;
2412         }
2413         return cp;
2414 }
2415
2416 /** get memory used by waiting tcp entry (in use or not) */
2417 static size_t
2418 waiting_tcp_get_mem(struct waiting_tcp* w)
2419 {
2420         size_t s;
2421         if(!w) return 0;
2422         s = sizeof(*w) + w->pkt_len;
2423         if(w->timer)
2424                 s += comm_timer_get_mem(w->timer);
2425         return s;
2426 }
2427
2428 /** get memory used by port if */
2429 static size_t
2430 if_get_mem(struct port_if* pif)
2431 {
2432         size_t s;
2433         int i;
2434         s = sizeof(*pif) + sizeof(int)*pif->avail_total +
2435                 sizeof(struct port_comm*)*pif->maxout;
2436         for(i=0; i<pif->inuse; i++)
2437                 s += sizeof(*pif->out[i]) + 
2438                         comm_point_get_mem(pif->out[i]->cp);
2439         return s;
2440 }
2441
2442 /** get memory used by waiting udp */
2443 static size_t
2444 waiting_udp_get_mem(struct pending* w)
2445 {
2446         size_t s;
2447         s = sizeof(*w) + comm_timer_get_mem(w->timer) + w->pkt_len;
2448         return s;
2449 }
2450
2451 size_t outnet_get_mem(struct outside_network* outnet)
2452 {
2453         size_t i;
2454         int k;
2455         struct waiting_tcp* w;
2456         struct pending* u;
2457         struct serviced_query* sq;
2458         struct service_callback* sb;
2459         struct port_comm* pc;
2460         size_t s = sizeof(*outnet) + sizeof(*outnet->base) + 
2461                 sizeof(*outnet->udp_buff) + 
2462                 sldns_buffer_capacity(outnet->udp_buff);
2463         /* second buffer is not ours */
2464         for(pc = outnet->unused_fds; pc; pc = pc->next) {
2465                 s += sizeof(*pc) + comm_point_get_mem(pc->cp);
2466         }
2467         for(k=0; k<outnet->num_ip4; k++)
2468                 s += if_get_mem(&outnet->ip4_ifs[k]);
2469         for(k=0; k<outnet->num_ip6; k++)
2470                 s += if_get_mem(&outnet->ip6_ifs[k]);
2471         for(u=outnet->udp_wait_first; u; u=u->next_waiting)
2472                 s += waiting_udp_get_mem(u);
2473         
2474         s += sizeof(struct pending_tcp*)*outnet->num_tcp;
2475         for(i=0; i<outnet->num_tcp; i++) {
2476                 s += sizeof(struct pending_tcp);
2477                 s += comm_point_get_mem(outnet->tcp_conns[i]->c);
2478                 if(outnet->tcp_conns[i]->query)
2479                         s += waiting_tcp_get_mem(outnet->tcp_conns[i]->query);
2480         }
2481         for(w=outnet->tcp_wait_first; w; w = w->next_waiting)
2482                 s += waiting_tcp_get_mem(w);
2483         s += sizeof(*outnet->pending);
2484         s += (sizeof(struct pending) + comm_timer_get_mem(NULL)) * 
2485                 outnet->pending->count;
2486         s += sizeof(*outnet->serviced);
2487         s += outnet->svcd_overhead;
2488         RBTREE_FOR(sq, struct serviced_query*, outnet->serviced) {
2489                 s += sizeof(*sq) + sq->qbuflen;
2490                 for(sb = sq->cblist; sb; sb = sb->next)
2491                         s += sizeof(*sb);
2492         }
2493         return s;
2494 }
2495
2496 size_t 
2497 serviced_get_mem(struct serviced_query* sq)
2498 {
2499         struct service_callback* sb;
2500         size_t s;
2501         s = sizeof(*sq) + sq->qbuflen;
2502         for(sb = sq->cblist; sb; sb = sb->next)
2503                 s += sizeof(*sb);
2504         if(sq->status == serviced_query_UDP_EDNS ||
2505                 sq->status == serviced_query_UDP ||
2506                 sq->status == serviced_query_UDP_EDNS_FRAG ||
2507                 sq->status == serviced_query_UDP_EDNS_fallback) {
2508                 s += sizeof(struct pending);
2509                 s += comm_timer_get_mem(NULL);
2510         } else {
2511                 /* does not have size of the pkt pointer */
2512                 /* always has a timer except on malloc failures */
2513
2514                 /* these sizes are part of the main outside network mem */
2515                 /*
2516                 s += sizeof(struct waiting_tcp);
2517                 s += comm_timer_get_mem(NULL);
2518                 */
2519         }
2520         return s;
2521 }
2522