• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* dnsmasq is Copyright (c) 2000-2009 Simon Kelley
2 
3    This program is free software; you can redistribute it and/or modify
4    it under the terms of the GNU General Public License as published by
5    the Free Software Foundation; version 2 dated June, 1991, or
6    (at your option) version 3 dated 29 June, 2007.
7 
8    This program is distributed in the hope that it will be useful,
9    but WITHOUT ANY WARRANTY; without even the implied warranty of
10    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11    GNU General Public License for more details.
12 
13    You should have received a copy of the GNU General Public License
14    along with this program.  If not, see <http://www.gnu.org/licenses/>.
15 */
16 
17 #include "dnsmasq.h"
18 
19 static const char SEPARATOR[] = "|";
20 
21 #ifdef HAVE_LINUX_NETWORK
22 
indextoname(int fd,int index,char * name)23 int indextoname(int fd, int index, char* name) {
24     struct ifreq ifr;
25 
26     if (index == 0) return 0;
27 
28     ifr.ifr_ifindex = index;
29     if (ioctl(fd, SIOCGIFNAME, &ifr) == -1) return 0;
30 
31     strncpy(name, ifr.ifr_name, IF_NAMESIZE);
32 
33     return 1;
34 }
35 
36 #else
37 
indextoname(int fd,int index,char * name)38 int indextoname(int fd, int index, char* name) {
39     if (index == 0 || !if_indextoname(index, name)) return 0;
40 
41     return 1;
42 }
43 
44 #endif
45 
iface_check(int family,struct all_addr * addr,char * name,int * indexp)46 int iface_check(int family, struct all_addr* addr, char* name, int* indexp) {
47     struct iname* tmp;
48     int ret = 1;
49 
50     /* Note: have to check all and not bail out early, so that we set the
51        "used" flags. */
52 
53     if (indexp) {
54         /* One form of bridging on BSD has the property that packets
55        can be recieved on bridge interfaces which do not have an IP address.
56        We allow these to be treated as aliases of another interface which does have
57        an IP address with --dhcp-bridge=interface,alias,alias */
58         struct dhcp_bridge *bridge, *alias;
59         for (bridge = daemon->bridges; bridge; bridge = bridge->next) {
60             for (alias = bridge->alias; alias; alias = alias->next)
61                 if (strncmp(name, alias->iface, IF_NAMESIZE) == 0) {
62                     int newindex;
63 
64                     if (!(newindex = if_nametoindex(bridge->iface))) {
65                         my_syslog(LOG_WARNING, _("unknown interface %s in bridge-interface"), name);
66                         return 0;
67                     } else {
68                         *indexp = newindex;
69                         strncpy(name, bridge->iface, IF_NAMESIZE);
70                         break;
71                     }
72                 }
73             if (alias) break;
74         }
75     }
76 
77     if (daemon->if_names || (addr && daemon->if_addrs)) {
78         ret = 0;
79 
80         for (tmp = daemon->if_names; tmp; tmp = tmp->next)
81             if (tmp->name && (strcmp(tmp->name, name) == 0)) ret = tmp->used = 1;
82 
83         for (tmp = daemon->if_addrs; tmp; tmp = tmp->next)
84             if (addr && tmp->addr.sa.sa_family == family) {
85                 if (family == AF_INET && tmp->addr.in.sin_addr.s_addr == addr->addr.addr4.s_addr)
86                     ret = tmp->used = 1;
87 #ifdef HAVE_IPV6
88                 else if (family == AF_INET6 &&
89                          IN6_ARE_ADDR_EQUAL(&tmp->addr.in6.sin6_addr, &addr->addr.addr6) &&
90                          (!IN6_IS_ADDR_LINKLOCAL(&addr->addr.addr6) ||
91                           (tmp->addr.in6.sin6_scope_id == (uint32_t) *indexp)))
92                     ret = tmp->used = 1;
93 #endif
94             }
95     }
96 
97     for (tmp = daemon->if_except; tmp; tmp = tmp->next)
98         if (tmp->name && (strcmp(tmp->name, name) == 0)) ret = 0;
99 
100     return ret;
101 }
102 
iface_allowed(struct irec ** irecp,int if_index,union mysockaddr * addr,struct in_addr netmask)103 static int iface_allowed(struct irec** irecp, int if_index, union mysockaddr* addr,
104                          struct in_addr netmask) {
105     struct irec* iface;
106     int fd, mtu = 0, loopback;
107     struct ifreq ifr;
108     int dhcp_ok = 1;
109     struct iname* tmp;
110 
111     /* check whether the interface IP has been added already
112        we call this routine multiple times. */
113     for (iface = *irecp; iface; iface = iface->next)
114         if (sockaddr_isequal(&iface->addr, addr)) return 1;
115 
116     if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) == -1 || !indextoname(fd, if_index, ifr.ifr_name) ||
117         ioctl(fd, SIOCGIFFLAGS, &ifr) == -1) {
118         if (fd != -1) {
119             int errsave = errno;
120             close(fd);
121             errno = errsave;
122         }
123         return 0;
124     }
125 
126     loopback = ifr.ifr_flags & IFF_LOOPBACK;
127 
128     if (ioctl(fd, SIOCGIFMTU, &ifr) != -1) mtu = ifr.ifr_mtu;
129 
130     close(fd);
131 
132     /* If we are restricting the set of interfaces to use, make
133        sure that loopback interfaces are in that set. */
134     if (daemon->if_names && loopback) {
135         struct iname* lo;
136         for (lo = daemon->if_names; lo; lo = lo->next)
137             if (lo->name && strcmp(lo->name, ifr.ifr_name) == 0) {
138                 lo->isloop = 1;
139                 break;
140             }
141 
142         if (!lo && (lo = whine_malloc(sizeof(struct iname))) &&
143             (lo->name = whine_malloc(strlen(ifr.ifr_name) + 1))) {
144             strcpy(lo->name, ifr.ifr_name);
145             lo->isloop = lo->used = 1;
146             lo->next = daemon->if_names;
147             daemon->if_names = lo;
148         }
149     }
150 
151     if (addr->sa.sa_family == AF_INET &&
152         !iface_check(AF_INET, (struct all_addr*) &addr->in.sin_addr, ifr.ifr_name, NULL))
153         return 1;
154 
155     for (tmp = daemon->dhcp_except; tmp; tmp = tmp->next)
156         if (tmp->name && (strcmp(tmp->name, ifr.ifr_name) == 0)) dhcp_ok = 0;
157 
158 #ifdef HAVE_IPV6
159     int ifindex = (int) addr->in6.sin6_scope_id;
160     if (addr->sa.sa_family == AF_INET6 &&
161         !iface_check(AF_INET6, (struct all_addr*) &addr->in6.sin6_addr, ifr.ifr_name, &ifindex))
162         return 1;
163 #endif
164 
165     /* add to list */
166     if ((iface = whine_malloc(sizeof(struct irec)))) {
167         iface->addr = *addr;
168         iface->netmask = netmask;
169         iface->dhcp_ok = dhcp_ok;
170         iface->mtu = mtu;
171         iface->next = *irecp;
172         *irecp = iface;
173         return 1;
174     }
175 
176     errno = ENOMEM;
177     return 0;
178 }
179 
180 #ifdef HAVE_IPV6
iface_allowed_v6(struct in6_addr * local,int scope,int if_index,void * vparam)181 static int iface_allowed_v6(struct in6_addr* local, int scope, int if_index, void* vparam) {
182     union mysockaddr addr;
183     struct in_addr netmask; /* dummy */
184 
185     netmask.s_addr = 0;
186 
187     memset(&addr, 0, sizeof(addr));
188     addr.in6.sin6_family = AF_INET6;
189     addr.in6.sin6_addr = *local;
190     addr.in6.sin6_port = htons(daemon->port);
191     /**
192      * Only populate the scope ID if the address is link-local.
193      * Scope IDs are not meaningful for global addresses. Also, we do not want to
194      * think that two addresses are different if they differ only in scope ID,
195      * because the kernel will treat them as if they are the same.
196      */
197     if (IN6_IS_ADDR_LINKLOCAL(local)) {
198         addr.in6.sin6_scope_id = scope;
199     }
200 
201     return iface_allowed((struct irec**) vparam, if_index, &addr, netmask);
202 }
203 #endif
204 
iface_allowed_v4(struct in_addr local,int if_index,struct in_addr netmask,struct in_addr broadcast,void * vparam)205 static int iface_allowed_v4(struct in_addr local, int if_index, struct in_addr netmask,
206                             struct in_addr broadcast, void* vparam) {
207     union mysockaddr addr;
208 
209     memset(&addr, 0, sizeof(addr));
210     addr.in.sin_family = AF_INET;
211     addr.in.sin_addr = broadcast; /* warning */
212     addr.in.sin_addr = local;
213     addr.in.sin_port = htons(daemon->port);
214 
215     return iface_allowed((struct irec**) vparam, if_index, &addr, netmask);
216 }
217 
enumerate_interfaces(void)218 int enumerate_interfaces(void) {
219 #ifdef HAVE_IPV6
220     return iface_enumerate(&daemon->interfaces, iface_allowed_v4, iface_allowed_v6);
221 #else
222     return iface_enumerate(&daemon->interfaces, iface_allowed_v4, NULL);
223 #endif
224 }
225 
226 /* set NONBLOCK bit on fd: See Stevens 16.6 */
fix_fd(int fd)227 int fix_fd(int fd) {
228     int flags;
229 
230     if ((flags = fcntl(fd, F_GETFL)) == -1 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
231         return 0;
232 
233     return 1;
234 }
235 
236 #if defined(HAVE_IPV6)
create_ipv6_listener(struct listener ** link,int port)237 static int create_ipv6_listener(struct listener** link, int port) {
238     union mysockaddr addr;
239     int tcpfd, fd;
240     struct listener* l;
241     int opt = 1;
242 
243     memset(&addr, 0, sizeof(addr));
244     addr.in6.sin6_family = AF_INET6;
245     addr.in6.sin6_addr = in6addr_any;
246     addr.in6.sin6_port = htons(port);
247 
248     /* No error of the kernel doesn't support IPv6 */
249     if ((fd = socket(AF_INET6, SOCK_DGRAM, 0)) == -1)
250         return (errno == EPROTONOSUPPORT || errno == EAFNOSUPPORT || errno == EINVAL);
251 
252     if ((tcpfd = socket(AF_INET6, SOCK_STREAM, 0)) == -1) return 0;
253 
254     if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
255         setsockopt(tcpfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
256         setsockopt(fd, IPV6_LEVEL, IPV6_V6ONLY, &opt, sizeof(opt)) == -1 ||
257         setsockopt(tcpfd, IPV6_LEVEL, IPV6_V6ONLY, &opt, sizeof(opt)) == -1 || !fix_fd(fd) ||
258         !fix_fd(tcpfd) ||
259 #ifdef IPV6_RECVPKTINFO
260         setsockopt(fd, IPV6_LEVEL, IPV6_RECVPKTINFO, &opt, sizeof(opt)) == -1 ||
261 #else
262         setsockopt(fd, IPV6_LEVEL, IPV6_PKTINFO, &opt, sizeof(opt)) == -1 ||
263 #endif
264         bind(tcpfd, (struct sockaddr*) &addr, sa_len(&addr)) == -1 || listen(tcpfd, 5) == -1 ||
265         bind(fd, (struct sockaddr*) &addr, sa_len(&addr)) == -1)
266         return 0;
267 
268     l = safe_malloc(sizeof(struct listener));
269     l->fd = fd;
270     l->tcpfd = tcpfd;
271     l->family = AF_INET6;
272     l->iface = NULL;
273     l->next = NULL;
274     *link = l;
275 
276     return 1;
277 }
278 #endif
279 
create_wildcard_listeners(void)280 struct listener* create_wildcard_listeners(void) {
281     union mysockaddr addr;
282     int opt = 1;
283     struct listener *l, *l6 = NULL;
284     int tcpfd = -1, fd = -1;
285 
286     memset(&addr, 0, sizeof(addr));
287     addr.in.sin_family = AF_INET;
288     addr.in.sin_addr.s_addr = INADDR_ANY;
289     addr.in.sin_port = htons(daemon->port);
290 
291     if (daemon->port != 0) {
292         if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1 ||
293             (tcpfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
294             return NULL;
295 
296         if (setsockopt(tcpfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
297             bind(tcpfd, (struct sockaddr*) &addr, sa_len(&addr)) == -1 || listen(tcpfd, 5) == -1 ||
298             !fix_fd(tcpfd) ||
299 #ifdef HAVE_IPV6
300             !create_ipv6_listener(&l6, daemon->port) ||
301 #endif
302             setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 || !fix_fd(fd) ||
303 #if defined(HAVE_LINUX_NETWORK)
304             setsockopt(fd, SOL_IP, IP_PKTINFO, &opt, sizeof(opt)) == -1 ||
305 #elif defined(IP_RECVDSTADDR) && defined(IP_RECVIF)
306             setsockopt(fd, IPPROTO_IP, IP_RECVDSTADDR, &opt, sizeof(opt)) == -1 ||
307             setsockopt(fd, IPPROTO_IP, IP_RECVIF, &opt, sizeof(opt)) == -1 ||
308 #endif
309             bind(fd, (struct sockaddr*) &addr, sa_len(&addr)) == -1)
310             return NULL;
311 
312 #ifdef __ANDROID__
313         uint32_t mark = daemon->listen_mark;
314         if (mark != 0 && (setsockopt(fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) == -1 ||
315                           setsockopt(tcpfd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) == -1 ||
316                           setsockopt(l6->fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) == -1 ||
317                           setsockopt(l6->tcpfd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) == -1)) {
318             my_syslog(LOG_WARNING, _("setsockopt(SO_MARK, 0x%x: %s"), mark, strerror(errno));
319             close(fd);
320             close(tcpfd);
321             close(l6->fd);
322             close(l6->tcpfd);
323             return NULL;
324         }
325     }
326 #endif /* __ANDROID__ */
327 
328     l = safe_malloc(sizeof(struct listener));
329     l->family = AF_INET;
330     l->fd = fd;
331     l->tcpfd = tcpfd;
332     l->iface = NULL;
333     l->next = l6;
334 
335     return l;
336 }
337 
338 #ifdef __ANDROID__
339 /**
340  * for a single given irec (interface name and address) create
341  * a set of sockets listening.  This is a copy of the code inside the loop
342  * of create_bound_listeners below and is added here to allow us
343  * to create just a single new listener dynamically when our interface
344  * list is changed.
345  *
346  * iface - input of the new interface details to listen on
347  * listeners - output.  Creates a new struct listener and inserts at head of the list
348  *
349  * die's on errors, so don't pass bad data.
350  */
create_bound_listener(struct listener ** listeners,struct irec * iface)351 void create_bound_listener(struct listener** listeners, struct irec* iface) {
352     int rc, opt = 1;
353 #ifdef HAVE_IPV6
354     static int dad_count = 0;
355 #endif
356 
357     struct listener* new = safe_malloc(sizeof(struct listener));
358     new->family = iface->addr.sa.sa_family;
359     new->iface = iface;
360     new->next = *listeners;
361     new->tcpfd = -1;
362     new->fd = -1;
363     *listeners = new;
364 
365     if (daemon->port != 0) {
366         if ((new->tcpfd = socket(iface->addr.sa.sa_family, SOCK_STREAM, 0)) == -1 ||
367             (new->fd = socket(iface->addr.sa.sa_family, SOCK_DGRAM, 0)) == -1 ||
368             setsockopt(new->fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
369             setsockopt(new->tcpfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
370             !fix_fd(new->tcpfd) || !fix_fd(new->fd))
371             die(_("failed to create listening socket: %s"), NULL, EC_BADNET);
372 
373 #ifdef HAVE_IPV6
374         if (iface->addr.sa.sa_family == AF_INET6) {
375             if (setsockopt(new->fd, IPV6_LEVEL, IPV6_V6ONLY, &opt, sizeof(opt)) == -1 ||
376                 setsockopt(new->tcpfd, IPV6_LEVEL, IPV6_V6ONLY, &opt, sizeof(opt)) == -1)
377                 die(_("failed to set IPV6 options on listening socket: %s"), NULL, EC_BADNET);
378         }
379 #endif
380 
381         while (1) {
382             if ((rc = bind(new->fd, &iface->addr.sa, sa_len(&iface->addr))) != -1) break;
383 
384 #ifdef HAVE_IPV6
385             /* An interface may have an IPv6 address which is still undergoing DAD.
386                If so, the bind will fail until the DAD completes, so we try over 20 seconds
387                before failing. */
388             /* TODO: What to do here? 20 seconds is way too long. We use optimistic addresses, so
389                bind() will only fail if the address has already failed DAD, in which case retrying
390                won't help. */
391             if (iface->addr.sa.sa_family == AF_INET6 &&
392                 (errno == ENODEV || errno == EADDRNOTAVAIL) && dad_count++ < DAD_WAIT) {
393                 sleep(1);
394                 continue;
395             }
396 #endif
397             break;
398         }
399 
400         if (rc == -1 || bind(new->tcpfd, &iface->addr.sa, sa_len(&iface->addr)) == -1) {
401             prettyprint_addr(&iface->addr, daemon->namebuff);
402             die(_("failed to bind listening socket for %s: %s"), daemon->namebuff, EC_BADNET);
403         }
404 
405         uint32_t mark = daemon->listen_mark;
406         if (mark != 0 && (setsockopt(new->fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) == -1 ||
407                           setsockopt(new->tcpfd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) == -1))
408             die(_("failed to set SO_MARK on listen socket: %s"), NULL, EC_BADNET);
409 
410         if (listen(new->tcpfd, 5) == -1) die(_("failed to listen on socket: %s"), NULL, EC_BADNET);
411     }
412 }
413 
414 /**
415  * If a listener has a struct irec pointer whose address matches the newly
416  * malloc()d struct irec's address, update its pointer to refer to this new
417  * struct irec instance.
418  *
419  * Otherwise, any listeners that are preserved across interface list changes
420  * will point at interface structures that are free()d at the end of
421  * set_interfaces(), and can get overwritten by subsequent memory allocations.
422  *
423  * See b/17475756 for further discussion.
424  */
fixup_possible_existing_listener(struct irec * new_iface)425 void fixup_possible_existing_listener(struct irec* new_iface) {
426     /* find the listener, if present */
427     struct listener* l;
428     for (l = daemon->listeners; l; l = l->next) {
429         struct irec* listener_iface = l->iface;
430         if (listener_iface) {
431             if (sockaddr_isequal(&listener_iface->addr, &new_iface->addr)) {
432                 l->iface = new_iface;
433                 return;
434             }
435         }
436     }
437 }
438 
439 /**
440  * Closes the sockets of the specified listener, deletes it from the list, and frees it.
441  *
442  */
delete_listener(struct listener ** l)443 int delete_listener(struct listener** l) {
444     struct listener* listener = *l;
445     if (listener == NULL) return 0;
446 
447     if (listener->iface) {
448         int port = prettyprint_addr(&listener->iface->addr, daemon->namebuff);
449         my_syslog(LOG_INFO, _("Closing listener [%s]:%d"), daemon->namebuff, port);
450     } else {
451         my_syslog(LOG_INFO, _("Closing wildcard listener family=%d"), listener->family);
452     }
453 
454     if (listener->tcpfd != -1) {
455         close(listener->tcpfd);
456         listener->tcpfd = -1;
457     }
458     if (listener->fd != -1) {
459         close(listener->fd);
460         listener->fd = -1;
461     }
462     *l = listener->next;
463     free(listener);
464     return -1;
465 }
466 
467 /**
468  * Close the sockets listening on the given interface
469  *
470  * This new function is needed as we're dynamically changing the interfaces
471  * we listen on.  Before they'd be opened once in create_bound_listeners and stay
472  * until we exited.  Now, if an interface moves off the to-listen list we need to
473  * close out the listeners and keep trucking.
474  *
475  * interface - input of the interface details to listen on
476  */
close_bound_listener(struct irec * iface)477 int close_bound_listener(struct irec* iface) {
478     /* find the listener */
479     int ret = 0;
480     struct listener** l = &daemon->listeners;
481     while (*l) {
482         struct irec* listener_iface = (*l)->iface;
483         struct listener** next = &((*l)->next);
484         if (iface && listener_iface && sockaddr_isequal(&listener_iface->addr, &iface->addr)) {
485             // Listener bound to an IP address. There can be only one of these.
486             ret = delete_listener(l);
487             break;
488         }
489         if (iface == NULL && listener_iface == NULL) {
490             // Wildcard listener. There is one of these per address family.
491             ret = delete_listener(l);
492             continue;
493         }
494         l = next;
495     }
496     return ret;
497 }
498 #endif /* __ANDROID__ */
499 
create_bound_listeners(void)500 struct listener* create_bound_listeners(void) {
501     struct listener* listeners = NULL;
502     struct irec* iface;
503 #ifndef __ANDROID__
504     int rc, opt = 1;
505 #ifdef HAVE_IPV6
506     static int dad_count = 0;
507 #endif
508 #endif
509 
510     for (iface = daemon->interfaces; iface; iface = iface->next) {
511 #ifdef __ANDROID__
512         create_bound_listener(&listeners, iface);
513 #else
514             struct listener* new = safe_malloc(sizeof(struct listener));
515             new->family = iface->addr.sa.sa_family;
516             new->iface = iface;
517             new->next = listeners;
518             new->tcpfd = -1;
519             new->fd = -1;
520             listeners = new;
521 
522             if (daemon->port != 0) {
523                 if ((new->tcpfd = socket(iface->addr.sa.sa_family, SOCK_STREAM, 0)) == -1 ||
524                     (new->fd = socket(iface->addr.sa.sa_family, SOCK_DGRAM, 0)) == -1 ||
525                     setsockopt(new->fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
526                     setsockopt(new->tcpfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
527                     !fix_fd(new->tcpfd) || !fix_fd(new->fd))
528                     die(_("failed to create listening socket: %s"), NULL, EC_BADNET);
529 
530 #ifdef HAVE_IPV6
531                 if (iface->addr.sa.sa_family == AF_INET6) {
532                     if (setsockopt(new->fd, IPV6_LEVEL, IPV6_V6ONLY, &opt, sizeof(opt)) == -1 ||
533                         setsockopt(new->tcpfd, IPV6_LEVEL, IPV6_V6ONLY, &opt, sizeof(opt)) == -1)
534                         die(_("failed to set IPV6 options on listening socket: %s"), NULL,
535                             EC_BADNET);
536                 }
537 #endif
538 
539                 while (1) {
540                     if ((rc = bind(new->fd, &iface->addr.sa, sa_len(&iface->addr))) != -1) break;
541 
542 #ifdef HAVE_IPV6
543                     /* An interface may have an IPv6 address which is still undergoing DAD.
544                    If so, the bind will fail until the DAD completes, so we try over 20 seconds
545                    before failing. */
546                     if (iface->addr.sa.sa_family == AF_INET6 &&
547                         (errno == ENODEV || errno == EADDRNOTAVAIL) && dad_count++ < DAD_WAIT) {
548                         sleep(1);
549                         continue;
550                     }
551 #endif
552                     break;
553                 }
554 
555                 if (rc == -1 || bind(new->tcpfd, &iface->addr.sa, sa_len(&iface->addr)) == -1) {
556                     prettyprint_addr(&iface->addr, daemon->namebuff);
557                     die(_("failed to bind listening socket for %s: %s"), daemon->namebuff,
558                         EC_BADNET);
559                 }
560 
561                 if (listen(new->tcpfd, 5) == -1)
562                     die(_("failed to listen on socket: %s"), NULL, EC_BADNET);
563             }
564 #endif /* !__ANDROID */
565     }
566 
567     return listeners;
568 }
569 
570 /* return a UDP socket bound to a random port, have to cope with straying into
571    occupied port nos and reserved ones. */
random_sock(int family)572 int random_sock(int family) {
573     int fd;
574 
575     if ((fd = socket(family, SOCK_DGRAM, 0)) != -1) {
576         union mysockaddr addr;
577         unsigned int ports_avail = 65536u - (unsigned short) daemon->min_port;
578         int tries = ports_avail < 30 ? 3 * ports_avail : 100;
579 
580         memset(&addr, 0, sizeof(addr));
581         addr.sa.sa_family = family;
582 
583         /* don't loop forever if all ports in use. */
584 
585         if (fix_fd(fd))
586             while (tries--) {
587                 unsigned short port = rand16();
588 
589                 if (daemon->min_port != 0)
590                     port = htons(daemon->min_port + (port % ((unsigned short) ports_avail)));
591 
592                 if (family == AF_INET) {
593                     addr.in.sin_addr.s_addr = INADDR_ANY;
594                     addr.in.sin_port = port;
595                 } else {
596                     addr.in6.sin6_addr = in6addr_any;
597                     addr.in6.sin6_port = port;
598                 }
599 
600                 if (bind(fd, (struct sockaddr*) &addr, sa_len(&addr)) == 0) return fd;
601 
602                 if (errno != EADDRINUSE && errno != EACCES) break;
603             }
604 
605         close(fd);
606     }
607 
608     return -1;
609 }
610 
local_bind(int fd,union mysockaddr * addr,char * intname,uint32_t mark,int is_tcp)611 int local_bind(int fd, union mysockaddr* addr, char* intname, uint32_t mark, int is_tcp) {
612     union mysockaddr addr_copy = *addr;
613 
614     /* cannot set source _port_ for TCP connections. */
615     if (is_tcp) {
616         if (addr_copy.sa.sa_family == AF_INET) addr_copy.in.sin_port = 0;
617 #ifdef HAVE_IPV6
618         else
619             addr_copy.in6.sin6_port = 0;
620 #endif
621     }
622 
623     if (bind(fd, (struct sockaddr*) &addr_copy, sa_len(&addr_copy)) == -1) return 0;
624 
625 #if defined(SO_BINDTODEVICE)
626     if (intname[0] != 0 &&
627         setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, intname, strlen(intname)) == -1)
628         return 0;
629 #endif
630 
631     if (mark != 0 && setsockopt(fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) == -1) return 0;
632 
633     return 1;
634 }
635 
allocate_sfd(union mysockaddr * addr,char * intname,uint32_t mark)636 static struct serverfd* allocate_sfd(union mysockaddr* addr, char* intname, uint32_t mark) {
637     struct serverfd* sfd;
638     int errsave;
639 
640     /* when using random ports, servers which would otherwise use
641        the INADDR_ANY/port0 socket have sfd set to NULL */
642     if (!daemon->osport && intname[0] == 0) {
643         errno = 0;
644 
645         if (addr->sa.sa_family == AF_INET && addr->in.sin_addr.s_addr == INADDR_ANY &&
646             addr->in.sin_port == htons(0))
647             return NULL;
648 
649 #ifdef HAVE_IPV6
650         if (addr->sa.sa_family == AF_INET6 &&
651             memcmp(&addr->in6.sin6_addr, &in6addr_any, sizeof(in6addr_any)) == 0 &&
652             addr->in6.sin6_port == htons(0))
653             return NULL;
654 #endif
655     }
656 
657     /* may have a suitable one already */
658     for (sfd = daemon->sfds; sfd; sfd = sfd->next)
659         if (sockaddr_isequal(&sfd->source_addr, addr) && mark == sfd->mark &&
660             strcmp(intname, sfd->interface) == 0)
661             return sfd;
662 
663     /* need to make a new one. */
664     errno = ENOMEM; /* in case malloc fails. */
665     if (!(sfd = whine_malloc(sizeof(struct serverfd)))) return NULL;
666 
667     if ((sfd->fd = socket(addr->sa.sa_family, SOCK_DGRAM, 0)) == -1) {
668         free(sfd);
669         return NULL;
670     }
671 
672     if (!local_bind(sfd->fd, addr, intname, mark, 0) || !fix_fd(sfd->fd)) {
673         errsave = errno; /* save error from bind. */
674         close(sfd->fd);
675         free(sfd);
676         errno = errsave;
677         return NULL;
678     }
679 
680     strcpy(sfd->interface, intname);
681     sfd->source_addr = *addr;
682     sfd->mark = mark;
683     sfd->next = daemon->sfds;
684     daemon->sfds = sfd;
685     return sfd;
686 }
687 
688 /* create upstream sockets during startup, before root is dropped which may be needed
689    this allows query_port to be a low port and interface binding */
pre_allocate_sfds(void)690 void pre_allocate_sfds(void) {
691     struct server* srv;
692 
693     if (daemon->query_port != 0) {
694         union mysockaddr addr;
695         memset(&addr, 0, sizeof(addr));
696         addr.in.sin_family = AF_INET;
697         addr.in.sin_addr.s_addr = INADDR_ANY;
698         addr.in.sin_port = htons(daemon->query_port);
699         allocate_sfd(&addr, "", 0);
700 #ifdef HAVE_IPV6
701         memset(&addr, 0, sizeof(addr));
702         addr.in6.sin6_family = AF_INET6;
703         addr.in6.sin6_addr = in6addr_any;
704         addr.in6.sin6_port = htons(daemon->query_port);
705         allocate_sfd(&addr, "", 0);
706 #endif
707     }
708 
709     for (srv = daemon->servers; srv; srv = srv->next)
710         if (!(srv->flags & (SERV_LITERAL_ADDRESS | SERV_NO_ADDR)) &&
711             !allocate_sfd(&srv->source_addr, srv->interface, srv->mark) && errno != 0 &&
712             (daemon->options & OPT_NOWILD)) {
713             prettyprint_addr(&srv->addr, daemon->namebuff);
714             if (srv->interface[0] != 0) {
715                 strcat(daemon->namebuff, " ");
716                 strcat(daemon->namebuff, srv->interface);
717             }
718             die(_("failed to bind server socket for %s: %s"), daemon->namebuff, EC_BADNET);
719         }
720 }
721 
check_servers(void)722 void check_servers(void) {
723     struct irec* iface;
724     struct server* new, *tmp, *ret = NULL;
725     int port = 0;
726 
727     for (new = daemon->servers; new; new = tmp) {
728         tmp = new->next;
729 
730         if (!(new->flags&(SERV_LITERAL_ADDRESS | SERV_NO_ADDR))) {
731             port = prettyprint_addr(&new->addr, daemon->namebuff);
732 
733             /* 0.0.0.0 is nothing, the stack treats it like 127.0.0.1 */
734             if (new->addr.sa.sa_family == AF_INET && new->addr.in.sin_addr.s_addr == 0) {
735                 free(new);
736                 continue;
737             }
738 
739             for (iface = daemon->interfaces; iface; iface = iface->next)
740                 if (sockaddr_isequal(&new->addr, &iface->addr)) break;
741             if (iface) {
742                 my_syslog(LOG_WARNING, _("ignoring nameserver %s - local interface"),
743                           daemon->namebuff);
744                 free(new);
745                 continue;
746             }
747 
748             /* Do we need a socket set? */
749             if (!new->sfd &&
750                 !(new->sfd = allocate_sfd(&new->source_addr, new->interface, new->mark)) &&
751                 errno != 0) {
752                 my_syslog(LOG_WARNING, _("ignoring nameserver %s - cannot make/bind socket: %s"),
753                           daemon->namebuff, strerror(errno));
754                 free(new);
755                 continue;
756             }
757         }
758 
759         /* reverse order - gets it right. */
760         new->next = ret;
761         ret = new;
762 
763         if (new->flags&(SERV_HAS_DOMAIN | SERV_FOR_NODOTS)) {
764             char *s1, *s2;
765             if (!(new->flags& SERV_HAS_DOMAIN))
766                 s1 = _("unqualified"), s2 = _("names");
767             else if (strlen(new->domain) == 0)
768                 s1 = _("default"), s2 = "";
769             else
770                 s1 = _("domain"), s2 = new->domain;
771 
772             if (new->flags & SERV_NO_ADDR)
773                 my_syslog(LOG_INFO, _("using local addresses only for %s %s"), s1, s2);
774             else if (!(new->flags& SERV_LITERAL_ADDRESS))
775                 my_syslog(LOG_INFO, _("using nameserver %s#%d for %s %s"), daemon->namebuff, port,
776                           s1, s2);
777         } else if (new->interface[0] != 0)
778             my_syslog(LOG_INFO, _("using nameserver %s#%d(via %s)"), daemon->namebuff, port,
779                       new->interface);
780         else
781             my_syslog(LOG_INFO, _("using nameserver %s#%d"), daemon->namebuff, port);
782     }
783 
784     daemon->servers = ret;
785 }
786 
787 #ifdef __ANDROID__
788 /* #define __ANDROID_DEBUG__ 1 */
789 /*
790  * Ingests a new list of interfaces and starts to listen on them, adding only the new
791  * and stopping to listen to any interfaces not on the new list.
792  *
793  * interfaces - input in the format "bt-pan|eth0|wlan0|..>" up to 1024 bytes long
794  */
set_interfaces(const char * interfaces)795 void set_interfaces(const char* interfaces) {
796     struct iname* if_tmp;
797     struct iname* prev_if_names;
798     struct irec *old_iface, *new_iface, *prev_interfaces;
799     char s[1024];
800     char* next = s;
801     char* interface;
802     int was_wild = 0;
803 
804 #ifdef __ANDROID_DEBUG__
805     my_syslog(LOG_DEBUG, _("set_interfaces(%s)"), interfaces);
806 #endif
807     prev_if_names = daemon->if_names;
808     daemon->if_names = NULL;
809 
810     prev_interfaces = daemon->interfaces;
811     daemon->interfaces = NULL;
812 
813     if (strlen(interfaces) > sizeof(s)) {
814         die(_("interface string too long: %s"), NULL, EC_BADNET);
815     }
816     strncpy(s, interfaces, sizeof(s));
817     while ((interface = strsep(&next, SEPARATOR))) {
818         if (!if_nametoindex(interface)) {
819             my_syslog(LOG_ERR, _("interface given in %s: '%s' has no ifindex; ignoring"),
820                       __FUNCTION__, interface);
821             continue;
822         }
823         if_tmp = safe_malloc(sizeof(struct iname));
824         memset(if_tmp, 0, sizeof(struct iname));
825         if ((if_tmp->name = strdup(interface)) == NULL) {
826             die(_("malloc failure in set_interfaces: %s"), NULL, EC_BADNET);
827         }
828         if_tmp->next = daemon->if_names;
829         daemon->if_names = if_tmp;
830     }
831 
832     /*
833      * Enumerate IP addresses (via RTM_GETADDR), adding IP entries to
834      * daemon->interfaces for interface names listed in daemon->if_names.
835      * The sockets are created by the create_bound_listener call below.
836      * Only do this if at least one interface was found. Otherwise,
837      * enumerate_interfaces will start listening on all interfaces on
838      * the system.
839      */
840     if (daemon->if_names != NULL && !enumerate_interfaces()) {
841         die(_("enumerate interfaces error in set_interfaces: %s"), NULL, EC_BADNET);
842     }
843 
844     for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next) {
845         if (if_tmp->name && !if_tmp->used) {
846             my_syslog(LOG_ERR, _("unknown interface given %s in set_interfaces()"), if_tmp->name);
847         }
848     }
849 
850     /* success! - setup to free the old */
851     /* check for any that have been removed */
852     for (old_iface = prev_interfaces; old_iface; old_iface = old_iface->next) {
853         int found = 0;
854         for (new_iface = daemon->interfaces; new_iface; new_iface = new_iface->next) {
855             if (sockaddr_isequal(&old_iface->addr, &new_iface->addr)) {
856                 found = 1;
857                 break;
858             }
859         }
860 
861         if (found) {
862             fixup_possible_existing_listener(new_iface);
863         } else {
864 #ifdef __ANDROID_DEBUG__
865             char debug_buff[MAXDNAME];
866             prettyprint_addr(&old_iface->addr, debug_buff);
867             my_syslog(LOG_DEBUG, _("closing listener for %s"), debug_buff);
868 #endif
869 
870             close_bound_listener(old_iface);
871         }
872     }
873 
874     /* remove wildchar listeners */
875     was_wild = close_bound_listener(NULL);
876     if (was_wild) daemon->options |= OPT_NOWILD;
877 
878     /* check for any that have been added */
879     for (new_iface = daemon->interfaces; new_iface; new_iface = new_iface->next) {
880         int found = 0;
881 
882         /* if the previous setup used a wildchar, then add any current interfaces */
883         if (!was_wild) {
884             for (old_iface = prev_interfaces; old_iface; old_iface = old_iface->next) {
885                 if (sockaddr_isequal(&old_iface->addr, &new_iface->addr)) {
886                     found = -1;
887                     break;
888                 }
889             }
890         }
891         if (!found) {
892 #ifdef __ANDROID_DEBUG__
893             char debug_buff[MAXDNAME];
894             prettyprint_addr(&new_iface->addr, debug_buff);
895             my_syslog(LOG_DEBUG, _("adding listener for %s"), debug_buff);
896 #endif
897             create_bound_listener(&(daemon->listeners), new_iface);
898         }
899     }
900 
901     while (prev_if_names) {
902         if (prev_if_names->name) free(prev_if_names->name);
903         if_tmp = prev_if_names->next;
904         free(prev_if_names);
905         prev_if_names = if_tmp;
906     }
907     while (prev_interfaces) {
908         struct irec* tmp_irec = prev_interfaces->next;
909         free(prev_interfaces);
910         prev_interfaces = tmp_irec;
911     }
912 #ifdef __ANDROID_DEBUG__
913     my_syslog(LOG_DEBUG, _("done with setInterfaces"));
914 #endif
915 }
916 
917 /*
918  * Takes a string in the format "0x100b|1.2.3.4|1.2.3.4|..." - up to 1024 bytes in length
919  *  - The first element is the socket mark to set on sockets that forward DNS queries.
920  *  - The subsequent elements are the DNS servers to forward queries to.
921  */
set_servers(const char * servers)922 int set_servers(const char* servers) {
923     char s[1024];
924     struct server* old_servers = NULL;
925     struct server* new_servers = NULL;
926     struct server* serv;
927     char* mark_string;
928     uint32_t mark;
929 
930     strncpy(s, servers, sizeof(s));
931 
932     /* move old servers to free list - we can reuse the memory
933        and not risk malloc if there are the same or fewer new servers.
934        Servers which were specced on the command line go to the new list. */
935     for (serv = daemon->servers; serv;) {
936         struct server* tmp = serv->next;
937         if (serv->flags & SERV_FROM_RESOLV) {
938             serv->next = old_servers;
939             old_servers = serv;
940             /* forward table rules reference servers, so have to blow them away */
941             server_gone(serv);
942         } else {
943             serv->next = new_servers;
944             new_servers = serv;
945         }
946         serv = tmp;
947     }
948 
949     char* next = s;
950     char* saddr;
951 
952     /* Parse the mark. */
953     mark_string = strsep(&next, SEPARATOR);
954     mark = strtoul(mark_string, NULL, 0);
955 
956     while ((saddr = strsep(&next, SEPARATOR))) {
957         union mysockaddr addr, source_addr;
958         memset(&addr, 0, sizeof(addr));
959         memset(&source_addr, 0, sizeof(source_addr));
960 
961         if (parse_addr(AF_INET, saddr, &addr) == 0) {
962             addr.in.sin_port = htons(NAMESERVER_PORT);
963             source_addr.in.sin_family = AF_INET;
964             source_addr.in.sin_addr.s_addr = INADDR_ANY;
965             source_addr.in.sin_port = htons(daemon->query_port);
966         }
967 #ifdef HAVE_IPV6
968         else if (parse_addr(AF_INET6, saddr, &addr) == 0) {
969             addr.in6.sin6_port = htons(NAMESERVER_PORT);
970             source_addr.in6.sin6_family = AF_INET6;
971             source_addr.in6.sin6_addr = in6addr_any;
972             source_addr.in6.sin6_port = htons(daemon->query_port);
973         }
974 #endif /* IPV6 */
975         else
976             continue;
977 
978         if (old_servers) {
979             serv = old_servers;
980             old_servers = old_servers->next;
981         } else if (!(serv = whine_malloc(sizeof(struct server))))
982             continue;
983 
984         /* this list is reverse ordered:
985        it gets reversed again in check_servers */
986         serv->next = new_servers;
987         new_servers = serv;
988         serv->addr = addr;
989         serv->source_addr = source_addr;
990         serv->domain = NULL;
991         serv->interface[0] = 0;
992         serv->mark = mark;
993         serv->sfd = NULL;
994         serv->flags = SERV_FROM_RESOLV;
995         serv->queries = serv->failed_queries = 0;
996     }
997 
998     /* Free any memory not used. */
999     while (old_servers) {
1000         struct server* tmp = old_servers->next;
1001         free(old_servers);
1002         old_servers = tmp;
1003     }
1004 
1005     daemon->servers = new_servers;
1006     return 0;
1007 }
1008 #endif
1009 
1010 /* Return zero if no servers found, in that case we keep polling.
1011    This is a protection against an update-time/write race on resolv.conf */
reload_servers(char * fname)1012 int reload_servers(char* fname) {
1013     FILE* f;
1014     char* line;
1015     struct server* old_servers = NULL;
1016     struct server* new_servers = NULL;
1017     struct server* serv;
1018     int gotone = 0;
1019 
1020     /* buff happens to be MAXDNAME long... */
1021     if (!(f = fopen(fname, "r"))) {
1022         my_syslog(LOG_ERR, _("failed to read %s: %s"), fname, strerror(errno));
1023         return 0;
1024     }
1025 
1026     /* move old servers to free list - we can reuse the memory
1027        and not risk malloc if there are the same or fewer new servers.
1028        Servers which were specced on the command line go to the new list. */
1029     for (serv = daemon->servers; serv;) {
1030         struct server* tmp = serv->next;
1031         if (serv->flags & SERV_FROM_RESOLV) {
1032             serv->next = old_servers;
1033             old_servers = serv;
1034             /* forward table rules reference servers, so have to blow them away */
1035             server_gone(serv);
1036         } else {
1037             serv->next = new_servers;
1038             new_servers = serv;
1039         }
1040         serv = tmp;
1041     }
1042 
1043     while ((line = fgets(daemon->namebuff, MAXDNAME, f))) {
1044         union mysockaddr addr, source_addr;
1045         char* token = strtok(line, " \t\n\r");
1046 
1047         if (!token) continue;
1048         if (strcmp(token, "nameserver") != 0 && strcmp(token, "server") != 0) continue;
1049         if (!(token = strtok(NULL, " \t\n\r"))) continue;
1050 
1051         memset(&addr, 0, sizeof(addr));
1052         memset(&source_addr, 0, sizeof(source_addr));
1053 
1054         if (parse_addr(AF_INET, token, &addr) == 0) {
1055             addr.in.sin_port = htons(NAMESERVER_PORT);
1056             source_addr.in.sin_family = AF_INET;
1057             source_addr.in.sin_addr.s_addr = INADDR_ANY;
1058             source_addr.in.sin_port = htons(daemon->query_port);
1059         }
1060 #ifdef HAVE_IPV6
1061         else if (parse_addr(AF_INET6, token, &addr) == 0) {
1062             addr.in6.sin6_port = htons(NAMESERVER_PORT);
1063             source_addr.in6.sin6_family = AF_INET6;
1064             source_addr.in6.sin6_addr = in6addr_any;
1065             source_addr.in6.sin6_port = htons(daemon->query_port);
1066         }
1067 #endif /* IPV6 */
1068         else
1069             continue;
1070 
1071         if (old_servers) {
1072             serv = old_servers;
1073             old_servers = old_servers->next;
1074         } else if (!(serv = whine_malloc(sizeof(struct server))))
1075             continue;
1076 
1077         /* this list is reverse ordered:
1078        it gets reversed again in check_servers */
1079         serv->next = new_servers;
1080         new_servers = serv;
1081         serv->addr = addr;
1082         serv->source_addr = source_addr;
1083         serv->domain = NULL;
1084         serv->interface[0] = 0;
1085         serv->mark = 0;
1086         serv->sfd = NULL;
1087         serv->flags = SERV_FROM_RESOLV;
1088         serv->queries = serv->failed_queries = 0;
1089         gotone = 1;
1090     }
1091 
1092     /* Free any memory not used. */
1093     while (old_servers) {
1094         struct server* tmp = old_servers->next;
1095         free(old_servers);
1096         old_servers = tmp;
1097     }
1098 
1099     daemon->servers = new_servers;
1100     fclose(f);
1101 
1102     return gotone;
1103 }
1104 
1105 /* Use an IPv4 listener socket for ioctling */
get_ifaddr(char * intr)1106 struct in_addr get_ifaddr(char* intr) {
1107     struct listener* l;
1108     struct ifreq ifr;
1109 
1110     for (l = daemon->listeners; l && l->family != AF_INET; l = l->next)
1111         ;
1112 
1113     strncpy(ifr.ifr_name, intr, IF_NAMESIZE);
1114     ifr.ifr_addr.sa_family = AF_INET;
1115 
1116     if (!l || ioctl(l->fd, SIOCGIFADDR, &ifr) == -1)
1117         ((struct sockaddr_in*) &ifr.ifr_addr)->sin_addr.s_addr = -1;
1118 
1119     return ((struct sockaddr_in*) &ifr.ifr_addr)->sin_addr;
1120 }
1121