xref: /aosp_15_r20/external/dnsmasq/src/network.c (revision c2c26c8b25cb2c9c4fe49a734c2305a522f5635e)
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; /* unused */
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 
364     if (daemon->port != 0) {
365         if ((new->tcpfd = socket(iface->addr.sa.sa_family, SOCK_STREAM, 0)) == -1 ||
366             (new->fd = socket(iface->addr.sa.sa_family, SOCK_DGRAM, 0)) == -1 ||
367             setsockopt(new->fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
368             setsockopt(new->tcpfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
369             !fix_fd(new->tcpfd) || !fix_fd(new->fd))
370             die(_("failed to create listening socket: %s"), NULL, EC_BADNET);
371 
372 #ifdef HAVE_IPV6
373         if (iface->addr.sa.sa_family == AF_INET6) {
374             if (setsockopt(new->fd, IPV6_LEVEL, IPV6_V6ONLY, &opt, sizeof(opt)) == -1 ||
375                 setsockopt(new->tcpfd, IPV6_LEVEL, IPV6_V6ONLY, &opt, sizeof(opt)) == -1)
376                 die(_("failed to set IPV6 options on listening socket: %s"), NULL, EC_BADNET);
377         }
378 #endif
379 
380         /* Unless the IPv6 address is added with IFA_F_NODAD, bind() can fail even if DAD
381            is disabled on the interface. This is because without IFA_F_NODAD the IPv6
382            address creation call moves the IPv6 address to tentative. A timer will
383            fire to immediately remove the tentative flag, but this is not sufficient to
384            avoid a race condition (see comments in tun_interface.cpp and iproute.py). */
385         while (1) {
386             if ((rc = bind(new->fd, &iface->addr.sa, sa_len(&iface->addr))) != -1) break;
387 
388 #ifdef HAVE_IPV6
389             /* An interface may have an IPv6 address which is still undergoing DAD.
390                If so, the bind will fail until the DAD completes, so we try again
391                before failing. */
392             /* TODO: What to do here? 20 seconds is way too long. We use optimistic addresses, so
393                bind() will only fail if the address has already failed DAD, in which case retrying
394                won't help. */
395             if (iface->addr.sa.sa_family == AF_INET6 &&
396                 (errno == ENODEV || errno == EADDRNOTAVAIL) && dad_count++ < DAD_WAIT) {
397                 sleep(1);
398                 continue;
399             }
400 #endif
401             break;
402         }
403 
404         if (rc == -1 || bind(new->tcpfd, &iface->addr.sa, sa_len(&iface->addr)) == -1) {
405             prettyprint_addr(&iface->addr, daemon->namebuff);
406             close(new->fd);
407             close(new->tcpfd);
408             free(new);
409             syslog(LOG_ERR, _("failed to bind listening socket for %s"), daemon->namebuff);
410             return;
411         }
412 
413         uint32_t mark = daemon->listen_mark;
414         if (mark != 0 && (setsockopt(new->fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) == -1 ||
415                           setsockopt(new->tcpfd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) == -1))
416             die(_("failed to set SO_MARK on listen socket: %s"), NULL, EC_BADNET);
417 
418         if (listen(new->tcpfd, 5) == -1) die(_("failed to listen on socket: %s"), NULL, EC_BADNET);
419     }
420     *listeners = new;
421 }
422 
423 /**
424  * If a listener has a struct irec pointer whose address matches the newly
425  * malloc()d struct irec's address, update its pointer to refer to this new
426  * struct irec instance.
427  *
428  * Otherwise, any listeners that are preserved across interface list changes
429  * will point at interface structures that are free()d at the end of
430  * set_interfaces(), and can get overwritten by subsequent memory allocations.
431  *
432  * See b/17475756 for further discussion.
433  */
fixup_possible_existing_listener(struct irec * new_iface)434 void fixup_possible_existing_listener(struct irec* new_iface) {
435     /* find the listener, if present */
436     struct listener* l;
437     for (l = daemon->listeners; l; l = l->next) {
438         struct irec* listener_iface = l->iface;
439         if (listener_iface) {
440             if (sockaddr_isequal(&listener_iface->addr, &new_iface->addr)) {
441                 l->iface = new_iface;
442                 return;
443             }
444         }
445     }
446 }
447 
448 /**
449  * Closes the sockets of the specified listener, deletes it from the list, and frees it.
450  *
451  */
delete_listener(struct listener ** l)452 int delete_listener(struct listener** l) {
453     struct listener* listener = *l;
454     if (listener == NULL) return 0;
455 
456     if (listener->iface) {
457         int port = prettyprint_addr(&listener->iface->addr, daemon->namebuff);
458         my_syslog(LOG_INFO, _("Closing listener [%s]:%d"), daemon->namebuff, port);
459     } else {
460         my_syslog(LOG_INFO, _("Closing wildcard listener family=%d"), listener->family);
461     }
462 
463     if (listener->tcpfd != -1) {
464         close(listener->tcpfd);
465         listener->tcpfd = -1;
466     }
467     if (listener->fd != -1) {
468         close(listener->fd);
469         listener->fd = -1;
470     }
471     *l = listener->next;
472     free(listener);
473     return -1;
474 }
475 
476 /**
477  * Close the sockets listening on the given interface
478  *
479  * This new function is needed as we're dynamically changing the interfaces
480  * we listen on.  Before they'd be opened once in create_bound_listeners and stay
481  * until we exited.  Now, if an interface moves off the to-listen list we need to
482  * close out the listeners and keep trucking.
483  *
484  * interface - input of the interface details to listen on
485  */
close_bound_listener(struct irec * iface)486 int close_bound_listener(struct irec* iface) {
487     /* find the listener */
488     int ret = 0;
489     struct listener** l = &daemon->listeners;
490     while (*l) {
491         struct irec* listener_iface = (*l)->iface;
492         struct listener** next = &((*l)->next);
493         if (iface && listener_iface && sockaddr_isequal(&listener_iface->addr, &iface->addr)) {
494             // Listener bound to an IP address. There can be only one of these.
495             ret = delete_listener(l);
496             break;
497         }
498         if (iface == NULL && listener_iface == NULL) {
499             // Wildcard listener. There is one of these per address family.
500             ret = delete_listener(l);
501             continue;
502         }
503         l = next;
504     }
505     return ret;
506 }
507 #endif /* __ANDROID__ */
508 
create_bound_listeners(void)509 struct listener* create_bound_listeners(void) {
510     struct listener* listeners = NULL;
511     struct irec* iface;
512 #ifndef __ANDROID__
513     int rc, opt = 1;
514 #ifdef HAVE_IPV6
515     static int dad_count = 0;
516 #endif
517 #endif
518 
519     for (iface = daemon->interfaces; iface; iface = iface->next) {
520 #ifdef __ANDROID__
521         create_bound_listener(&listeners, iface);
522 #else
523             struct listener* new = safe_malloc(sizeof(struct listener));
524             new->family = iface->addr.sa.sa_family;
525             new->iface = iface;
526             new->next = listeners;
527             new->tcpfd = -1;
528             new->fd = -1;
529             listeners = new;
530 
531             if (daemon->port != 0) {
532                 if ((new->tcpfd = socket(iface->addr.sa.sa_family, SOCK_STREAM, 0)) == -1 ||
533                     (new->fd = socket(iface->addr.sa.sa_family, SOCK_DGRAM, 0)) == -1 ||
534                     setsockopt(new->fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
535                     setsockopt(new->tcpfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 ||
536                     !fix_fd(new->tcpfd) || !fix_fd(new->fd))
537                     die(_("failed to create listening socket: %s"), NULL, EC_BADNET);
538 
539 #ifdef HAVE_IPV6
540                 if (iface->addr.sa.sa_family == AF_INET6) {
541                     if (setsockopt(new->fd, IPV6_LEVEL, IPV6_V6ONLY, &opt, sizeof(opt)) == -1 ||
542                         setsockopt(new->tcpfd, IPV6_LEVEL, IPV6_V6ONLY, &opt, sizeof(opt)) == -1)
543                         die(_("failed to set IPV6 options on listening socket: %s"), NULL,
544                             EC_BADNET);
545                 }
546 #endif
547 
548                 while (1) {
549                     if ((rc = bind(new->fd, &iface->addr.sa, sa_len(&iface->addr))) != -1) break;
550 
551 #ifdef HAVE_IPV6
552                     /* An interface may have an IPv6 address which is still undergoing DAD.
553                    If so, the bind will fail until the DAD completes, so we try over 20 seconds
554                    before failing. */
555                     if (iface->addr.sa.sa_family == AF_INET6 &&
556                         (errno == ENODEV || errno == EADDRNOTAVAIL) && dad_count++ < DAD_WAIT) {
557                         sleep(1);
558                         continue;
559                     }
560 #endif
561                     break;
562                 }
563 
564                 if (rc == -1 || bind(new->tcpfd, &iface->addr.sa, sa_len(&iface->addr)) == -1) {
565                     prettyprint_addr(&iface->addr, daemon->namebuff);
566                     die(_("failed to bind listening socket for %s: %s"), daemon->namebuff,
567                         EC_BADNET);
568                 }
569 
570                 if (listen(new->tcpfd, 5) == -1)
571                     die(_("failed to listen on socket: %s"), NULL, EC_BADNET);
572             }
573 #endif /* !__ANDROID */
574     }
575 
576     return listeners;
577 }
578 
579 /* return a UDP socket bound to a random port, have to cope with straying into
580    occupied port nos and reserved ones. */
random_sock(int family)581 int random_sock(int family) {
582     int fd;
583 
584     if ((fd = socket(family, SOCK_DGRAM, 0)) != -1) {
585         union mysockaddr addr;
586         unsigned int ports_avail = 65536u - (unsigned short) daemon->min_port;
587         int tries = ports_avail < 30 ? 3 * ports_avail : 100;
588 
589         memset(&addr, 0, sizeof(addr));
590         addr.sa.sa_family = family;
591 
592         /* don't loop forever if all ports in use. */
593 
594         if (fix_fd(fd))
595             while (tries--) {
596                 unsigned short port = rand16();
597 
598                 if (daemon->min_port != 0)
599                     port = htons(daemon->min_port + (port % ((unsigned short) ports_avail)));
600 
601                 if (family == AF_INET) {
602                     addr.in.sin_addr.s_addr = INADDR_ANY;
603                     addr.in.sin_port = port;
604                 } else {
605                     addr.in6.sin6_addr = in6addr_any;
606                     addr.in6.sin6_port = port;
607                 }
608 
609                 if (bind(fd, (struct sockaddr*) &addr, sa_len(&addr)) == 0) return fd;
610 
611                 if (errno != EADDRINUSE && errno != EACCES) break;
612             }
613 
614         close(fd);
615     }
616 
617     return -1;
618 }
619 
local_bind(int fd,union mysockaddr * addr,char * intname,uint32_t mark,int is_tcp)620 int local_bind(int fd, union mysockaddr* addr, char* intname, uint32_t mark, int is_tcp) {
621     union mysockaddr addr_copy = *addr;
622 
623     /* cannot set source _port_ for TCP connections. */
624     if (is_tcp) {
625         if (addr_copy.sa.sa_family == AF_INET) addr_copy.in.sin_port = 0;
626 #ifdef HAVE_IPV6
627         else
628             addr_copy.in6.sin6_port = 0;
629 #endif
630     }
631 
632     if (bind(fd, (struct sockaddr*) &addr_copy, sa_len(&addr_copy)) == -1) return 0;
633 
634 #if defined(SO_BINDTODEVICE)
635     if (intname[0] != 0 &&
636         setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, intname, strlen(intname)) == -1)
637         return 0;
638 #endif
639 
640     if (mark != 0 && setsockopt(fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) == -1) return 0;
641 
642     return 1;
643 }
644 
allocate_sfd(union mysockaddr * addr,char * intname,uint32_t mark)645 static struct serverfd* allocate_sfd(union mysockaddr* addr, char* intname, uint32_t mark) {
646     struct serverfd* sfd;
647     int errsave;
648 
649     /* when using random ports, servers which would otherwise use
650        the INADDR_ANY/port0 socket have sfd set to NULL */
651     if (!daemon->osport && intname[0] == 0) {
652         errno = 0;
653 
654         if (addr->sa.sa_family == AF_INET && addr->in.sin_addr.s_addr == INADDR_ANY &&
655             addr->in.sin_port == htons(0))
656             return NULL;
657 
658 #ifdef HAVE_IPV6
659         if (addr->sa.sa_family == AF_INET6 &&
660             memcmp(&addr->in6.sin6_addr, &in6addr_any, sizeof(in6addr_any)) == 0 &&
661             addr->in6.sin6_port == htons(0))
662             return NULL;
663 #endif
664     }
665 
666     /* may have a suitable one already */
667     for (sfd = daemon->sfds; sfd; sfd = sfd->next)
668         if (sockaddr_isequal(&sfd->source_addr, addr) && mark == sfd->mark &&
669             strcmp(intname, sfd->interface) == 0)
670             return sfd;
671 
672     /* need to make a new one. */
673     errno = ENOMEM; /* in case malloc fails. */
674     if (!(sfd = whine_malloc(sizeof(struct serverfd)))) return NULL;
675 
676     if ((sfd->fd = socket(addr->sa.sa_family, SOCK_DGRAM, 0)) == -1) {
677         free(sfd);
678         return NULL;
679     }
680 
681     if (!local_bind(sfd->fd, addr, intname, mark, 0) || !fix_fd(sfd->fd)) {
682         errsave = errno; /* save error from bind. */
683         close(sfd->fd);
684         free(sfd);
685         errno = errsave;
686         return NULL;
687     }
688 
689     strcpy(sfd->interface, intname);
690     sfd->source_addr = *addr;
691     sfd->mark = mark;
692     sfd->next = daemon->sfds;
693     daemon->sfds = sfd;
694     return sfd;
695 }
696 
697 /* create upstream sockets during startup, before root is dropped which may be needed
698    this allows query_port to be a low port and interface binding */
pre_allocate_sfds(void)699 void pre_allocate_sfds(void) {
700     struct server* srv;
701 
702     if (daemon->query_port != 0) {
703         union mysockaddr addr;
704         memset(&addr, 0, sizeof(addr));
705         addr.in.sin_family = AF_INET;
706         addr.in.sin_addr.s_addr = INADDR_ANY;
707         addr.in.sin_port = htons(daemon->query_port);
708         allocate_sfd(&addr, "", 0);
709 #ifdef HAVE_IPV6
710         memset(&addr, 0, sizeof(addr));
711         addr.in6.sin6_family = AF_INET6;
712         addr.in6.sin6_addr = in6addr_any;
713         addr.in6.sin6_port = htons(daemon->query_port);
714         allocate_sfd(&addr, "", 0);
715 #endif
716     }
717 
718     for (srv = daemon->servers; srv; srv = srv->next)
719         if (!(srv->flags & (SERV_LITERAL_ADDRESS | SERV_NO_ADDR)) &&
720             !allocate_sfd(&srv->source_addr, srv->interface, srv->mark) && errno != 0 &&
721             (daemon->options & OPT_NOWILD)) {
722             prettyprint_addr(&srv->addr, daemon->namebuff);
723             if (srv->interface[0] != 0) {
724                 strcat(daemon->namebuff, " ");
725                 strcat(daemon->namebuff, srv->interface);
726             }
727             die(_("failed to bind server socket for %s: %s"), daemon->namebuff, EC_BADNET);
728         }
729 }
730 
check_servers(void)731 void check_servers(void) {
732     struct irec* iface;
733     struct server* new, *tmp, *ret = NULL;
734     int port = 0;
735 
736     for (new = daemon->servers; new; new = tmp) {
737         tmp = new->next;
738 
739         if (!(new->flags&(SERV_LITERAL_ADDRESS | SERV_NO_ADDR))) {
740             port = prettyprint_addr(&new->addr, daemon->namebuff);
741 
742             /* 0.0.0.0 is nothing, the stack treats it like 127.0.0.1 */
743             if (new->addr.sa.sa_family == AF_INET && new->addr.in.sin_addr.s_addr == 0) {
744                 free(new);
745                 continue;
746             }
747 
748             for (iface = daemon->interfaces; iface; iface = iface->next)
749                 if (sockaddr_isequal(&new->addr, &iface->addr)) break;
750             if (iface) {
751                 my_syslog(LOG_WARNING, _("ignoring nameserver %s - local interface"),
752                           daemon->namebuff);
753                 free(new);
754                 continue;
755             }
756 
757             /* Do we need a socket set? */
758             if (!new->sfd &&
759                 !(new->sfd = allocate_sfd(&new->source_addr, new->interface, new->mark)) &&
760                 errno != 0) {
761                 my_syslog(LOG_WARNING, _("ignoring nameserver %s - cannot make/bind socket: %s"),
762                           daemon->namebuff, strerror(errno));
763                 free(new);
764                 continue;
765             }
766         }
767 
768         /* reverse order - gets it right. */
769         new->next = ret;
770         ret = new;
771 
772         if (new->flags&(SERV_HAS_DOMAIN | SERV_FOR_NODOTS)) {
773             char *s1, *s2;
774             if (!(new->flags& SERV_HAS_DOMAIN))
775                 s1 = _("unqualified"), s2 = _("names");
776             else if (strlen(new->domain) == 0)
777                 s1 = _("default"), s2 = "";
778             else
779                 s1 = _("domain"), s2 = new->domain;
780 
781             if (new->flags & SERV_NO_ADDR)
782                 my_syslog(LOG_INFO, _("using local addresses only for %s %s"), s1, s2);
783             else if (!(new->flags& SERV_LITERAL_ADDRESS))
784                 my_syslog(LOG_INFO, _("using nameserver %s#%d for %s %s"), daemon->namebuff, port,
785                           s1, s2);
786         } else if (new->interface[0] != 0)
787             my_syslog(LOG_INFO, _("using nameserver %s#%d(via %s)"), daemon->namebuff, port,
788                       new->interface);
789         else
790             my_syslog(LOG_INFO, _("using nameserver %s#%d"), daemon->namebuff, port);
791     }
792 
793     daemon->servers = ret;
794 }
795 
796 #ifdef __ANDROID__
797 /* #define __ANDROID_DEBUG__ 1 */
798 /*
799  * Ingests a new list of interfaces and starts to listen on them, adding only the new
800  * and stopping to listen to any interfaces not on the new list.
801  *
802  * interfaces - input in the format "bt-pan|eth0|wlan0|..>" up to 1024 bytes long
803  */
set_interfaces(const char * interfaces)804 void set_interfaces(const char* interfaces) {
805     struct iname* if_tmp;
806     struct iname* prev_if_names;
807     struct irec *old_iface, *new_iface, *prev_interfaces;
808     char s[1024];
809     char* next = s;
810     char* interface;
811     int was_wild = 0;
812 
813 #ifdef __ANDROID_DEBUG__
814     my_syslog(LOG_DEBUG, _("set_interfaces(%s)"), interfaces);
815 #endif
816     prev_if_names = daemon->if_names;
817     daemon->if_names = NULL;
818 
819     prev_interfaces = daemon->interfaces;
820     daemon->interfaces = NULL;
821 
822     if (strlen(interfaces) > sizeof(s)) {
823         die(_("interface string too long: %s"), NULL, EC_BADNET);
824     }
825     strncpy(s, interfaces, sizeof(s));
826     while ((interface = strsep(&next, SEPARATOR))) {
827         if (!if_nametoindex(interface)) {
828             my_syslog(LOG_ERR, _("interface given in %s: '%s' has no ifindex; ignoring"),
829                       __FUNCTION__, interface);
830             continue;
831         }
832         if_tmp = safe_malloc(sizeof(struct iname));
833         memset(if_tmp, 0, sizeof(struct iname));
834         if ((if_tmp->name = strdup(interface)) == NULL) {
835             die(_("malloc failure in set_interfaces: %s"), NULL, EC_BADNET);
836         }
837         if_tmp->next = daemon->if_names;
838         daemon->if_names = if_tmp;
839     }
840 
841     /*
842      * Enumerate IP addresses (via RTM_GETADDR), adding IP entries to
843      * daemon->interfaces for interface names listed in daemon->if_names.
844      * The sockets are created by the create_bound_listener call below.
845      * Only do this if at least one interface was found. Otherwise,
846      * enumerate_interfaces will start listening on all interfaces on
847      * the system.
848      */
849     if (daemon->if_names != NULL && !enumerate_interfaces()) {
850         die(_("enumerate interfaces error in set_interfaces: %s"), NULL, EC_BADNET);
851     }
852 
853     for (if_tmp = daemon->if_names; if_tmp; if_tmp = if_tmp->next) {
854         if (if_tmp->name && !if_tmp->used) {
855             my_syslog(LOG_ERR, _("unknown interface given %s in set_interfaces()"), if_tmp->name);
856         }
857     }
858 
859     /* success! - setup to free the old */
860     /* check for any that have been removed */
861     for (old_iface = prev_interfaces; old_iface; old_iface = old_iface->next) {
862         int found = 0;
863         for (new_iface = daemon->interfaces; new_iface; new_iface = new_iface->next) {
864             if (sockaddr_isequal(&old_iface->addr, &new_iface->addr)) {
865                 found = 1;
866                 break;
867             }
868         }
869 
870         if (found) {
871             fixup_possible_existing_listener(new_iface);
872         } else {
873 #ifdef __ANDROID_DEBUG__
874             char debug_buff[MAXDNAME];
875             prettyprint_addr(&old_iface->addr, debug_buff);
876             my_syslog(LOG_DEBUG, _("closing listener for %s"), debug_buff);
877 #endif
878 
879             close_bound_listener(old_iface);
880         }
881     }
882 
883     /* remove wildchar listeners */
884     was_wild = close_bound_listener(NULL);
885     if (was_wild) daemon->options |= OPT_NOWILD;
886 
887     /* check for any that have been added */
888     for (new_iface = daemon->interfaces; new_iface; new_iface = new_iface->next) {
889         int found = 0;
890 
891         /* if the previous setup used a wildchar, then add any current interfaces */
892         if (!was_wild) {
893             for (old_iface = prev_interfaces; old_iface; old_iface = old_iface->next) {
894                 if (sockaddr_isequal(&old_iface->addr, &new_iface->addr)) {
895                     found = -1;
896                     break;
897                 }
898             }
899         }
900         if (!found) {
901 #ifdef __ANDROID_DEBUG__
902             char debug_buff[MAXDNAME];
903             prettyprint_addr(&new_iface->addr, debug_buff);
904             my_syslog(LOG_DEBUG, _("adding listener for %s"), debug_buff);
905 #endif
906             create_bound_listener(&(daemon->listeners), new_iface);
907         }
908     }
909 
910     while (prev_if_names) {
911         if (prev_if_names->name) free(prev_if_names->name);
912         if_tmp = prev_if_names->next;
913         free(prev_if_names);
914         prev_if_names = if_tmp;
915     }
916     while (prev_interfaces) {
917         struct irec* tmp_irec = prev_interfaces->next;
918         free(prev_interfaces);
919         prev_interfaces = tmp_irec;
920     }
921 #ifdef __ANDROID_DEBUG__
922     my_syslog(LOG_DEBUG, _("done with setInterfaces"));
923 #endif
924 }
925 
926 /*
927  * Takes a string in the format "0x100b|1.2.3.4|1.2.3.4|..." - up to 1024 bytes in length
928  *  - The first element is the socket mark to set on sockets that forward DNS queries.
929  *  - The subsequent elements are the DNS servers to forward queries to.
930  */
set_servers(const char * servers)931 int set_servers(const char* servers) {
932     char s[1024];
933     struct server* old_servers = NULL;
934     struct server* new_servers = NULL;
935     struct server* serv;
936     char* mark_string;
937     uint32_t mark;
938 
939     strncpy(s, servers, sizeof(s));
940 
941     /* move old servers to free list - we can reuse the memory
942        and not risk malloc if there are the same or fewer new servers.
943        Servers which were specced on the command line go to the new list. */
944     for (serv = daemon->servers; serv;) {
945         struct server* tmp = serv->next;
946         if (serv->flags & SERV_FROM_RESOLV) {
947             serv->next = old_servers;
948             old_servers = serv;
949             /* forward table rules reference servers, so have to blow them away */
950             server_gone(serv);
951         } else {
952             serv->next = new_servers;
953             new_servers = serv;
954         }
955         serv = tmp;
956     }
957 
958     char* next = s;
959     char* saddr;
960 
961     /* Parse the mark. */
962     mark_string = strsep(&next, SEPARATOR);
963     mark = strtoul(mark_string, NULL, 0);
964 
965     while ((saddr = strsep(&next, SEPARATOR))) {
966         union mysockaddr addr, source_addr;
967         memset(&addr, 0, sizeof(addr));
968         memset(&source_addr, 0, sizeof(source_addr));
969 
970         if (parse_addr(AF_INET, saddr, &addr) == 0) {
971             addr.in.sin_port = htons(NAMESERVER_PORT);
972             source_addr.in.sin_family = AF_INET;
973             source_addr.in.sin_addr.s_addr = INADDR_ANY;
974             source_addr.in.sin_port = htons(daemon->query_port);
975         }
976 #ifdef HAVE_IPV6
977         else if (parse_addr(AF_INET6, saddr, &addr) == 0) {
978             addr.in6.sin6_port = htons(NAMESERVER_PORT);
979             source_addr.in6.sin6_family = AF_INET6;
980             source_addr.in6.sin6_addr = in6addr_any;
981             source_addr.in6.sin6_port = htons(daemon->query_port);
982         }
983 #endif /* IPV6 */
984         else
985             continue;
986 
987         if (old_servers) {
988             serv = old_servers;
989             old_servers = old_servers->next;
990         } else if (!(serv = whine_malloc(sizeof(struct server))))
991             continue;
992 
993         /* this list is reverse ordered:
994        it gets reversed again in check_servers */
995         serv->next = new_servers;
996         new_servers = serv;
997         serv->addr = addr;
998         serv->source_addr = source_addr;
999         serv->domain = NULL;
1000         serv->interface[0] = 0;
1001         serv->mark = mark;
1002         serv->sfd = NULL;
1003         serv->flags = SERV_FROM_RESOLV;
1004         serv->queries = serv->failed_queries = 0;
1005     }
1006 
1007     /* Free any memory not used. */
1008     while (old_servers) {
1009         struct server* tmp = old_servers->next;
1010         free(old_servers);
1011         old_servers = tmp;
1012     }
1013 
1014     daemon->servers = new_servers;
1015     return 0;
1016 }
1017 #endif
1018 
1019 /* Return zero if no servers found, in that case we keep polling.
1020    This is a protection against an update-time/write race on resolv.conf */
reload_servers(char * fname)1021 int reload_servers(char* fname) {
1022     FILE* f;
1023     char* line;
1024     struct server* old_servers = NULL;
1025     struct server* new_servers = NULL;
1026     struct server* serv;
1027     int gotone = 0;
1028 
1029     /* buff happens to be MAXDNAME long... */
1030     if (!(f = fopen(fname, "r"))) {
1031         my_syslog(LOG_ERR, _("failed to read %s: %s"), fname, strerror(errno));
1032         return 0;
1033     }
1034 
1035     /* move old servers to free list - we can reuse the memory
1036        and not risk malloc if there are the same or fewer new servers.
1037        Servers which were specced on the command line go to the new list. */
1038     for (serv = daemon->servers; serv;) {
1039         struct server* tmp = serv->next;
1040         if (serv->flags & SERV_FROM_RESOLV) {
1041             serv->next = old_servers;
1042             old_servers = serv;
1043             /* forward table rules reference servers, so have to blow them away */
1044             server_gone(serv);
1045         } else {
1046             serv->next = new_servers;
1047             new_servers = serv;
1048         }
1049         serv = tmp;
1050     }
1051 
1052     while ((line = fgets(daemon->namebuff, MAXDNAME, f))) {
1053         union mysockaddr addr, source_addr;
1054         char* token = strtok(line, " \t\n\r");
1055 
1056         if (!token) continue;
1057         if (strcmp(token, "nameserver") != 0 && strcmp(token, "server") != 0) continue;
1058         if (!(token = strtok(NULL, " \t\n\r"))) continue;
1059 
1060         memset(&addr, 0, sizeof(addr));
1061         memset(&source_addr, 0, sizeof(source_addr));
1062 
1063         if (parse_addr(AF_INET, token, &addr) == 0) {
1064             addr.in.sin_port = htons(NAMESERVER_PORT);
1065             source_addr.in.sin_family = AF_INET;
1066             source_addr.in.sin_addr.s_addr = INADDR_ANY;
1067             source_addr.in.sin_port = htons(daemon->query_port);
1068         }
1069 #ifdef HAVE_IPV6
1070         else if (parse_addr(AF_INET6, token, &addr) == 0) {
1071             addr.in6.sin6_port = htons(NAMESERVER_PORT);
1072             source_addr.in6.sin6_family = AF_INET6;
1073             source_addr.in6.sin6_addr = in6addr_any;
1074             source_addr.in6.sin6_port = htons(daemon->query_port);
1075         }
1076 #endif /* IPV6 */
1077         else
1078             continue;
1079 
1080         if (old_servers) {
1081             serv = old_servers;
1082             old_servers = old_servers->next;
1083         } else if (!(serv = whine_malloc(sizeof(struct server))))
1084             continue;
1085 
1086         /* this list is reverse ordered:
1087        it gets reversed again in check_servers */
1088         serv->next = new_servers;
1089         new_servers = serv;
1090         serv->addr = addr;
1091         serv->source_addr = source_addr;
1092         serv->domain = NULL;
1093         serv->interface[0] = 0;
1094         serv->mark = 0;
1095         serv->sfd = NULL;
1096         serv->flags = SERV_FROM_RESOLV;
1097         serv->queries = serv->failed_queries = 0;
1098         gotone = 1;
1099     }
1100 
1101     /* Free any memory not used. */
1102     while (old_servers) {
1103         struct server* tmp = old_servers->next;
1104         free(old_servers);
1105         old_servers = tmp;
1106     }
1107 
1108     daemon->servers = new_servers;
1109     fclose(f);
1110 
1111     return gotone;
1112 }
1113 
1114 /* Use an IPv4 listener socket for ioctling */
get_ifaddr(char * intr)1115 struct in_addr get_ifaddr(char* intr) {
1116     struct listener* l;
1117     struct ifreq ifr;
1118 
1119     for (l = daemon->listeners; l && l->family != AF_INET; l = l->next)
1120         ;
1121 
1122     strncpy(ifr.ifr_name, intr, IF_NAMESIZE);
1123     ifr.ifr_addr.sa_family = AF_INET;
1124 
1125     if (!l || ioctl(l->fd, SIOCGIFADDR, &ifr) == -1)
1126         ((struct sockaddr_in*) &ifr.ifr_addr)->sin_addr.s_addr = -1;
1127 
1128     return ((struct sockaddr_in*) &ifr.ifr_addr)->sin_addr;
1129 }
1130