]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - services/listen_dnsport.c
Vendor import of Unbound 1.9.0.
[FreeBSD/FreeBSD.git] / services / listen_dnsport.c
1 /*
2  * services/listen_dnsport.c - listen on port 53 for incoming DNS queries.
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 get queries from clients.
40  */
41 #include "config.h"
42 #ifdef HAVE_SYS_TYPES_H
43 #  include <sys/types.h>
44 #endif
45 #include <sys/time.h>
46 #ifdef USE_TCP_FASTOPEN
47 #include <netinet/tcp.h>
48 #endif
49 #include "services/listen_dnsport.h"
50 #include "services/outside_network.h"
51 #include "util/netevent.h"
52 #include "util/log.h"
53 #include "util/config_file.h"
54 #include "util/net_help.h"
55 #include "sldns/sbuffer.h"
56 #include "services/mesh.h"
57 #include "util/fptr_wlist.h"
58 #include "util/locks.h"
59
60 #ifdef HAVE_NETDB_H
61 #include <netdb.h>
62 #endif
63 #include <fcntl.h>
64
65 #ifdef HAVE_SYS_UN_H
66 #include <sys/un.h>
67 #endif
68
69 #ifdef HAVE_SYSTEMD
70 #include <systemd/sd-daemon.h>
71 #endif
72
73 /** number of queued TCP connections for listen() */
74 #define TCP_BACKLOG 256 
75
76 /** number of simultaneous requests a client can have */
77 #define TCP_MAX_REQ_SIMULTANEOUS 32
78
79 #ifndef THREADS_DISABLED
80 /** lock on the counter of stream buffer memory */
81 static lock_basic_type stream_wait_count_lock;
82 #endif
83 /** size (in bytes) of stream wait buffers */
84 static size_t stream_wait_count = 0;
85 /** is the lock initialised for stream wait buffers */
86 static int stream_wait_lock_inited = 0;
87
88 /**
89  * Debug print of the getaddrinfo returned address.
90  * @param addr: the address returned.
91  */
92 static void
93 verbose_print_addr(struct addrinfo *addr)
94 {
95         if(verbosity >= VERB_ALGO) {
96                 char buf[100];
97                 void* sinaddr = &((struct sockaddr_in*)addr->ai_addr)->sin_addr;
98 #ifdef INET6
99                 if(addr->ai_family == AF_INET6)
100                         sinaddr = &((struct sockaddr_in6*)addr->ai_addr)->
101                                 sin6_addr;
102 #endif /* INET6 */
103                 if(inet_ntop(addr->ai_family, sinaddr, buf,
104                         (socklen_t)sizeof(buf)) == 0) {
105                         (void)strlcpy(buf, "(null)", sizeof(buf));
106                 }
107                 buf[sizeof(buf)-1] = 0;
108                 verbose(VERB_ALGO, "creating %s%s socket %s %d", 
109                         addr->ai_socktype==SOCK_DGRAM?"udp":
110                         addr->ai_socktype==SOCK_STREAM?"tcp":"otherproto",
111                         addr->ai_family==AF_INET?"4":
112                         addr->ai_family==AF_INET6?"6":
113                         "_otherfam", buf, 
114                         ntohs(((struct sockaddr_in*)addr->ai_addr)->sin_port));
115         }
116 }
117
118 #ifdef HAVE_SYSTEMD
119 static int
120 systemd_get_activated(int family, int socktype, int listen,
121                       struct sockaddr *addr, socklen_t addrlen,
122                       const char *path)
123 {
124         int i = 0;
125         int r = 0;
126         int s = -1;
127         const char* listen_pid, *listen_fds;
128
129         /* We should use "listen" option only for stream protocols. For UDP it should be -1 */
130
131         if((r = sd_booted()) < 1) {
132                 if(r == 0)
133                         log_warn("systemd is not running");
134                 else
135                         log_err("systemd sd_booted(): %s", strerror(-r));
136                 return -1;
137         }
138
139         listen_pid = getenv("LISTEN_PID");
140         listen_fds = getenv("LISTEN_FDS");
141
142         if (!listen_pid) {
143                 log_warn("Systemd mandatory ENV variable is not defined: LISTEN_PID");
144                 return -1;
145         }
146
147         if (!listen_fds) {
148                 log_warn("Systemd mandatory ENV variable is not defined: LISTEN_FDS");
149                 return -1;
150         }
151
152         if((r = sd_listen_fds(0)) < 1) {
153                 if(r == 0)
154                         log_warn("systemd: did not return socket, check unit configuration");
155                 else
156                         log_err("systemd sd_listen_fds(): %s", strerror(-r));
157                 return -1;
158         }
159         
160         for(i = 0; i < r; i++) {
161                 if(sd_is_socket(SD_LISTEN_FDS_START + i, family, socktype, listen)) {
162                         s = SD_LISTEN_FDS_START + i;
163                         break;
164                 }
165         }
166         if (s == -1) {
167                 if (addr)
168                         log_err_addr("systemd sd_listen_fds()",
169                                      "no such socket",
170                                      (struct sockaddr_storage *)addr, addrlen);
171                 else
172                         log_err("systemd sd_listen_fds(): %s", path);
173         }
174         return s;
175 }
176 #endif
177
178 int
179 create_udp_sock(int family, int socktype, struct sockaddr* addr,
180         socklen_t addrlen, int v6only, int* inuse, int* noproto,
181         int rcv, int snd, int listen, int* reuseport, int transparent,
182         int freebind, int use_systemd)
183 {
184         int s;
185 #if defined(SO_REUSEADDR) || defined(SO_REUSEPORT) || defined(IPV6_USE_MIN_MTU)  || defined(IP_TRANSPARENT) || defined(IP_BINDANY) || defined(IP_FREEBIND) || defined (SO_BINDANY)
186         int on=1;
187 #endif
188 #ifdef IPV6_MTU
189         int mtu = IPV6_MIN_MTU;
190 #endif
191 #if !defined(SO_RCVBUFFORCE) && !defined(SO_RCVBUF)
192         (void)rcv;
193 #endif
194 #if !defined(SO_SNDBUFFORCE) && !defined(SO_SNDBUF)
195         (void)snd;
196 #endif
197 #ifndef IPV6_V6ONLY
198         (void)v6only;
199 #endif
200 #if !defined(IP_TRANSPARENT) && !defined(IP_BINDANY) && !defined(SO_BINDANY)
201         (void)transparent;
202 #endif
203 #if !defined(IP_FREEBIND)
204         (void)freebind;
205 #endif
206 #ifdef HAVE_SYSTEMD
207         int got_fd_from_systemd = 0;
208
209         if (!use_systemd
210             || (use_systemd
211                 && (s = systemd_get_activated(family, socktype, -1, addr,
212                                               addrlen, NULL)) == -1)) {
213 #else
214         (void)use_systemd;
215 #endif
216         if((s = socket(family, socktype, 0)) == -1) {
217                 *inuse = 0;
218 #ifndef USE_WINSOCK
219                 if(errno == EAFNOSUPPORT || errno == EPROTONOSUPPORT) {
220                         *noproto = 1;
221                         return -1;
222                 }
223                 log_err("can't create socket: %s", strerror(errno));
224 #else
225                 if(WSAGetLastError() == WSAEAFNOSUPPORT || 
226                         WSAGetLastError() == WSAEPROTONOSUPPORT) {
227                         *noproto = 1;
228                         return -1;
229                 }
230                 log_err("can't create socket: %s", 
231                         wsa_strerror(WSAGetLastError()));
232 #endif
233                 *noproto = 0;
234                 return -1;
235         }
236 #ifdef HAVE_SYSTEMD
237         } else {
238                 got_fd_from_systemd = 1;
239         }
240 #endif
241         if(listen) {
242 #ifdef SO_REUSEADDR
243                 if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&on, 
244                         (socklen_t)sizeof(on)) < 0) {
245 #ifndef USE_WINSOCK
246                         log_err("setsockopt(.. SO_REUSEADDR ..) failed: %s",
247                                 strerror(errno));
248                         if(errno != ENOSYS) {
249                                 close(s);
250                                 *noproto = 0;
251                                 *inuse = 0;
252                                 return -1;
253                         }
254 #else
255                         log_err("setsockopt(.. SO_REUSEADDR ..) failed: %s",
256                                 wsa_strerror(WSAGetLastError()));
257                         closesocket(s);
258                         *noproto = 0;
259                         *inuse = 0;
260                         return -1;
261 #endif
262                 }
263 #endif /* SO_REUSEADDR */
264 #ifdef SO_REUSEPORT
265 #  ifdef SO_REUSEPORT_LB
266                 /* on FreeBSD 12 we have SO_REUSEPORT_LB that does loadbalance
267                  * like SO_REUSEPORT on Linux.  This is what the users want
268                  * with the config option in unbound.conf; if we actually
269                  * need local address and port reuse they'll also need to
270                  * have SO_REUSEPORT set for them, assume it was _LB they want.
271                  */
272                 if (reuseport && *reuseport &&
273                     setsockopt(s, SOL_SOCKET, SO_REUSEPORT_LB, (void*)&on,
274                         (socklen_t)sizeof(on)) < 0) {
275 #ifdef ENOPROTOOPT
276                         if(errno != ENOPROTOOPT || verbosity >= 3)
277                                 log_warn("setsockopt(.. SO_REUSEPORT_LB ..) failed: %s",
278                                         strerror(errno));
279 #endif
280                         /* this option is not essential, we can continue */
281                         *reuseport = 0;
282                 }
283 #  else /* no SO_REUSEPORT_LB */
284
285                 /* try to set SO_REUSEPORT so that incoming
286                  * queries are distributed evenly among the receiving threads.
287                  * Each thread must have its own socket bound to the same port,
288                  * with SO_REUSEPORT set on each socket.
289                  */
290                 if (reuseport && *reuseport &&
291                     setsockopt(s, SOL_SOCKET, SO_REUSEPORT, (void*)&on,
292                         (socklen_t)sizeof(on)) < 0) {
293 #ifdef ENOPROTOOPT
294                         if(errno != ENOPROTOOPT || verbosity >= 3)
295                                 log_warn("setsockopt(.. SO_REUSEPORT ..) failed: %s",
296                                         strerror(errno));
297 #endif
298                         /* this option is not essential, we can continue */
299                         *reuseport = 0;
300                 }
301 #  endif /* SO_REUSEPORT_LB */
302 #else
303                 (void)reuseport;
304 #endif /* defined(SO_REUSEPORT) */
305 #ifdef IP_TRANSPARENT
306                 if (transparent &&
307                     setsockopt(s, IPPROTO_IP, IP_TRANSPARENT, (void*)&on,
308                     (socklen_t)sizeof(on)) < 0) {
309                         log_warn("setsockopt(.. IP_TRANSPARENT ..) failed: %s",
310                         strerror(errno));
311                 }
312 #elif defined(IP_BINDANY)
313                 if (transparent &&
314                     setsockopt(s, (family==AF_INET6? IPPROTO_IPV6:IPPROTO_IP),
315                     (family == AF_INET6? IPV6_BINDANY:IP_BINDANY),
316                     (void*)&on, (socklen_t)sizeof(on)) < 0) {
317                         log_warn("setsockopt(.. IP%s_BINDANY ..) failed: %s",
318                         (family==AF_INET6?"V6":""), strerror(errno));
319                 }
320 #elif defined(SO_BINDANY)
321                 if (transparent &&
322                     setsockopt(s, SOL_SOCKET, SO_BINDANY, (void*)&on,
323                     (socklen_t)sizeof(on)) < 0) {
324                         log_warn("setsockopt(.. SO_BINDANY ..) failed: %s",
325                         strerror(errno));
326                 }
327 #endif /* IP_TRANSPARENT || IP_BINDANY || SO_BINDANY */
328         }
329 #ifdef IP_FREEBIND
330         if(freebind &&
331             setsockopt(s, IPPROTO_IP, IP_FREEBIND, (void*)&on,
332             (socklen_t)sizeof(on)) < 0) {
333                 log_warn("setsockopt(.. IP_FREEBIND ..) failed: %s",
334                 strerror(errno));
335         }
336 #endif /* IP_FREEBIND */
337         if(rcv) {
338 #ifdef SO_RCVBUF
339                 int got;
340                 socklen_t slen = (socklen_t)sizeof(got);
341 #  ifdef SO_RCVBUFFORCE
342                 /* Linux specific: try to use root permission to override
343                  * system limits on rcvbuf. The limit is stored in 
344                  * /proc/sys/net/core/rmem_max or sysctl net.core.rmem_max */
345                 if(setsockopt(s, SOL_SOCKET, SO_RCVBUFFORCE, (void*)&rcv, 
346                         (socklen_t)sizeof(rcv)) < 0) {
347                         if(errno != EPERM) {
348 #    ifndef USE_WINSOCK
349                                 log_err("setsockopt(..., SO_RCVBUFFORCE, "
350                                         "...) failed: %s", strerror(errno));
351                                 close(s);
352 #    else
353                                 log_err("setsockopt(..., SO_RCVBUFFORCE, "
354                                         "...) failed: %s", 
355                                         wsa_strerror(WSAGetLastError()));
356                                 closesocket(s);
357 #    endif
358                                 *noproto = 0;
359                                 *inuse = 0;
360                                 return -1;
361                         }
362 #  endif /* SO_RCVBUFFORCE */
363                         if(setsockopt(s, SOL_SOCKET, SO_RCVBUF, (void*)&rcv, 
364                                 (socklen_t)sizeof(rcv)) < 0) {
365 #  ifndef USE_WINSOCK
366                                 log_err("setsockopt(..., SO_RCVBUF, "
367                                         "...) failed: %s", strerror(errno));
368                                 close(s);
369 #  else
370                                 log_err("setsockopt(..., SO_RCVBUF, "
371                                         "...) failed: %s", 
372                                         wsa_strerror(WSAGetLastError()));
373                                 closesocket(s);
374 #  endif
375                                 *noproto = 0;
376                                 *inuse = 0;
377                                 return -1;
378                         }
379                         /* check if we got the right thing or if system
380                          * reduced to some system max.  Warn if so */
381                         if(getsockopt(s, SOL_SOCKET, SO_RCVBUF, (void*)&got, 
382                                 &slen) >= 0 && got < rcv/2) {
383                                 log_warn("so-rcvbuf %u was not granted. "
384                                         "Got %u. To fix: start with "
385                                         "root permissions(linux) or sysctl "
386                                         "bigger net.core.rmem_max(linux) or "
387                                         "kern.ipc.maxsockbuf(bsd) values.",
388                                         (unsigned)rcv, (unsigned)got);
389                         }
390 #  ifdef SO_RCVBUFFORCE
391                 }
392 #  endif
393 #endif /* SO_RCVBUF */
394         }
395         /* first do RCVBUF as the receive buffer is more important */
396         if(snd) {
397 #ifdef SO_SNDBUF
398                 int got;
399                 socklen_t slen = (socklen_t)sizeof(got);
400 #  ifdef SO_SNDBUFFORCE
401                 /* Linux specific: try to use root permission to override
402                  * system limits on sndbuf. The limit is stored in 
403                  * /proc/sys/net/core/wmem_max or sysctl net.core.wmem_max */
404                 if(setsockopt(s, SOL_SOCKET, SO_SNDBUFFORCE, (void*)&snd, 
405                         (socklen_t)sizeof(snd)) < 0) {
406                         if(errno != EPERM) {
407 #    ifndef USE_WINSOCK
408                                 log_err("setsockopt(..., SO_SNDBUFFORCE, "
409                                         "...) failed: %s", strerror(errno));
410                                 close(s);
411 #    else
412                                 log_err("setsockopt(..., SO_SNDBUFFORCE, "
413                                         "...) failed: %s", 
414                                         wsa_strerror(WSAGetLastError()));
415                                 closesocket(s);
416 #    endif
417                                 *noproto = 0;
418                                 *inuse = 0;
419                                 return -1;
420                         }
421 #  endif /* SO_SNDBUFFORCE */
422                         if(setsockopt(s, SOL_SOCKET, SO_SNDBUF, (void*)&snd, 
423                                 (socklen_t)sizeof(snd)) < 0) {
424 #  ifndef USE_WINSOCK
425                                 log_err("setsockopt(..., SO_SNDBUF, "
426                                         "...) failed: %s", strerror(errno));
427                                 close(s);
428 #  else
429                                 log_err("setsockopt(..., SO_SNDBUF, "
430                                         "...) failed: %s", 
431                                         wsa_strerror(WSAGetLastError()));
432                                 closesocket(s);
433 #  endif
434                                 *noproto = 0;
435                                 *inuse = 0;
436                                 return -1;
437                         }
438                         /* check if we got the right thing or if system
439                          * reduced to some system max.  Warn if so */
440                         if(getsockopt(s, SOL_SOCKET, SO_SNDBUF, (void*)&got, 
441                                 &slen) >= 0 && got < snd/2) {
442                                 log_warn("so-sndbuf %u was not granted. "
443                                         "Got %u. To fix: start with "
444                                         "root permissions(linux) or sysctl "
445                                         "bigger net.core.wmem_max(linux) or "
446                                         "kern.ipc.maxsockbuf(bsd) values.",
447                                         (unsigned)snd, (unsigned)got);
448                         }
449 #  ifdef SO_SNDBUFFORCE
450                 }
451 #  endif
452 #endif /* SO_SNDBUF */
453         }
454         if(family == AF_INET6) {
455 # if defined(IPV6_V6ONLY)
456                 if(v6only) {
457                         int val=(v6only==2)?0:1;
458                         if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, 
459                                 (void*)&val, (socklen_t)sizeof(val)) < 0) {
460 #ifndef USE_WINSOCK
461                                 log_err("setsockopt(..., IPV6_V6ONLY"
462                                         ", ...) failed: %s", strerror(errno));
463                                 close(s);
464 #else
465                                 log_err("setsockopt(..., IPV6_V6ONLY"
466                                         ", ...) failed: %s", 
467                                         wsa_strerror(WSAGetLastError()));
468                                 closesocket(s);
469 #endif
470                                 *noproto = 0;
471                                 *inuse = 0;
472                                 return -1;
473                         }
474                 }
475 # endif
476 # if defined(IPV6_USE_MIN_MTU)
477                 /*
478                  * There is no fragmentation of IPv6 datagrams
479                  * during forwarding in the network. Therefore
480                  * we do not send UDP datagrams larger than
481                  * the minimum IPv6 MTU of 1280 octets. The
482                  * EDNS0 message length can be larger if the
483                  * network stack supports IPV6_USE_MIN_MTU.
484                  */
485                 if (setsockopt(s, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
486                         (void*)&on, (socklen_t)sizeof(on)) < 0) {
487 #  ifndef USE_WINSOCK
488                         log_err("setsockopt(..., IPV6_USE_MIN_MTU, "
489                                 "...) failed: %s", strerror(errno));
490                         close(s);
491 #  else
492                         log_err("setsockopt(..., IPV6_USE_MIN_MTU, "
493                                 "...) failed: %s", 
494                                 wsa_strerror(WSAGetLastError()));
495                         closesocket(s);
496 #  endif
497                         *noproto = 0;
498                         *inuse = 0;
499                         return -1;
500                 }
501 # elif defined(IPV6_MTU)
502                 /*
503                  * On Linux, to send no larger than 1280, the PMTUD is
504                  * disabled by default for datagrams anyway, so we set
505                  * the MTU to use.
506                  */
507                 if (setsockopt(s, IPPROTO_IPV6, IPV6_MTU,
508                         (void*)&mtu, (socklen_t)sizeof(mtu)) < 0) {
509 #  ifndef USE_WINSOCK
510                         log_err("setsockopt(..., IPV6_MTU, ...) failed: %s", 
511                                 strerror(errno));
512                         close(s);
513 #  else
514                         log_err("setsockopt(..., IPV6_MTU, ...) failed: %s", 
515                                 wsa_strerror(WSAGetLastError()));
516                         closesocket(s);
517 #  endif
518                         *noproto = 0;
519                         *inuse = 0;
520                         return -1;
521                 }
522 # endif /* IPv6 MTU */
523         } else if(family == AF_INET) {
524 #  if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
525 /* linux 3.15 has IP_PMTUDISC_OMIT, Hannes Frederic Sowa made it so that
526  * PMTU information is not accepted, but fragmentation is allowed
527  * if and only if the packet size exceeds the outgoing interface MTU
528  * (and also uses the interface mtu to determine the size of the packets).
529  * So there won't be any EMSGSIZE error.  Against DNS fragmentation attacks.
530  * FreeBSD already has same semantics without setting the option. */
531                 int omit_set = 0;
532                 int action;
533 #   if defined(IP_PMTUDISC_OMIT)
534                 action = IP_PMTUDISC_OMIT;
535                 if (setsockopt(s, IPPROTO_IP, IP_MTU_DISCOVER, 
536                         &action, (socklen_t)sizeof(action)) < 0) {
537
538                         if (errno != EINVAL) {
539                                 log_err("setsockopt(..., IP_MTU_DISCOVER, IP_PMTUDISC_OMIT...) failed: %s",
540                                         strerror(errno));
541
542 #    ifndef USE_WINSOCK
543                                 close(s);
544 #    else
545                                 closesocket(s);
546 #    endif
547                                 *noproto = 0;
548                                 *inuse = 0;
549                                 return -1;
550                         }
551                 }
552                 else
553                 {
554                     omit_set = 1;
555                 }
556 #   endif
557                 if (omit_set == 0) {
558                         action = IP_PMTUDISC_DONT;
559                         if (setsockopt(s, IPPROTO_IP, IP_MTU_DISCOVER,
560                                 &action, (socklen_t)sizeof(action)) < 0) {
561                                 log_err("setsockopt(..., IP_MTU_DISCOVER, IP_PMTUDISC_DONT...) failed: %s",
562                                         strerror(errno));
563 #    ifndef USE_WINSOCK
564                                 close(s);
565 #    else
566                                 closesocket(s);
567 #    endif
568                                 *noproto = 0;
569                                 *inuse = 0;
570                                 return -1;
571                         }
572                 }
573 #  elif defined(IP_DONTFRAG)
574                 int off = 0;
575                 if (setsockopt(s, IPPROTO_IP, IP_DONTFRAG, 
576                         &off, (socklen_t)sizeof(off)) < 0) {
577                         log_err("setsockopt(..., IP_DONTFRAG, ...) failed: %s",
578                                 strerror(errno));
579 #    ifndef USE_WINSOCK
580                         close(s);
581 #    else
582                         closesocket(s);
583 #    endif
584                         *noproto = 0;
585                         *inuse = 0;
586                         return -1;
587                 }
588 #  endif /* IPv4 MTU */
589         }
590         if(
591 #ifdef HAVE_SYSTEMD
592                 !got_fd_from_systemd &&
593 #endif
594                 bind(s, (struct sockaddr*)addr, addrlen) != 0) {
595                 *noproto = 0;
596                 *inuse = 0;
597 #ifndef USE_WINSOCK
598 #ifdef EADDRINUSE
599                 *inuse = (errno == EADDRINUSE);
600                 /* detect freebsd jail with no ipv6 permission */
601                 if(family==AF_INET6 && errno==EINVAL)
602                         *noproto = 1;
603                 else if(errno != EADDRINUSE &&
604                         !(errno == EACCES && verbosity < 4 && !listen)
605 #ifdef EADDRNOTAVAIL
606                         && !(errno == EADDRNOTAVAIL && verbosity < 4 && !listen)
607 #endif
608                         ) {
609                         log_err_addr("can't bind socket", strerror(errno),
610                                 (struct sockaddr_storage*)addr, addrlen);
611                 }
612 #endif /* EADDRINUSE */
613                 close(s);
614 #else /* USE_WINSOCK */
615                 if(WSAGetLastError() != WSAEADDRINUSE &&
616                         WSAGetLastError() != WSAEADDRNOTAVAIL &&
617                         !(WSAGetLastError() == WSAEACCES && verbosity < 4 && !listen)) {
618                         log_err_addr("can't bind socket", 
619                                 wsa_strerror(WSAGetLastError()),
620                                 (struct sockaddr_storage*)addr, addrlen);
621                 }
622                 closesocket(s);
623 #endif /* USE_WINSOCK */
624                 return -1;
625         }
626         if(!fd_set_nonblock(s)) {
627                 *noproto = 0;
628                 *inuse = 0;
629 #ifndef USE_WINSOCK
630                 close(s);
631 #else
632                 closesocket(s);
633 #endif
634                 return -1;
635         }
636         return s;
637 }
638
639 int
640 create_tcp_accept_sock(struct addrinfo *addr, int v6only, int* noproto,
641         int* reuseport, int transparent, int mss, int freebind, int use_systemd)
642 {
643         int s;
644 #if defined(SO_REUSEADDR) || defined(SO_REUSEPORT) || defined(IPV6_V6ONLY) || defined(IP_TRANSPARENT) || defined(IP_BINDANY) || defined(IP_FREEBIND) || defined(SO_BINDANY)
645         int on = 1;
646 #endif
647 #ifdef HAVE_SYSTEMD
648         int got_fd_from_systemd = 0;
649 #endif
650 #ifdef USE_TCP_FASTOPEN
651         int qlen;
652 #endif
653 #if !defined(IP_TRANSPARENT) && !defined(IP_BINDANY) && !defined(SO_BINDANY)
654         (void)transparent;
655 #endif
656 #if !defined(IP_FREEBIND)
657         (void)freebind;
658 #endif
659         verbose_print_addr(addr);
660         *noproto = 0;
661 #ifdef HAVE_SYSTEMD
662         if (!use_systemd ||
663             (use_systemd
664              && (s = systemd_get_activated(addr->ai_family, addr->ai_socktype, 1,
665                                            addr->ai_addr, addr->ai_addrlen,
666                                            NULL)) == -1)) {
667 #else
668         (void)use_systemd;
669 #endif
670         if((s = socket(addr->ai_family, addr->ai_socktype, 0)) == -1) {
671 #ifndef USE_WINSOCK
672                 if(errno == EAFNOSUPPORT || errno == EPROTONOSUPPORT) {
673                         *noproto = 1;
674                         return -1;
675                 }
676                 log_err("can't create socket: %s", strerror(errno));
677 #else
678                 if(WSAGetLastError() == WSAEAFNOSUPPORT ||
679                         WSAGetLastError() == WSAEPROTONOSUPPORT) {
680                         *noproto = 1;
681                         return -1;
682                 }
683                 log_err("can't create socket: %s", 
684                         wsa_strerror(WSAGetLastError()));
685 #endif
686                 return -1;
687         }
688         if (mss > 0) {
689 #if defined(IPPROTO_TCP) && defined(TCP_MAXSEG)
690                 if(setsockopt(s, IPPROTO_TCP, TCP_MAXSEG, (void*)&mss,
691                         (socklen_t)sizeof(mss)) < 0) {
692                         #ifndef USE_WINSOCK
693                         log_err(" setsockopt(.. TCP_MAXSEG ..) failed: %s",
694                                 strerror(errno));
695                         #else
696                         log_err(" setsockopt(.. TCP_MAXSEG ..) failed: %s",
697                                 wsa_strerror(WSAGetLastError()));
698                         #endif
699                 } else {
700                         verbose(VERB_ALGO,
701                                 " tcp socket mss set to %d", mss);
702                 }
703 #else
704                 log_warn(" setsockopt(TCP_MAXSEG) unsupported");
705 #endif /* defined(IPPROTO_TCP) && defined(TCP_MAXSEG) */
706         }
707 #ifdef HAVE_SYSTEMD
708         } else {
709                 got_fd_from_systemd = 1;
710     }
711 #endif
712 #ifdef SO_REUSEADDR
713         if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&on, 
714                 (socklen_t)sizeof(on)) < 0) {
715 #ifndef USE_WINSOCK
716                 log_err("setsockopt(.. SO_REUSEADDR ..) failed: %s",
717                         strerror(errno));
718                 close(s);
719 #else
720                 log_err("setsockopt(.. SO_REUSEADDR ..) failed: %s",
721                         wsa_strerror(WSAGetLastError()));
722                 closesocket(s);
723 #endif
724                 return -1;
725         }
726 #endif /* SO_REUSEADDR */
727 #ifdef IP_FREEBIND
728         if (freebind && setsockopt(s, IPPROTO_IP, IP_FREEBIND, (void*)&on,
729             (socklen_t)sizeof(on)) < 0) {
730                 log_warn("setsockopt(.. IP_FREEBIND ..) failed: %s",
731                 strerror(errno));
732         }
733 #endif /* IP_FREEBIND */
734 #ifdef SO_REUSEPORT
735         /* try to set SO_REUSEPORT so that incoming
736          * connections are distributed evenly among the receiving threads.
737          * Each thread must have its own socket bound to the same port,
738          * with SO_REUSEPORT set on each socket.
739          */
740         if (reuseport && *reuseport &&
741                 setsockopt(s, SOL_SOCKET, SO_REUSEPORT, (void*)&on,
742                 (socklen_t)sizeof(on)) < 0) {
743 #ifdef ENOPROTOOPT
744                 if(errno != ENOPROTOOPT || verbosity >= 3)
745                         log_warn("setsockopt(.. SO_REUSEPORT ..) failed: %s",
746                                 strerror(errno));
747 #endif
748                 /* this option is not essential, we can continue */
749                 *reuseport = 0;
750         }
751 #else
752         (void)reuseport;
753 #endif /* defined(SO_REUSEPORT) */
754 #if defined(IPV6_V6ONLY)
755         if(addr->ai_family == AF_INET6 && v6only) {
756                 if(setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, 
757                         (void*)&on, (socklen_t)sizeof(on)) < 0) {
758 #ifndef USE_WINSOCK
759                         log_err("setsockopt(..., IPV6_V6ONLY, ...) failed: %s",
760                                 strerror(errno));
761                         close(s);
762 #else
763                         log_err("setsockopt(..., IPV6_V6ONLY, ...) failed: %s",
764                                 wsa_strerror(WSAGetLastError()));
765                         closesocket(s);
766 #endif
767                         return -1;
768                 }
769         }
770 #else
771         (void)v6only;
772 #endif /* IPV6_V6ONLY */
773 #ifdef IP_TRANSPARENT
774         if (transparent &&
775             setsockopt(s, IPPROTO_IP, IP_TRANSPARENT, (void*)&on,
776             (socklen_t)sizeof(on)) < 0) {
777                 log_warn("setsockopt(.. IP_TRANSPARENT ..) failed: %s",
778                         strerror(errno));
779         }
780 #elif defined(IP_BINDANY)
781         if (transparent &&
782             setsockopt(s, (addr->ai_family==AF_INET6? IPPROTO_IPV6:IPPROTO_IP),
783             (addr->ai_family == AF_INET6? IPV6_BINDANY:IP_BINDANY),
784             (void*)&on, (socklen_t)sizeof(on)) < 0) {
785                 log_warn("setsockopt(.. IP%s_BINDANY ..) failed: %s",
786                 (addr->ai_family==AF_INET6?"V6":""), strerror(errno));
787         }
788 #elif defined(SO_BINDANY)
789         if (transparent &&
790             setsockopt(s, SOL_SOCKET, SO_BINDANY, (void*)&on, (socklen_t)
791             sizeof(on)) < 0) {
792                 log_warn("setsockopt(.. SO_BINDANY ..) failed: %s",
793                 strerror(errno));
794         }
795 #endif /* IP_TRANSPARENT || IP_BINDANY || SO_BINDANY */
796         if(
797 #ifdef HAVE_SYSTEMD
798                 !got_fd_from_systemd &&
799 #endif
800         bind(s, addr->ai_addr, addr->ai_addrlen) != 0) {
801 #ifndef USE_WINSOCK
802                 /* detect freebsd jail with no ipv6 permission */
803                 if(addr->ai_family==AF_INET6 && errno==EINVAL)
804                         *noproto = 1;
805                 else {
806                         log_err_addr("can't bind socket", strerror(errno),
807                                 (struct sockaddr_storage*)addr->ai_addr,
808                                 addr->ai_addrlen);
809                 }
810                 close(s);
811 #else
812                 log_err_addr("can't bind socket", 
813                         wsa_strerror(WSAGetLastError()),
814                         (struct sockaddr_storage*)addr->ai_addr,
815                         addr->ai_addrlen);
816                 closesocket(s);
817 #endif
818                 return -1;
819         }
820         if(!fd_set_nonblock(s)) {
821 #ifndef USE_WINSOCK
822                 close(s);
823 #else
824                 closesocket(s);
825 #endif
826                 return -1;
827         }
828         if(listen(s, TCP_BACKLOG) == -1) {
829 #ifndef USE_WINSOCK
830                 log_err("can't listen: %s", strerror(errno));
831                 close(s);
832 #else
833                 log_err("can't listen: %s", wsa_strerror(WSAGetLastError()));
834                 closesocket(s);
835 #endif
836                 return -1;
837         }
838 #ifdef USE_TCP_FASTOPEN
839         /* qlen specifies how many outstanding TFO requests to allow. Limit is a defense
840            against IP spoofing attacks as suggested in RFC7413 */
841 #ifdef __APPLE__
842         /* OS X implementation only supports qlen of 1 via this call. Actual
843            value is configured by the net.inet.tcp.fastopen_backlog kernel parm. */
844         qlen = 1;
845 #else
846         /* 5 is recommended on linux */
847         qlen = 5;
848 #endif
849         if ((setsockopt(s, IPPROTO_TCP, TCP_FASTOPEN, &qlen, 
850                   sizeof(qlen))) == -1 ) {
851 #ifdef ENOPROTOOPT
852                 /* squelch ENOPROTOOPT: freebsd server mode with kernel support
853                    disabled, except when verbosity enabled for debugging */
854                 if(errno != ENOPROTOOPT || verbosity >= 3)
855 #endif
856                   if(errno == EPERM) {
857                         log_warn("Setting TCP Fast Open as server failed: %s ; this could likely be because sysctl net.inet.tcp.fastopen.enabled, net.inet.tcp.fastopen.server_enable, or net.ipv4.tcp_fastopen is disabled", strerror(errno));
858                   } else {
859                         log_err("Setting TCP Fast Open as server failed: %s", strerror(errno));
860                   }
861         }
862 #endif
863         return s;
864 }
865
866 int
867 create_local_accept_sock(const char *path, int* noproto, int use_systemd)
868 {
869 #ifdef HAVE_SYSTEMD
870         int ret;
871
872         if (use_systemd && (ret = systemd_get_activated(AF_LOCAL, SOCK_STREAM, 1, NULL, 0, path)) != -1)
873                 return ret;
874         else {
875 #endif
876 #ifdef HAVE_SYS_UN_H
877         int s;
878         struct sockaddr_un usock;
879 #ifndef HAVE_SYSTEMD
880         (void)use_systemd;
881 #endif
882
883         verbose(VERB_ALGO, "creating unix socket %s", path);
884 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
885         /* this member exists on BSDs, not Linux */
886         usock.sun_len = (unsigned)sizeof(usock);
887 #endif
888         usock.sun_family = AF_LOCAL;
889         /* length is 92-108, 104 on FreeBSD */
890         (void)strlcpy(usock.sun_path, path, sizeof(usock.sun_path));
891
892         if ((s = socket(AF_LOCAL, SOCK_STREAM, 0)) == -1) {
893                 log_err("Cannot create local socket %s (%s)",
894                         path, strerror(errno));
895                 return -1;
896         }
897
898         if (unlink(path) && errno != ENOENT) {
899                 /* The socket already exists and cannot be removed */
900                 log_err("Cannot remove old local socket %s (%s)",
901                         path, strerror(errno));
902                 goto err;
903         }
904
905         if (bind(s, (struct sockaddr *)&usock,
906                 (socklen_t)sizeof(struct sockaddr_un)) == -1) {
907                 log_err("Cannot bind local socket %s (%s)",
908                         path, strerror(errno));
909                 goto err;
910         }
911
912         if (!fd_set_nonblock(s)) {
913                 log_err("Cannot set non-blocking mode");
914                 goto err;
915         }
916
917         if (listen(s, TCP_BACKLOG) == -1) {
918                 log_err("can't listen: %s", strerror(errno));
919                 goto err;
920         }
921
922         (void)noproto; /*unused*/
923         return s;
924
925 err:
926 #ifndef USE_WINSOCK
927         close(s);
928 #else
929         closesocket(s);
930 #endif
931         return -1;
932
933 #ifdef HAVE_SYSTEMD
934         }
935 #endif
936 #else
937         (void)use_systemd;
938         (void)path;
939         log_err("Local sockets are not supported");
940         *noproto = 1;
941         return -1;
942 #endif
943 }
944
945
946 /**
947  * Create socket from getaddrinfo results
948  */
949 static int
950 make_sock(int stype, const char* ifname, const char* port, 
951         struct addrinfo *hints, int v6only, int* noip6, size_t rcv, size_t snd,
952         int* reuseport, int transparent, int tcp_mss, int freebind, int use_systemd)
953 {
954         struct addrinfo *res = NULL;
955         int r, s, inuse, noproto;
956         hints->ai_socktype = stype;
957         *noip6 = 0;
958         if((r=getaddrinfo(ifname, port, hints, &res)) != 0 || !res) {
959 #ifdef USE_WINSOCK
960                 if(r == EAI_NONAME && hints->ai_family == AF_INET6){
961                         *noip6 = 1; /* 'Host not found' for IP6 on winXP */
962                         return -1;
963                 }
964 #endif
965                 log_err("node %s:%s getaddrinfo: %s %s", 
966                         ifname?ifname:"default", port, gai_strerror(r),
967 #ifdef EAI_SYSTEM
968                         r==EAI_SYSTEM?(char*)strerror(errno):""
969 #else
970                         ""
971 #endif
972                 );
973                 return -1;
974         }
975         if(stype == SOCK_DGRAM) {
976                 verbose_print_addr(res);
977                 s = create_udp_sock(res->ai_family, res->ai_socktype,
978                         (struct sockaddr*)res->ai_addr, res->ai_addrlen,
979                         v6only, &inuse, &noproto, (int)rcv, (int)snd, 1,
980                         reuseport, transparent, freebind, use_systemd);
981                 if(s == -1 && inuse) {
982                         log_err("bind: address already in use");
983                 } else if(s == -1 && noproto && hints->ai_family == AF_INET6){
984                         *noip6 = 1;
985                 }
986         } else  {
987                 s = create_tcp_accept_sock(res, v6only, &noproto, reuseport,
988                         transparent, tcp_mss, freebind, use_systemd);
989                 if(s == -1 && noproto && hints->ai_family == AF_INET6){
990                         *noip6 = 1;
991                 }
992         }
993         freeaddrinfo(res);
994         return s;
995 }
996
997 /** make socket and first see if ifname contains port override info */
998 static int
999 make_sock_port(int stype, const char* ifname, const char* port, 
1000         struct addrinfo *hints, int v6only, int* noip6, size_t rcv, size_t snd,
1001         int* reuseport, int transparent, int tcp_mss, int freebind, int use_systemd)
1002 {
1003         char* s = strchr(ifname, '@');
1004         if(s) {
1005                 /* override port with ifspec@port */
1006                 char p[16];
1007                 char newif[128];
1008                 if((size_t)(s-ifname) >= sizeof(newif)) {
1009                         log_err("ifname too long: %s", ifname);
1010                         *noip6 = 0;
1011                         return -1;
1012                 }
1013                 if(strlen(s+1) >= sizeof(p)) {
1014                         log_err("portnumber too long: %s", ifname);
1015                         *noip6 = 0;
1016                         return -1;
1017                 }
1018                 (void)strlcpy(newif, ifname, sizeof(newif));
1019                 newif[s-ifname] = 0;
1020                 (void)strlcpy(p, s+1, sizeof(p));
1021                 p[strlen(s+1)]=0;
1022                 return make_sock(stype, newif, p, hints, v6only, noip6,
1023                         rcv, snd, reuseport, transparent, tcp_mss, freebind, use_systemd);
1024         }
1025         return make_sock(stype, ifname, port, hints, v6only, noip6, rcv, snd,
1026                 reuseport, transparent, tcp_mss, freebind, use_systemd);
1027 }
1028
1029 /**
1030  * Add port to open ports list.
1031  * @param list: list head. changed.
1032  * @param s: fd.
1033  * @param ftype: if fd is UDP.
1034  * @return false on failure. list in unchanged then.
1035  */
1036 static int
1037 port_insert(struct listen_port** list, int s, enum listen_type ftype)
1038 {
1039         struct listen_port* item = (struct listen_port*)malloc(
1040                 sizeof(struct listen_port));
1041         if(!item)
1042                 return 0;
1043         item->next = *list;
1044         item->fd = s;
1045         item->ftype = ftype;
1046         *list = item;
1047         return 1;
1048 }
1049
1050 /** set fd to receive source address packet info */
1051 static int
1052 set_recvpktinfo(int s, int family) 
1053 {
1054 #if defined(IPV6_RECVPKTINFO) || defined(IPV6_PKTINFO) || (defined(IP_RECVDSTADDR) && defined(IP_SENDSRCADDR)) || defined(IP_PKTINFO)
1055         int on = 1;
1056 #else
1057         (void)s;
1058 #endif
1059         if(family == AF_INET6) {
1060 #           ifdef IPV6_RECVPKTINFO
1061                 if(setsockopt(s, IPPROTO_IPV6, IPV6_RECVPKTINFO,
1062                         (void*)&on, (socklen_t)sizeof(on)) < 0) {
1063                         log_err("setsockopt(..., IPV6_RECVPKTINFO, ...) failed: %s",
1064                                 strerror(errno));
1065                         return 0;
1066                 }
1067 #           elif defined(IPV6_PKTINFO)
1068                 if(setsockopt(s, IPPROTO_IPV6, IPV6_PKTINFO,
1069                         (void*)&on, (socklen_t)sizeof(on)) < 0) {
1070                         log_err("setsockopt(..., IPV6_PKTINFO, ...) failed: %s",
1071                                 strerror(errno));
1072                         return 0;
1073                 }
1074 #           else
1075                 log_err("no IPV6_RECVPKTINFO and no IPV6_PKTINFO option, please "
1076                         "disable interface-automatic or do-ip6 in config");
1077                 return 0;
1078 #           endif /* defined IPV6_RECVPKTINFO */
1079
1080         } else if(family == AF_INET) {
1081 #           ifdef IP_PKTINFO
1082                 if(setsockopt(s, IPPROTO_IP, IP_PKTINFO,
1083                         (void*)&on, (socklen_t)sizeof(on)) < 0) {
1084                         log_err("setsockopt(..., IP_PKTINFO, ...) failed: %s",
1085                                 strerror(errno));
1086                         return 0;
1087                 }
1088 #           elif defined(IP_RECVDSTADDR) && defined(IP_SENDSRCADDR)
1089                 if(setsockopt(s, IPPROTO_IP, IP_RECVDSTADDR,
1090                         (void*)&on, (socklen_t)sizeof(on)) < 0) {
1091                         log_err("setsockopt(..., IP_RECVDSTADDR, ...) failed: %s",
1092                                 strerror(errno));
1093                         return 0;
1094                 }
1095 #           else
1096                 log_err("no IP_SENDSRCADDR or IP_PKTINFO option, please disable "
1097                         "interface-automatic or do-ip4 in config");
1098                 return 0;
1099 #           endif /* IP_PKTINFO */
1100
1101         }
1102         return 1;
1103 }
1104
1105 /** see if interface is ssl, its port number == the ssl port number */
1106 static int
1107 if_is_ssl(const char* ifname, const char* port, int ssl_port,
1108         struct config_strlist* tls_additional_port)
1109 {
1110         struct config_strlist* s;
1111         char* p = strchr(ifname, '@');
1112         if(!p && atoi(port) == ssl_port)
1113                 return 1;
1114         if(p && atoi(p+1) == ssl_port)
1115                 return 1;
1116         for(s = tls_additional_port; s; s = s->next) {
1117                 if(p && atoi(p+1) == atoi(s->str))
1118                         return 1;
1119                 if(!p && atoi(port) == atoi(s->str))
1120                         return 1;
1121         }
1122         return 0;
1123 }
1124
1125 /**
1126  * Helper for ports_open. Creates one interface (or NULL for default).
1127  * @param ifname: The interface ip address.
1128  * @param do_auto: use automatic interface detection.
1129  *      If enabled, then ifname must be the wildcard name.
1130  * @param do_udp: if udp should be used.
1131  * @param do_tcp: if udp should be used.
1132  * @param hints: for getaddrinfo. family and flags have to be set by caller.
1133  * @param port: Port number to use (as string).
1134  * @param list: list of open ports, appended to, changed to point to list head.
1135  * @param rcv: receive buffer size for UDP
1136  * @param snd: send buffer size for UDP
1137  * @param ssl_port: ssl service port number
1138  * @param tls_additional_port: list of additional ssl service port numbers.
1139  * @param reuseport: try to set SO_REUSEPORT if nonNULL and true.
1140  *      set to false on exit if reuseport failed due to no kernel support.
1141  * @param transparent: set IP_TRANSPARENT socket option.
1142  * @param tcp_mss: maximum segment size of tcp socket. default if zero.
1143  * @param freebind: set IP_FREEBIND socket option.
1144  * @param use_systemd: if true, fetch sockets from systemd.
1145  * @param dnscrypt_port: dnscrypt service port number
1146  * @return: returns false on error.
1147  */
1148 static int
1149 ports_create_if(const char* ifname, int do_auto, int do_udp, int do_tcp, 
1150         struct addrinfo *hints, const char* port, struct listen_port** list,
1151         size_t rcv, size_t snd, int ssl_port,
1152         struct config_strlist* tls_additional_port, int* reuseport,
1153         int transparent, int tcp_mss, int freebind, int use_systemd,
1154         int dnscrypt_port)
1155 {
1156         int s, noip6=0;
1157 #ifdef USE_DNSCRYPT
1158         int is_dnscrypt = ((strchr(ifname, '@') && 
1159                         atoi(strchr(ifname, '@')+1) == dnscrypt_port) ||
1160                         (!strchr(ifname, '@') && atoi(port) == dnscrypt_port));
1161 #else
1162         int is_dnscrypt = 0;
1163         (void)dnscrypt_port;
1164 #endif
1165
1166         if(!do_udp && !do_tcp)
1167                 return 0;
1168         if(do_auto) {
1169                 if((s = make_sock_port(SOCK_DGRAM, ifname, port, hints, 1, 
1170                         &noip6, rcv, snd, reuseport, transparent,
1171                         tcp_mss, freebind, use_systemd)) == -1) {
1172                         if(noip6) {
1173                                 log_warn("IPv6 protocol not available");
1174                                 return 1;
1175                         }
1176                         return 0;
1177                 }
1178                 /* getting source addr packet info is highly non-portable */
1179                 if(!set_recvpktinfo(s, hints->ai_family)) {
1180 #ifndef USE_WINSOCK
1181                         close(s);
1182 #else
1183                         closesocket(s);
1184 #endif
1185                         return 0;
1186                 }
1187                 if(!port_insert(list, s,
1188                    is_dnscrypt?listen_type_udpancil_dnscrypt:listen_type_udpancil)) {
1189 #ifndef USE_WINSOCK
1190                         close(s);
1191 #else
1192                         closesocket(s);
1193 #endif
1194                         return 0;
1195                 }
1196         } else if(do_udp) {
1197                 /* regular udp socket */
1198                 if((s = make_sock_port(SOCK_DGRAM, ifname, port, hints, 1, 
1199                         &noip6, rcv, snd, reuseport, transparent,
1200                         tcp_mss, freebind, use_systemd)) == -1) {
1201                         if(noip6) {
1202                                 log_warn("IPv6 protocol not available");
1203                                 return 1;
1204                         }
1205                         return 0;
1206                 }
1207                 if(!port_insert(list, s,
1208                    is_dnscrypt?listen_type_udp_dnscrypt:listen_type_udp)) {
1209 #ifndef USE_WINSOCK
1210                         close(s);
1211 #else
1212                         closesocket(s);
1213 #endif
1214                         return 0;
1215                 }
1216         }
1217         if(do_tcp) {
1218                 int is_ssl = if_is_ssl(ifname, port, ssl_port,
1219                         tls_additional_port);
1220                 if((s = make_sock_port(SOCK_STREAM, ifname, port, hints, 1, 
1221                         &noip6, 0, 0, reuseport, transparent, tcp_mss,
1222                         freebind, use_systemd)) == -1) {
1223                         if(noip6) {
1224                                 /*log_warn("IPv6 protocol not available");*/
1225                                 return 1;
1226                         }
1227                         return 0;
1228                 }
1229                 if(is_ssl)
1230                         verbose(VERB_ALGO, "setup TCP for SSL service");
1231                 if(!port_insert(list, s, is_ssl?listen_type_ssl:
1232                         (is_dnscrypt?listen_type_tcp_dnscrypt:listen_type_tcp))) {
1233 #ifndef USE_WINSOCK
1234                         close(s);
1235 #else
1236                         closesocket(s);
1237 #endif
1238                         return 0;
1239                 }
1240         }
1241         return 1;
1242 }
1243
1244 /** 
1245  * Add items to commpoint list in front.
1246  * @param c: commpoint to add.
1247  * @param front: listen struct.
1248  * @return: false on failure.
1249  */
1250 static int
1251 listen_cp_insert(struct comm_point* c, struct listen_dnsport* front)
1252 {
1253         struct listen_list* item = (struct listen_list*)malloc(
1254                 sizeof(struct listen_list));
1255         if(!item)
1256                 return 0;
1257         item->com = c;
1258         item->next = front->cps;
1259         front->cps = item;
1260         return 1;
1261 }
1262
1263 struct listen_dnsport* 
1264 listen_create(struct comm_base* base, struct listen_port* ports,
1265         size_t bufsize, int tcp_accept_count, int tcp_idle_timeout,
1266         struct tcl_list* tcp_conn_limit, void* sslctx,
1267         struct dt_env* dtenv, comm_point_callback_type* cb, void *cb_arg)
1268 {
1269         struct listen_dnsport* front = (struct listen_dnsport*)
1270                 malloc(sizeof(struct listen_dnsport));
1271         if(!front)
1272                 return NULL;
1273         front->cps = NULL;
1274         front->udp_buff = sldns_buffer_new(bufsize);
1275 #ifdef USE_DNSCRYPT
1276         front->dnscrypt_udp_buff = NULL;
1277 #endif
1278         if(!front->udp_buff) {
1279                 free(front);
1280                 return NULL;
1281         }
1282         if(!stream_wait_lock_inited) {
1283                 lock_basic_init(&stream_wait_count_lock);
1284                 stream_wait_lock_inited = 1;
1285         }
1286
1287         /* create comm points as needed */
1288         while(ports) {
1289                 struct comm_point* cp = NULL;
1290                 if(ports->ftype == listen_type_udp ||
1291                    ports->ftype == listen_type_udp_dnscrypt)
1292                         cp = comm_point_create_udp(base, ports->fd, 
1293                                 front->udp_buff, cb, cb_arg);
1294                 else if(ports->ftype == listen_type_tcp ||
1295                                 ports->ftype == listen_type_tcp_dnscrypt)
1296                         cp = comm_point_create_tcp(base, ports->fd, 
1297                                 tcp_accept_count, tcp_idle_timeout,
1298                                 tcp_conn_limit, bufsize, front->udp_buff,
1299                                 cb, cb_arg);
1300                 else if(ports->ftype == listen_type_ssl) {
1301                         cp = comm_point_create_tcp(base, ports->fd, 
1302                                 tcp_accept_count, tcp_idle_timeout,
1303                                 tcp_conn_limit, bufsize, front->udp_buff,
1304                                 cb, cb_arg);
1305                         cp->ssl = sslctx;
1306                 } else if(ports->ftype == listen_type_udpancil ||
1307                                   ports->ftype == listen_type_udpancil_dnscrypt)
1308                         cp = comm_point_create_udp_ancil(base, ports->fd, 
1309                                 front->udp_buff, cb, cb_arg);
1310                 if(!cp) {
1311                         log_err("can't create commpoint");      
1312                         listen_delete(front);
1313                         return NULL;
1314                 }
1315                 cp->dtenv = dtenv;
1316                 cp->do_not_close = 1;
1317 #ifdef USE_DNSCRYPT
1318                 if (ports->ftype == listen_type_udp_dnscrypt ||
1319                         ports->ftype == listen_type_tcp_dnscrypt ||
1320                         ports->ftype == listen_type_udpancil_dnscrypt) {
1321                         cp->dnscrypt = 1;
1322                         cp->dnscrypt_buffer = sldns_buffer_new(bufsize);
1323                         if(!cp->dnscrypt_buffer) {
1324                                 log_err("can't alloc dnscrypt_buffer");
1325                                 comm_point_delete(cp);
1326                                 listen_delete(front);
1327                                 return NULL;
1328                         }
1329                         front->dnscrypt_udp_buff = cp->dnscrypt_buffer;
1330                 }
1331 #endif
1332                 if(!listen_cp_insert(cp, front)) {
1333                         log_err("malloc failed");
1334                         comm_point_delete(cp);
1335                         listen_delete(front);
1336                         return NULL;
1337                 }
1338                 ports = ports->next;
1339         }
1340         if(!front->cps) {
1341                 log_err("Could not open sockets to accept queries.");
1342                 listen_delete(front);
1343                 return NULL;
1344         }
1345
1346         return front;
1347 }
1348
1349 void
1350 listen_list_delete(struct listen_list* list)
1351 {
1352         struct listen_list *p = list, *pn;
1353         while(p) {
1354                 pn = p->next;
1355                 comm_point_delete(p->com);
1356                 free(p);
1357                 p = pn;
1358         }
1359 }
1360
1361 void 
1362 listen_delete(struct listen_dnsport* front)
1363 {
1364         if(!front) 
1365                 return;
1366         listen_list_delete(front->cps);
1367 #ifdef USE_DNSCRYPT
1368         if(front->dnscrypt_udp_buff &&
1369                 front->udp_buff != front->dnscrypt_udp_buff) {
1370                 sldns_buffer_free(front->dnscrypt_udp_buff);
1371         }
1372 #endif
1373         sldns_buffer_free(front->udp_buff);
1374         free(front);
1375         if(stream_wait_lock_inited) {
1376                 stream_wait_lock_inited = 0;
1377                 lock_basic_destroy(&stream_wait_count_lock);
1378         }
1379 }
1380
1381 struct listen_port* 
1382 listening_ports_open(struct config_file* cfg, int* reuseport)
1383 {
1384         struct listen_port* list = NULL;
1385         struct addrinfo hints;
1386         int i, do_ip4, do_ip6;
1387         int do_tcp, do_auto;
1388         char portbuf[32];
1389         snprintf(portbuf, sizeof(portbuf), "%d", cfg->port);
1390         do_ip4 = cfg->do_ip4;
1391         do_ip6 = cfg->do_ip6;
1392         do_tcp = cfg->do_tcp;
1393         do_auto = cfg->if_automatic && cfg->do_udp;
1394         if(cfg->incoming_num_tcp == 0)
1395                 do_tcp = 0;
1396
1397         /* getaddrinfo */
1398         memset(&hints, 0, sizeof(hints));
1399         hints.ai_flags = AI_PASSIVE;
1400         /* no name lookups on our listening ports */
1401         if(cfg->num_ifs > 0)
1402                 hints.ai_flags |= AI_NUMERICHOST;
1403         hints.ai_family = AF_UNSPEC;
1404 #ifndef INET6
1405         do_ip6 = 0;
1406 #endif
1407         if(!do_ip4 && !do_ip6) {
1408                 return NULL;
1409         }
1410         /* create ip4 and ip6 ports so that return addresses are nice. */
1411         if(do_auto || cfg->num_ifs == 0) {
1412                 if(do_ip6) {
1413                         hints.ai_family = AF_INET6;
1414                         if(!ports_create_if(do_auto?"::0":"::1", 
1415                                 do_auto, cfg->do_udp, do_tcp, 
1416                                 &hints, portbuf, &list,
1417                                 cfg->so_rcvbuf, cfg->so_sndbuf,
1418                                 cfg->ssl_port, cfg->tls_additional_port,
1419                                 reuseport, cfg->ip_transparent,
1420                                 cfg->tcp_mss, cfg->ip_freebind, cfg->use_systemd,
1421                                 cfg->dnscrypt_port)) {
1422                                 listening_ports_free(list);
1423                                 return NULL;
1424                         }
1425                 }
1426                 if(do_ip4) {
1427                         hints.ai_family = AF_INET;
1428                         if(!ports_create_if(do_auto?"0.0.0.0":"127.0.0.1", 
1429                                 do_auto, cfg->do_udp, do_tcp, 
1430                                 &hints, portbuf, &list,
1431                                 cfg->so_rcvbuf, cfg->so_sndbuf,
1432                                 cfg->ssl_port, cfg->tls_additional_port,
1433                                 reuseport, cfg->ip_transparent,
1434                                 cfg->tcp_mss, cfg->ip_freebind, cfg->use_systemd,
1435                                 cfg->dnscrypt_port)) {
1436                                 listening_ports_free(list);
1437                                 return NULL;
1438                         }
1439                 }
1440         } else for(i = 0; i<cfg->num_ifs; i++) {
1441                 if(str_is_ip6(cfg->ifs[i])) {
1442                         if(!do_ip6)
1443                                 continue;
1444                         hints.ai_family = AF_INET6;
1445                         if(!ports_create_if(cfg->ifs[i], 0, cfg->do_udp, 
1446                                 do_tcp, &hints, portbuf, &list, 
1447                                 cfg->so_rcvbuf, cfg->so_sndbuf,
1448                                 cfg->ssl_port, cfg->tls_additional_port,
1449                                 reuseport, cfg->ip_transparent,
1450                                 cfg->tcp_mss, cfg->ip_freebind, cfg->use_systemd,
1451                                 cfg->dnscrypt_port)) {
1452                                 listening_ports_free(list);
1453                                 return NULL;
1454                         }
1455                 } else {
1456                         if(!do_ip4)
1457                                 continue;
1458                         hints.ai_family = AF_INET;
1459                         if(!ports_create_if(cfg->ifs[i], 0, cfg->do_udp, 
1460                                 do_tcp, &hints, portbuf, &list, 
1461                                 cfg->so_rcvbuf, cfg->so_sndbuf,
1462                                 cfg->ssl_port, cfg->tls_additional_port,
1463                                 reuseport, cfg->ip_transparent,
1464                                 cfg->tcp_mss, cfg->ip_freebind, cfg->use_systemd,
1465                                 cfg->dnscrypt_port)) {
1466                                 listening_ports_free(list);
1467                                 return NULL;
1468                         }
1469                 }
1470         }
1471         return list;
1472 }
1473
1474 void listening_ports_free(struct listen_port* list)
1475 {
1476         struct listen_port* nx;
1477         while(list) {
1478                 nx = list->next;
1479                 if(list->fd != -1) {
1480 #ifndef USE_WINSOCK
1481                         close(list->fd);
1482 #else
1483                         closesocket(list->fd);
1484 #endif
1485                 }
1486                 free(list);
1487                 list = nx;
1488         }
1489 }
1490
1491 size_t listen_get_mem(struct listen_dnsport* listen)
1492 {
1493         struct listen_list* p;
1494         size_t s = sizeof(*listen) + sizeof(*listen->base) + 
1495                 sizeof(*listen->udp_buff) + 
1496                 sldns_buffer_capacity(listen->udp_buff);
1497 #ifdef USE_DNSCRYPT
1498         s += sizeof(*listen->dnscrypt_udp_buff);
1499         if(listen->udp_buff != listen->dnscrypt_udp_buff){
1500                 s += sldns_buffer_capacity(listen->dnscrypt_udp_buff);
1501         }
1502 #endif
1503         for(p = listen->cps; p; p = p->next) {
1504                 s += sizeof(*p);
1505                 s += comm_point_get_mem(p->com);
1506         }
1507         return s;
1508 }
1509
1510 void listen_stop_accept(struct listen_dnsport* listen)
1511 {
1512         /* do not stop the ones that have no tcp_free list
1513          * (they have already stopped listening) */
1514         struct listen_list* p;
1515         for(p=listen->cps; p; p=p->next) {
1516                 if(p->com->type == comm_tcp_accept &&
1517                         p->com->tcp_free != NULL) {
1518                         comm_point_stop_listening(p->com);
1519                 }
1520         }
1521 }
1522
1523 void listen_start_accept(struct listen_dnsport* listen)
1524 {
1525         /* do not start the ones that have no tcp_free list, it is no
1526          * use to listen to them because they have no free tcp handlers */
1527         struct listen_list* p;
1528         for(p=listen->cps; p; p=p->next) {
1529                 if(p->com->type == comm_tcp_accept &&
1530                         p->com->tcp_free != NULL) {
1531                         comm_point_start_listening(p->com, -1, -1);
1532                 }
1533         }
1534 }
1535
1536 struct tcp_req_info*
1537 tcp_req_info_create(struct sldns_buffer* spoolbuf)
1538 {
1539         struct tcp_req_info* req = (struct tcp_req_info*)malloc(sizeof(*req));
1540         if(!req) {
1541                 log_err("malloc failure for new stream outoforder processing structure");
1542                 return NULL;
1543         }
1544         memset(req, 0, sizeof(*req));
1545         req->spool_buffer = spoolbuf;
1546         return req;
1547 }
1548
1549 void
1550 tcp_req_info_delete(struct tcp_req_info* req)
1551 {
1552         if(!req) return;
1553         tcp_req_info_clear(req);
1554         /* cp is pointer back to commpoint that owns this struct and
1555          * called delete on us */
1556         /* spool_buffer is shared udp buffer, not deleted here */
1557         free(req);
1558 }
1559
1560 void tcp_req_info_clear(struct tcp_req_info* req)
1561 {
1562         struct tcp_req_open_item* open, *nopen;
1563         struct tcp_req_done_item* item, *nitem;
1564         if(!req) return;
1565
1566         /* free outstanding request mesh reply entries */
1567         open = req->open_req_list;
1568         while(open) {
1569                 nopen = open->next;
1570                 mesh_state_remove_reply(open->mesh, open->mesh_state, req->cp);
1571                 free(open);
1572                 open = nopen;
1573         }
1574         req->open_req_list = NULL;
1575         req->num_open_req = 0;
1576         
1577         /* free pending writable result packets */
1578         item = req->done_req_list;
1579         while(item) {
1580                 nitem = item->next;
1581                 lock_basic_lock(&stream_wait_count_lock);
1582                 stream_wait_count -= (sizeof(struct tcp_req_done_item)
1583                         +item->len);
1584                 lock_basic_unlock(&stream_wait_count_lock);
1585                 free(item->buf);
1586                 free(item);
1587                 item = nitem;
1588         }
1589         req->done_req_list = NULL;
1590         req->num_done_req = 0;
1591         req->read_is_closed = 0;
1592 }
1593
1594 void
1595 tcp_req_info_remove_mesh_state(struct tcp_req_info* req, struct mesh_state* m)
1596 {
1597         struct tcp_req_open_item* open, *prev = NULL;
1598         if(!req || !m) return;
1599         open = req->open_req_list;
1600         while(open) {
1601                 if(open->mesh_state == m) {
1602                         struct tcp_req_open_item* next;
1603                         if(prev) prev->next = open->next;
1604                         else req->open_req_list = open->next;
1605                         /* caller has to manage the mesh state reply entry */
1606                         next = open->next;
1607                         free(open);
1608                         req->num_open_req --;
1609
1610                         /* prev = prev; */
1611                         open = next;
1612                         continue;
1613                 }
1614                 prev = open;
1615                 open = open->next;
1616         }
1617 }
1618
1619 /** setup listening for read or write */
1620 static void
1621 tcp_req_info_setup_listen(struct tcp_req_info* req)
1622 {
1623         int wr = 0;
1624         int rd = 0;
1625
1626         if(req->cp->tcp_byte_count != 0) {
1627                 /* cannot change, halfway through */
1628                 return;
1629         }
1630
1631         if(!req->cp->tcp_is_reading)
1632                 wr = 1;
1633         if(req->num_open_req + req->num_done_req < TCP_MAX_REQ_SIMULTANEOUS &&
1634                 !req->read_is_closed)
1635                 rd = 1;
1636         
1637         if(wr) {
1638                 req->cp->tcp_is_reading = 0;
1639                 comm_point_start_listening(req->cp, -1,
1640                         req->cp->tcp_timeout_msec);
1641         } else if(rd) {
1642                 req->cp->tcp_is_reading = 1;
1643                 comm_point_start_listening(req->cp, -1,
1644                         req->cp->tcp_timeout_msec);
1645                 /* and also read it (from SSL stack buffers), so
1646                  * no event read event is expected since the remainder of
1647                  * the TLS frame is sitting in the buffers. */
1648                 req->read_again = 1;
1649         } else {
1650                 comm_point_start_listening(req->cp, -1,
1651                         req->cp->tcp_timeout_msec);
1652                 comm_point_listen_for_rw(req->cp, 0, 0);
1653         }
1654 }
1655
1656 /** remove first item from list of pending results */
1657 static struct tcp_req_done_item*
1658 tcp_req_info_pop_done(struct tcp_req_info* req)
1659 {
1660         struct tcp_req_done_item* item;
1661         log_assert(req->num_done_req > 0 && req->done_req_list);
1662         item = req->done_req_list;
1663         lock_basic_lock(&stream_wait_count_lock);
1664         stream_wait_count -= (sizeof(struct tcp_req_done_item)+item->len);
1665         lock_basic_unlock(&stream_wait_count_lock);
1666         req->done_req_list = req->done_req_list->next;
1667         req->num_done_req --;
1668         return item;
1669 }
1670
1671 /** Send given buffer and setup to write */
1672 static void
1673 tcp_req_info_start_write_buf(struct tcp_req_info* req, uint8_t* buf,
1674         size_t len)
1675 {
1676         sldns_buffer_clear(req->cp->buffer);
1677         sldns_buffer_write(req->cp->buffer, buf, len);
1678         sldns_buffer_flip(req->cp->buffer);
1679
1680         req->cp->tcp_is_reading = 0; /* we are now writing */
1681 }
1682
1683 /** pick up the next result and start writing it to the channel */
1684 static void
1685 tcp_req_pickup_next_result(struct tcp_req_info* req)
1686 {
1687         if(req->num_done_req > 0) {
1688                 /* unlist the done item from the list of pending results */
1689                 struct tcp_req_done_item* item = tcp_req_info_pop_done(req);
1690                 tcp_req_info_start_write_buf(req, item->buf, item->len);
1691                 free(item->buf);
1692                 free(item);
1693         }
1694 }
1695
1696 /** the read channel has closed */
1697 int
1698 tcp_req_info_handle_read_close(struct tcp_req_info* req)
1699 {
1700         verbose(VERB_ALGO, "tcp channel read side closed %d", req->cp->fd);
1701         /* reset byte count for (potential) partial read */
1702         req->cp->tcp_byte_count = 0;
1703         /* if we still have results to write, pick up next and write it */
1704         if(req->num_done_req != 0) {
1705                 tcp_req_pickup_next_result(req);
1706                 tcp_req_info_setup_listen(req);
1707                 return 1;
1708         }
1709         /* if nothing to do, this closes the connection */
1710         if(req->num_open_req == 0 && req->num_done_req == 0)
1711                 return 0;
1712         /* otherwise, we must be waiting for dns resolve, wait with timeout */
1713         req->read_is_closed = 1;
1714         tcp_req_info_setup_listen(req);
1715         return 1;
1716 }
1717
1718 void
1719 tcp_req_info_handle_writedone(struct tcp_req_info* req)
1720 {
1721         /* back to reading state, we finished this write event */
1722         sldns_buffer_clear(req->cp->buffer);
1723         if(req->num_done_req == 0 && req->read_is_closed) {
1724                 /* no more to write and nothing to read, close it */
1725                 comm_point_drop_reply(&req->cp->repinfo);
1726                 return;
1727         }
1728         req->cp->tcp_is_reading = 1;
1729         /* see if another result needs writing */
1730         tcp_req_pickup_next_result(req);
1731
1732         /* see if there is more to write, if not stop_listening for writing */
1733         /* see if new requests are allowed, if so, start_listening
1734          * for reading */
1735         tcp_req_info_setup_listen(req);
1736 }
1737
1738 void
1739 tcp_req_info_handle_readdone(struct tcp_req_info* req)
1740 {
1741         struct comm_point* c = req->cp;
1742
1743         /* we want to read up several requests, unless there are
1744          * pending answers */
1745
1746         req->is_drop = 0;
1747         req->is_reply = 0;
1748         req->in_worker_handle = 1;
1749         /* handle the current request */
1750         /* this calls the worker handle request routine that could give
1751          * a cache response, or localdata response, or drop the reply,
1752          * or schedule a mesh entry for later */
1753         fptr_ok(fptr_whitelist_comm_point(c->callback));
1754         if( (*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, &c->repinfo) ) {
1755                 req->in_worker_handle = 0;
1756                 /* there is an answer, put it up.  It is already in the
1757                  * c->buffer, just send it. */
1758                 /* since we were just reading a query, the channel is
1759                  * clear to write to */
1760         send_it:
1761                 c->tcp_is_reading = 0;
1762                 comm_point_start_listening(c, -1, c->tcp_timeout_msec);
1763                 return;
1764         }
1765         req->in_worker_handle = 0;
1766         /* it should be waiting in the mesh for recursion.
1767          * If mesh failed to add a new entry and called commpoint_drop_reply. 
1768          * Then the mesh state has been cleared. */
1769         if(req->is_drop) {
1770                 /* we can now call drop_reply without recursing into ourselves
1771                  * whilst in the callback */
1772                 /* we have to close the stream because there is no reply,
1773                  * no servfail to send, but the query needs an action, for
1774                  * a stream that is close the connection */
1775                 sldns_buffer_clear(c->buffer);
1776                 comm_point_drop_reply(&c->repinfo);
1777                 return;
1778         }
1779         /* If mesh failed(mallocfail) and called commpoint_send_reply with
1780          * something like servfail then we pick up that reply below. */
1781         if(req->is_reply) {
1782                 goto send_it;
1783         }
1784
1785         sldns_buffer_clear(c->buffer);
1786         /* if pending answers, pick up an answer and start sending it */
1787         tcp_req_pickup_next_result(req);
1788
1789         /* if answers pending, start sending answers */
1790         /* read more requests if we can have more requests */
1791         tcp_req_info_setup_listen(req);
1792 }
1793
1794 int
1795 tcp_req_info_add_meshstate(struct tcp_req_info* req,
1796         struct mesh_area* mesh, struct mesh_state* m)
1797 {
1798         struct tcp_req_open_item* item;
1799         log_assert(req && mesh && m);
1800         item = (struct tcp_req_open_item*)malloc(sizeof(*item));
1801         if(!item) return 0;
1802         item->next = req->open_req_list;
1803         item->mesh = mesh;
1804         item->mesh_state = m;
1805         req->open_req_list = item;
1806         req->num_open_req++;
1807         return 1;
1808 }
1809
1810 /** Add a result to the result list.  At the end. */
1811 static int
1812 tcp_req_info_add_result(struct tcp_req_info* req, uint8_t* buf, size_t len)
1813 {
1814         struct tcp_req_done_item* last = NULL;
1815         struct tcp_req_done_item* item;
1816         size_t space;
1817
1818         /* see if we have space */
1819         space = sizeof(struct tcp_req_done_item) + len;
1820         lock_basic_lock(&stream_wait_count_lock);
1821         if(stream_wait_count + space > stream_wait_max) {
1822                 lock_basic_unlock(&stream_wait_count_lock);
1823                 verbose(VERB_ALGO, "drop stream reply, no space left, in stream-wait-size");
1824                 return 0;
1825         }
1826         stream_wait_count += space;
1827         lock_basic_unlock(&stream_wait_count_lock);
1828
1829         /* find last element */
1830         last = req->done_req_list;
1831         while(last && last->next)
1832                 last = last->next;
1833         
1834         /* create new element */
1835         item = (struct tcp_req_done_item*)malloc(sizeof(*item));
1836         if(!item) {
1837                 log_err("malloc failure, for stream result list");
1838                 return 0;
1839         }
1840         item->next = NULL;
1841         item->len = len;
1842         item->buf = memdup(buf, len);
1843         if(!item->buf) {
1844                 free(item);
1845                 log_err("malloc failure, adding reply to stream result list");
1846                 return 0;
1847         }
1848
1849         /* link in */
1850         if(last) last->next = item;
1851         else req->done_req_list = item;
1852         req->num_done_req++;
1853         return 1;
1854 }
1855
1856 void
1857 tcp_req_info_send_reply(struct tcp_req_info* req)
1858 {
1859         if(req->in_worker_handle) {
1860                 /* It is in the right buffer to answer straight away */
1861                 req->is_reply = 1;
1862                 return;
1863         }
1864         /* now that the query has been handled, that mesh_reply entry
1865          * should be removed, from the tcp_req_info list,
1866          * the mesh state cleanup removes then with region_cleanup and
1867          * replies_sent true. */
1868         /* see if we can send it straight away (we are not doing
1869          * anything else).  If so, copy to buffer and start */
1870         if(req->cp->tcp_is_reading && req->cp->tcp_byte_count == 0) {
1871                 /* buffer is free, and was ready to read new query into,
1872                  * but we are now going to use it to send this answer */
1873                 tcp_req_info_start_write_buf(req,
1874                         sldns_buffer_begin(req->spool_buffer),
1875                         sldns_buffer_limit(req->spool_buffer));
1876                 /* switch to listen to write events */
1877                 comm_point_stop_listening(req->cp);
1878                 comm_point_start_listening(req->cp, -1,
1879                         req->cp->tcp_timeout_msec);
1880                 return;
1881         }
1882         /* queue up the answer behind the others already pending */
1883         if(!tcp_req_info_add_result(req, sldns_buffer_begin(req->spool_buffer),
1884                 sldns_buffer_limit(req->spool_buffer))) {
1885                 /* drop the connection, we are out of resources */
1886                 comm_point_drop_reply(&req->cp->repinfo);
1887         }
1888 }
1889
1890 size_t tcp_req_info_get_stream_buffer_size(void)
1891 {
1892         size_t s;
1893         if(!stream_wait_lock_inited)
1894                 return stream_wait_count;
1895         lock_basic_lock(&stream_wait_count_lock);
1896         s = stream_wait_count;
1897         lock_basic_unlock(&stream_wait_count_lock);
1898         return s;
1899 }