"Fossies" - the Fresh Open Source Software Archive

Member "dnsmasq-2.85/src/network.c" (7 Apr 2021, 48978 Bytes) of package /linux/misc/dns/dnsmasq-2.85.tar.xz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "network.c" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 2.84_vs_2.85.

    1 /* dnsmasq is Copyright (c) 2000-2021 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 #ifdef HAVE_LINUX_NETWORK
   20 
   21 int indextoname(int fd, int index, char *name)
   22 {
   23   struct ifreq ifr;
   24   
   25   if (index == 0)
   26     return 0;
   27 
   28   ifr.ifr_ifindex = index;
   29   if (ioctl(fd, SIOCGIFNAME, &ifr) == -1)
   30     return 0;
   31 
   32   safe_strncpy(name, ifr.ifr_name, IF_NAMESIZE);
   33 
   34   return 1;
   35 }
   36 
   37 
   38 #elif defined(HAVE_SOLARIS_NETWORK)
   39 
   40 #include <zone.h>
   41 #include <alloca.h>
   42 #ifndef LIFC_UNDER_IPMP
   43 #  define LIFC_UNDER_IPMP 0
   44 #endif
   45 
   46 int indextoname(int fd, int index, char *name)
   47 {
   48   int64_t lifc_flags;
   49   struct lifnum lifn;
   50   int numifs, bufsize, i;
   51   struct lifconf lifc;
   52   struct lifreq *lifrp;
   53   
   54   if (index == 0)
   55     return 0;
   56   
   57   if (getzoneid() == GLOBAL_ZONEID) 
   58     {
   59       if (!if_indextoname(index, name))
   60     return 0;
   61       return 1;
   62     }
   63   
   64   lifc_flags = LIFC_NOXMIT | LIFC_TEMPORARY | LIFC_ALLZONES | LIFC_UNDER_IPMP;
   65   lifn.lifn_family = AF_UNSPEC;
   66   lifn.lifn_flags = lifc_flags;
   67   if (ioctl(fd, SIOCGLIFNUM, &lifn) < 0) 
   68     return 0;
   69   
   70   numifs = lifn.lifn_count;
   71   bufsize = numifs * sizeof(struct lifreq);
   72   
   73   lifc.lifc_family = AF_UNSPEC;
   74   lifc.lifc_flags = lifc_flags;
   75   lifc.lifc_len = bufsize;
   76   lifc.lifc_buf = alloca(bufsize);
   77   
   78   if (ioctl(fd, SIOCGLIFCONF, &lifc) < 0)  
   79     return 0;
   80   
   81   lifrp = lifc.lifc_req;
   82   for (i = lifc.lifc_len / sizeof(struct lifreq); i; i--, lifrp++) 
   83     {
   84       struct lifreq lifr;
   85       safe_strncpy(lifr.lifr_name, lifrp->lifr_name, IF_NAMESIZE);
   86       if (ioctl(fd, SIOCGLIFINDEX, &lifr) < 0) 
   87     return 0;
   88       
   89       if (lifr.lifr_index == index) {
   90     safe_strncpy(name, lifr.lifr_name, IF_NAMESIZE);
   91     return 1;
   92       }
   93     }
   94   return 0;
   95 }
   96 
   97 
   98 #else
   99 
  100 int indextoname(int fd, int index, char *name)
  101 { 
  102   (void)fd;
  103 
  104   if (index == 0 || !if_indextoname(index, name))
  105     return 0;
  106 
  107   return 1;
  108 }
  109 
  110 #endif
  111 
  112 int iface_check(int family, union all_addr *addr, char *name, int *auth)
  113 {
  114   struct iname *tmp;
  115   int ret = 1, match_addr = 0;
  116 
  117   /* Note: have to check all and not bail out early, so that we set the
  118      "used" flags.
  119 
  120      May be called with family == AF_LOCALto check interface by name only. */
  121   
  122   if (auth)
  123     *auth = 0;
  124   
  125   if (daemon->if_names || daemon->if_addrs)
  126     {
  127       ret = 0;
  128 
  129       for (tmp = daemon->if_names; tmp; tmp = tmp->next)
  130     if (tmp->name && wildcard_match(tmp->name, name))
  131       ret = tmp->used = 1;
  132             
  133       if (addr)
  134     for (tmp = daemon->if_addrs; tmp; tmp = tmp->next)
  135       if (tmp->addr.sa.sa_family == family)
  136         {
  137           if (family == AF_INET &&
  138           tmp->addr.in.sin_addr.s_addr == addr->addr4.s_addr)
  139         ret = match_addr = tmp->used = 1;
  140           else if (family == AF_INET6 &&
  141                IN6_ARE_ADDR_EQUAL(&tmp->addr.in6.sin6_addr, 
  142                       &addr->addr6))
  143         ret = match_addr = tmp->used = 1;
  144         }          
  145     }
  146   
  147   if (!match_addr)
  148     for (tmp = daemon->if_except; tmp; tmp = tmp->next)
  149       if (tmp->name && wildcard_match(tmp->name, name))
  150     ret = 0;
  151     
  152 
  153   for (tmp = daemon->authinterface; tmp; tmp = tmp->next)
  154     if (tmp->name)
  155       {
  156     if (strcmp(tmp->name, name) == 0 &&
  157         (tmp->addr.sa.sa_family == 0 || tmp->addr.sa.sa_family == family))
  158       break;
  159       }
  160     else if (addr && tmp->addr.sa.sa_family == AF_INET && family == AF_INET &&
  161          tmp->addr.in.sin_addr.s_addr == addr->addr4.s_addr)
  162       break;
  163     else if (addr && tmp->addr.sa.sa_family == AF_INET6 && family == AF_INET6 &&
  164          IN6_ARE_ADDR_EQUAL(&tmp->addr.in6.sin6_addr, &addr->addr6))
  165       break;
  166 
  167   if (tmp && auth) 
  168     {
  169       *auth = 1;
  170       ret = 1;
  171     }
  172 
  173   return ret; 
  174 }
  175 
  176 
  177 /* Fix for problem that the kernel sometimes reports the loopback interface as the
  178    arrival interface when a packet originates locally, even when sent to address of 
  179    an interface other than the loopback. Accept packet if it arrived via a loopback 
  180    interface, even when we're not accepting packets that way, as long as the destination
  181    address is one we're believing. Interface list must be up-to-date before calling. */
  182 int loopback_exception(int fd, int family, union all_addr *addr, char *name)    
  183 {
  184   struct ifreq ifr;
  185   struct irec *iface;
  186 
  187   safe_strncpy(ifr.ifr_name, name, IF_NAMESIZE);
  188   if (ioctl(fd, SIOCGIFFLAGS, &ifr) != -1 &&
  189       ifr.ifr_flags & IFF_LOOPBACK)
  190     {
  191       for (iface = daemon->interfaces; iface; iface = iface->next)
  192     if (iface->addr.sa.sa_family == family)
  193       {
  194         if (family == AF_INET)
  195           {
  196         if (iface->addr.in.sin_addr.s_addr == addr->addr4.s_addr)
  197           return 1;
  198           }
  199         else if (IN6_ARE_ADDR_EQUAL(&iface->addr.in6.sin6_addr, &addr->addr6))
  200           return 1;
  201       }
  202     }
  203   return 0;
  204 }
  205 
  206 /* If we're configured with something like --interface=eth0:0 then we'll listen correctly
  207    on the relevant address, but the name of the arrival interface, derived from the
  208    index won't match the config. Check that we found an interface address for the arrival 
  209    interface: daemon->interfaces must be up-to-date. */
  210 int label_exception(int index, int family, union all_addr *addr)
  211 {
  212   struct irec *iface;
  213 
  214   /* labels only supported on IPv4 addresses. */
  215   if (family != AF_INET)
  216     return 0;
  217 
  218   for (iface = daemon->interfaces; iface; iface = iface->next)
  219     if (iface->index == index && iface->addr.sa.sa_family == AF_INET &&
  220     iface->addr.in.sin_addr.s_addr == addr->addr4.s_addr)
  221       return 1;
  222 
  223   return 0;
  224 }
  225 
  226 struct iface_param {
  227   struct addrlist *spare;
  228   int fd;
  229 };
  230 
  231 static int iface_allowed(struct iface_param *param, int if_index, char *label,
  232              union mysockaddr *addr, struct in_addr netmask, int prefixlen, int iface_flags) 
  233 {
  234   struct irec *iface;
  235   int loopback;
  236   struct ifreq ifr;
  237   int tftp_ok = !!option_bool(OPT_TFTP);
  238   int dhcp_ok = 1;
  239   int auth_dns = 0;
  240   int is_label = 0;
  241 #if defined(HAVE_DHCP) || defined(HAVE_TFTP)
  242   struct iname *tmp;
  243 #endif
  244 
  245   (void)prefixlen;
  246 
  247   if (!indextoname(param->fd, if_index, ifr.ifr_name) ||
  248       ioctl(param->fd, SIOCGIFFLAGS, &ifr) == -1)
  249     return 0;
  250    
  251   loopback = ifr.ifr_flags & IFF_LOOPBACK;
  252   
  253   if (loopback)
  254     dhcp_ok = 0;
  255   
  256   if (!label)
  257     label = ifr.ifr_name;
  258   else
  259     is_label = strcmp(label, ifr.ifr_name);
  260  
  261   /* maintain a list of all addresses on all interfaces for --local-service option */
  262   if (option_bool(OPT_LOCAL_SERVICE))
  263     {
  264       struct addrlist *al;
  265 
  266       if (param->spare)
  267     {
  268       al = param->spare;
  269       param->spare = al->next;
  270     }
  271       else
  272     al = whine_malloc(sizeof(struct addrlist));
  273       
  274       if (al)
  275     {
  276       al->next = daemon->interface_addrs;
  277       daemon->interface_addrs = al;
  278       al->prefixlen = prefixlen;
  279       
  280       if (addr->sa.sa_family == AF_INET)
  281         {
  282           al->addr.addr4 = addr->in.sin_addr;
  283           al->flags = 0;
  284         }
  285       else
  286         {
  287           al->addr.addr6 = addr->in6.sin6_addr;
  288           al->flags = ADDRLIST_IPV6;
  289         } 
  290     }
  291     }
  292   
  293   if (addr->sa.sa_family != AF_INET6 || !IN6_IS_ADDR_LINKLOCAL(&addr->in6.sin6_addr))
  294     {
  295       struct interface_name *int_name;
  296       struct addrlist *al;
  297 #ifdef HAVE_AUTH
  298       struct auth_zone *zone;
  299       struct auth_name_list *name;
  300 
  301       /* Find subnets in auth_zones */
  302       for (zone = daemon->auth_zones; zone; zone = zone->next)
  303     for (name = zone->interface_names; name; name = name->next)
  304       if (wildcard_match(name->name, label))
  305         {
  306           if (addr->sa.sa_family == AF_INET && (name->flags & AUTH4))
  307         {
  308           if (param->spare)
  309             {
  310               al = param->spare;
  311               param->spare = al->next;
  312             }
  313           else
  314             al = whine_malloc(sizeof(struct addrlist));
  315           
  316           if (al)
  317             {
  318               al->next = zone->subnet;
  319               zone->subnet = al;
  320               al->prefixlen = prefixlen;
  321               al->addr.addr4 = addr->in.sin_addr;
  322               al->flags = 0;
  323             }
  324         }
  325           
  326           if (addr->sa.sa_family == AF_INET6 && (name->flags & AUTH6))
  327         {
  328           if (param->spare)
  329             {
  330               al = param->spare;
  331               param->spare = al->next;
  332             }
  333           else
  334             al = whine_malloc(sizeof(struct addrlist));
  335           
  336           if (al)
  337             {
  338               al->next = zone->subnet;
  339               zone->subnet = al;
  340               al->prefixlen = prefixlen;
  341               al->addr.addr6 = addr->in6.sin6_addr;
  342               al->flags = ADDRLIST_IPV6;
  343             }
  344         } 
  345         }
  346 #endif
  347        
  348       /* Update addresses from interface_names. These are a set independent
  349      of the set we're listening on. */  
  350       for (int_name = daemon->int_names; int_name; int_name = int_name->next)
  351     if (strncmp(label, int_name->intr, IF_NAMESIZE) == 0)
  352       {
  353         struct addrlist *lp;
  354 
  355         al = NULL;
  356         
  357         if (addr->sa.sa_family == AF_INET && (int_name->flags & (IN4 | INP4)))
  358           {
  359         struct in_addr newaddr = addr->in.sin_addr;
  360         
  361         if (int_name->flags & INP4)
  362           {
  363             if (netmask.s_addr == 0xffff)
  364               continue;
  365 
  366             newaddr.s_addr = (addr->in.sin_addr.s_addr & netmask.s_addr) |
  367               (int_name->proto4.s_addr & ~netmask.s_addr);
  368           }
  369         
  370         /* check for duplicates. */
  371         for (lp = int_name->addr; lp; lp = lp->next)
  372           if (lp->flags == 0 && lp->addr.addr4.s_addr == newaddr.s_addr)
  373             break;
  374         
  375         if (!lp)
  376           {
  377             if (param->spare)
  378               {
  379             al = param->spare;
  380             param->spare = al->next;
  381               }
  382             else
  383               al = whine_malloc(sizeof(struct addrlist));
  384 
  385             if (al)
  386               {
  387             al->flags = 0;
  388             al->addr.addr4 = newaddr;
  389               }
  390           }
  391           }
  392 
  393         if (addr->sa.sa_family == AF_INET6 && (int_name->flags & (IN6 | INP6)))
  394           {
  395         struct in6_addr newaddr = addr->in6.sin6_addr;
  396         
  397         if (int_name->flags & INP6)
  398           {
  399             int i;
  400 
  401             /* No sense in doing /128. */
  402             if (prefixlen == 128)
  403               continue;
  404             
  405             for (i = 0; i < 16; i++)
  406               {
  407             int bits = ((i+1)*8) - prefixlen;
  408                
  409             if (bits >= 8)
  410               newaddr.s6_addr[i] = int_name->proto6.s6_addr[i];
  411             else if (bits >= 0)
  412               {
  413                 unsigned char mask = 0xff << bits;
  414                 newaddr.s6_addr[i] =
  415                   (addr->in6.sin6_addr.s6_addr[i] & mask) |
  416                   (int_name->proto6.s6_addr[i] & ~mask);
  417               }
  418               }
  419           }
  420         
  421         /* check for duplicates. */
  422         for (lp = int_name->addr; lp; lp = lp->next)
  423           if ((lp->flags & ADDRLIST_IPV6) &&
  424               IN6_ARE_ADDR_EQUAL(&lp->addr.addr6, &newaddr))
  425             break;
  426                     
  427         if (!lp)
  428           {
  429             if (param->spare)
  430               {
  431             al = param->spare;
  432             param->spare = al->next;
  433               }
  434             else
  435               al = whine_malloc(sizeof(struct addrlist));
  436             
  437             if (al)
  438               {
  439             al->flags = ADDRLIST_IPV6;
  440             al->addr.addr6 = newaddr;
  441 
  442             /* Privacy addresses and addresses still undergoing DAD and deprecated addresses
  443                don't appear in forward queries, but will in reverse ones. */
  444             if (!(iface_flags & IFACE_PERMANENT) || (iface_flags & (IFACE_DEPRECATED | IFACE_TENTATIVE)))
  445               al->flags |= ADDRLIST_REVONLY;
  446               }
  447           }
  448           }
  449         
  450         if (al)
  451           {
  452         al->next = int_name->addr;
  453         int_name->addr = al;
  454           }
  455       }
  456     }
  457  
  458   /* check whether the interface IP has been added already 
  459      we call this routine multiple times. */
  460   for (iface = daemon->interfaces; iface; iface = iface->next) 
  461     if (sockaddr_isequal(&iface->addr, addr) && iface->index == if_index)
  462       {
  463     iface->dad = !!(iface_flags & IFACE_TENTATIVE);
  464     iface->found = 1; /* for garbage collection */
  465     iface->netmask = netmask;
  466     return 1;
  467       }
  468 
  469  /* If we are restricting the set of interfaces to use, make
  470      sure that loopback interfaces are in that set. */
  471   if (daemon->if_names && loopback)
  472     {
  473       struct iname *lo;
  474       for (lo = daemon->if_names; lo; lo = lo->next)
  475     if (lo->name && strcmp(lo->name, ifr.ifr_name) == 0)
  476       break;
  477       
  478       if (!lo && (lo = whine_malloc(sizeof(struct iname)))) 
  479     {
  480       if ((lo->name = whine_malloc(strlen(ifr.ifr_name)+1)))
  481         {
  482           strcpy(lo->name, ifr.ifr_name);
  483           lo->used = 1;
  484           lo->next = daemon->if_names;
  485           daemon->if_names = lo;
  486         }
  487       else
  488         free(lo);
  489     }
  490     }
  491   
  492   if (addr->sa.sa_family == AF_INET &&
  493       !iface_check(AF_INET, (union all_addr *)&addr->in.sin_addr, label, &auth_dns))
  494     return 1;
  495 
  496   if (addr->sa.sa_family == AF_INET6 &&
  497       !iface_check(AF_INET6, (union all_addr *)&addr->in6.sin6_addr, label, &auth_dns))
  498     return 1;
  499     
  500 #ifdef HAVE_DHCP
  501   /* No DHCP where we're doing auth DNS. */
  502   if (auth_dns)
  503     {
  504       tftp_ok = 0;
  505       dhcp_ok = 0;
  506     }
  507   else
  508     for (tmp = daemon->dhcp_except; tmp; tmp = tmp->next)
  509       if (tmp->name && wildcard_match(tmp->name, ifr.ifr_name))
  510     {
  511       tftp_ok = 0;
  512       dhcp_ok = 0;
  513     }
  514 #endif
  515  
  516   
  517 #ifdef HAVE_TFTP
  518   if (daemon->tftp_interfaces)
  519     {
  520       /* dedicated tftp interface list */
  521       tftp_ok = 0;
  522       for (tmp = daemon->tftp_interfaces; tmp; tmp = tmp->next)
  523     if (tmp->name && wildcard_match(tmp->name, ifr.ifr_name))
  524       tftp_ok = 1;
  525     }
  526 #endif
  527   
  528   /* add to list */
  529   if ((iface = whine_malloc(sizeof(struct irec))))
  530     {
  531       int mtu = 0;
  532 
  533       if (ioctl(param->fd, SIOCGIFMTU, &ifr) != -1)
  534     mtu = ifr.ifr_mtu;
  535 
  536       iface->addr = *addr;
  537       iface->netmask = netmask;
  538       iface->tftp_ok = tftp_ok;
  539       iface->dhcp_ok = dhcp_ok;
  540       iface->dns_auth = auth_dns;
  541       iface->mtu = mtu;
  542       iface->dad = !!(iface_flags & IFACE_TENTATIVE);
  543       iface->found = 1;
  544       iface->done = iface->multicast_done = iface->warned = 0;
  545       iface->index = if_index;
  546       iface->label = is_label;
  547       if ((iface->name = whine_malloc(strlen(ifr.ifr_name)+1)))
  548     {
  549       strcpy(iface->name, ifr.ifr_name);
  550       iface->next = daemon->interfaces;
  551       daemon->interfaces = iface;
  552       return 1;
  553     }
  554       free(iface);
  555 
  556     }
  557   
  558   errno = ENOMEM; 
  559   return 0;
  560 }
  561 
  562 static int iface_allowed_v6(struct in6_addr *local, int prefix, 
  563                 int scope, int if_index, int flags, 
  564                 int preferred, int valid, void *vparam)
  565 {
  566   union mysockaddr addr;
  567   struct in_addr netmask; /* dummy */
  568   netmask.s_addr = 0;
  569 
  570   (void)scope; /* warning */
  571   (void)preferred;
  572   (void)valid;
  573   
  574   memset(&addr, 0, sizeof(addr));
  575 #ifdef HAVE_SOCKADDR_SA_LEN
  576   addr.in6.sin6_len = sizeof(addr.in6);
  577 #endif
  578   addr.in6.sin6_family = AF_INET6;
  579   addr.in6.sin6_addr = *local;
  580   addr.in6.sin6_port = htons(daemon->port);
  581   /* FreeBSD insists this is zero for non-linklocal addresses */
  582   if (IN6_IS_ADDR_LINKLOCAL(local))
  583     addr.in6.sin6_scope_id = if_index;
  584   else
  585     addr.in6.sin6_scope_id = 0;
  586   
  587   return iface_allowed((struct iface_param *)vparam, if_index, NULL, &addr, netmask, prefix, flags);
  588 }
  589 
  590 static int iface_allowed_v4(struct in_addr local, int if_index, char *label,
  591                 struct in_addr netmask, struct in_addr broadcast, void *vparam)
  592 {
  593   union mysockaddr addr;
  594   int prefix, bit;
  595  
  596   (void)broadcast; /* warning */
  597 
  598   memset(&addr, 0, sizeof(addr));
  599 #ifdef HAVE_SOCKADDR_SA_LEN
  600   addr.in.sin_len = sizeof(addr.in);
  601 #endif
  602   addr.in.sin_family = AF_INET;
  603   addr.in.sin_addr = local;
  604   addr.in.sin_port = htons(daemon->port);
  605 
  606   /* determine prefix length from netmask */
  607   for (prefix = 32, bit = 1; (bit & ntohl(netmask.s_addr)) == 0 && prefix != 0; bit = bit << 1, prefix--);
  608 
  609   return iface_allowed((struct iface_param *)vparam, if_index, label, &addr, netmask, prefix, 0);
  610 }
  611 
  612 /*
  613  * Clean old interfaces no longer found.
  614  */
  615 static void clean_interfaces()
  616 {
  617   struct irec *iface;
  618   struct irec **up = &daemon->interfaces;
  619 
  620   for (iface = *up; iface; iface = *up)
  621   {
  622     if (!iface->found && !iface->done)
  623       {
  624         *up = iface->next;
  625         free(iface->name);
  626         free(iface);
  627       }
  628     else
  629       {
  630         up = &iface->next;
  631       }
  632   }
  633 }
  634 
  635 /** Release listener if no other interface needs it.
  636  *
  637  * @return 1 if released, 0 if still required
  638  */
  639 static int release_listener(struct listener *l)
  640 {
  641   if (l->used > 1)
  642     {
  643       struct irec *iface;
  644       for (iface = daemon->interfaces; iface; iface = iface->next)
  645     if (iface->done && sockaddr_isequal(&l->addr, &iface->addr))
  646       {
  647         if (iface->found)
  648           {
  649         /* update listener to point to active interface instead */
  650         if (!l->iface->found)
  651           l->iface = iface;
  652           }
  653         else
  654           {
  655         l->used--;
  656         iface->done = 0;
  657           }
  658       }
  659 
  660       /* Someone is still using this listener, skip its deletion */
  661       if (l->used > 0)
  662     return 0;
  663     }
  664 
  665   if (l->iface->done)
  666     {
  667       int port;
  668 
  669       port = prettyprint_addr(&l->iface->addr, daemon->addrbuff);
  670       my_syslog(LOG_DEBUG|MS_DEBUG, _("stopped listening on %s(#%d): %s port %d"),
  671         l->iface->name, l->iface->index, daemon->addrbuff, port);
  672       /* In case it ever returns */
  673       l->iface->done = 0;
  674     }
  675 
  676   if (l->fd != -1)
  677     close(l->fd);
  678   if (l->tcpfd != -1)
  679     close(l->tcpfd);
  680   if (l->tftpfd != -1)
  681     close(l->tftpfd);
  682 
  683   free(l);
  684   return 1;
  685 }
  686 
  687 int enumerate_interfaces(int reset)
  688 {
  689   static struct addrlist *spare = NULL;
  690   static int done = 0;
  691   struct iface_param param;
  692   int errsave, ret = 1;
  693   struct addrlist *addr, *tmp;
  694   struct interface_name *intname;
  695   struct irec *iface;
  696 #ifdef HAVE_AUTH
  697   struct auth_zone *zone;
  698 #endif
  699   struct server *serv;
  700   
  701   /* Do this max once per select cycle  - also inhibits netlink socket use
  702    in TCP child processes. */
  703 
  704   if (reset)
  705     {
  706       done = 0;
  707       return 1;
  708     }
  709 
  710   if (done)
  711     return 1;
  712 
  713   done = 1;
  714 
  715   if ((param.fd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
  716     return 0;
  717 
  718   /* iface indexes can change when interfaces are created/destroyed. 
  719      We use them in the main forwarding control path, when the path
  720      to a server is specified by an interface, so cache them.
  721      Update the cache here. */
  722   for (serv = daemon->servers; serv; serv = serv->next)
  723     if (serv->interface[0] != 0)
  724       {
  725 #ifdef HAVE_LINUX_NETWORK
  726     struct ifreq ifr;
  727     
  728     safe_strncpy(ifr.ifr_name, serv->interface, IF_NAMESIZE);
  729     if (ioctl(param.fd, SIOCGIFINDEX, &ifr) != -1) 
  730       serv->ifindex = ifr.ifr_ifindex;
  731 #else
  732     serv->ifindex = if_nametoindex(serv->interface);
  733 #endif
  734       }
  735     
  736 again:
  737   /* Mark interfaces for garbage collection */
  738   for (iface = daemon->interfaces; iface; iface = iface->next) 
  739     iface->found = 0;
  740 
  741   /* remove addresses stored against interface_names */
  742   for (intname = daemon->int_names; intname; intname = intname->next)
  743     {
  744       for (addr = intname->addr; addr; addr = tmp)
  745     {
  746       tmp = addr->next;
  747       addr->next = spare;
  748       spare = addr;
  749     }
  750       
  751       intname->addr = NULL;
  752     }
  753 
  754   /* Remove list of addresses of local interfaces */
  755   for (addr = daemon->interface_addrs; addr; addr = tmp)
  756     {
  757       tmp = addr->next;
  758       addr->next = spare;
  759       spare = addr;
  760     }
  761   daemon->interface_addrs = NULL;
  762   
  763 #ifdef HAVE_AUTH
  764   /* remove addresses stored against auth_zone subnets, but not 
  765    ones configured as address literals */
  766   for (zone = daemon->auth_zones; zone; zone = zone->next)
  767     if (zone->interface_names)
  768       {
  769     struct addrlist **up;
  770     for (up = &zone->subnet, addr = zone->subnet; addr; addr = tmp)
  771       {
  772         tmp = addr->next;
  773         if (addr->flags & ADDRLIST_LITERAL)
  774           up = &addr->next;
  775         else
  776           {
  777         *up = addr->next;
  778         addr->next = spare;
  779         spare = addr;
  780           }
  781       }
  782       }
  783 #endif
  784 
  785   param.spare = spare;
  786   
  787   ret = iface_enumerate(AF_INET6, &param, iface_allowed_v6);
  788   if (ret < 0)
  789     goto again;
  790   else if (ret)
  791     {
  792       ret = iface_enumerate(AF_INET, &param, iface_allowed_v4);
  793       if (ret < 0)
  794     goto again;
  795     }
  796  
  797   errsave = errno;
  798   close(param.fd);
  799   
  800   if (option_bool(OPT_CLEVERBIND))
  801     { 
  802       /* Garbage-collect listeners listening on addresses that no longer exist.
  803      Does nothing when not binding interfaces or for listeners on localhost, 
  804      since the ->iface field is NULL. Note that this needs the protections
  805      against reentrancy, hence it's here.  It also means there's a possibility,
  806      in OPT_CLEVERBIND mode, that at listener will just disappear after
  807      a call to enumerate_interfaces, this is checked OK on all calls. */
  808       struct listener *l, *tmp, **up;
  809       int freed = 0;
  810       
  811       for (up = &daemon->listeners, l = daemon->listeners; l; l = tmp)
  812     {
  813       tmp = l->next;
  814       
  815       if (!l->iface || l->iface->found)
  816         up = &l->next;
  817       else if (release_listener(l))
  818         {
  819           *up = tmp;
  820           freed = 1;
  821         }
  822     }
  823 
  824       if (freed)
  825     clean_interfaces();
  826     }
  827 
  828   errno = errsave;
  829   spare = param.spare;
  830   
  831   return ret;
  832 }
  833 
  834 /* set NONBLOCK bit on fd: See Stevens 16.6 */
  835 int fix_fd(int fd)
  836 {
  837   int flags;
  838 
  839   if ((flags = fcntl(fd, F_GETFL)) == -1 ||
  840       fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
  841     return 0;
  842   
  843   return 1;
  844 }
  845 
  846 static int make_sock(union mysockaddr *addr, int type, int dienow)
  847 {
  848   int family = addr->sa.sa_family;
  849   int fd, rc, opt = 1;
  850   
  851   if ((fd = socket(family, type, 0)) == -1)
  852     {
  853       int port, errsave;
  854       char *s;
  855 
  856       /* No error if the kernel just doesn't support this IP flavour */
  857       if (errno == EPROTONOSUPPORT ||
  858       errno == EAFNOSUPPORT ||
  859       errno == EINVAL)
  860     return -1;
  861       
  862     err:
  863       errsave = errno;
  864       port = prettyprint_addr(addr, daemon->addrbuff);
  865       if (!option_bool(OPT_NOWILD) && !option_bool(OPT_CLEVERBIND))
  866     sprintf(daemon->addrbuff, "port %d", port);
  867       s = _("failed to create listening socket for %s: %s");
  868       
  869       if (fd != -1)
  870     close (fd);
  871     
  872       errno = errsave;
  873 
  874       if (dienow)
  875     {
  876       /* failure to bind addresses given by --listen-address at this point
  877          is OK if we're doing bind-dynamic */
  878       if (!option_bool(OPT_CLEVERBIND))
  879         die(s, daemon->addrbuff, EC_BADNET);
  880     }
  881       else
  882     my_syslog(LOG_WARNING, s, daemon->addrbuff, strerror(errno));
  883       
  884       return -1;
  885     }   
  886   
  887   if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1 || !fix_fd(fd))
  888     goto err;
  889   
  890   if (family == AF_INET6 && setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &opt, sizeof(opt)) == -1)
  891     goto err;
  892   
  893   if ((rc = bind(fd, (struct sockaddr *)addr, sa_len(addr))) == -1)
  894     goto err;
  895   
  896   if (type == SOCK_STREAM)
  897     {
  898 #ifdef TCP_FASTOPEN
  899       int qlen = 5;                           
  900       setsockopt(fd, IPPROTO_TCP, TCP_FASTOPEN, &qlen, sizeof(qlen));
  901 #endif
  902       
  903       if (listen(fd, TCP_BACKLOG) == -1)
  904     goto err;
  905     }
  906   else if (family == AF_INET)
  907     {
  908       if (!option_bool(OPT_NOWILD))
  909     {
  910 #if defined(HAVE_LINUX_NETWORK) 
  911       if (setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &opt, sizeof(opt)) == -1)
  912         goto err;
  913 #elif defined(IP_RECVDSTADDR) && defined(IP_RECVIF)
  914       if (setsockopt(fd, IPPROTO_IP, IP_RECVDSTADDR, &opt, sizeof(opt)) == -1 ||
  915           setsockopt(fd, IPPROTO_IP, IP_RECVIF, &opt, sizeof(opt)) == -1)
  916         goto err;
  917 #endif
  918     }
  919     }
  920   else if (!set_ipv6pktinfo(fd))
  921     goto err;
  922   
  923   return fd;
  924 }
  925 
  926 int set_ipv6pktinfo(int fd)
  927 {
  928   int opt = 1;
  929 
  930   /* The API changed around Linux 2.6.14 but the old ABI is still supported:
  931      handle all combinations of headers and kernel.
  932      OpenWrt note that this fixes the problem addressed by your very broken patch. */
  933   daemon->v6pktinfo = IPV6_PKTINFO;
  934   
  935 #ifdef IPV6_RECVPKTINFO
  936   if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &opt, sizeof(opt)) != -1)
  937     return 1;
  938 # ifdef IPV6_2292PKTINFO
  939   else if (errno == ENOPROTOOPT && setsockopt(fd, IPPROTO_IPV6, IPV6_2292PKTINFO, &opt, sizeof(opt)) != -1)
  940     {
  941       daemon->v6pktinfo = IPV6_2292PKTINFO;
  942       return 1;
  943     }
  944 # endif 
  945 #else
  946   if (setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, &opt, sizeof(opt)) != -1)
  947     return 1;
  948 #endif
  949 
  950   return 0;
  951 }
  952 
  953 
  954 /* Find the interface on which a TCP connection arrived, if possible, or zero otherwise. */
  955 int tcp_interface(int fd, int af)
  956 { 
  957   (void)fd; /* suppress potential unused warning */
  958   (void)af; /* suppress potential unused warning */
  959   int if_index = 0;
  960 
  961 #ifdef HAVE_LINUX_NETWORK
  962   int opt = 1;
  963   struct cmsghdr *cmptr;
  964   struct msghdr msg;
  965   socklen_t len;
  966   
  967   /* use mshdr so that the CMSDG_* macros are available */
  968   msg.msg_control = daemon->packet;
  969   msg.msg_controllen = len = daemon->packet_buff_sz;
  970 
  971   /* we overwrote the buffer... */
  972   daemon->srv_save = NULL; 
  973 
  974   if (af == AF_INET)
  975     {
  976       if (setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &opt, sizeof(opt)) != -1 &&
  977       getsockopt(fd, IPPROTO_IP, IP_PKTOPTIONS, msg.msg_control, &len) != -1)
  978     {
  979       msg.msg_controllen = len;
  980       for (cmptr = CMSG_FIRSTHDR(&msg); cmptr; cmptr = CMSG_NXTHDR(&msg, cmptr))
  981         if (cmptr->cmsg_level == IPPROTO_IP && cmptr->cmsg_type == IP_PKTINFO)
  982           {
  983         union {
  984           unsigned char *c;
  985           struct in_pktinfo *p;
  986         } p;
  987         
  988         p.c = CMSG_DATA(cmptr);
  989         if_index = p.p->ipi_ifindex;
  990           }
  991     }
  992     }
  993   else
  994     {
  995       /* Only the RFC-2292 API has the ability to find the interface for TCP connections,
  996      it was removed in RFC-3542 !!!! 
  997 
  998      Fortunately, Linux kept the 2292 ABI when it moved to 3542. The following code always
  999      uses the old ABI, and should work with pre- and post-3542 kernel headers */
 1000 
 1001 #ifdef IPV6_2292PKTOPTIONS   
 1002 #  define PKTOPTIONS IPV6_2292PKTOPTIONS
 1003 #else
 1004 #  define PKTOPTIONS IPV6_PKTOPTIONS
 1005 #endif
 1006 
 1007       if (set_ipv6pktinfo(fd) &&
 1008       getsockopt(fd, IPPROTO_IPV6, PKTOPTIONS, msg.msg_control, &len) != -1)
 1009     {
 1010           msg.msg_controllen = len;
 1011       for (cmptr = CMSG_FIRSTHDR(&msg); cmptr; cmptr = CMSG_NXTHDR(&msg, cmptr))
 1012             if (cmptr->cmsg_level == IPPROTO_IPV6 && cmptr->cmsg_type == daemon->v6pktinfo)
 1013               {
 1014                 union {
 1015                   unsigned char *c;
 1016                   struct in6_pktinfo *p;
 1017                 } p;
 1018                 p.c = CMSG_DATA(cmptr);
 1019         
 1020         if_index = p.p->ipi6_ifindex;
 1021               }
 1022     }
 1023     }
 1024 #endif /* Linux */
 1025  
 1026   return if_index;
 1027 }
 1028       
 1029 static struct listener *create_listeners(union mysockaddr *addr, int do_tftp, int dienow)
 1030 {
 1031   struct listener *l = NULL;
 1032   int fd = -1, tcpfd = -1, tftpfd = -1;
 1033 
 1034   (void)do_tftp;
 1035 
 1036   if (daemon->port != 0)
 1037     {
 1038       fd = make_sock(addr, SOCK_DGRAM, dienow);
 1039       tcpfd = make_sock(addr, SOCK_STREAM, dienow);
 1040     }
 1041   
 1042 #ifdef HAVE_TFTP
 1043   if (do_tftp)
 1044     {
 1045       if (addr->sa.sa_family == AF_INET)
 1046     {
 1047       /* port must be restored to DNS port for TCP code */
 1048       short save = addr->in.sin_port;
 1049       addr->in.sin_port = htons(TFTP_PORT);
 1050       tftpfd = make_sock(addr, SOCK_DGRAM, dienow);
 1051       addr->in.sin_port = save;
 1052     }
 1053       else
 1054     {
 1055       short save = addr->in6.sin6_port;
 1056       addr->in6.sin6_port = htons(TFTP_PORT);
 1057       tftpfd = make_sock(addr, SOCK_DGRAM, dienow);
 1058       addr->in6.sin6_port = save;
 1059     }  
 1060     }
 1061 #endif
 1062 
 1063   if (fd != -1 || tcpfd != -1 || tftpfd != -1)
 1064     {
 1065       l = safe_malloc(sizeof(struct listener));
 1066       l->next = NULL;
 1067       l->fd = fd;
 1068       l->tcpfd = tcpfd;
 1069       l->tftpfd = tftpfd;
 1070       l->addr = *addr;
 1071       l->used = 1;
 1072       l->iface = NULL;
 1073     }
 1074 
 1075   return l;
 1076 }
 1077 
 1078 void create_wildcard_listeners(void)
 1079 {
 1080   union mysockaddr addr;
 1081   struct listener *l, *l6;
 1082 
 1083   memset(&addr, 0, sizeof(addr));
 1084 #ifdef HAVE_SOCKADDR_SA_LEN
 1085   addr.in.sin_len = sizeof(addr.in);
 1086 #endif
 1087   addr.in.sin_family = AF_INET;
 1088   addr.in.sin_addr.s_addr = INADDR_ANY;
 1089   addr.in.sin_port = htons(daemon->port);
 1090 
 1091   l = create_listeners(&addr, !!option_bool(OPT_TFTP), 1);
 1092 
 1093   memset(&addr, 0, sizeof(addr));
 1094 #ifdef HAVE_SOCKADDR_SA_LEN
 1095   addr.in6.sin6_len = sizeof(addr.in6);
 1096 #endif
 1097   addr.in6.sin6_family = AF_INET6;
 1098   addr.in6.sin6_addr = in6addr_any;
 1099   addr.in6.sin6_port = htons(daemon->port);
 1100  
 1101   l6 = create_listeners(&addr, !!option_bool(OPT_TFTP), 1);
 1102   if (l) 
 1103     l->next = l6;
 1104   else 
 1105     l = l6;
 1106 
 1107   daemon->listeners = l;
 1108 }
 1109 
 1110 static struct listener *find_listener(union mysockaddr *addr)
 1111 {
 1112   struct listener *l;
 1113   for (l = daemon->listeners; l; l = l->next)
 1114     if (sockaddr_isequal(&l->addr, addr))
 1115       return l;
 1116   return NULL;
 1117 }
 1118 
 1119 void create_bound_listeners(int dienow)
 1120 {
 1121   struct listener *new;
 1122   struct irec *iface;
 1123   struct iname *if_tmp;
 1124   struct listener *existing;
 1125 
 1126   for (iface = daemon->interfaces; iface; iface = iface->next)
 1127     if (!iface->done && !iface->dad && iface->found)
 1128       {
 1129     existing = find_listener(&iface->addr);
 1130     if (existing)
 1131       {
 1132         iface->done = 1;
 1133         existing->used++; /* increase usage counter */
 1134       }
 1135     else if ((new = create_listeners(&iface->addr, iface->tftp_ok, dienow)))
 1136       {
 1137         new->iface = iface;
 1138         new->next = daemon->listeners;
 1139         daemon->listeners = new;
 1140         iface->done = 1;
 1141 
 1142         /* Don't log the initial set of listen addresses created
 1143                at startup, since this is happening before the logging
 1144                system is initialised and the sign-on printed. */
 1145             if (!dienow)
 1146               {
 1147         int port = prettyprint_addr(&iface->addr, daemon->addrbuff);
 1148         my_syslog(LOG_DEBUG|MS_DEBUG, _("listening on %s(#%d): %s port %d"),
 1149               iface->name, iface->index, daemon->addrbuff, port);
 1150           }
 1151       }
 1152       }
 1153 
 1154   /* Check for --listen-address options that haven't been used because there's
 1155      no interface with a matching address. These may be valid: eg it's possible
 1156      to listen on 127.0.1.1 even if the loopback interface is 127.0.0.1
 1157 
 1158      If the address isn't valid the bind() will fail and we'll die() 
 1159      (except in bind-dynamic mode, when we'll complain but keep trying.)
 1160 
 1161      The resulting listeners have the ->iface field NULL, and this has to be
 1162      handled by the DNS and TFTP code. It disables --localise-queries processing
 1163      (no netmask) and some MTU login the tftp code. */
 1164 
 1165   for (if_tmp = daemon->if_addrs; if_tmp; if_tmp = if_tmp->next)
 1166     if (!if_tmp->used && 
 1167     (new = create_listeners(&if_tmp->addr, !!option_bool(OPT_TFTP), dienow)))
 1168       {
 1169     new->next = daemon->listeners;
 1170     daemon->listeners = new;
 1171 
 1172     if (!dienow)
 1173       {
 1174         int port = prettyprint_addr(&if_tmp->addr, daemon->addrbuff);
 1175         my_syslog(LOG_DEBUG|MS_DEBUG, _("listening on %s port %d"), daemon->addrbuff, port);
 1176       }
 1177       }
 1178 }
 1179 
 1180 /* In --bind-interfaces, the only access control is the addresses we're listening on. 
 1181    There's nothing to avoid a query to the address of an internal interface arriving via
 1182    an external interface where we don't want to accept queries, except that in the usual 
 1183    case the addresses of internal interfaces are RFC1918. When bind-interfaces in use, 
 1184    and we listen on an address that looks like it's probably globally routeable, shout.
 1185 
 1186    The fix is to use --bind-dynamic, which actually checks the arrival interface too.
 1187    Tough if your platform doesn't support this.
 1188 
 1189    Note that checking the arrival interface is supported in the standard IPv6 API and
 1190    always done, so we don't warn about any IPv6 addresses here.
 1191 */
 1192 
 1193 void warn_bound_listeners(void)
 1194 {
 1195   struct irec *iface;   
 1196   int advice = 0;
 1197 
 1198   for (iface = daemon->interfaces; iface; iface = iface->next)
 1199     if (!iface->dns_auth)
 1200       {
 1201     if (iface->addr.sa.sa_family == AF_INET)
 1202       {
 1203         if (!private_net(iface->addr.in.sin_addr, 1))
 1204           {
 1205         inet_ntop(AF_INET, &iface->addr.in.sin_addr, daemon->addrbuff, ADDRSTRLEN);
 1206         iface->warned = advice = 1;
 1207         my_syslog(LOG_WARNING, 
 1208               _("LOUD WARNING: listening on %s may accept requests via interfaces other than %s"),
 1209               daemon->addrbuff, iface->name);
 1210           }
 1211       }
 1212       }
 1213   
 1214   if (advice)
 1215     my_syslog(LOG_WARNING, _("LOUD WARNING: use --bind-dynamic rather than --bind-interfaces to avoid DNS amplification attacks via these interface(s)")); 
 1216 }
 1217 
 1218 void warn_wild_labels(void)
 1219 {
 1220   struct irec *iface;
 1221 
 1222   for (iface = daemon->interfaces; iface; iface = iface->next)
 1223     if (iface->found && iface->name && iface->label)
 1224       my_syslog(LOG_WARNING, _("warning: using interface %s instead"), iface->name);
 1225 }
 1226 
 1227 void warn_int_names(void)
 1228 {
 1229   struct interface_name *intname;
 1230  
 1231   for (intname = daemon->int_names; intname; intname = intname->next)
 1232     if (!intname->addr)
 1233       my_syslog(LOG_WARNING, _("warning: no addresses found for interface %s"), intname->intr);
 1234 }
 1235  
 1236 int is_dad_listeners(void)
 1237 {
 1238   struct irec *iface;
 1239   
 1240   if (option_bool(OPT_NOWILD))
 1241     for (iface = daemon->interfaces; iface; iface = iface->next)
 1242       if (iface->dad && !iface->done)
 1243     return 1;
 1244   
 1245   return 0;
 1246 }
 1247 
 1248 #ifdef HAVE_DHCP6
 1249 void join_multicast(int dienow)      
 1250 {
 1251   struct irec *iface, *tmp;
 1252 
 1253   for (iface = daemon->interfaces; iface; iface = iface->next)
 1254     if (iface->addr.sa.sa_family == AF_INET6 && iface->dhcp_ok && !iface->multicast_done)
 1255       {
 1256     /* There's an irec per address but we only want to join for multicast 
 1257        once per interface. Weed out duplicates. */
 1258     for (tmp = daemon->interfaces; tmp; tmp = tmp->next)
 1259       if (tmp->multicast_done && tmp->index == iface->index)
 1260         break;
 1261     
 1262     iface->multicast_done = 1;
 1263     
 1264     if (!tmp)
 1265       {
 1266         struct ipv6_mreq mreq;
 1267         int err = 0;
 1268 
 1269         mreq.ipv6mr_interface = iface->index;
 1270         
 1271         inet_pton(AF_INET6, ALL_RELAY_AGENTS_AND_SERVERS, &mreq.ipv6mr_multiaddr);
 1272         
 1273         if ((daemon->doing_dhcp6 || daemon->relay6) &&
 1274         setsockopt(daemon->dhcp6fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof(mreq)) == -1)
 1275           err = errno;
 1276         
 1277         inet_pton(AF_INET6, ALL_SERVERS, &mreq.ipv6mr_multiaddr);
 1278         
 1279         if (daemon->doing_dhcp6 && 
 1280         setsockopt(daemon->dhcp6fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof(mreq)) == -1)
 1281           err = errno;
 1282         
 1283         inet_pton(AF_INET6, ALL_ROUTERS, &mreq.ipv6mr_multiaddr);
 1284         
 1285         if (daemon->doing_ra &&
 1286         setsockopt(daemon->icmp6fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof(mreq)) == -1)
 1287           err = errno;
 1288         
 1289         if (err)
 1290           {
 1291         char *s = _("interface %s failed to join DHCPv6 multicast group: %s");
 1292         errno = err;
 1293 
 1294 #ifdef HAVE_LINUX_NETWORK
 1295         if (errno == ENOMEM)
 1296           my_syslog(LOG_ERR, _("try increasing /proc/sys/net/core/optmem_max"));
 1297 #endif
 1298 
 1299         if (dienow)
 1300           die(s, iface->name, EC_BADNET);
 1301         else
 1302           my_syslog(LOG_ERR, s, iface->name, strerror(errno));
 1303           }
 1304       }
 1305       }
 1306 }
 1307 #endif
 1308 
 1309 int local_bind(int fd, union mysockaddr *addr, char *intname, unsigned int ifindex, int is_tcp)
 1310 {
 1311   union mysockaddr addr_copy = *addr;
 1312   unsigned short port;
 1313   int tries = 1;
 1314   unsigned short ports_avail = 1;
 1315 
 1316   if (addr_copy.sa.sa_family == AF_INET)
 1317     port = addr_copy.in.sin_port;
 1318   else
 1319     port = addr_copy.in6.sin6_port;
 1320 
 1321   /* cannot set source _port_ for TCP connections. */
 1322   if (is_tcp)
 1323     port = 0;
 1324   else if (port == 0 && daemon->max_port != 0)
 1325     {
 1326       /* Bind a random port within the range given by min-port and max-port if either
 1327      or both are set. Otherwise use the OS's random ephemeral port allocation by
 1328      leaving port == 0 and tries == 1 */
 1329       ports_avail = daemon->max_port - daemon->min_port + 1;
 1330       tries = ports_avail < 30 ? 3 * ports_avail : 100;
 1331       port = htons(daemon->min_port + (rand16() % ports_avail));
 1332     }
 1333   
 1334   while (1)
 1335     {
 1336       /* elide bind() call if it's to port 0, address 0 */
 1337       if (addr_copy.sa.sa_family == AF_INET)
 1338     {
 1339       if (port == 0 && addr_copy.in.sin_addr.s_addr == 0)
 1340         break;
 1341       addr_copy.in.sin_port = port;
 1342     }
 1343       else
 1344     {
 1345       if (port == 0 && IN6_IS_ADDR_UNSPECIFIED(&addr_copy.in6.sin6_addr))
 1346         break;
 1347       addr_copy.in6.sin6_port = port;
 1348     }
 1349       
 1350       if (bind(fd, (struct sockaddr *)&addr_copy, sa_len(&addr_copy)) != -1)
 1351     break;
 1352       
 1353        if (errno != EADDRINUSE && errno != EACCES) 
 1354      return 0;
 1355 
 1356       if (--tries == 0)
 1357     return 0;
 1358 
 1359       port = htons(daemon->min_port + (rand16() % ports_avail));
 1360     }
 1361 
 1362   if (!is_tcp && ifindex > 0)
 1363     {
 1364 #if defined(IP_UNICAST_IF)
 1365       if (addr_copy.sa.sa_family == AF_INET)
 1366         {
 1367           uint32_t ifindex_opt = htonl(ifindex);
 1368           return setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex_opt, sizeof(ifindex_opt)) == 0;
 1369         }
 1370 #endif
 1371 #if defined (IPV6_UNICAST_IF)
 1372       if (addr_copy.sa.sa_family == AF_INET6)
 1373         {
 1374           uint32_t ifindex_opt = htonl(ifindex);
 1375           return setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_IF, &ifindex_opt, sizeof(ifindex_opt)) == 0;
 1376         }
 1377 #endif
 1378     }
 1379 
 1380   (void)intname; /* suppress potential unused warning */
 1381 #if defined(SO_BINDTODEVICE)
 1382   if (intname[0] != 0 &&
 1383       setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, intname, IF_NAMESIZE) == -1)
 1384     return 0;
 1385 #endif
 1386 
 1387   return 1;
 1388 }
 1389 
 1390 static struct serverfd *allocate_sfd(union mysockaddr *addr, char *intname, unsigned int ifindex)
 1391 {
 1392   struct serverfd *sfd;
 1393   int errsave;
 1394   int opt = 1;
 1395   
 1396   /* when using random ports, servers which would otherwise use
 1397      the INADDR_ANY/port0 socket have sfd set to NULL, this is 
 1398      anything without an explictly set source port. */
 1399   if (!daemon->osport)
 1400     {
 1401       errno = 0;
 1402       
 1403       if (addr->sa.sa_family == AF_INET &&
 1404       addr->in.sin_port == htons(0)) 
 1405     return NULL;
 1406 
 1407       if (addr->sa.sa_family == AF_INET6 &&
 1408       addr->in6.sin6_port == htons(0)) 
 1409     return NULL;
 1410     }
 1411 
 1412   /* may have a suitable one already */
 1413   for (sfd = daemon->sfds; sfd; sfd = sfd->next )
 1414     if (ifindex == sfd->ifindex &&
 1415     sockaddr_isequal(&sfd->source_addr, addr) &&
 1416     strcmp(intname, sfd->interface) == 0)
 1417       return sfd;
 1418   
 1419   /* need to make a new one. */
 1420   errno = ENOMEM; /* in case malloc fails. */
 1421   if (!(sfd = whine_malloc(sizeof(struct serverfd))))
 1422     return NULL;
 1423   
 1424   if ((sfd->fd = socket(addr->sa.sa_family, SOCK_DGRAM, 0)) == -1)
 1425     {
 1426       free(sfd);
 1427       return NULL;
 1428     }
 1429 
 1430   if ((addr->sa.sa_family == AF_INET6 && setsockopt(sfd->fd, IPPROTO_IPV6, IPV6_V6ONLY, &opt, sizeof(opt)) == -1) ||
 1431       !local_bind(sfd->fd, addr, intname, ifindex, 0) || !fix_fd(sfd->fd))
 1432     { 
 1433       errsave = errno; /* save error from bind/setsockopt. */
 1434       close(sfd->fd);
 1435       free(sfd);
 1436       errno = errsave;
 1437       return NULL;
 1438     }
 1439 
 1440   safe_strncpy(sfd->interface, intname, sizeof(sfd->interface)); 
 1441   sfd->source_addr = *addr;
 1442   sfd->next = daemon->sfds;
 1443   sfd->ifindex = ifindex;
 1444   sfd->preallocated = 0;
 1445   daemon->sfds = sfd;
 1446 
 1447   return sfd; 
 1448 }
 1449 
 1450 /* create upstream sockets during startup, before root is dropped which may be needed
 1451    this allows query_port to be a low port and interface binding */
 1452 void pre_allocate_sfds(void)
 1453 {
 1454   struct server *srv;
 1455   struct serverfd *sfd;
 1456   
 1457   if (daemon->query_port != 0)
 1458     {
 1459       union  mysockaddr addr;
 1460       memset(&addr, 0, sizeof(addr));
 1461       addr.in.sin_family = AF_INET;
 1462       addr.in.sin_addr.s_addr = INADDR_ANY;
 1463       addr.in.sin_port = htons(daemon->query_port);
 1464 #ifdef HAVE_SOCKADDR_SA_LEN
 1465       addr.in.sin_len = sizeof(struct sockaddr_in);
 1466 #endif
 1467       if ((sfd = allocate_sfd(&addr, "", 0)))
 1468     sfd->preallocated = 1;
 1469 
 1470       memset(&addr, 0, sizeof(addr));
 1471       addr.in6.sin6_family = AF_INET6;
 1472       addr.in6.sin6_addr = in6addr_any;
 1473       addr.in6.sin6_port = htons(daemon->query_port);
 1474 #ifdef HAVE_SOCKADDR_SA_LEN
 1475       addr.in6.sin6_len = sizeof(struct sockaddr_in6);
 1476 #endif
 1477       if ((sfd = allocate_sfd(&addr, "", 0)))
 1478     sfd->preallocated = 1;
 1479     }
 1480   
 1481   for (srv = daemon->servers; srv; srv = srv->next)
 1482     if (!(srv->flags & (SERV_LITERAL_ADDRESS | SERV_NO_ADDR | SERV_USE_RESOLV | SERV_NO_REBIND)) &&
 1483     !allocate_sfd(&srv->source_addr, srv->interface, srv->ifindex) &&
 1484     errno != 0 &&
 1485     option_bool(OPT_NOWILD))
 1486       {
 1487     (void)prettyprint_addr(&srv->source_addr, daemon->namebuff);
 1488     if (srv->interface[0] != 0)
 1489       {
 1490         strcat(daemon->namebuff, " ");
 1491         strcat(daemon->namebuff, srv->interface);
 1492       }
 1493     die(_("failed to bind server socket for %s: %s"),
 1494         daemon->namebuff, EC_BADNET);
 1495       }  
 1496 }
 1497 
 1498 void mark_servers(int flag)
 1499 {
 1500   struct server *serv;
 1501 
 1502   /* mark everything with argument flag */
 1503   for (serv = daemon->servers; serv; serv = serv->next)
 1504     {
 1505       if (serv->flags & flag)
 1506     serv->flags |= SERV_MARK;
 1507 #ifdef HAVE_LOOP
 1508       /* Give looped servers another chance */
 1509       serv->flags &= ~SERV_LOOP;
 1510 #endif
 1511     }
 1512 }
 1513 
 1514 void cleanup_servers(void)
 1515 {
 1516   struct server *serv, *tmp, **up;
 1517 
 1518   /* unlink and free anything still marked. */
 1519   for (serv = daemon->servers, up = &daemon->servers; serv; serv = tmp) 
 1520     {
 1521       tmp = serv->next;
 1522       if (serv->flags & SERV_MARK)
 1523        {
 1524          server_gone(serv);
 1525          *up = serv->next;
 1526          if (serv->domain)
 1527        free(serv->domain);
 1528      free(serv);
 1529        }
 1530       else 
 1531        up = &serv->next;
 1532     }
 1533 
 1534 #ifdef HAVE_LOOP
 1535   /* Now we have a new set of servers, test for loops. */
 1536   loop_send_probes();
 1537 #endif
 1538 }
 1539 
 1540 void add_update_server(int flags,
 1541                union mysockaddr *addr,
 1542                union mysockaddr *source_addr,
 1543                const char *interface,
 1544                const char *domain)
 1545 {
 1546   struct server *serv, *next = NULL;
 1547   char *domain_str = NULL;
 1548   
 1549   /* See if there is a suitable candidate, and unmark */
 1550   for (serv = daemon->servers; serv; serv = serv->next)
 1551     if (serv->flags & SERV_MARK)
 1552       {
 1553     if (domain)
 1554       {
 1555         if (!(serv->flags & SERV_HAS_DOMAIN) || !hostname_isequal(domain, serv->domain))
 1556           continue;
 1557       }
 1558     else
 1559       {
 1560         if (serv->flags & SERV_HAS_DOMAIN)
 1561           continue;
 1562       }
 1563     
 1564         break;
 1565       }
 1566 
 1567   if (serv)
 1568     {
 1569       domain_str = serv->domain;
 1570       next = serv->next;
 1571     }
 1572   else if ((serv = whine_malloc(sizeof (struct server))))
 1573     {
 1574       /* Not found, create a new one. */
 1575       if (domain && !(domain_str = whine_malloc(strlen(domain)+1)))
 1576     {
 1577       free(serv);
 1578           serv = NULL;
 1579         }
 1580       else
 1581         {
 1582       struct server *s;
 1583       /* Add to the end of the chain, for order */
 1584       if (!daemon->servers)
 1585         daemon->servers = serv;
 1586       else
 1587         {
 1588           for (s = daemon->servers; s->next; s = s->next);
 1589           s->next = serv;
 1590         }
 1591       if (domain)
 1592         strcpy(domain_str, domain);
 1593     }
 1594     }
 1595   
 1596   if (serv)
 1597     {
 1598       memset(serv, 0, sizeof(struct server));
 1599       serv->flags = flags;
 1600       serv->domain = domain_str;
 1601       serv->next = next;
 1602       serv->queries = serv->failed_queries = 0;
 1603 #ifdef HAVE_LOOP
 1604       serv->uid = rand32();
 1605 #endif      
 1606 
 1607       if (domain)
 1608     serv->flags |= SERV_HAS_DOMAIN;
 1609       
 1610       if (interface)
 1611     safe_strncpy(serv->interface, interface, sizeof(serv->interface));
 1612       if (addr)
 1613     serv->addr = *addr;
 1614       if (source_addr)
 1615     serv->source_addr = *source_addr;
 1616     }
 1617 }
 1618 
 1619 void check_servers(void)
 1620 {
 1621   struct irec *iface;
 1622   struct server *serv;
 1623   struct serverfd *sfd, *tmp, **up;
 1624   int port = 0, count;
 1625   int locals = 0;
 1626 
 1627   /* interface may be new since startup */
 1628   if (!option_bool(OPT_NOWILD))
 1629     enumerate_interfaces(0);
 1630 
 1631   /* don't garbage collect pre-allocated sfds. */
 1632   for (sfd = daemon->sfds; sfd; sfd = sfd->next)
 1633     sfd->used = sfd->preallocated;
 1634 
 1635   for (count = 0, serv = daemon->servers; serv; serv = serv->next)
 1636     {
 1637       if (!(serv->flags & (SERV_LITERAL_ADDRESS | SERV_NO_ADDR | SERV_USE_RESOLV | SERV_NO_REBIND)))
 1638     {
 1639       /* Init edns_pktsz for newly created server records. */
 1640       if (serv->edns_pktsz == 0)
 1641         serv->edns_pktsz = daemon->edns_pktsz;
 1642       
 1643 #ifdef HAVE_DNSSEC
 1644       if (option_bool(OPT_DNSSEC_VALID))
 1645         { 
 1646           if (!(serv->flags & SERV_FOR_NODOTS))
 1647         serv->flags |= SERV_DO_DNSSEC;
 1648           
 1649           /* Disable DNSSEC validation when using server=/domain/.... servers
 1650          unless there's a configured trust anchor. */
 1651           if (serv->flags & SERV_HAS_DOMAIN)
 1652         {
 1653           struct ds_config *ds;
 1654           char *domain = serv->domain;
 1655           
 1656           /* .example.com is valid */
 1657           while (*domain == '.')
 1658             domain++;
 1659           
 1660           for (ds = daemon->ds; ds; ds = ds->next)
 1661             if (ds->name[0] != 0 && hostname_isequal(domain, ds->name))
 1662               break;
 1663           
 1664           if (!ds)
 1665             serv->flags &= ~SERV_DO_DNSSEC;
 1666         }
 1667         }
 1668 #endif
 1669 
 1670       port = prettyprint_addr(&serv->addr, daemon->namebuff);
 1671       
 1672       /* 0.0.0.0 is nothing, the stack treats it like 127.0.0.1 */
 1673       if (serv->addr.sa.sa_family == AF_INET &&
 1674           serv->addr.in.sin_addr.s_addr == 0)
 1675         {
 1676           serv->flags |= SERV_MARK;
 1677           continue;
 1678         }
 1679 
 1680       for (iface = daemon->interfaces; iface; iface = iface->next)
 1681         if (sockaddr_isequal(&serv->addr, &iface->addr))
 1682           break;
 1683       if (iface)
 1684         {
 1685           my_syslog(LOG_WARNING, _("ignoring nameserver %s - local interface"), daemon->namebuff);
 1686           serv->flags |= SERV_MARK;
 1687           continue;
 1688         }
 1689       
 1690       /* Do we need a socket set? */
 1691       if (!serv->sfd && 
 1692           !(serv->sfd = allocate_sfd(&serv->source_addr, serv->interface, serv->ifindex)) &&
 1693           errno != 0)
 1694         {
 1695           my_syslog(LOG_WARNING, 
 1696             _("ignoring nameserver %s - cannot make/bind socket: %s"),
 1697             daemon->namebuff, strerror(errno));
 1698           serv->flags |= SERV_MARK;
 1699           continue;
 1700         }
 1701       
 1702       if (serv->sfd)
 1703         serv->sfd->used = 1;
 1704     }
 1705       
 1706       if (!(serv->flags & SERV_NO_REBIND) && !(serv->flags & SERV_LITERAL_ADDRESS))
 1707     {
 1708       if (++count > SERVERS_LOGGED)
 1709         continue;
 1710       
 1711       if (serv->flags & (SERV_HAS_DOMAIN | SERV_FOR_NODOTS | SERV_USE_RESOLV))
 1712         {
 1713           char *s1, *s2, *s3 = "";
 1714 #ifdef HAVE_DNSSEC
 1715           if (option_bool(OPT_DNSSEC_VALID) && !(serv->flags & SERV_DO_DNSSEC))
 1716         s3 = _("(no DNSSEC)");
 1717 #endif
 1718           if (!(serv->flags & SERV_HAS_DOMAIN))
 1719         s1 = _("unqualified"), s2 = _("names");
 1720           else if (strlen(serv->domain) == 0)
 1721         s1 = _("default"), s2 = "";
 1722           else
 1723         s1 = _("domain"), s2 = serv->domain;
 1724           
 1725           if (serv->flags & SERV_NO_ADDR)
 1726         {
 1727           count--;
 1728           if (++locals <= LOCALS_LOGGED)
 1729             my_syslog(LOG_INFO, _("using only locally-known addresses for %s %s"), s1, s2);
 1730             }
 1731           else if (serv->flags & SERV_USE_RESOLV)
 1732         my_syslog(LOG_INFO, _("using standard nameservers for %s %s"), s1, s2);
 1733           else 
 1734         my_syslog(LOG_INFO, _("using nameserver %s#%d for %s %s %s"), daemon->namebuff, port, s1, s2, s3);
 1735         }
 1736 #ifdef HAVE_LOOP
 1737       else if (serv->flags & SERV_LOOP)
 1738         my_syslog(LOG_INFO, _("NOT using nameserver %s#%d - query loop detected"), daemon->namebuff, port); 
 1739 #endif
 1740       else if (serv->interface[0] != 0)
 1741         my_syslog(LOG_INFO, _("using nameserver %s#%d(via %s)"), daemon->namebuff, port, serv->interface); 
 1742       else
 1743         my_syslog(LOG_INFO, _("using nameserver %s#%d"), daemon->namebuff, port); 
 1744     }
 1745     }
 1746   
 1747   if (locals > LOCALS_LOGGED)
 1748     my_syslog(LOG_INFO, _("using %d more local addresses"), locals - LOCALS_LOGGED);
 1749   if (count - 1 > SERVERS_LOGGED)
 1750     my_syslog(LOG_INFO, _("using %d more nameservers"), count - SERVERS_LOGGED - 1);
 1751 
 1752   /* Remove unused sfds */
 1753   for (sfd = daemon->sfds, up = &daemon->sfds; sfd; sfd = tmp)
 1754     {
 1755        tmp = sfd->next;
 1756        if (!sfd->used) 
 1757     {
 1758       *up = sfd->next;
 1759       close(sfd->fd);
 1760       free(sfd);
 1761     } 
 1762       else
 1763     up = &sfd->next;
 1764     }
 1765   
 1766   cleanup_servers();
 1767 }
 1768 
 1769 /* Return zero if no servers found, in that case we keep polling.
 1770    This is a protection against an update-time/write race on resolv.conf */
 1771 int reload_servers(char *fname)
 1772 {
 1773   FILE *f;
 1774   char *line;
 1775   int gotone = 0;
 1776 
 1777   /* buff happens to be MAXDNAME long... */
 1778   if (!(f = fopen(fname, "r")))
 1779     {
 1780       my_syslog(LOG_ERR, _("failed to read %s: %s"), fname, strerror(errno));
 1781       return 0;
 1782     }
 1783    
 1784   mark_servers(SERV_FROM_RESOLV);
 1785     
 1786   while ((line = fgets(daemon->namebuff, MAXDNAME, f)))
 1787     {
 1788       union mysockaddr addr, source_addr;
 1789       char *token = strtok(line, " \t\n\r");
 1790       
 1791       if (!token)
 1792     continue;
 1793       if (strcmp(token, "nameserver") != 0 && strcmp(token, "server") != 0)
 1794     continue;
 1795       if (!(token = strtok(NULL, " \t\n\r")))
 1796     continue;
 1797       
 1798       memset(&addr, 0, sizeof(addr));
 1799       memset(&source_addr, 0, sizeof(source_addr));
 1800       
 1801       if ((addr.in.sin_addr.s_addr = inet_addr(token)) != (in_addr_t) -1)
 1802     {
 1803 #ifdef HAVE_SOCKADDR_SA_LEN
 1804       source_addr.in.sin_len = addr.in.sin_len = sizeof(source_addr.in);
 1805 #endif
 1806       source_addr.in.sin_family = addr.in.sin_family = AF_INET;
 1807       addr.in.sin_port = htons(NAMESERVER_PORT);
 1808       source_addr.in.sin_addr.s_addr = INADDR_ANY;
 1809       source_addr.in.sin_port = htons(daemon->query_port);
 1810     }
 1811       else 
 1812     {   
 1813       int scope_index = 0;
 1814       char *scope_id = strchr(token, '%');
 1815       
 1816       if (scope_id)
 1817         {
 1818           *(scope_id++) = 0;
 1819           scope_index = if_nametoindex(scope_id);
 1820         }
 1821       
 1822       if (inet_pton(AF_INET6, token, &addr.in6.sin6_addr) > 0)
 1823         {
 1824 #ifdef HAVE_SOCKADDR_SA_LEN
 1825           source_addr.in6.sin6_len = addr.in6.sin6_len = sizeof(source_addr.in6);
 1826 #endif
 1827           source_addr.in6.sin6_family = addr.in6.sin6_family = AF_INET6;
 1828           source_addr.in6.sin6_flowinfo = addr.in6.sin6_flowinfo = 0;
 1829           addr.in6.sin6_port = htons(NAMESERVER_PORT);
 1830           addr.in6.sin6_scope_id = scope_index;
 1831           source_addr.in6.sin6_addr = in6addr_any;
 1832           source_addr.in6.sin6_port = htons(daemon->query_port);
 1833           source_addr.in6.sin6_scope_id = 0;
 1834         }
 1835       else
 1836         continue;
 1837     }
 1838 
 1839       add_update_server(SERV_FROM_RESOLV, &addr, &source_addr, NULL, NULL);
 1840       gotone = 1;
 1841     }
 1842   
 1843   fclose(f);
 1844   cleanup_servers();
 1845 
 1846   return gotone;
 1847 }
 1848 
 1849 /* Called when addresses are added or deleted from an interface */
 1850 void newaddress(time_t now)
 1851 {
 1852   (void)now;
 1853   
 1854   if (option_bool(OPT_CLEVERBIND) || option_bool(OPT_LOCAL_SERVICE) ||
 1855       daemon->doing_dhcp6 || daemon->relay6 || daemon->doing_ra)
 1856     enumerate_interfaces(0);
 1857   
 1858   if (option_bool(OPT_CLEVERBIND))
 1859     create_bound_listeners(0);
 1860   
 1861 #ifdef HAVE_DHCP6
 1862   if (daemon->doing_dhcp6 || daemon->relay6 || daemon->doing_ra)
 1863     join_multicast(0);
 1864   
 1865   if (daemon->doing_dhcp6 || daemon->doing_ra)
 1866     dhcp_construct_contexts(now);
 1867   
 1868   if (daemon->doing_dhcp6)
 1869     lease_find_interfaces(now);
 1870 #endif
 1871 }
 1872 
 1873 
 1874 
 1875 
 1876