]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/unbound/services/listen_dnsport.c
MFV CK@r336629: Import CK as of commit 1c1f9901c2dea7a883342cd03d3906a1bc482583
[FreeBSD/FreeBSD.git] / contrib / unbound / 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
57 #ifdef HAVE_NETDB_H
58 #include <netdb.h>
59 #endif
60 #include <fcntl.h>
61
62 #ifdef HAVE_SYS_UN_H
63 #include <sys/un.h>
64 #endif
65
66 #ifdef HAVE_SYSTEMD
67 #include <systemd/sd-daemon.h>
68 #endif
69
70 /** number of queued TCP connections for listen() */
71 #define TCP_BACKLOG 256 
72
73 /**
74  * Debug print of the getaddrinfo returned address.
75  * @param addr: the address returned.
76  */
77 static void
78 verbose_print_addr(struct addrinfo *addr)
79 {
80         if(verbosity >= VERB_ALGO) {
81                 char buf[100];
82                 void* sinaddr = &((struct sockaddr_in*)addr->ai_addr)->sin_addr;
83 #ifdef INET6
84                 if(addr->ai_family == AF_INET6)
85                         sinaddr = &((struct sockaddr_in6*)addr->ai_addr)->
86                                 sin6_addr;
87 #endif /* INET6 */
88                 if(inet_ntop(addr->ai_family, sinaddr, buf,
89                         (socklen_t)sizeof(buf)) == 0) {
90                         (void)strlcpy(buf, "(null)", sizeof(buf));
91                 }
92                 buf[sizeof(buf)-1] = 0;
93                 verbose(VERB_ALGO, "creating %s%s socket %s %d", 
94                         addr->ai_socktype==SOCK_DGRAM?"udp":
95                         addr->ai_socktype==SOCK_STREAM?"tcp":"otherproto",
96                         addr->ai_family==AF_INET?"4":
97                         addr->ai_family==AF_INET6?"6":
98                         "_otherfam", buf, 
99                         ntohs(((struct sockaddr_in*)addr->ai_addr)->sin_port));
100         }
101 }
102
103 #ifdef HAVE_SYSTEMD
104 static int
105 systemd_get_activated(int family, int socktype, int listen,
106                       struct sockaddr *addr, socklen_t addrlen,
107                       const char *path)
108 {
109         int i = 0;
110         int r = 0;
111         int s = -1;
112         const char* listen_pid, *listen_fds;
113
114         /* We should use "listen" option only for stream protocols. For UDP it should be -1 */
115
116         if((r = sd_booted()) < 1) {
117                 if(r == 0)
118                         log_warn("systemd is not running");
119                 else
120                         log_err("systemd sd_booted(): %s", strerror(-r));
121                 return -1;
122         }
123
124         listen_pid = getenv("LISTEN_PID");
125         listen_fds = getenv("LISTEN_FDS");
126
127         if (!listen_pid) {
128                 log_warn("Systemd mandatory ENV variable is not defined: LISTEN_PID");
129                 return -1;
130         }
131
132         if (!listen_fds) {
133                 log_warn("Systemd mandatory ENV variable is not defined: LISTEN_FDS");
134                 return -1;
135         }
136
137         if((r = sd_listen_fds(0)) < 1) {
138                 if(r == 0)
139                         log_warn("systemd: did not return socket, check unit configuration");
140                 else
141                         log_err("systemd sd_listen_fds(): %s", strerror(-r));
142                 return -1;
143         }
144         
145         for(i = 0; i < r; i++) {
146                 if(sd_is_socket(SD_LISTEN_FDS_START + i, family, socktype, listen)) {
147                         s = SD_LISTEN_FDS_START + i;
148                         break;
149                 }
150         }
151         if (s == -1) {
152                 if (addr)
153                         log_err_addr("systemd sd_listen_fds()",
154                                      "no such socket",
155                                      (struct sockaddr_storage *)addr, addrlen);
156                 else
157                         log_err("systemd sd_listen_fds(): %s", path);
158         }
159         return s;
160 }
161 #endif
162
163 int
164 create_udp_sock(int family, int socktype, struct sockaddr* addr,
165         socklen_t addrlen, int v6only, int* inuse, int* noproto,
166         int rcv, int snd, int listen, int* reuseport, int transparent,
167         int freebind, int use_systemd)
168 {
169         int s;
170 #if defined(SO_REUSEADDR) || defined(SO_REUSEPORT) || defined(IPV6_USE_MIN_MTU)  || defined(IP_TRANSPARENT) || defined(IP_BINDANY) || defined(IP_FREEBIND) || defined (SO_BINDANY)
171         int on=1;
172 #endif
173 #ifdef IPV6_MTU
174         int mtu = IPV6_MIN_MTU;
175 #endif
176 #if !defined(SO_RCVBUFFORCE) && !defined(SO_RCVBUF)
177         (void)rcv;
178 #endif
179 #if !defined(SO_SNDBUFFORCE) && !defined(SO_SNDBUF)
180         (void)snd;
181 #endif
182 #ifndef IPV6_V6ONLY
183         (void)v6only;
184 #endif
185 #if !defined(IP_TRANSPARENT) && !defined(IP_BINDANY) && !defined(SO_BINDANY)
186         (void)transparent;
187 #endif
188 #if !defined(IP_FREEBIND)
189         (void)freebind;
190 #endif
191 #ifdef HAVE_SYSTEMD
192         int got_fd_from_systemd = 0;
193
194         if (!use_systemd
195             || (use_systemd
196                 && (s = systemd_get_activated(family, socktype, -1, addr,
197                                               addrlen, NULL)) == -1)) {
198 #else
199         (void)use_systemd;
200 #endif
201         if((s = socket(family, socktype, 0)) == -1) {
202                 *inuse = 0;
203 #ifndef USE_WINSOCK
204                 if(errno == EAFNOSUPPORT || errno == EPROTONOSUPPORT) {
205                         *noproto = 1;
206                         return -1;
207                 }
208                 log_err("can't create socket: %s", strerror(errno));
209 #else
210                 if(WSAGetLastError() == WSAEAFNOSUPPORT || 
211                         WSAGetLastError() == WSAEPROTONOSUPPORT) {
212                         *noproto = 1;
213                         return -1;
214                 }
215                 log_err("can't create socket: %s", 
216                         wsa_strerror(WSAGetLastError()));
217 #endif
218                 *noproto = 0;
219                 return -1;
220         }
221 #ifdef HAVE_SYSTEMD
222         } else {
223                 got_fd_from_systemd = 1;
224         }
225 #endif
226         if(listen) {
227 #ifdef SO_REUSEADDR
228                 if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&on, 
229                         (socklen_t)sizeof(on)) < 0) {
230 #ifndef USE_WINSOCK
231                         log_err("setsockopt(.. SO_REUSEADDR ..) failed: %s",
232                                 strerror(errno));
233                         if(errno != ENOSYS) {
234                                 close(s);
235                                 *noproto = 0;
236                                 *inuse = 0;
237                                 return -1;
238                         }
239 #else
240                         log_err("setsockopt(.. SO_REUSEADDR ..) failed: %s",
241                                 wsa_strerror(WSAGetLastError()));
242                         closesocket(s);
243                         *noproto = 0;
244                         *inuse = 0;
245                         return -1;
246 #endif
247                 }
248 #endif /* SO_REUSEADDR */
249 #ifdef SO_REUSEPORT
250                 /* try to set SO_REUSEPORT so that incoming
251                  * queries are distributed evenly among the receiving threads.
252                  * Each thread must have its own socket bound to the same port,
253                  * with SO_REUSEPORT set on each socket.
254                  */
255                 if (reuseport && *reuseport &&
256                     setsockopt(s, SOL_SOCKET, SO_REUSEPORT, (void*)&on,
257                         (socklen_t)sizeof(on)) < 0) {
258 #ifdef ENOPROTOOPT
259                         if(errno != ENOPROTOOPT || verbosity >= 3)
260                                 log_warn("setsockopt(.. SO_REUSEPORT ..) failed: %s",
261                                         strerror(errno));
262 #endif
263                         /* this option is not essential, we can continue */
264                         *reuseport = 0;
265                 }
266 #else
267                 (void)reuseport;
268 #endif /* defined(SO_REUSEPORT) */
269 #ifdef IP_TRANSPARENT
270                 if (transparent &&
271                     setsockopt(s, IPPROTO_IP, IP_TRANSPARENT, (void*)&on,
272                     (socklen_t)sizeof(on)) < 0) {
273                         log_warn("setsockopt(.. IP_TRANSPARENT ..) failed: %s",
274                         strerror(errno));
275                 }
276 #elif defined(IP_BINDANY)
277                 if (transparent &&
278                     setsockopt(s, (family==AF_INET6? IPPROTO_IPV6:IPPROTO_IP),
279                     (family == AF_INET6? IPV6_BINDANY:IP_BINDANY),
280                     (void*)&on, (socklen_t)sizeof(on)) < 0) {
281                         log_warn("setsockopt(.. IP%s_BINDANY ..) failed: %s",
282                         (family==AF_INET6?"V6":""), strerror(errno));
283                 }
284 #elif defined(SO_BINDANY)
285                 if (transparent &&
286                     setsockopt(s, SOL_SOCKET, SO_BINDANY, (void*)&on,
287                     (socklen_t)sizeof(on)) < 0) {
288                         log_warn("setsockopt(.. SO_BINDANY ..) failed: %s",
289                         strerror(errno));
290                 }
291 #endif /* IP_TRANSPARENT || IP_BINDANY || SO_BINDANY */
292         }
293 #ifdef IP_FREEBIND
294         if(freebind &&
295             setsockopt(s, IPPROTO_IP, IP_FREEBIND, (void*)&on,
296             (socklen_t)sizeof(on)) < 0) {
297                 log_warn("setsockopt(.. IP_FREEBIND ..) failed: %s",
298                 strerror(errno));
299         }
300 #endif /* IP_FREEBIND */
301         if(rcv) {
302 #ifdef SO_RCVBUF
303                 int got;
304                 socklen_t slen = (socklen_t)sizeof(got);
305 #  ifdef SO_RCVBUFFORCE
306                 /* Linux specific: try to use root permission to override
307                  * system limits on rcvbuf. The limit is stored in 
308                  * /proc/sys/net/core/rmem_max or sysctl net.core.rmem_max */
309                 if(setsockopt(s, SOL_SOCKET, SO_RCVBUFFORCE, (void*)&rcv, 
310                         (socklen_t)sizeof(rcv)) < 0) {
311                         if(errno != EPERM) {
312 #    ifndef USE_WINSOCK
313                                 log_err("setsockopt(..., SO_RCVBUFFORCE, "
314                                         "...) failed: %s", strerror(errno));
315                                 close(s);
316 #    else
317                                 log_err("setsockopt(..., SO_RCVBUFFORCE, "
318                                         "...) failed: %s", 
319                                         wsa_strerror(WSAGetLastError()));
320                                 closesocket(s);
321 #    endif
322                                 *noproto = 0;
323                                 *inuse = 0;
324                                 return -1;
325                         }
326 #  endif /* SO_RCVBUFFORCE */
327                         if(setsockopt(s, SOL_SOCKET, SO_RCVBUF, (void*)&rcv, 
328                                 (socklen_t)sizeof(rcv)) < 0) {
329 #  ifndef USE_WINSOCK
330                                 log_err("setsockopt(..., SO_RCVBUF, "
331                                         "...) failed: %s", strerror(errno));
332                                 close(s);
333 #  else
334                                 log_err("setsockopt(..., SO_RCVBUF, "
335                                         "...) failed: %s", 
336                                         wsa_strerror(WSAGetLastError()));
337                                 closesocket(s);
338 #  endif
339                                 *noproto = 0;
340                                 *inuse = 0;
341                                 return -1;
342                         }
343                         /* check if we got the right thing or if system
344                          * reduced to some system max.  Warn if so */
345                         if(getsockopt(s, SOL_SOCKET, SO_RCVBUF, (void*)&got, 
346                                 &slen) >= 0 && got < rcv/2) {
347                                 log_warn("so-rcvbuf %u was not granted. "
348                                         "Got %u. To fix: start with "
349                                         "root permissions(linux) or sysctl "
350                                         "bigger net.core.rmem_max(linux) or "
351                                         "kern.ipc.maxsockbuf(bsd) values.",
352                                         (unsigned)rcv, (unsigned)got);
353                         }
354 #  ifdef SO_RCVBUFFORCE
355                 }
356 #  endif
357 #endif /* SO_RCVBUF */
358         }
359         /* first do RCVBUF as the receive buffer is more important */
360         if(snd) {
361 #ifdef SO_SNDBUF
362                 int got;
363                 socklen_t slen = (socklen_t)sizeof(got);
364 #  ifdef SO_SNDBUFFORCE
365                 /* Linux specific: try to use root permission to override
366                  * system limits on sndbuf. The limit is stored in 
367                  * /proc/sys/net/core/wmem_max or sysctl net.core.wmem_max */
368                 if(setsockopt(s, SOL_SOCKET, SO_SNDBUFFORCE, (void*)&snd, 
369                         (socklen_t)sizeof(snd)) < 0) {
370                         if(errno != EPERM) {
371 #    ifndef USE_WINSOCK
372                                 log_err("setsockopt(..., SO_SNDBUFFORCE, "
373                                         "...) failed: %s", strerror(errno));
374                                 close(s);
375 #    else
376                                 log_err("setsockopt(..., SO_SNDBUFFORCE, "
377                                         "...) failed: %s", 
378                                         wsa_strerror(WSAGetLastError()));
379                                 closesocket(s);
380 #    endif
381                                 *noproto = 0;
382                                 *inuse = 0;
383                                 return -1;
384                         }
385 #  endif /* SO_SNDBUFFORCE */
386                         if(setsockopt(s, SOL_SOCKET, SO_SNDBUF, (void*)&snd, 
387                                 (socklen_t)sizeof(snd)) < 0) {
388 #  ifndef USE_WINSOCK
389                                 log_err("setsockopt(..., SO_SNDBUF, "
390                                         "...) failed: %s", strerror(errno));
391                                 close(s);
392 #  else
393                                 log_err("setsockopt(..., SO_SNDBUF, "
394                                         "...) failed: %s", 
395                                         wsa_strerror(WSAGetLastError()));
396                                 closesocket(s);
397 #  endif
398                                 *noproto = 0;
399                                 *inuse = 0;
400                                 return -1;
401                         }
402                         /* check if we got the right thing or if system
403                          * reduced to some system max.  Warn if so */
404                         if(getsockopt(s, SOL_SOCKET, SO_SNDBUF, (void*)&got, 
405                                 &slen) >= 0 && got < snd/2) {
406                                 log_warn("so-sndbuf %u was not granted. "
407                                         "Got %u. To fix: start with "
408                                         "root permissions(linux) or sysctl "
409                                         "bigger net.core.wmem_max(linux) or "
410                                         "kern.ipc.maxsockbuf(bsd) values.",
411                                         (unsigned)snd, (unsigned)got);
412                         }
413 #  ifdef SO_SNDBUFFORCE
414                 }
415 #  endif
416 #endif /* SO_SNDBUF */
417         }
418         if(family == AF_INET6) {
419 # if defined(IPV6_V6ONLY)
420                 if(v6only) {
421                         int val=(v6only==2)?0:1;
422                         if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, 
423                                 (void*)&val, (socklen_t)sizeof(val)) < 0) {
424 #ifndef USE_WINSOCK
425                                 log_err("setsockopt(..., IPV6_V6ONLY"
426                                         ", ...) failed: %s", strerror(errno));
427                                 close(s);
428 #else
429                                 log_err("setsockopt(..., IPV6_V6ONLY"
430                                         ", ...) failed: %s", 
431                                         wsa_strerror(WSAGetLastError()));
432                                 closesocket(s);
433 #endif
434                                 *noproto = 0;
435                                 *inuse = 0;
436                                 return -1;
437                         }
438                 }
439 # endif
440 # if defined(IPV6_USE_MIN_MTU)
441                 /*
442                  * There is no fragmentation of IPv6 datagrams
443                  * during forwarding in the network. Therefore
444                  * we do not send UDP datagrams larger than
445                  * the minimum IPv6 MTU of 1280 octets. The
446                  * EDNS0 message length can be larger if the
447                  * network stack supports IPV6_USE_MIN_MTU.
448                  */
449                 if (setsockopt(s, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
450                         (void*)&on, (socklen_t)sizeof(on)) < 0) {
451 #  ifndef USE_WINSOCK
452                         log_err("setsockopt(..., IPV6_USE_MIN_MTU, "
453                                 "...) failed: %s", strerror(errno));
454                         close(s);
455 #  else
456                         log_err("setsockopt(..., IPV6_USE_MIN_MTU, "
457                                 "...) failed: %s", 
458                                 wsa_strerror(WSAGetLastError()));
459                         closesocket(s);
460 #  endif
461                         *noproto = 0;
462                         *inuse = 0;
463                         return -1;
464                 }
465 # elif defined(IPV6_MTU)
466                 /*
467                  * On Linux, to send no larger than 1280, the PMTUD is
468                  * disabled by default for datagrams anyway, so we set
469                  * the MTU to use.
470                  */
471                 if (setsockopt(s, IPPROTO_IPV6, IPV6_MTU,
472                         (void*)&mtu, (socklen_t)sizeof(mtu)) < 0) {
473 #  ifndef USE_WINSOCK
474                         log_err("setsockopt(..., IPV6_MTU, ...) failed: %s", 
475                                 strerror(errno));
476                         close(s);
477 #  else
478                         log_err("setsockopt(..., IPV6_MTU, ...) failed: %s", 
479                                 wsa_strerror(WSAGetLastError()));
480                         closesocket(s);
481 #  endif
482                         *noproto = 0;
483                         *inuse = 0;
484                         return -1;
485                 }
486 # endif /* IPv6 MTU */
487         } else if(family == AF_INET) {
488 #  if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
489 /* linux 3.15 has IP_PMTUDISC_OMIT, Hannes Frederic Sowa made it so that
490  * PMTU information is not accepted, but fragmentation is allowed
491  * if and only if the packet size exceeds the outgoing interface MTU
492  * (and also uses the interface mtu to determine the size of the packets).
493  * So there won't be any EMSGSIZE error.  Against DNS fragmentation attacks.
494  * FreeBSD already has same semantics without setting the option. */
495                 int omit_set = 0;
496                 int action;
497 #   if defined(IP_PMTUDISC_OMIT)
498                 action = IP_PMTUDISC_OMIT;
499                 if (setsockopt(s, IPPROTO_IP, IP_MTU_DISCOVER, 
500                         &action, (socklen_t)sizeof(action)) < 0) {
501
502                         if (errno != EINVAL) {
503                                 log_err("setsockopt(..., IP_MTU_DISCOVER, IP_PMTUDISC_OMIT...) failed: %s",
504                                         strerror(errno));
505
506 #    ifndef USE_WINSOCK
507                                 close(s);
508 #    else
509                                 closesocket(s);
510 #    endif
511                                 *noproto = 0;
512                                 *inuse = 0;
513                                 return -1;
514                         }
515                 }
516                 else
517                 {
518                     omit_set = 1;
519                 }
520 #   endif
521                 if (omit_set == 0) {
522                         action = IP_PMTUDISC_DONT;
523                         if (setsockopt(s, IPPROTO_IP, IP_MTU_DISCOVER,
524                                 &action, (socklen_t)sizeof(action)) < 0) {
525                                 log_err("setsockopt(..., IP_MTU_DISCOVER, IP_PMTUDISC_DONT...) failed: %s",
526                                         strerror(errno));
527 #    ifndef USE_WINSOCK
528                                 close(s);
529 #    else
530                                 closesocket(s);
531 #    endif
532                                 *noproto = 0;
533                                 *inuse = 0;
534                                 return -1;
535                         }
536                 }
537 #  elif defined(IP_DONTFRAG)
538                 int off = 0;
539                 if (setsockopt(s, IPPROTO_IP, IP_DONTFRAG, 
540                         &off, (socklen_t)sizeof(off)) < 0) {
541                         log_err("setsockopt(..., IP_DONTFRAG, ...) failed: %s",
542                                 strerror(errno));
543 #    ifndef USE_WINSOCK
544                         close(s);
545 #    else
546                         closesocket(s);
547 #    endif
548                         *noproto = 0;
549                         *inuse = 0;
550                         return -1;
551                 }
552 #  endif /* IPv4 MTU */
553         }
554         if(
555 #ifdef HAVE_SYSTEMD
556                 !got_fd_from_systemd &&
557 #endif
558                 bind(s, (struct sockaddr*)addr, addrlen) != 0) {
559                 *noproto = 0;
560                 *inuse = 0;
561 #ifndef USE_WINSOCK
562 #ifdef EADDRINUSE
563                 *inuse = (errno == EADDRINUSE);
564                 /* detect freebsd jail with no ipv6 permission */
565                 if(family==AF_INET6 && errno==EINVAL)
566                         *noproto = 1;
567                 else if(errno != EADDRINUSE) {
568                         log_err_addr("can't bind socket", strerror(errno),
569                                 (struct sockaddr_storage*)addr, addrlen);
570                 }
571 #endif /* EADDRINUSE */
572                 close(s);
573 #else /* USE_WINSOCK */
574                 if(WSAGetLastError() != WSAEADDRINUSE &&
575                         WSAGetLastError() != WSAEADDRNOTAVAIL) {
576                         log_err_addr("can't bind socket", 
577                                 wsa_strerror(WSAGetLastError()),
578                                 (struct sockaddr_storage*)addr, addrlen);
579                 }
580                 closesocket(s);
581 #endif /* USE_WINSOCK */
582                 return -1;
583         }
584         if(!fd_set_nonblock(s)) {
585                 *noproto = 0;
586                 *inuse = 0;
587 #ifndef USE_WINSOCK
588                 close(s);
589 #else
590                 closesocket(s);
591 #endif
592                 return -1;
593         }
594         return s;
595 }
596
597 int
598 create_tcp_accept_sock(struct addrinfo *addr, int v6only, int* noproto,
599         int* reuseport, int transparent, int mss, int freebind, int use_systemd)
600 {
601         int s;
602 #if defined(SO_REUSEADDR) || defined(SO_REUSEPORT) || defined(IPV6_V6ONLY) || defined(IP_TRANSPARENT) || defined(IP_BINDANY) || defined(IP_FREEBIND) || defined(SO_BINDANY)
603         int on = 1;
604 #endif
605 #ifdef HAVE_SYSTEMD
606         int got_fd_from_systemd = 0;
607 #endif
608 #ifdef USE_TCP_FASTOPEN
609         int qlen;
610 #endif
611 #if !defined(IP_TRANSPARENT) && !defined(IP_BINDANY) && !defined(SO_BINDANY)
612         (void)transparent;
613 #endif
614 #if !defined(IP_FREEBIND)
615         (void)freebind;
616 #endif
617         verbose_print_addr(addr);
618         *noproto = 0;
619 #ifdef HAVE_SYSTEMD
620         if (!use_systemd ||
621             (use_systemd
622              && (s = systemd_get_activated(addr->ai_family, addr->ai_socktype, 1,
623                                            addr->ai_addr, addr->ai_addrlen,
624                                            NULL)) == -1)) {
625 #else
626         (void)use_systemd;
627 #endif
628         if((s = socket(addr->ai_family, addr->ai_socktype, 0)) == -1) {
629 #ifndef USE_WINSOCK
630                 if(errno == EAFNOSUPPORT || errno == EPROTONOSUPPORT) {
631                         *noproto = 1;
632                         return -1;
633                 }
634                 log_err("can't create socket: %s", strerror(errno));
635 #else
636                 if(WSAGetLastError() == WSAEAFNOSUPPORT ||
637                         WSAGetLastError() == WSAEPROTONOSUPPORT) {
638                         *noproto = 1;
639                         return -1;
640                 }
641                 log_err("can't create socket: %s", 
642                         wsa_strerror(WSAGetLastError()));
643 #endif
644                 return -1;
645         }
646         if (mss > 0) {
647 #if defined(IPPROTO_TCP) && defined(TCP_MAXSEG)
648                 if(setsockopt(s, IPPROTO_TCP, TCP_MAXSEG, (void*)&mss,
649                         (socklen_t)sizeof(mss)) < 0) {
650                         #ifndef USE_WINSOCK
651                         log_err(" setsockopt(.. TCP_MAXSEG ..) failed: %s",
652                                 strerror(errno));
653                         #else
654                         log_err(" setsockopt(.. TCP_MAXSEG ..) failed: %s",
655                                 wsa_strerror(WSAGetLastError()));
656                         #endif
657                 } else {
658                         verbose(VERB_ALGO,
659                                 " tcp socket mss set to %d", mss);
660                 }
661 #else
662                 log_warn(" setsockopt(TCP_MAXSEG) unsupported");
663 #endif /* defined(IPPROTO_TCP) && defined(TCP_MAXSEG) */
664         }
665 #ifdef HAVE_SYSTEMD
666         } else {
667                 got_fd_from_systemd = 1;
668     }
669 #endif
670 #ifdef SO_REUSEADDR
671         if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&on, 
672                 (socklen_t)sizeof(on)) < 0) {
673 #ifndef USE_WINSOCK
674                 log_err("setsockopt(.. SO_REUSEADDR ..) failed: %s",
675                         strerror(errno));
676                 close(s);
677 #else
678                 log_err("setsockopt(.. SO_REUSEADDR ..) failed: %s",
679                         wsa_strerror(WSAGetLastError()));
680                 closesocket(s);
681 #endif
682                 return -1;
683         }
684 #endif /* SO_REUSEADDR */
685 #ifdef IP_FREEBIND
686         if (freebind && setsockopt(s, IPPROTO_IP, IP_FREEBIND, (void*)&on,
687             (socklen_t)sizeof(on)) < 0) {
688                 log_warn("setsockopt(.. IP_FREEBIND ..) failed: %s",
689                 strerror(errno));
690         }
691 #endif /* IP_FREEBIND */
692 #ifdef SO_REUSEPORT
693         /* try to set SO_REUSEPORT so that incoming
694          * connections are distributed evenly among the receiving threads.
695          * Each thread must have its own socket bound to the same port,
696          * with SO_REUSEPORT set on each socket.
697          */
698         if (reuseport && *reuseport &&
699                 setsockopt(s, SOL_SOCKET, SO_REUSEPORT, (void*)&on,
700                 (socklen_t)sizeof(on)) < 0) {
701 #ifdef ENOPROTOOPT
702                 if(errno != ENOPROTOOPT || verbosity >= 3)
703                         log_warn("setsockopt(.. SO_REUSEPORT ..) failed: %s",
704                                 strerror(errno));
705 #endif
706                 /* this option is not essential, we can continue */
707                 *reuseport = 0;
708         }
709 #else
710         (void)reuseport;
711 #endif /* defined(SO_REUSEPORT) */
712 #if defined(IPV6_V6ONLY)
713         if(addr->ai_family == AF_INET6 && v6only) {
714                 if(setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, 
715                         (void*)&on, (socklen_t)sizeof(on)) < 0) {
716 #ifndef USE_WINSOCK
717                         log_err("setsockopt(..., IPV6_V6ONLY, ...) failed: %s",
718                                 strerror(errno));
719                         close(s);
720 #else
721                         log_err("setsockopt(..., IPV6_V6ONLY, ...) failed: %s",
722                                 wsa_strerror(WSAGetLastError()));
723                         closesocket(s);
724 #endif
725                         return -1;
726                 }
727         }
728 #else
729         (void)v6only;
730 #endif /* IPV6_V6ONLY */
731 #ifdef IP_TRANSPARENT
732         if (transparent &&
733             setsockopt(s, IPPROTO_IP, IP_TRANSPARENT, (void*)&on,
734             (socklen_t)sizeof(on)) < 0) {
735                 log_warn("setsockopt(.. IP_TRANSPARENT ..) failed: %s",
736                         strerror(errno));
737         }
738 #elif defined(IP_BINDANY)
739         if (transparent &&
740             setsockopt(s, (addr->ai_family==AF_INET6? IPPROTO_IPV6:IPPROTO_IP),
741             (addr->ai_family == AF_INET6? IPV6_BINDANY:IP_BINDANY),
742             (void*)&on, (socklen_t)sizeof(on)) < 0) {
743                 log_warn("setsockopt(.. IP%s_BINDANY ..) failed: %s",
744                 (addr->ai_family==AF_INET6?"V6":""), strerror(errno));
745         }
746 #elif defined(SO_BINDANY)
747         if (transparent &&
748             setsockopt(s, SOL_SOCKET, SO_BINDANY, (void*)&on, (socklen_t)
749             sizeof(on)) < 0) {
750                 log_warn("setsockopt(.. SO_BINDANY ..) failed: %s",
751                 strerror(errno));
752         }
753 #endif /* IP_TRANSPARENT || IP_BINDANY || SO_BINDANY */
754         if(
755 #ifdef HAVE_SYSTEMD
756                 !got_fd_from_systemd &&
757 #endif
758         bind(s, addr->ai_addr, addr->ai_addrlen) != 0) {
759 #ifndef USE_WINSOCK
760                 /* detect freebsd jail with no ipv6 permission */
761                 if(addr->ai_family==AF_INET6 && errno==EINVAL)
762                         *noproto = 1;
763                 else {
764                         log_err_addr("can't bind socket", strerror(errno),
765                                 (struct sockaddr_storage*)addr->ai_addr,
766                                 addr->ai_addrlen);
767                 }
768                 close(s);
769 #else
770                 log_err_addr("can't bind socket", 
771                         wsa_strerror(WSAGetLastError()),
772                         (struct sockaddr_storage*)addr->ai_addr,
773                         addr->ai_addrlen);
774                 closesocket(s);
775 #endif
776                 return -1;
777         }
778         if(!fd_set_nonblock(s)) {
779 #ifndef USE_WINSOCK
780                 close(s);
781 #else
782                 closesocket(s);
783 #endif
784                 return -1;
785         }
786         if(listen(s, TCP_BACKLOG) == -1) {
787 #ifndef USE_WINSOCK
788                 log_err("can't listen: %s", strerror(errno));
789                 close(s);
790 #else
791                 log_err("can't listen: %s", wsa_strerror(WSAGetLastError()));
792                 closesocket(s);
793 #endif
794                 return -1;
795         }
796 #ifdef USE_TCP_FASTOPEN
797         /* qlen specifies how many outstanding TFO requests to allow. Limit is a defense
798            against IP spoofing attacks as suggested in RFC7413 */
799 #ifdef __APPLE__
800         /* OS X implementation only supports qlen of 1 via this call. Actual
801            value is configured by the net.inet.tcp.fastopen_backlog kernel parm. */
802         qlen = 1;
803 #else
804         /* 5 is recommended on linux */
805         qlen = 5;
806 #endif
807         if ((setsockopt(s, IPPROTO_TCP, TCP_FASTOPEN, &qlen, 
808                   sizeof(qlen))) == -1 ) {
809 #ifdef ENOPROTOOPT
810                 /* squelch ENOPROTOOPT: freebsd server mode with kernel support
811                    disabled, except when verbosity enabled for debugging */
812                 if(errno != ENOPROTOOPT || verbosity >= 3)
813 #endif
814                   log_err("Setting TCP Fast Open as server failed: %s", strerror(errno));
815         }
816 #endif
817         return s;
818 }
819
820 int
821 create_local_accept_sock(const char *path, int* noproto, int use_systemd)
822 {
823 #ifdef HAVE_SYSTEMD
824         int ret;
825
826         if (use_systemd && (ret = systemd_get_activated(AF_LOCAL, SOCK_STREAM, 1, NULL, 0, path)) != -1)
827                 return ret;
828         else {
829 #endif
830 #ifdef HAVE_SYS_UN_H
831         int s;
832         struct sockaddr_un usock;
833 #ifndef HAVE_SYSTEMD
834         (void)use_systemd;
835 #endif
836
837         verbose(VERB_ALGO, "creating unix socket %s", path);
838 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
839         /* this member exists on BSDs, not Linux */
840         usock.sun_len = (unsigned)sizeof(usock);
841 #endif
842         usock.sun_family = AF_LOCAL;
843         /* length is 92-108, 104 on FreeBSD */
844         (void)strlcpy(usock.sun_path, path, sizeof(usock.sun_path));
845
846         if ((s = socket(AF_LOCAL, SOCK_STREAM, 0)) == -1) {
847                 log_err("Cannot create local socket %s (%s)",
848                         path, strerror(errno));
849                 return -1;
850         }
851
852         if (unlink(path) && errno != ENOENT) {
853                 /* The socket already exists and cannot be removed */
854                 log_err("Cannot remove old local socket %s (%s)",
855                         path, strerror(errno));
856                 goto err;
857         }
858
859         if (bind(s, (struct sockaddr *)&usock,
860                 (socklen_t)sizeof(struct sockaddr_un)) == -1) {
861                 log_err("Cannot bind local socket %s (%s)",
862                         path, strerror(errno));
863                 goto err;
864         }
865
866         if (!fd_set_nonblock(s)) {
867                 log_err("Cannot set non-blocking mode");
868                 goto err;
869         }
870
871         if (listen(s, TCP_BACKLOG) == -1) {
872                 log_err("can't listen: %s", strerror(errno));
873                 goto err;
874         }
875
876         (void)noproto; /*unused*/
877         return s;
878
879 err:
880 #ifndef USE_WINSOCK
881         close(s);
882 #else
883         closesocket(s);
884 #endif
885         return -1;
886
887 #ifdef HAVE_SYSTEMD
888         }
889 #endif
890 #else
891         (void)use_systemd;
892         (void)path;
893         log_err("Local sockets are not supported");
894         *noproto = 1;
895         return -1;
896 #endif
897 }
898
899
900 /**
901  * Create socket from getaddrinfo results
902  */
903 static int
904 make_sock(int stype, const char* ifname, const char* port, 
905         struct addrinfo *hints, int v6only, int* noip6, size_t rcv, size_t snd,
906         int* reuseport, int transparent, int tcp_mss, int freebind, int use_systemd)
907 {
908         struct addrinfo *res = NULL;
909         int r, s, inuse, noproto;
910         hints->ai_socktype = stype;
911         *noip6 = 0;
912         if((r=getaddrinfo(ifname, port, hints, &res)) != 0 || !res) {
913 #ifdef USE_WINSOCK
914                 if(r == EAI_NONAME && hints->ai_family == AF_INET6){
915                         *noip6 = 1; /* 'Host not found' for IP6 on winXP */
916                         return -1;
917                 }
918 #endif
919                 log_err("node %s:%s getaddrinfo: %s %s", 
920                         ifname?ifname:"default", port, gai_strerror(r),
921 #ifdef EAI_SYSTEM
922                         r==EAI_SYSTEM?(char*)strerror(errno):""
923 #else
924                         ""
925 #endif
926                 );
927                 return -1;
928         }
929         if(stype == SOCK_DGRAM) {
930                 verbose_print_addr(res);
931                 s = create_udp_sock(res->ai_family, res->ai_socktype,
932                         (struct sockaddr*)res->ai_addr, res->ai_addrlen,
933                         v6only, &inuse, &noproto, (int)rcv, (int)snd, 1,
934                         reuseport, transparent, freebind, use_systemd);
935                 if(s == -1 && inuse) {
936                         log_err("bind: address already in use");
937                 } else if(s == -1 && noproto && hints->ai_family == AF_INET6){
938                         *noip6 = 1;
939                 }
940         } else  {
941                 s = create_tcp_accept_sock(res, v6only, &noproto, reuseport,
942                         transparent, tcp_mss, freebind, use_systemd);
943                 if(s == -1 && noproto && hints->ai_family == AF_INET6){
944                         *noip6 = 1;
945                 }
946         }
947         freeaddrinfo(res);
948         return s;
949 }
950
951 /** make socket and first see if ifname contains port override info */
952 static int
953 make_sock_port(int stype, const char* ifname, const char* port, 
954         struct addrinfo *hints, int v6only, int* noip6, size_t rcv, size_t snd,
955         int* reuseport, int transparent, int tcp_mss, int freebind, int use_systemd)
956 {
957         char* s = strchr(ifname, '@');
958         if(s) {
959                 /* override port with ifspec@port */
960                 char p[16];
961                 char newif[128];
962                 if((size_t)(s-ifname) >= sizeof(newif)) {
963                         log_err("ifname too long: %s", ifname);
964                         *noip6 = 0;
965                         return -1;
966                 }
967                 if(strlen(s+1) >= sizeof(p)) {
968                         log_err("portnumber too long: %s", ifname);
969                         *noip6 = 0;
970                         return -1;
971                 }
972                 (void)strlcpy(newif, ifname, sizeof(newif));
973                 newif[s-ifname] = 0;
974                 (void)strlcpy(p, s+1, sizeof(p));
975                 p[strlen(s+1)]=0;
976                 return make_sock(stype, newif, p, hints, v6only, noip6,
977                         rcv, snd, reuseport, transparent, tcp_mss, freebind, use_systemd);
978         }
979         return make_sock(stype, ifname, port, hints, v6only, noip6, rcv, snd,
980                 reuseport, transparent, tcp_mss, freebind, use_systemd);
981 }
982
983 /**
984  * Add port to open ports list.
985  * @param list: list head. changed.
986  * @param s: fd.
987  * @param ftype: if fd is UDP.
988  * @return false on failure. list in unchanged then.
989  */
990 static int
991 port_insert(struct listen_port** list, int s, enum listen_type ftype)
992 {
993         struct listen_port* item = (struct listen_port*)malloc(
994                 sizeof(struct listen_port));
995         if(!item)
996                 return 0;
997         item->next = *list;
998         item->fd = s;
999         item->ftype = ftype;
1000         *list = item;
1001         return 1;
1002 }
1003
1004 /** set fd to receive source address packet info */
1005 static int
1006 set_recvpktinfo(int s, int family) 
1007 {
1008 #if defined(IPV6_RECVPKTINFO) || defined(IPV6_PKTINFO) || (defined(IP_RECVDSTADDR) && defined(IP_SENDSRCADDR)) || defined(IP_PKTINFO)
1009         int on = 1;
1010 #else
1011         (void)s;
1012 #endif
1013         if(family == AF_INET6) {
1014 #           ifdef IPV6_RECVPKTINFO
1015                 if(setsockopt(s, IPPROTO_IPV6, IPV6_RECVPKTINFO,
1016                         (void*)&on, (socklen_t)sizeof(on)) < 0) {
1017                         log_err("setsockopt(..., IPV6_RECVPKTINFO, ...) failed: %s",
1018                                 strerror(errno));
1019                         return 0;
1020                 }
1021 #           elif defined(IPV6_PKTINFO)
1022                 if(setsockopt(s, IPPROTO_IPV6, IPV6_PKTINFO,
1023                         (void*)&on, (socklen_t)sizeof(on)) < 0) {
1024                         log_err("setsockopt(..., IPV6_PKTINFO, ...) failed: %s",
1025                                 strerror(errno));
1026                         return 0;
1027                 }
1028 #           else
1029                 log_err("no IPV6_RECVPKTINFO and no IPV6_PKTINFO option, please "
1030                         "disable interface-automatic or do-ip6 in config");
1031                 return 0;
1032 #           endif /* defined IPV6_RECVPKTINFO */
1033
1034         } else if(family == AF_INET) {
1035 #           ifdef IP_PKTINFO
1036                 if(setsockopt(s, IPPROTO_IP, IP_PKTINFO,
1037                         (void*)&on, (socklen_t)sizeof(on)) < 0) {
1038                         log_err("setsockopt(..., IP_PKTINFO, ...) failed: %s",
1039                                 strerror(errno));
1040                         return 0;
1041                 }
1042 #           elif defined(IP_RECVDSTADDR) && defined(IP_SENDSRCADDR)
1043                 if(setsockopt(s, IPPROTO_IP, IP_RECVDSTADDR,
1044                         (void*)&on, (socklen_t)sizeof(on)) < 0) {
1045                         log_err("setsockopt(..., IP_RECVDSTADDR, ...) failed: %s",
1046                                 strerror(errno));
1047                         return 0;
1048                 }
1049 #           else
1050                 log_err("no IP_SENDSRCADDR or IP_PKTINFO option, please disable "
1051                         "interface-automatic or do-ip4 in config");
1052                 return 0;
1053 #           endif /* IP_PKTINFO */
1054
1055         }
1056         return 1;
1057 }
1058
1059 /** see if interface is ssl, its port number == the ssl port number */
1060 static int
1061 if_is_ssl(const char* ifname, const char* port, int ssl_port,
1062         struct config_strlist* additional_tls_port)
1063 {
1064         struct config_strlist* s;
1065         char* p = strchr(ifname, '@');
1066         if(!p && atoi(port) == ssl_port)
1067                 return 1;
1068         if(p && atoi(p+1) == ssl_port)
1069                 return 1;
1070         for(s = additional_tls_port; s; s = s->next) {
1071                 if(p && atoi(p+1) == atoi(s->str))
1072                         return 1;
1073                 if(!p && atoi(port) == atoi(s->str))
1074                         return 1;
1075         }
1076         return 0;
1077 }
1078
1079 /**
1080  * Helper for ports_open. Creates one interface (or NULL for default).
1081  * @param ifname: The interface ip address.
1082  * @param do_auto: use automatic interface detection.
1083  *      If enabled, then ifname must be the wildcard name.
1084  * @param do_udp: if udp should be used.
1085  * @param do_tcp: if udp should be used.
1086  * @param hints: for getaddrinfo. family and flags have to be set by caller.
1087  * @param port: Port number to use (as string).
1088  * @param list: list of open ports, appended to, changed to point to list head.
1089  * @param rcv: receive buffer size for UDP
1090  * @param snd: send buffer size for UDP
1091  * @param ssl_port: ssl service port number
1092  * @param additional_tls_port: list of additional ssl service port numbers.
1093  * @param reuseport: try to set SO_REUSEPORT if nonNULL and true.
1094  *      set to false on exit if reuseport failed due to no kernel support.
1095  * @param transparent: set IP_TRANSPARENT socket option.
1096  * @param tcp_mss: maximum segment size of tcp socket. default if zero.
1097  * @param freebind: set IP_FREEBIND socket option.
1098  * @param use_systemd: if true, fetch sockets from systemd.
1099  * @param dnscrypt_port: dnscrypt service port number
1100  * @return: returns false on error.
1101  */
1102 static int
1103 ports_create_if(const char* ifname, int do_auto, int do_udp, int do_tcp, 
1104         struct addrinfo *hints, const char* port, struct listen_port** list,
1105         size_t rcv, size_t snd, int ssl_port,
1106         struct config_strlist* additional_tls_port, int* reuseport,
1107         int transparent, int tcp_mss, int freebind, int use_systemd,
1108         int dnscrypt_port)
1109 {
1110         int s, noip6=0;
1111 #ifdef USE_DNSCRYPT
1112         int is_dnscrypt = ((strchr(ifname, '@') && 
1113                         atoi(strchr(ifname, '@')+1) == dnscrypt_port) ||
1114                         (!strchr(ifname, '@') && atoi(port) == dnscrypt_port));
1115 #else
1116         int is_dnscrypt = 0;
1117         (void)dnscrypt_port;
1118 #endif
1119
1120         if(!do_udp && !do_tcp)
1121                 return 0;
1122         if(do_auto) {
1123                 if((s = make_sock_port(SOCK_DGRAM, ifname, port, hints, 1, 
1124                         &noip6, rcv, snd, reuseport, transparent,
1125                         tcp_mss, freebind, use_systemd)) == -1) {
1126                         if(noip6) {
1127                                 log_warn("IPv6 protocol not available");
1128                                 return 1;
1129                         }
1130                         return 0;
1131                 }
1132                 /* getting source addr packet info is highly non-portable */
1133                 if(!set_recvpktinfo(s, hints->ai_family)) {
1134 #ifndef USE_WINSOCK
1135                         close(s);
1136 #else
1137                         closesocket(s);
1138 #endif
1139                         return 0;
1140                 }
1141                 if(!port_insert(list, s,
1142                    is_dnscrypt?listen_type_udpancil_dnscrypt:listen_type_udpancil)) {
1143 #ifndef USE_WINSOCK
1144                         close(s);
1145 #else
1146                         closesocket(s);
1147 #endif
1148                         return 0;
1149                 }
1150         } else if(do_udp) {
1151                 /* regular udp socket */
1152                 if((s = make_sock_port(SOCK_DGRAM, ifname, port, hints, 1, 
1153                         &noip6, rcv, snd, reuseport, transparent,
1154                         tcp_mss, freebind, use_systemd)) == -1) {
1155                         if(noip6) {
1156                                 log_warn("IPv6 protocol not available");
1157                                 return 1;
1158                         }
1159                         return 0;
1160                 }
1161                 if(!port_insert(list, s,
1162                    is_dnscrypt?listen_type_udp_dnscrypt:listen_type_udp)) {
1163 #ifndef USE_WINSOCK
1164                         close(s);
1165 #else
1166                         closesocket(s);
1167 #endif
1168                         return 0;
1169                 }
1170         }
1171         if(do_tcp) {
1172                 int is_ssl = if_is_ssl(ifname, port, ssl_port,
1173                         additional_tls_port);
1174                 if((s = make_sock_port(SOCK_STREAM, ifname, port, hints, 1, 
1175                         &noip6, 0, 0, reuseport, transparent, tcp_mss,
1176                         freebind, use_systemd)) == -1) {
1177                         if(noip6) {
1178                                 /*log_warn("IPv6 protocol not available");*/
1179                                 return 1;
1180                         }
1181                         return 0;
1182                 }
1183                 if(is_ssl)
1184                         verbose(VERB_ALGO, "setup TCP for SSL service");
1185                 if(!port_insert(list, s, is_ssl?listen_type_ssl:
1186                         (is_dnscrypt?listen_type_tcp_dnscrypt:listen_type_tcp))) {
1187 #ifndef USE_WINSOCK
1188                         close(s);
1189 #else
1190                         closesocket(s);
1191 #endif
1192                         return 0;
1193                 }
1194         }
1195         return 1;
1196 }
1197
1198 /** 
1199  * Add items to commpoint list in front.
1200  * @param c: commpoint to add.
1201  * @param front: listen struct.
1202  * @return: false on failure.
1203  */
1204 static int
1205 listen_cp_insert(struct comm_point* c, struct listen_dnsport* front)
1206 {
1207         struct listen_list* item = (struct listen_list*)malloc(
1208                 sizeof(struct listen_list));
1209         if(!item)
1210                 return 0;
1211         item->com = c;
1212         item->next = front->cps;
1213         front->cps = item;
1214         return 1;
1215 }
1216
1217 struct listen_dnsport* 
1218 listen_create(struct comm_base* base, struct listen_port* ports,
1219         size_t bufsize, int tcp_accept_count, void* sslctx,
1220         struct dt_env* dtenv, comm_point_callback_type* cb, void *cb_arg)
1221 {
1222         struct listen_dnsport* front = (struct listen_dnsport*)
1223                 malloc(sizeof(struct listen_dnsport));
1224         if(!front)
1225                 return NULL;
1226         front->cps = NULL;
1227         front->udp_buff = sldns_buffer_new(bufsize);
1228 #ifdef USE_DNSCRYPT
1229         front->dnscrypt_udp_buff = NULL;
1230 #endif
1231         if(!front->udp_buff) {
1232                 free(front);
1233                 return NULL;
1234         }
1235
1236         /* create comm points as needed */
1237         while(ports) {
1238                 struct comm_point* cp = NULL;
1239                 if(ports->ftype == listen_type_udp ||
1240                    ports->ftype == listen_type_udp_dnscrypt)
1241                         cp = comm_point_create_udp(base, ports->fd, 
1242                                 front->udp_buff, cb, cb_arg);
1243                 else if(ports->ftype == listen_type_tcp ||
1244                                 ports->ftype == listen_type_tcp_dnscrypt)
1245                         cp = comm_point_create_tcp(base, ports->fd, 
1246                                 tcp_accept_count, bufsize, cb, cb_arg);
1247                 else if(ports->ftype == listen_type_ssl) {
1248                         cp = comm_point_create_tcp(base, ports->fd, 
1249                                 tcp_accept_count, bufsize, cb, cb_arg);
1250                         cp->ssl = sslctx;
1251                 } else if(ports->ftype == listen_type_udpancil ||
1252                                   ports->ftype == listen_type_udpancil_dnscrypt)
1253                         cp = comm_point_create_udp_ancil(base, ports->fd, 
1254                                 front->udp_buff, cb, cb_arg);
1255                 if(!cp) {
1256                         log_err("can't create commpoint");      
1257                         listen_delete(front);
1258                         return NULL;
1259                 }
1260                 cp->dtenv = dtenv;
1261                 cp->do_not_close = 1;
1262 #ifdef USE_DNSCRYPT
1263                 if (ports->ftype == listen_type_udp_dnscrypt ||
1264                         ports->ftype == listen_type_tcp_dnscrypt ||
1265                         ports->ftype == listen_type_udpancil_dnscrypt) {
1266                         cp->dnscrypt = 1;
1267                         cp->dnscrypt_buffer = sldns_buffer_new(bufsize);
1268                         if(!cp->dnscrypt_buffer) {
1269                                 log_err("can't alloc dnscrypt_buffer");
1270                                 comm_point_delete(cp);
1271                                 listen_delete(front);
1272                                 return NULL;
1273                         }
1274                         front->dnscrypt_udp_buff = cp->dnscrypt_buffer;
1275                 }
1276 #endif
1277                 if(!listen_cp_insert(cp, front)) {
1278                         log_err("malloc failed");
1279                         comm_point_delete(cp);
1280                         listen_delete(front);
1281                         return NULL;
1282                 }
1283                 ports = ports->next;
1284         }
1285         if(!front->cps) {
1286                 log_err("Could not open sockets to accept queries.");
1287                 listen_delete(front);
1288                 return NULL;
1289         }
1290
1291         return front;
1292 }
1293
1294 void
1295 listen_list_delete(struct listen_list* list)
1296 {
1297         struct listen_list *p = list, *pn;
1298         while(p) {
1299                 pn = p->next;
1300                 comm_point_delete(p->com);
1301                 free(p);
1302                 p = pn;
1303         }
1304 }
1305
1306 void 
1307 listen_delete(struct listen_dnsport* front)
1308 {
1309         if(!front) 
1310                 return;
1311         listen_list_delete(front->cps);
1312 #ifdef USE_DNSCRYPT
1313         if(front->dnscrypt_udp_buff &&
1314                 front->udp_buff != front->dnscrypt_udp_buff) {
1315                 sldns_buffer_free(front->dnscrypt_udp_buff);
1316         }
1317 #endif
1318         sldns_buffer_free(front->udp_buff);
1319         free(front);
1320 }
1321
1322 struct listen_port* 
1323 listening_ports_open(struct config_file* cfg, int* reuseport)
1324 {
1325         struct listen_port* list = NULL;
1326         struct addrinfo hints;
1327         int i, do_ip4, do_ip6;
1328         int do_tcp, do_auto;
1329         char portbuf[32];
1330         snprintf(portbuf, sizeof(portbuf), "%d", cfg->port);
1331         do_ip4 = cfg->do_ip4;
1332         do_ip6 = cfg->do_ip6;
1333         do_tcp = cfg->do_tcp;
1334         do_auto = cfg->if_automatic && cfg->do_udp;
1335         if(cfg->incoming_num_tcp == 0)
1336                 do_tcp = 0;
1337
1338         /* getaddrinfo */
1339         memset(&hints, 0, sizeof(hints));
1340         hints.ai_flags = AI_PASSIVE;
1341         /* no name lookups on our listening ports */
1342         if(cfg->num_ifs > 0)
1343                 hints.ai_flags |= AI_NUMERICHOST;
1344         hints.ai_family = AF_UNSPEC;
1345 #ifndef INET6
1346         do_ip6 = 0;
1347 #endif
1348         if(!do_ip4 && !do_ip6) {
1349                 return NULL;
1350         }
1351         /* create ip4 and ip6 ports so that return addresses are nice. */
1352         if(do_auto || cfg->num_ifs == 0) {
1353                 if(do_ip6) {
1354                         hints.ai_family = AF_INET6;
1355                         if(!ports_create_if(do_auto?"::0":"::1", 
1356                                 do_auto, cfg->do_udp, do_tcp, 
1357                                 &hints, portbuf, &list,
1358                                 cfg->so_rcvbuf, cfg->so_sndbuf,
1359                                 cfg->ssl_port, cfg->additional_tls_port,
1360                                 reuseport, cfg->ip_transparent,
1361                                 cfg->tcp_mss, cfg->ip_freebind, cfg->use_systemd,
1362                                 cfg->dnscrypt_port)) {
1363                                 listening_ports_free(list);
1364                                 return NULL;
1365                         }
1366                 }
1367                 if(do_ip4) {
1368                         hints.ai_family = AF_INET;
1369                         if(!ports_create_if(do_auto?"0.0.0.0":"127.0.0.1", 
1370                                 do_auto, cfg->do_udp, do_tcp, 
1371                                 &hints, portbuf, &list,
1372                                 cfg->so_rcvbuf, cfg->so_sndbuf,
1373                                 cfg->ssl_port, cfg->additional_tls_port,
1374                                 reuseport, cfg->ip_transparent,
1375                                 cfg->tcp_mss, cfg->ip_freebind, cfg->use_systemd,
1376                                 cfg->dnscrypt_port)) {
1377                                 listening_ports_free(list);
1378                                 return NULL;
1379                         }
1380                 }
1381         } else for(i = 0; i<cfg->num_ifs; i++) {
1382                 if(str_is_ip6(cfg->ifs[i])) {
1383                         if(!do_ip6)
1384                                 continue;
1385                         hints.ai_family = AF_INET6;
1386                         if(!ports_create_if(cfg->ifs[i], 0, cfg->do_udp, 
1387                                 do_tcp, &hints, portbuf, &list, 
1388                                 cfg->so_rcvbuf, cfg->so_sndbuf,
1389                                 cfg->ssl_port, cfg->additional_tls_port,
1390                                 reuseport, cfg->ip_transparent,
1391                                 cfg->tcp_mss, cfg->ip_freebind, cfg->use_systemd,
1392                                 cfg->dnscrypt_port)) {
1393                                 listening_ports_free(list);
1394                                 return NULL;
1395                         }
1396                 } else {
1397                         if(!do_ip4)
1398                                 continue;
1399                         hints.ai_family = AF_INET;
1400                         if(!ports_create_if(cfg->ifs[i], 0, cfg->do_udp, 
1401                                 do_tcp, &hints, portbuf, &list, 
1402                                 cfg->so_rcvbuf, cfg->so_sndbuf,
1403                                 cfg->ssl_port, cfg->additional_tls_port,
1404                                 reuseport, cfg->ip_transparent,
1405                                 cfg->tcp_mss, cfg->ip_freebind, cfg->use_systemd,
1406                                 cfg->dnscrypt_port)) {
1407                                 listening_ports_free(list);
1408                                 return NULL;
1409                         }
1410                 }
1411         }
1412         return list;
1413 }
1414
1415 void listening_ports_free(struct listen_port* list)
1416 {
1417         struct listen_port* nx;
1418         while(list) {
1419                 nx = list->next;
1420                 if(list->fd != -1) {
1421 #ifndef USE_WINSOCK
1422                         close(list->fd);
1423 #else
1424                         closesocket(list->fd);
1425 #endif
1426                 }
1427                 free(list);
1428                 list = nx;
1429         }
1430 }
1431
1432 size_t listen_get_mem(struct listen_dnsport* listen)
1433 {
1434         struct listen_list* p;
1435         size_t s = sizeof(*listen) + sizeof(*listen->base) + 
1436                 sizeof(*listen->udp_buff) + 
1437                 sldns_buffer_capacity(listen->udp_buff);
1438 #ifdef USE_DNSCRYPT
1439         s += sizeof(*listen->dnscrypt_udp_buff);
1440         if(listen->udp_buff != listen->dnscrypt_udp_buff){
1441                 s += sldns_buffer_capacity(listen->dnscrypt_udp_buff);
1442         }
1443 #endif
1444         for(p = listen->cps; p; p = p->next) {
1445                 s += sizeof(*p);
1446                 s += comm_point_get_mem(p->com);
1447         }
1448         return s;
1449 }
1450
1451 void listen_stop_accept(struct listen_dnsport* listen)
1452 {
1453         /* do not stop the ones that have no tcp_free list
1454          * (they have already stopped listening) */
1455         struct listen_list* p;
1456         for(p=listen->cps; p; p=p->next) {
1457                 if(p->com->type == comm_tcp_accept &&
1458                         p->com->tcp_free != NULL) {
1459                         comm_point_stop_listening(p->com);
1460                 }
1461         }
1462 }
1463
1464 void listen_start_accept(struct listen_dnsport* listen)
1465 {
1466         /* do not start the ones that have no tcp_free list, it is no
1467          * use to listen to them because they have no free tcp handlers */
1468         struct listen_list* p;
1469         for(p=listen->cps; p; p=p->next) {
1470                 if(p->com->type == comm_tcp_accept &&
1471                         p->com->tcp_free != NULL) {
1472                         comm_point_start_listening(p->com, -1, -1);
1473                 }
1474         }
1475 }
1476