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