• 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      */
837     if (!enumerate_interfaces()) {
838         die(_("enumerate interfaces error in set_interfaces: %s"), NULL, EC_BADNET);
839     }
840 
841     for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next) {
842         if (if_tmp->name && !if_tmp->used) {
843             my_syslog(LOG_ERR, _("unknown interface given %s in set_interfaces()"), if_tmp->name);
844         }
845     }
846 
847     /* success! - setup to free the old */
848     /* check for any that have been removed */
849     for (old_iface = prev_interfaces; old_iface; old_iface = old_iface->next) {
850         int found = 0;
851         for (new_iface = daemon->interfaces; new_iface; new_iface = new_iface->next) {
852             if (sockaddr_isequal(&old_iface->addr, &new_iface->addr)) {
853                 found = 1;
854                 break;
855             }
856         }
857 
858         if (found) {
859             fixup_possible_existing_listener(new_iface);
860         } else {
861 #ifdef __ANDROID_DEBUG__
862             char debug_buff[MAXDNAME];
863             prettyprint_addr(&old_iface->addr, debug_buff);
864             my_syslog(LOG_DEBUG, _("closing listener for %s"), debug_buff);
865 #endif
866 
867             close_bound_listener(old_iface);
868         }
869     }
870 
871     /* remove wildchar listeners */
872     was_wild = close_bound_listener(NULL);
873     if (was_wild) daemon->options |= OPT_NOWILD;
874 
875     /* check for any that have been added */
876     for (new_iface = daemon->interfaces; new_iface; new_iface = new_iface->next) {
877         int found = 0;
878 
879         /* if the previous setup used a wildchar, then add any current interfaces */
880         if (!was_wild) {
881             for (old_iface = prev_interfaces; old_iface; old_iface = old_iface->next) {
882                 if (sockaddr_isequal(&old_iface->addr, &new_iface->addr)) {
883                     found = -1;
884                     break;
885                 }
886             }
887         }
888         if (!found) {
889 #ifdef __ANDROID_DEBUG__
890             char debug_buff[MAXDNAME];
891             prettyprint_addr(&new_iface->addr, debug_buff);
892             my_syslog(LOG_DEBUG, _("adding listener for %s"), debug_buff);
893 #endif
894             create_bound_listener(&(daemon->listeners), new_iface);
895         }
896     }
897 
898     while (prev_if_names) {
899         if (prev_if_names->name) free(prev_if_names->name);
900         if_tmp = prev_if_names->next;
901         free(prev_if_names);
902         prev_if_names = if_tmp;
903     }
904     while (prev_interfaces) {
905         struct irec* tmp_irec = prev_interfaces->next;
906         free(prev_interfaces);
907         prev_interfaces = tmp_irec;
908     }
909 #ifdef __ANDROID_DEBUG__
910     my_syslog(LOG_DEBUG, _("done with setInterfaces"));
911 #endif
912 }
913 
914 /*
915  * Takes a string in the format "0x100b|1.2.3.4|1.2.3.4|..." - up to 1024 bytes in length
916  *  - The first element is the socket mark to set on sockets that forward DNS queries.
917  *  - The subsequent elements are the DNS servers to forward queries to.
918  */
set_servers(const char * servers)919 int set_servers(const char* servers) {
920     char s[1024];
921     struct server* old_servers = NULL;
922     struct server* new_servers = NULL;
923     struct server* serv;
924     char* mark_string;
925     uint32_t mark;
926 
927     strncpy(s, servers, sizeof(s));
928 
929     /* move old servers to free list - we can reuse the memory
930        and not risk malloc if there are the same or fewer new servers.
931        Servers which were specced on the command line go to the new list. */
932     for (serv = daemon->servers; serv;) {
933         struct server* tmp = serv->next;
934         if (serv->flags & SERV_FROM_RESOLV) {
935             serv->next = old_servers;
936             old_servers = serv;
937             /* forward table rules reference servers, so have to blow them away */
938             server_gone(serv);
939         } else {
940             serv->next = new_servers;
941             new_servers = serv;
942         }
943         serv = tmp;
944     }
945 
946     char* next = s;
947     char* saddr;
948 
949     /* Parse the mark. */
950     mark_string = strsep(&next, SEPARATOR);
951     mark = strtoul(mark_string, NULL, 0);
952 
953     while ((saddr = strsep(&next, SEPARATOR))) {
954         union mysockaddr addr, source_addr;
955         memset(&addr, 0, sizeof(addr));
956         memset(&source_addr, 0, sizeof(source_addr));
957 
958         if (parse_addr(AF_INET, saddr, &addr) == 0) {
959             addr.in.sin_port = htons(NAMESERVER_PORT);
960             source_addr.in.sin_family = AF_INET;
961             source_addr.in.sin_addr.s_addr = INADDR_ANY;
962             source_addr.in.sin_port = htons(daemon->query_port);
963         }
964 #ifdef HAVE_IPV6
965         else if (parse_addr(AF_INET6, saddr, &addr) == 0) {
966             addr.in6.sin6_port = htons(NAMESERVER_PORT);
967             source_addr.in6.sin6_family = AF_INET6;
968             source_addr.in6.sin6_addr = in6addr_any;
969             source_addr.in6.sin6_port = htons(daemon->query_port);
970         }
971 #endif /* IPV6 */
972         else
973             continue;
974 
975         if (old_servers) {
976             serv = old_servers;
977             old_servers = old_servers->next;
978         } else if (!(serv = whine_malloc(sizeof(struct server))))
979             continue;
980 
981         /* this list is reverse ordered:
982        it gets reversed again in check_servers */
983         serv->next = new_servers;
984         new_servers = serv;
985         serv->addr = addr;
986         serv->source_addr = source_addr;
987         serv->domain = NULL;
988         serv->interface[0] = 0;
989         serv->mark = mark;
990         serv->sfd = NULL;
991         serv->flags = SERV_FROM_RESOLV;
992         serv->queries = serv->failed_queries = 0;
993     }
994 
995     /* Free any memory not used. */
996     while (old_servers) {
997         struct server* tmp = old_servers->next;
998         free(old_servers);
999         old_servers = tmp;
1000     }
1001 
1002     daemon->servers = new_servers;
1003     return 0;
1004 }
1005 #endif
1006 
1007 /* Return zero if no servers found, in that case we keep polling.
1008    This is a protection against an update-time/write race on resolv.conf */
reload_servers(char * fname)1009 int reload_servers(char* fname) {
1010     FILE* f;
1011     char* line;
1012     struct server* old_servers = NULL;
1013     struct server* new_servers = NULL;
1014     struct server* serv;
1015     int gotone = 0;
1016 
1017     /* buff happens to be MAXDNAME long... */
1018     if (!(f = fopen(fname, "r"))) {
1019         my_syslog(LOG_ERR, _("failed to read %s: %s"), fname, strerror(errno));
1020         return 0;
1021     }
1022 
1023     /* move old servers to free list - we can reuse the memory
1024        and not risk malloc if there are the same or fewer new servers.
1025        Servers which were specced on the command line go to the new list. */
1026     for (serv = daemon->servers; serv;) {
1027         struct server* tmp = serv->next;
1028         if (serv->flags & SERV_FROM_RESOLV) {
1029             serv->next = old_servers;
1030             old_servers = serv;
1031             /* forward table rules reference servers, so have to blow them away */
1032             server_gone(serv);
1033         } else {
1034             serv->next = new_servers;
1035             new_servers = serv;
1036         }
1037         serv = tmp;
1038     }
1039 
1040     while ((line = fgets(daemon->namebuff, MAXDNAME, f))) {
1041         union mysockaddr addr, source_addr;
1042         char* token = strtok(line, " \t\n\r");
1043 
1044         if (!token) continue;
1045         if (strcmp(token, "nameserver") != 0 && strcmp(token, "server") != 0) continue;
1046         if (!(token = strtok(NULL, " \t\n\r"))) continue;
1047 
1048         memset(&addr, 0, sizeof(addr));
1049         memset(&source_addr, 0, sizeof(source_addr));
1050 
1051         if (parse_addr(AF_INET, token, &addr) == 0) {
1052             addr.in.sin_port = htons(NAMESERVER_PORT);
1053             source_addr.in.sin_family = AF_INET;
1054             source_addr.in.sin_addr.s_addr = INADDR_ANY;
1055             source_addr.in.sin_port = htons(daemon->query_port);
1056         }
1057 #ifdef HAVE_IPV6
1058         else if (parse_addr(AF_INET6, token, &addr) == 0) {
1059             addr.in6.sin6_port = htons(NAMESERVER_PORT);
1060             source_addr.in6.sin6_family = AF_INET6;
1061             source_addr.in6.sin6_addr = in6addr_any;
1062             source_addr.in6.sin6_port = htons(daemon->query_port);
1063         }
1064 #endif /* IPV6 */
1065         else
1066             continue;
1067 
1068         if (old_servers) {
1069             serv = old_servers;
1070             old_servers = old_servers->next;
1071         } else if (!(serv = whine_malloc(sizeof(struct server))))
1072             continue;
1073 
1074         /* this list is reverse ordered:
1075        it gets reversed again in check_servers */
1076         serv->next = new_servers;
1077         new_servers = serv;
1078         serv->addr = addr;
1079         serv->source_addr = source_addr;
1080         serv->domain = NULL;
1081         serv->interface[0] = 0;
1082         serv->mark = 0;
1083         serv->sfd = NULL;
1084         serv->flags = SERV_FROM_RESOLV;
1085         serv->queries = serv->failed_queries = 0;
1086         gotone = 1;
1087     }
1088 
1089     /* Free any memory not used. */
1090     while (old_servers) {
1091         struct server* tmp = old_servers->next;
1092         free(old_servers);
1093         old_servers = tmp;
1094     }
1095 
1096     daemon->servers = new_servers;
1097     fclose(f);
1098 
1099     return gotone;
1100 }
1101 
1102 /* Use an IPv4 listener socket for ioctling */
get_ifaddr(char * intr)1103 struct in_addr get_ifaddr(char* intr) {
1104     struct listener* l;
1105     struct ifreq ifr;
1106 
1107     for (l = daemon->listeners; l && l->family != AF_INET; l = l->next)
1108         ;
1109 
1110     strncpy(ifr.ifr_name, intr, IF_NAMESIZE);
1111     ifr.ifr_addr.sa_family = AF_INET;
1112 
1113     if (!l || ioctl(l->fd, SIOCGIFADDR, &ifr) == -1)
1114         ((struct sockaddr_in*) &ifr.ifr_addr)->sin_addr.s_addr = -1;
1115 
1116     return ((struct sockaddr_in*) &ifr.ifr_addr)->sin_addr;
1117 }
1118