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