]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - services/listen_dnsport.c
import unbound 1.4.17
[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 LIMITED
25  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
27  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * 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 #include "services/listen_dnsport.h"
47 #include "services/outside_network.h"
48 #include "util/netevent.h"
49 #include "util/log.h"
50 #include "util/config_file.h"
51 #include "util/net_help.h"
52
53 #ifdef HAVE_NETDB_H
54 #include <netdb.h>
55 #endif
56 #include <fcntl.h>
57
58 /** number of queued TCP connections for listen() */
59 #define TCP_BACKLOG 5 
60
61 /**
62  * Debug print of the getaddrinfo returned address.
63  * @param addr: the address returned.
64  */
65 static void
66 verbose_print_addr(struct addrinfo *addr)
67 {
68         if(verbosity >= VERB_ALGO) {
69                 char buf[100];
70                 void* sinaddr = &((struct sockaddr_in*)addr->ai_addr)->sin_addr;
71 #ifdef INET6
72                 if(addr->ai_family == AF_INET6)
73                         sinaddr = &((struct sockaddr_in6*)addr->ai_addr)->
74                                 sin6_addr;
75 #endif /* INET6 */
76                 if(inet_ntop(addr->ai_family, sinaddr, buf,
77                         (socklen_t)sizeof(buf)) == 0) {
78                         strncpy(buf, "(null)", sizeof(buf));
79                 }
80                 buf[sizeof(buf)-1] = 0;
81                 verbose(VERB_ALGO, "creating %s%s socket %s %d", 
82                         addr->ai_socktype==SOCK_DGRAM?"udp":
83                         addr->ai_socktype==SOCK_STREAM?"tcp":"otherproto",
84                         addr->ai_family==AF_INET?"4":
85                         addr->ai_family==AF_INET6?"6":
86                         "_otherfam", buf, 
87                         ntohs(((struct sockaddr_in*)addr->ai_addr)->sin_port));
88         }
89 }
90
91 int
92 create_udp_sock(int family, int socktype, struct sockaddr* addr,
93         socklen_t addrlen, int v6only, int* inuse, int* noproto,
94         int rcv, int snd)
95 {
96         int s;
97 #if defined(IPV6_USE_MIN_MTU)
98         int on=1;
99 #endif
100 #ifdef IPV6_MTU
101         int mtu = IPV6_MIN_MTU;
102 #endif
103 #if !defined(SO_RCVBUFFORCE) && !defined(SO_RCVBUF)
104         (void)rcv;
105 #endif
106 #if !defined(SO_SNDBUFFORCE) && !defined(SO_SNDBUF)
107         (void)snd;
108 #endif
109 #ifndef IPV6_V6ONLY
110         (void)v6only;
111 #endif
112         if((s = socket(family, socktype, 0)) == -1) {
113                 *inuse = 0;
114 #ifndef USE_WINSOCK
115                 if(errno == EAFNOSUPPORT || errno == EPROTONOSUPPORT) {
116                         *noproto = 1;
117                         return -1;
118                 }
119                 log_err("can't create socket: %s", strerror(errno));
120 #else
121                 if(WSAGetLastError() == WSAEAFNOSUPPORT || 
122                         WSAGetLastError() == WSAEPROTONOSUPPORT) {
123                         *noproto = 1;
124                         return -1;
125                 }
126                 log_err("can't create socket: %s", 
127                         wsa_strerror(WSAGetLastError()));
128 #endif
129                 *noproto = 0;
130                 return -1;
131         }
132         if(rcv) {
133 #ifdef SO_RCVBUF
134                 int got;
135                 socklen_t slen = (socklen_t)sizeof(got);
136 #  ifdef SO_RCVBUFFORCE
137                 /* Linux specific: try to use root permission to override
138                  * system limits on rcvbuf. The limit is stored in 
139                  * /proc/sys/net/core/rmem_max or sysctl net.core.rmem_max */
140                 if(setsockopt(s, SOL_SOCKET, SO_RCVBUFFORCE, (void*)&rcv, 
141                         (socklen_t)sizeof(rcv)) < 0) {
142                         if(errno != EPERM) {
143 #    ifndef USE_WINSOCK
144                                 log_err("setsockopt(..., SO_RCVBUFFORCE, "
145                                         "...) failed: %s", strerror(errno));
146                                 close(s);
147 #    else
148                                 log_err("setsockopt(..., SO_RCVBUFFORCE, "
149                                         "...) failed: %s", 
150                                         wsa_strerror(WSAGetLastError()));
151                                 closesocket(s);
152 #    endif
153                                 *noproto = 0;
154                                 *inuse = 0;
155                                 return -1;
156                         }
157 #  endif /* SO_RCVBUFFORCE */
158                         if(setsockopt(s, SOL_SOCKET, SO_RCVBUF, (void*)&rcv, 
159                                 (socklen_t)sizeof(rcv)) < 0) {
160 #  ifndef USE_WINSOCK
161                                 log_err("setsockopt(..., SO_RCVBUF, "
162                                         "...) failed: %s", strerror(errno));
163                                 close(s);
164 #  else
165                                 log_err("setsockopt(..., SO_RCVBUF, "
166                                         "...) failed: %s", 
167                                         wsa_strerror(WSAGetLastError()));
168                                 closesocket(s);
169 #  endif
170                                 *noproto = 0;
171                                 *inuse = 0;
172                                 return -1;
173                         }
174                         /* check if we got the right thing or if system
175                          * reduced to some system max.  Warn if so */
176                         if(getsockopt(s, SOL_SOCKET, SO_RCVBUF, (void*)&got, 
177                                 &slen) >= 0 && got < rcv/2) {
178                                 log_warn("so-rcvbuf %u was not granted. "
179                                         "Got %u. To fix: start with "
180                                         "root permissions(linux) or sysctl "
181                                         "bigger net.core.rmem_max(linux) or "
182                                         "kern.ipc.maxsockbuf(bsd) values.",
183                                         (unsigned)rcv, (unsigned)got);
184                         }
185 #  ifdef SO_RCVBUFFORCE
186                 }
187 #  endif
188 #endif /* SO_RCVBUF */
189         }
190         /* first do RCVBUF as the receive buffer is more important */
191         if(snd) {
192 #ifdef SO_SNDBUF
193                 int got;
194                 socklen_t slen = (socklen_t)sizeof(got);
195 #  ifdef SO_SNDBUFFORCE
196                 /* Linux specific: try to use root permission to override
197                  * system limits on sndbuf. The limit is stored in 
198                  * /proc/sys/net/core/wmem_max or sysctl net.core.wmem_max */
199                 if(setsockopt(s, SOL_SOCKET, SO_SNDBUFFORCE, (void*)&snd, 
200                         (socklen_t)sizeof(snd)) < 0) {
201                         if(errno != EPERM) {
202 #    ifndef USE_WINSOCK
203                                 log_err("setsockopt(..., SO_SNDBUFFORCE, "
204                                         "...) failed: %s", strerror(errno));
205                                 close(s);
206 #    else
207                                 log_err("setsockopt(..., SO_SNDBUFFORCE, "
208                                         "...) failed: %s", 
209                                         wsa_strerror(WSAGetLastError()));
210                                 closesocket(s);
211 #    endif
212                                 *noproto = 0;
213                                 *inuse = 0;
214                                 return -1;
215                         }
216 #  endif /* SO_SNDBUFFORCE */
217                         if(setsockopt(s, SOL_SOCKET, SO_SNDBUF, (void*)&snd, 
218                                 (socklen_t)sizeof(snd)) < 0) {
219 #  ifndef USE_WINSOCK
220                                 log_err("setsockopt(..., SO_SNDBUF, "
221                                         "...) failed: %s", strerror(errno));
222                                 close(s);
223 #  else
224                                 log_err("setsockopt(..., SO_SNDBUF, "
225                                         "...) failed: %s", 
226                                         wsa_strerror(WSAGetLastError()));
227                                 closesocket(s);
228 #  endif
229                                 *noproto = 0;
230                                 *inuse = 0;
231                                 return -1;
232                         }
233                         /* check if we got the right thing or if system
234                          * reduced to some system max.  Warn if so */
235                         if(getsockopt(s, SOL_SOCKET, SO_SNDBUF, (void*)&got, 
236                                 &slen) >= 0 && got < snd/2) {
237                                 log_warn("so-sndbuf %u was not granted. "
238                                         "Got %u. To fix: start with "
239                                         "root permissions(linux) or sysctl "
240                                         "bigger net.core.wmem_max(linux) or "
241                                         "kern.ipc.maxsockbuf(bsd) values.",
242                                         (unsigned)snd, (unsigned)got);
243                         }
244 #  ifdef SO_SNDBUFFORCE
245                 }
246 #  endif
247 #endif /* SO_SNDBUF */
248         }
249         if(family == AF_INET6) {
250 # if defined(IPV6_V6ONLY)
251                 if(v6only) {
252                         int val=(v6only==2)?0:1;
253                         if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, 
254                                 (void*)&val, (socklen_t)sizeof(val)) < 0) {
255 #ifndef USE_WINSOCK
256                                 log_err("setsockopt(..., IPV6_V6ONLY"
257                                         ", ...) failed: %s", strerror(errno));
258                                 close(s);
259 #else
260                                 log_err("setsockopt(..., IPV6_V6ONLY"
261                                         ", ...) failed: %s", 
262                                         wsa_strerror(WSAGetLastError()));
263                                 closesocket(s);
264 #endif
265                                 *noproto = 0;
266                                 *inuse = 0;
267                                 return -1;
268                         }
269                 }
270 # endif
271 # if defined(IPV6_USE_MIN_MTU)
272                 /*
273                  * There is no fragmentation of IPv6 datagrams
274                  * during forwarding in the network. Therefore
275                  * we do not send UDP datagrams larger than
276                  * the minimum IPv6 MTU of 1280 octets. The
277                  * EDNS0 message length can be larger if the
278                  * network stack supports IPV6_USE_MIN_MTU.
279                  */
280                 if (setsockopt(s, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
281                         (void*)&on, (socklen_t)sizeof(on)) < 0) {
282 #  ifndef USE_WINSOCK
283                         log_err("setsockopt(..., IPV6_USE_MIN_MTU, "
284                                 "...) failed: %s", strerror(errno));
285                         close(s);
286 #  else
287                         log_err("setsockopt(..., IPV6_USE_MIN_MTU, "
288                                 "...) failed: %s", 
289                                 wsa_strerror(WSAGetLastError()));
290                         closesocket(s);
291 #  endif
292                         *noproto = 0;
293                         *inuse = 0;
294                         return -1;
295                 }
296 # elif defined(IPV6_MTU)
297                 /*
298                  * On Linux, to send no larger than 1280, the PMTUD is
299                  * disabled by default for datagrams anyway, so we set
300                  * the MTU to use.
301                  */
302                 if (setsockopt(s, IPPROTO_IPV6, IPV6_MTU,
303                         (void*)&mtu, (socklen_t)sizeof(mtu)) < 0) {
304 #  ifndef USE_WINSOCK
305                         log_err("setsockopt(..., IPV6_MTU, ...) failed: %s", 
306                                 strerror(errno));
307                         close(s);
308 #  else
309                         log_err("setsockopt(..., IPV6_MTU, ...) failed: %s", 
310                                 wsa_strerror(WSAGetLastError()));
311                         closesocket(s);
312 #  endif
313                         *noproto = 0;
314                         *inuse = 0;
315                         return -1;
316                 }
317 # endif /* IPv6 MTU */
318         } else if(family == AF_INET) {
319 #  if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
320                 int action = IP_PMTUDISC_DONT;
321                 if (setsockopt(s, IPPROTO_IP, IP_MTU_DISCOVER, 
322                         &action, (socklen_t)sizeof(action)) < 0) {
323                         log_err("setsockopt(..., IP_MTU_DISCOVER, "
324                                 "IP_PMTUDISC_DONT...) failed: %s",
325                                 strerror(errno));
326                         return -1;
327                 }
328 #  elif defined(IP_DONTFRAG)
329                 int off = 0;
330                 if (setsockopt(s, IPPROTO_IP, IP_DONTFRAG, 
331                         &off, (socklen_t)sizeof(off)) < 0) {
332                         log_err("setsockopt(..., IP_DONTFRAG, ...) failed: %s",
333                                 strerror(errno));
334                         return -1;
335                 }
336 #  endif /* IPv4 MTU */
337         }
338         if(bind(s, (struct sockaddr*)addr, addrlen) != 0) {
339                 *noproto = 0;
340 #ifndef USE_WINSOCK
341 #ifdef EADDRINUSE
342                 *inuse = (errno == EADDRINUSE);
343                 /* detect freebsd jail with no ipv6 permission */
344                 if(family==AF_INET6 && errno==EINVAL)
345                         *noproto = 1;
346                 else if(errno != EADDRINUSE) {
347                         log_err("can't bind socket: %s", strerror(errno));
348                         log_addr(0, "failed address",
349                                 (struct sockaddr_storage*)addr, addrlen);
350                 }
351 #endif /* EADDRINUSE */
352                 close(s);
353 #else /* USE_WINSOCK */
354                 if(WSAGetLastError() != WSAEADDRINUSE &&
355                         WSAGetLastError() != WSAEADDRNOTAVAIL) {
356                         log_err("can't bind socket: %s", 
357                                 wsa_strerror(WSAGetLastError()));
358                         log_addr(0, "failed address",
359                                 (struct sockaddr_storage*)addr, addrlen);
360                 }
361                 closesocket(s);
362 #endif
363                 return -1;
364         }
365         if(!fd_set_nonblock(s)) {
366                 *noproto = 0;
367                 *inuse = 0;
368 #ifndef USE_WINSOCK
369                 close(s);
370 #else
371                 closesocket(s);
372 #endif
373                 return -1;
374         }
375         return s;
376 }
377
378 int
379 create_tcp_accept_sock(struct addrinfo *addr, int v6only, int* noproto)
380 {
381         int s;
382 #if defined(SO_REUSEADDR) || defined(IPV6_V6ONLY)
383         int on = 1;
384 #endif /* SO_REUSEADDR || IPV6_V6ONLY */
385         verbose_print_addr(addr);
386         *noproto = 0;
387         if((s = socket(addr->ai_family, addr->ai_socktype, 0)) == -1) {
388 #ifndef USE_WINSOCK
389                 if(errno == EAFNOSUPPORT || errno == EPROTONOSUPPORT) {
390                         *noproto = 1;
391                         return -1;
392                 }
393                 log_err("can't create socket: %s", strerror(errno));
394 #else
395                 if(WSAGetLastError() == WSAEAFNOSUPPORT ||
396                         WSAGetLastError() == WSAEPROTONOSUPPORT) {
397                         *noproto = 1;
398                         return -1;
399                 }
400                 log_err("can't create socket: %s", 
401                         wsa_strerror(WSAGetLastError()));
402 #endif
403                 return -1;
404         }
405 #ifdef SO_REUSEADDR
406         if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&on, 
407                 (socklen_t)sizeof(on)) < 0) {
408 #ifndef USE_WINSOCK
409                 log_err("setsockopt(.. SO_REUSEADDR ..) failed: %s",
410                         strerror(errno));
411 #else
412                 log_err("setsockopt(.. SO_REUSEADDR ..) failed: %s",
413                         wsa_strerror(WSAGetLastError()));
414 #endif
415                 return -1;
416         }
417 #endif /* SO_REUSEADDR */
418 #if defined(IPV6_V6ONLY)
419         if(addr->ai_family == AF_INET6 && v6only) {
420                 if(setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, 
421                         (void*)&on, (socklen_t)sizeof(on)) < 0) {
422 #ifndef USE_WINSOCK
423                         log_err("setsockopt(..., IPV6_V6ONLY, ...) failed: %s",
424                                 strerror(errno));
425 #else
426                         log_err("setsockopt(..., IPV6_V6ONLY, ...) failed: %s",
427                                 wsa_strerror(WSAGetLastError()));
428 #endif
429                         return -1;
430                 }
431         }
432 #else
433         (void)v6only;
434 #endif /* IPV6_V6ONLY */
435         if(bind(s, addr->ai_addr, addr->ai_addrlen) != 0) {
436 #ifndef USE_WINSOCK
437                 /* detect freebsd jail with no ipv6 permission */
438                 if(addr->ai_family==AF_INET6 && errno==EINVAL)
439                         *noproto = 1;
440                 else {
441                         log_err("can't bind socket: %s", strerror(errno));
442                         log_addr(0, "failed address",
443                                 (struct sockaddr_storage*)addr->ai_addr,
444                                 addr->ai_addrlen);
445                 }
446 #else
447                 log_err("can't bind socket: %s", 
448                         wsa_strerror(WSAGetLastError()));
449                 log_addr(0, "failed address",
450                         (struct sockaddr_storage*)addr->ai_addr,
451                         addr->ai_addrlen);
452 #endif
453                 return -1;
454         }
455         if(!fd_set_nonblock(s)) {
456                 return -1;
457         }
458         if(listen(s, TCP_BACKLOG) == -1) {
459 #ifndef USE_WINSOCK
460                 log_err("can't listen: %s", strerror(errno));
461 #else
462                 log_err("can't listen: %s", wsa_strerror(WSAGetLastError()));
463 #endif
464                 return -1;
465         }
466         return s;
467 }
468
469 /**
470  * Create socket from getaddrinfo results
471  */
472 static int
473 make_sock(int stype, const char* ifname, const char* port, 
474         struct addrinfo *hints, int v6only, int* noip6, size_t rcv, size_t snd)
475 {
476         struct addrinfo *res = NULL;
477         int r, s, inuse, noproto;
478         hints->ai_socktype = stype;
479         *noip6 = 0;
480         if((r=getaddrinfo(ifname, port, hints, &res)) != 0 || !res) {
481 #ifdef USE_WINSOCK
482                 if(r == EAI_NONAME && hints->ai_family == AF_INET6){
483                         *noip6 = 1; /* 'Host not found' for IP6 on winXP */
484                         return -1;
485                 }
486 #endif
487                 log_err("node %s:%s getaddrinfo: %s %s", 
488                         ifname?ifname:"default", port, gai_strerror(r),
489 #ifdef EAI_SYSTEM
490                         r==EAI_SYSTEM?(char*)strerror(errno):""
491 #else
492                         ""
493 #endif
494                 );
495                 return -1;
496         }
497         if(stype == SOCK_DGRAM) {
498                 verbose_print_addr(res);
499                 s = create_udp_sock(res->ai_family, res->ai_socktype,
500                         (struct sockaddr*)res->ai_addr, res->ai_addrlen,
501                         v6only, &inuse, &noproto, (int)rcv, (int)snd);
502                 if(s == -1 && inuse) {
503                         log_err("bind: address already in use");
504                 } else if(s == -1 && noproto && hints->ai_family == AF_INET6){
505                         *noip6 = 1;
506                 }
507         } else  {
508                 s = create_tcp_accept_sock(res, v6only, &noproto);
509                 if(s == -1 && noproto && hints->ai_family == AF_INET6){
510                         *noip6 = 1;
511                 }
512         }
513         freeaddrinfo(res);
514         return s;
515 }
516
517 /** make socket and first see if ifname contains port override info */
518 static int
519 make_sock_port(int stype, const char* ifname, const char* port, 
520         struct addrinfo *hints, int v6only, int* noip6, size_t rcv, size_t snd)
521 {
522         char* s = strchr(ifname, '@');
523         if(s) {
524                 /* override port with ifspec@port */
525                 char p[16];
526                 char newif[128];
527                 if((size_t)(s-ifname) >= sizeof(newif)) {
528                         log_err("ifname too long: %s", ifname);
529                         *noip6 = 0;
530                         return -1;
531                 }
532                 if(strlen(s+1) >= sizeof(p)) {
533                         log_err("portnumber too long: %s", ifname);
534                         *noip6 = 0;
535                         return -1;
536                 }
537                 strncpy(newif, ifname, sizeof(newif));
538                 newif[s-ifname] = 0;
539                 strncpy(p, s+1, sizeof(p));
540                 p[strlen(s+1)]=0;
541                 return make_sock(stype, newif, p, hints, v6only, noip6,
542                         rcv, snd);
543         }
544         return make_sock(stype, ifname, port, hints, v6only, noip6, rcv, snd);
545 }
546
547 /**
548  * Add port to open ports list.
549  * @param list: list head. changed.
550  * @param s: fd.
551  * @param ftype: if fd is UDP.
552  * @return false on failure. list in unchanged then.
553  */
554 static int
555 port_insert(struct listen_port** list, int s, enum listen_type ftype)
556 {
557         struct listen_port* item = (struct listen_port*)malloc(
558                 sizeof(struct listen_port));
559         if(!item)
560                 return 0;
561         item->next = *list;
562         item->fd = s;
563         item->ftype = ftype;
564         *list = item;
565         return 1;
566 }
567
568 /** set fd to receive source address packet info */
569 static int
570 set_recvpktinfo(int s, int family) 
571 {
572 #if defined(IPV6_RECVPKTINFO) || defined(IPV6_PKTINFO) || (defined(IP_RECVDSTADDR) && defined(IP_SENDSRCADDR)) || defined(IP_PKTINFO)
573         int on = 1;
574 #else
575         (void)s;
576 #endif
577         if(family == AF_INET6) {
578 #           ifdef IPV6_RECVPKTINFO
579                 if(setsockopt(s, IPPROTO_IPV6, IPV6_RECVPKTINFO,
580                         (void*)&on, (socklen_t)sizeof(on)) < 0) {
581                         log_err("setsockopt(..., IPV6_RECVPKTINFO, ...) failed: %s",
582                                 strerror(errno));
583                         return 0;
584                 }
585 #           elif defined(IPV6_PKTINFO)
586                 if(setsockopt(s, IPPROTO_IPV6, IPV6_PKTINFO,
587                         (void*)&on, (socklen_t)sizeof(on)) < 0) {
588                         log_err("setsockopt(..., IPV6_PKTINFO, ...) failed: %s",
589                                 strerror(errno));
590                         return 0;
591                 }
592 #           else
593                 log_err("no IPV6_RECVPKTINFO and no IPV6_PKTINFO option, please "
594                         "disable interface-automatic in config");
595                 return 0;
596 #           endif /* defined IPV6_RECVPKTINFO */
597
598         } else if(family == AF_INET) {
599 #           ifdef IP_PKTINFO
600                 if(setsockopt(s, IPPROTO_IP, IP_PKTINFO,
601                         (void*)&on, (socklen_t)sizeof(on)) < 0) {
602                         log_err("setsockopt(..., IP_PKTINFO, ...) failed: %s",
603                                 strerror(errno));
604                         return 0;
605                 }
606 #           elif defined(IP_RECVDSTADDR) && defined(IP_SENDSRCADDR)
607                 if(setsockopt(s, IPPROTO_IP, IP_RECVDSTADDR,
608                         (void*)&on, (socklen_t)sizeof(on)) < 0) {
609                         log_err("setsockopt(..., IP_RECVDSTADDR, ...) failed: %s",
610                                 strerror(errno));
611                         return 0;
612                 }
613 #           else
614                 log_err("no IP_SENDSRCADDR or IP_PKTINFO option, please disable "
615                         "interface-automatic in config");
616                 return 0;
617 #           endif /* IP_PKTINFO */
618
619         }
620         return 1;
621 }
622
623 /**
624  * Helper for ports_open. Creates one interface (or NULL for default).
625  * @param ifname: The interface ip address.
626  * @param do_auto: use automatic interface detection.
627  *      If enabled, then ifname must be the wildcard name.
628  * @param do_udp: if udp should be used.
629  * @param do_tcp: if udp should be used.
630  * @param hints: for getaddrinfo. family and flags have to be set by caller.
631  * @param port: Port number to use (as string).
632  * @param list: list of open ports, appended to, changed to point to list head.
633  * @param rcv: receive buffer size for UDP
634  * @param snd: send buffer size for UDP
635  * @param ssl_port: ssl service port number
636  * @return: returns false on error.
637  */
638 static int
639 ports_create_if(const char* ifname, int do_auto, int do_udp, int do_tcp, 
640         struct addrinfo *hints, const char* port, struct listen_port** list,
641         size_t rcv, size_t snd, int ssl_port)
642 {
643         int s, noip6=0;
644         if(!do_udp && !do_tcp)
645                 return 0;
646         if(do_auto) {
647                 if((s = make_sock_port(SOCK_DGRAM, ifname, port, hints, 1, 
648                         &noip6, rcv, snd)) == -1) {
649                         if(noip6) {
650                                 log_warn("IPv6 protocol not available");
651                                 return 1;
652                         }
653                         return 0;
654                 }
655                 /* getting source addr packet info is highly non-portable */
656                 if(!set_recvpktinfo(s, hints->ai_family))
657                         return 0;
658                 if(!port_insert(list, s, listen_type_udpancil)) {
659 #ifndef USE_WINSOCK
660                         close(s);
661 #else
662                         closesocket(s);
663 #endif
664                         return 0;
665                 }
666         } else if(do_udp) {
667                 /* regular udp socket */
668                 if((s = make_sock_port(SOCK_DGRAM, ifname, port, hints, 1, 
669                         &noip6, rcv, snd)) == -1) {
670                         if(noip6) {
671                                 log_warn("IPv6 protocol not available");
672                                 return 1;
673                         }
674                         return 0;
675                 }
676                 if(!port_insert(list, s, listen_type_udp)) {
677 #ifndef USE_WINSOCK
678                         close(s);
679 #else
680                         closesocket(s);
681 #endif
682                         return 0;
683                 }
684         }
685         if(do_tcp) {
686                 int is_ssl = ((strchr(ifname, '@') && 
687                         atoi(strchr(ifname, '@')+1) == ssl_port) ||
688                         (!strchr(ifname, '@') && atoi(port) == ssl_port));
689                 if((s = make_sock_port(SOCK_STREAM, ifname, port, hints, 1, 
690                         &noip6, 0, 0)) == -1) {
691                         if(noip6) {
692                                 /*log_warn("IPv6 protocol not available");*/
693                                 return 1;
694                         }
695                         return 0;
696                 }
697                 if(is_ssl)
698                         verbose(VERB_ALGO, "setup TCP for SSL service");
699                 if(!port_insert(list, s, is_ssl?listen_type_ssl:
700                         listen_type_tcp)) {
701 #ifndef USE_WINSOCK
702                         close(s);
703 #else
704                         closesocket(s);
705 #endif
706                         return 0;
707                 }
708         }
709         return 1;
710 }
711
712 /** 
713  * Add items to commpoint list in front.
714  * @param c: commpoint to add.
715  * @param front: listen struct.
716  * @return: false on failure.
717  */
718 static int
719 listen_cp_insert(struct comm_point* c, struct listen_dnsport* front)
720 {
721         struct listen_list* item = (struct listen_list*)malloc(
722                 sizeof(struct listen_list));
723         if(!item)
724                 return 0;
725         item->com = c;
726         item->next = front->cps;
727         front->cps = item;
728         return 1;
729 }
730
731 struct listen_dnsport* 
732 listen_create(struct comm_base* base, struct listen_port* ports,
733         size_t bufsize, int tcp_accept_count, void* sslctx,
734         comm_point_callback_t* cb, void *cb_arg)
735 {
736         struct listen_dnsport* front = (struct listen_dnsport*)
737                 malloc(sizeof(struct listen_dnsport));
738         if(!front)
739                 return NULL;
740         front->cps = NULL;
741         front->udp_buff = ldns_buffer_new(bufsize);
742         if(!front->udp_buff) {
743                 free(front);
744                 return NULL;
745         }
746
747         /* create comm points as needed */
748         while(ports) {
749                 struct comm_point* cp = NULL;
750                 if(ports->ftype == listen_type_udp) 
751                         cp = comm_point_create_udp(base, ports->fd, 
752                                 front->udp_buff, cb, cb_arg);
753                 else if(ports->ftype == listen_type_tcp)
754                         cp = comm_point_create_tcp(base, ports->fd, 
755                                 tcp_accept_count, bufsize, cb, cb_arg);
756                 else if(ports->ftype == listen_type_ssl) {
757                         cp = comm_point_create_tcp(base, ports->fd, 
758                                 tcp_accept_count, bufsize, cb, cb_arg);
759                         cp->ssl = sslctx;
760                 } else if(ports->ftype == listen_type_udpancil) 
761                         cp = comm_point_create_udp_ancil(base, ports->fd, 
762                                 front->udp_buff, cb, cb_arg);
763                 if(!cp) {
764                         log_err("can't create commpoint");      
765                         listen_delete(front);
766                         return NULL;
767                 }
768                 cp->do_not_close = 1;
769                 if(!listen_cp_insert(cp, front)) {
770                         log_err("malloc failed");
771                         comm_point_delete(cp);
772                         listen_delete(front);
773                         return NULL;
774                 }
775                 ports = ports->next;
776         }
777         if(!front->cps) {
778                 log_err("Could not open sockets to accept queries.");
779                 listen_delete(front);
780                 return NULL;
781         }
782
783         return front;
784 }
785
786 void
787 listen_list_delete(struct listen_list* list)
788 {
789         struct listen_list *p = list, *pn;
790         while(p) {
791                 pn = p->next;
792                 comm_point_delete(p->com);
793                 free(p);
794                 p = pn;
795         }
796 }
797
798 void 
799 listen_delete(struct listen_dnsport* front)
800 {
801         if(!front) 
802                 return;
803         listen_list_delete(front->cps);
804         ldns_buffer_free(front->udp_buff);
805         free(front);
806 }
807
808 struct listen_port* 
809 listening_ports_open(struct config_file* cfg)
810 {
811         struct listen_port* list = NULL;
812         struct addrinfo hints;
813         int i, do_ip4, do_ip6;
814         int do_tcp, do_auto;
815         char portbuf[32];
816         snprintf(portbuf, sizeof(portbuf), "%d", cfg->port);
817         do_ip4 = cfg->do_ip4;
818         do_ip6 = cfg->do_ip6;
819         do_tcp = cfg->do_tcp;
820         do_auto = cfg->if_automatic && cfg->do_udp;
821         if(cfg->incoming_num_tcp == 0)
822                 do_tcp = 0;
823
824         /* getaddrinfo */
825         memset(&hints, 0, sizeof(hints));
826         hints.ai_flags = AI_PASSIVE;
827         /* no name lookups on our listening ports */
828         if(cfg->num_ifs > 0)
829                 hints.ai_flags |= AI_NUMERICHOST;
830         hints.ai_family = AF_UNSPEC;
831 #ifndef INET6
832         do_ip6 = 0;
833 #endif
834         if(!do_ip4 && !do_ip6) {
835                 return NULL;
836         }
837         /* create ip4 and ip6 ports so that return addresses are nice. */
838         if(do_auto || cfg->num_ifs == 0) {
839                 if(do_ip6) {
840                         hints.ai_family = AF_INET6;
841                         if(!ports_create_if(do_auto?"::0":"::1", 
842                                 do_auto, cfg->do_udp, do_tcp, 
843                                 &hints, portbuf, &list,
844                                 cfg->so_rcvbuf, cfg->so_sndbuf,
845                                 cfg->ssl_port)) {
846                                 listening_ports_free(list);
847                                 return NULL;
848                         }
849                 }
850                 if(do_ip4) {
851                         hints.ai_family = AF_INET;
852                         if(!ports_create_if(do_auto?"0.0.0.0":"127.0.0.1", 
853                                 do_auto, cfg->do_udp, do_tcp, 
854                                 &hints, portbuf, &list,
855                                 cfg->so_rcvbuf, cfg->so_sndbuf,
856                                 cfg->ssl_port)) {
857                                 listening_ports_free(list);
858                                 return NULL;
859                         }
860                 }
861         } else for(i = 0; i<cfg->num_ifs; i++) {
862                 if(str_is_ip6(cfg->ifs[i])) {
863                         if(!do_ip6)
864                                 continue;
865                         hints.ai_family = AF_INET6;
866                         if(!ports_create_if(cfg->ifs[i], 0, cfg->do_udp, 
867                                 do_tcp, &hints, portbuf, &list, 
868                                 cfg->so_rcvbuf, cfg->so_sndbuf,
869                                 cfg->ssl_port)) {
870                                 listening_ports_free(list);
871                                 return NULL;
872                         }
873                 } else {
874                         if(!do_ip4)
875                                 continue;
876                         hints.ai_family = AF_INET;
877                         if(!ports_create_if(cfg->ifs[i], 0, cfg->do_udp, 
878                                 do_tcp, &hints, portbuf, &list, 
879                                 cfg->so_rcvbuf, cfg->so_sndbuf,
880                                 cfg->ssl_port)) {
881                                 listening_ports_free(list);
882                                 return NULL;
883                         }
884                 }
885         }
886         return list;
887 }
888
889 void listening_ports_free(struct listen_port* list)
890 {
891         struct listen_port* nx;
892         while(list) {
893                 nx = list->next;
894                 if(list->fd != -1) {
895 #ifndef USE_WINSOCK
896                         close(list->fd);
897 #else
898                         closesocket(list->fd);
899 #endif
900                 }
901                 free(list);
902                 list = nx;
903         }
904 }
905
906 size_t listen_get_mem(struct listen_dnsport* listen)
907 {
908         size_t s = sizeof(*listen) + sizeof(*listen->base) + 
909                 sizeof(*listen->udp_buff) + 
910                 ldns_buffer_capacity(listen->udp_buff);
911         struct listen_list* p;
912         for(p = listen->cps; p; p = p->next) {
913                 s += sizeof(*p);
914                 s += comm_point_get_mem(p->com);
915         }
916         return s;
917 }
918
919 void listen_stop_accept(struct listen_dnsport* listen)
920 {
921         /* do not stop the ones that have no tcp_free list
922          * (they have already stopped listening) */
923         struct listen_list* p;
924         for(p=listen->cps; p; p=p->next) {
925                 if(p->com->type == comm_tcp_accept &&
926                         p->com->tcp_free != NULL) {
927                         comm_point_stop_listening(p->com);
928                 }
929         }
930 }
931
932 void listen_start_accept(struct listen_dnsport* listen)
933 {
934         /* do not start the ones that have no tcp_free list, it is no
935          * use to listen to them because they have no free tcp handlers */
936         struct listen_list* p;
937         for(p=listen->cps; p; p=p->next) {
938                 if(p->com->type == comm_tcp_accept &&
939                         p->com->tcp_free != NULL) {
940                         comm_point_start_listening(p->com, -1, -1);
941                 }
942         }
943 }
944