]> git.ipfire.org Git - thirdparty/glibc.git/blobdiff - resolv/res_hconf.c
Update copyright dates with scripts/update-copyrights.
[thirdparty/glibc.git] / resolv / res_hconf.c
index ab97e39554cdb8cf36975ae8c9ddb1233b4f29e0..50b6d7871152d328b242e3280d31c4fcbb05c88e 100644 (file)
@@ -1,4 +1,4 @@
-/* Copyright (C) 1993,95,96,97,98,99,2000,2001 Free Software Foundation, Inc.
+/* Copyright (C) 1993-2018 Free Software Foundation, Inc.
    This file is part of the GNU C Library.
    Contributed by David Mosberger (davidm@azstarnet.com).
 
    Lesser General Public License for more details.
 
    You should have received a copy of the GNU Lesser General Public
-   License along with the GNU C Library; if not, write to the Free
-   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
-   02111-1307 USA.  */
+   License along with the GNU C Library; if not, see
+   <http://www.gnu.org/licenses/>.  */
 
 /* This file provides a Linux /etc/host.conf compatible front end to
    the various name resolvers (/etc/hosts, named, NIS server, etc.).
    Though mostly compatibly, the following differences exist compared
    to the original implementation:
 
-       - new command "spoof" takes an arguments like RESOLV_SPOOF_CHECK
-         environment variable (i.e., `off', `nowarn', or `warn').
-
        - line comments can appear anywhere (not just at the beginning of
          a line)
 */
 
+#include <assert.h>
 #include <errno.h>
 #include <ctype.h>
+#include <libintl.h>
 #include <memory.h>
 #include <stdio.h>
 #include <stdio_ext.h>
 #include <sys/ioctl.h>
 #include <unistd.h>
 #include <netinet/in.h>
-#include <bits/libc-lock.h>
+#include <libc-lock.h>
 #include "ifreq.h"
 #include "res_hconf.h"
+#include <wchar.h>
+#include <atomic.h>
+
+#if IS_IN (libc)
+# define fgets_unlocked __fgets_unlocked
+#endif
 
 #define _PATH_HOSTCONF "/etc/host.conf"
 
 /* Environment vars that all user to override default behavior:  */
 #define ENV_HOSTCONF   "RESOLV_HOST_CONF"
-#define ENV_SERVORDER  "RESOLV_SERV_ORDER"
-#define ENV_SPOOF      "RESOLV_SPOOF_CHECK"
 #define ENV_TRIM_OVERR "RESOLV_OVERRIDE_TRIM_DOMAINS"
 #define ENV_TRIM_ADD   "RESOLV_ADD_TRIM_DOMAINS"
 #define ENV_MULTI      "RESOLV_MULTI"
 #define ENV_REORDER    "RESOLV_REORDER"
 
-static const char *arg_service_list (const char *, int, const char *,
-                                    unsigned int);
-static const char *arg_trimdomain_list (const char *, int, const char *,
-                                       unsigned int);
-static const char *arg_spoof (const char *, int, const char *, unsigned int);
-static const char *arg_bool (const char *, int, const char *, unsigned int);
+enum parse_cbs
+  {
+    CB_none,
+    CB_arg_trimdomain_list,
+    CB_arg_bool
+  };
 
-static struct cmd
+static const struct cmd
 {
-  const char *name;
-  const char *(*parse_args) (const char * filename, int line_num,
-                            const char * args, unsigned int arg);
+  const char name[11];
+  uint8_t cb;
   unsigned int arg;
 } cmd[] =
 {
-  {"order",            arg_service_list,       0},
-  {"trim",             arg_trimdomain_list,    0},
-  {"spoof",            arg_spoof,              0},
-  {"multi",            arg_bool,               HCONF_FLAG_MULTI},
-  {"nospoof",          arg_bool,               HCONF_FLAG_SPOOF},
-  {"spoofalert",       arg_bool,               HCONF_FLAG_SPOOFALERT},
-  {"reorder",          arg_bool,               HCONF_FLAG_REORDER}
+  {"order",            CB_none,                0},
+  {"trim",             CB_arg_trimdomain_list, 0},
+  {"multi",            CB_arg_bool,            HCONF_FLAG_MULTI},
+  {"reorder",          CB_arg_bool,            HCONF_FLAG_REORDER}
 };
 
 /* Structure containing the state.  */
@@ -102,23 +100,10 @@ skip_string (const char *str)
 
 
 static const char *
-arg_service_list (const char *fname, int line_num, const char *args,
-                 unsigned int arg)
+arg_trimdomain_list (const char *fname, int line_num, const char *args)
 {
-  enum Name_Service service;
-  const char *start;
+  const char * start;
   size_t len;
-  int i;
-  static struct
-  {
-    const char * name;
-    enum Name_Service service;
-  } svcs[] =
-    {
-      {"bind", SERVICE_BIND},
-      {"hosts",        SERVICE_HOSTS},
-      {"nis",  SERVICE_NIS},
-    };
 
   do
     {
@@ -126,71 +111,18 @@ arg_service_list (const char *fname, int line_num, const char *args,
       args = skip_string (args);
       len = args - start;
 
-      service = SERVICE_NONE;
-      for (i = 0; i < sizeof (svcs) / sizeof (svcs[0]); ++i)
-       {
-         if (__strncasecmp (start, svcs[i].name, len) == 0
-             && len == strlen (svcs[i].name))
-         {
-           service = svcs[i].service;
-           break;
-         }
-      }
-      if (service == SERVICE_NONE)
-       {
-         fprintf (stderr, "%s: line %d: expected service, found `%s'\n",
-                  fname, line_num, start);
-         return 0;
-       }
-      if (_res_hconf.num_services >= SERVICE_MAX)
+      if (_res_hconf.num_trimdomains >= TRIMDOMAINS_MAX)
        {
-         fprintf (stderr, "%s: line %d: cannot specify more than %d services",
-                  fname, line_num, SERVICE_MAX);
-         return 0;
-       }
-      _res_hconf.service[_res_hconf.num_services++] = service;
+         char *buf;
 
-      args = skip_ws (args);
-      switch (*args)
-       {
-       case ',':
-       case ';':
-       case ':':
-         args = skip_ws (++args);
-         if (!*args || *args == '#')
-           {
-             fprintf (stderr,
-                      "%s: line %d: list delimiter not followed by keyword",
-                      fname, line_num);
-             return 0;
-           }
-       default:
-         break;
-       }
-    }
-  while (*args && *args != '#');
-  return args;
-}
+         if (__asprintf (&buf, _("\
+%s: line %d: cannot specify more than %d trim domains"),
+                         fname, line_num, TRIMDOMAINS_MAX) < 0)
+           return 0;
 
+         __fxprintf (NULL, "%s", buf);
 
-static const char *
-arg_trimdomain_list (const char *fname, int line_num, const char *args,
-                    unsigned int flag)
-{
-  const char * start;
-  size_t len;
-
-  do
-    {
-      start = args;
-      args = skip_string (args);
-      len = args - start;
-
-      if (_res_hconf.num_trimdomains >= TRIMDOMAINS_MAX)
-       {
-         fprintf (stderr,
-                  "%s: line %d: cannot specify more than %d trim domains",
-                  fname, line_num, TRIMDOMAINS_MAX);
+         free (buf);
          return 0;
        }
       _res_hconf.trimdomain[_res_hconf.num_trimdomains++] =
@@ -202,9 +134,16 @@ arg_trimdomain_list (const char *fname, int line_num, const char *args,
          args = skip_ws (++args);
          if (!*args || *args == '#')
            {
-             fprintf (stderr,
-                      "%s: line %d: list delimiter not followed by domain",
-                      fname, line_num);
+             char *buf;
+
+             if (__asprintf (&buf, _("\
+%s: line %d: list delimiter not followed by domain"),
+                             fname, line_num) < 0)
+               return 0;
+
+             __fxprintf (NULL, "%s", buf);
+
+             free (buf);
              return 0;
            }
        default:
@@ -216,28 +155,6 @@ arg_trimdomain_list (const char *fname, int line_num, const char *args,
 }
 
 
-static const char *
-arg_spoof (const char *fname, int line_num, const char *args, unsigned flag)
-{
-  const char *start = args;
-  size_t len;
-
-  args = skip_string (args);
-  len = args - start;
-
-  if (len == 3 && __strncasecmp (start, "off", len) == 0)
-    _res_hconf.flags &= ~(HCONF_FLAG_SPOOF | HCONF_FLAG_SPOOFALERT);
-  else
-    {
-      _res_hconf.flags |= (HCONF_FLAG_SPOOF | HCONF_FLAG_SPOOFALERT);
-      if ((len == 6 && __strncasecmp (start, "nowarn", len) == 0)
-         || !(len == 4 && __strncasecmp (start, "warn", len) == 0))
-       _res_hconf.flags &= ~HCONF_FLAG_SPOOFALERT;
-    }
-  return args;
-}
-
-
 static const char *
 arg_bool (const char *fname, int line_num, const char *args, unsigned flag)
 {
@@ -253,8 +170,16 @@ arg_bool (const char *fname, int line_num, const char *args, unsigned flag)
     }
   else
     {
-      fprintf (stderr, "%s: line %d: expected `on' or `off', found `%s'\n",
-              fname, line_num, args);
+      char *buf;
+
+      if (__asprintf (&buf,
+                     _("%s: line %d: expected `on' or `off', found `%s'\n"),
+                     fname, line_num, args) < 0)
+       return 0;
+
+      __fxprintf (NULL, "%s", buf);
+
+      free (buf);
       return 0;
     }
   return args;
@@ -265,9 +190,9 @@ static void
 parse_line (const char *fname, int line_num, const char *str)
 {
   const char *start;
-  struct cmd *c = 0;
+  const struct cmd *c = 0;
   size_t len;
-  int i;
+  size_t i;
 
   str = skip_ws (str);
 
@@ -289,14 +214,29 @@ parse_line (const char *fname, int line_num, const char *str)
     }
   if (c == NULL)
     {
-      fprintf (stderr, "%s: line %d: bad command `%s'\n",
-              fname, line_num, start);
+      char *buf;
+
+      if (__asprintf (&buf, _("%s: line %d: bad command `%s'\n"),
+                     fname, line_num, start) < 0)
+       return;
+
+      __fxprintf (NULL, "%s", buf);
+
+      free (buf);
       return;
     }
 
   /* process args: */
   str = skip_ws (str);
-  str = (*c->parse_args) (fname, line_num, str, c->arg);
+
+  if (c->cb == CB_arg_trimdomain_list)
+    str = arg_trimdomain_list (fname, line_num, str);
+  else if (c->cb == CB_arg_bool)
+    str = arg_bool (fname, line_num, str, c->arg);
+  else
+    /* Ignore the line.  */
+    return;
+
   if (!str)
     return;
 
@@ -305,8 +245,18 @@ parse_line (const char *fname, int line_num, const char *str)
     {
       if (!isspace (*str)) {
        if (*str != '#')
-         fprintf (stderr, "%s: line %d: ignoring trailing garbage `%s'\n",
-                  fname, line_num, str);
+         {
+           char *buf;
+
+           if (__asprintf (&buf,
+                           _("%s: line %d: ignoring trailing garbage `%s'\n"),
+                           fname, line_num, str) < 0)
+             break;
+
+           __fxprintf (NULL, "%s", buf);
+
+           free (buf);
+         }
        break;
       }
       ++str;
@@ -314,30 +264,22 @@ parse_line (const char *fname, int line_num, const char *str)
 }
 
 
-/* Initialize hconf datastructure by reading host.conf file and
-   environment variables.  */
-void
-_res_hconf_init (void)
+static void
+do_init (void)
 {
   const char *hconf_name;
   int line_num = 0;
   char buf[256], *envval;
   FILE *fp;
 
-  if (_res_hconf.initialized)
-    return;
-
   memset (&_res_hconf, '\0', sizeof (_res_hconf));
 
   hconf_name = getenv (ENV_HOSTCONF);
   if (hconf_name == NULL)
     hconf_name = _PATH_HOSTCONF;
 
-  fp = fopen (hconf_name, "r");
-  if (!fp)
-    /* make up something reasonable: */
-    _res_hconf.service[_res_hconf.num_services++] = SERVICE_BIND;
-  else
+  fp = fopen (hconf_name, "rce");
+  if (fp)
     {
       /* No threads using this stream.  */
       __fsetlocking (fp, FSETLOCKING_BYCALLER);
@@ -351,17 +293,6 @@ _res_hconf_init (void)
       fclose (fp);
     }
 
-  envval = getenv (ENV_SERVORDER);
-  if (envval)
-    {
-      _res_hconf.num_services = 0;
-      arg_service_list (ENV_SERVORDER, 1, envval, 0);
-    }
-
-  envval = getenv (ENV_SPOOF);
-  if (envval)
-    arg_spoof (ENV_SPOOF, 1, envval, 0);
-
   envval = getenv (ENV_MULTI);
   if (envval)
     arg_bool (ENV_MULTI, 1, envval, HCONF_FLAG_MULTI);
@@ -372,20 +303,35 @@ _res_hconf_init (void)
 
   envval = getenv (ENV_TRIM_ADD);
   if (envval)
-    arg_trimdomain_list (ENV_TRIM_ADD, 1, envval, 0);
+    arg_trimdomain_list (ENV_TRIM_ADD, 1, envval);
 
   envval = getenv (ENV_TRIM_OVERR);
   if (envval)
     {
       _res_hconf.num_trimdomains = 0;
-      arg_trimdomain_list (ENV_TRIM_OVERR, 1, envval, 0);
+      arg_trimdomain_list (ENV_TRIM_OVERR, 1, envval);
     }
 
-  _res_hconf.initialized = 1;
+  /* See comments on the declaration of _res_hconf.  */
+  atomic_store_release (&_res_hconf.initialized, 1);
 }
 
 
+/* Initialize hconf datastructure by reading host.conf file and
+   environment variables.  */
+void
+_res_hconf_init (void)
+{
+  __libc_once_define (static, once);
+
+  __libc_once (once, do_init);
+}
+
+
+#if IS_IN (libc)
+# if defined SIOCGIFCONF && defined SIOCGIFNETMASK
 /* List of known interfaces.  */
+libc_freeres_ptr (
 static struct netaddr
 {
   int addrtype;
@@ -393,14 +339,12 @@ static struct netaddr
   {
     struct
     {
-      u_int32_t        addr;
-      u_int32_t        mask;
+      uint32_t addr;
+      uint32_t mask;
     } ipv4;
   } u;
-} *ifaddrs;
-
-/* We need to protect the dynamic buffer handling.  */
-__libc_lock_define_initialized (static, lock);
+} *ifaddrs);
+# endif
 
 /* Reorder addresses returned in a hostent such that the first address
    is an address on the local subnet, if there is such an address.
@@ -413,8 +357,15 @@ _res_hconf_reorder_addrs (struct hostent *hp)
 {
 #if defined SIOCGIFCONF && defined SIOCGIFNETMASK
   int i, j;
-  /* Number of interfaces.  */
+  /* Number of interfaces.  Also serves as a flag for the
+     double-checked locking idiom.  */
   static int num_ifs = -1;
+  /* Local copy of num_ifs, for non-atomic access.  */
+  int num_ifs_local;
+  /* We need to protect the dynamic buffer handling.  The lock is only
+     acquired during initialization.  Afterwards, a positive num_ifs
+     value indicates completed initialization.  */
+  __libc_lock_define_initialized (static, lock);
 
   /* Only reorder if we're supposed to.  */
   if ((_res_hconf.flags & HCONF_FLAG_REORDER) == 0)
@@ -424,7 +375,10 @@ _res_hconf_reorder_addrs (struct hostent *hp)
   if (hp->h_addrtype != AF_INET)
     return;
 
-  if (num_ifs <= 0)
+  /* This load synchronizes with the release MO store in the
+     initialization block below.  */
+  num_ifs_local = atomic_load_acquire (&num_ifs);
+  if (num_ifs_local <= 0)
     {
       struct ifreq *ifr, *cur_ifr;
       int sd, num, i;
@@ -433,68 +387,130 @@ _res_hconf_reorder_addrs (struct hostent *hp)
 
       /* Initialize interface table.  */
 
-      num_ifs = 0;
-
-      sd = __opensock ();
+      /* The SIOCGIFNETMASK ioctl will only work on an AF_INET socket.  */
+      sd = __socket (AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
       if (sd < 0)
        return;
 
       /* Get lock.  */
       __libc_lock_lock (lock);
 
-      /* Get a list of interfaces.  */
-      __ifreq (&ifr, &num);
-      if (!ifr)
-       goto cleanup;
-
-      ifaddrs = malloc (num * sizeof (ifaddrs[0]));
-      if (!ifaddrs)
-       goto cleanup1;
-
-      /* Copy usable interfaces in ifaddrs structure.  */
-      for (cur_ifr = ifr, i = 0;  i < num; ++cur_ifr, ++i)
+      /* Recheck, somebody else might have done the work by now.  No
+        ordering is required for the load because we have the lock,
+        and num_ifs is only updated under the lock.  Also see (3) in
+        the analysis below.  */
+      num_ifs_local = atomic_load_relaxed (&num_ifs);
+      if (num_ifs_local <= 0)
        {
-         if (cur_ifr->ifr_addr.sa_family != AF_INET)
-           continue;
+         /* This is the only block which writes to num_ifs.  It can
+            be executed several times (sequentially) if
+            initialization does not yield any interfaces, and num_ifs
+            remains zero.  However, once we stored a positive value
+            in num_ifs below, this block cannot be entered again due
+            to the condition above.  */
+         int new_num_ifs = 0;
+
+         /* Get a list of interfaces.  */
+         __ifreq (&ifr, &num, sd);
+         if (!ifr)
+           goto cleanup;
+
+         ifaddrs = malloc (num * sizeof (ifaddrs[0]));
+         if (!ifaddrs)
+           goto cleanup1;
+
+         /* Copy usable interfaces in ifaddrs structure.  */
+         for (cur_ifr = ifr, i = 0; i < num;
+              cur_ifr = __if_nextreq (cur_ifr), ++i)
+           {
+             union
+             {
+               struct sockaddr sa;
+               struct sockaddr_in sin;
+             } ss;
 
-         ifaddrs[num_ifs].addrtype = AF_INET;
-         ifaddrs[num_ifs].u.ipv4.addr =
-           ((struct sockaddr_in *) &cur_ifr->ifr_addr)->sin_addr.s_addr;
+             if (cur_ifr->ifr_addr.sa_family != AF_INET)
+               continue;
 
-         if (__ioctl (sd, SIOCGIFNETMASK, cur_ifr) < 0)
-           continue;
+             ifaddrs[new_num_ifs].addrtype = AF_INET;
+             ss.sa = cur_ifr->ifr_addr;
+             ifaddrs[new_num_ifs].u.ipv4.addr = ss.sin.sin_addr.s_addr;
 
-         ifaddrs[num_ifs].u.ipv4.mask =
-           ((struct sockaddr_in *) &cur_ifr->ifr_netmask)->sin_addr.s_addr;
+             if (__ioctl (sd, SIOCGIFNETMASK, cur_ifr) < 0)
+               continue;
 
-         /* Now we're committed to this entry.  */
-         ++num_ifs;
-       }
-      /* Just keep enough memory to hold all the interfaces we want.  */
-      ifaddrs = realloc (ifaddrs, num_ifs * sizeof (ifaddrs[0]));
+             ss.sa = cur_ifr->ifr_netmask;
+             ifaddrs[new_num_ifs].u.ipv4.mask = ss.sin.sin_addr.s_addr;
 
-    cleanup1:
-      __if_freereq (ifr);
+             /* Now we're committed to this entry.  */
+             ++new_num_ifs;
+           }
+         /* Just keep enough memory to hold all the interfaces we want.  */
+         ifaddrs = realloc (ifaddrs, new_num_ifs * sizeof (ifaddrs[0]));
+         assert (ifaddrs != NULL);
+
+       cleanup1:
+         __if_freereq (ifr, num);
+
+       cleanup:
+         /* Release lock, preserve error value, and close socket.  */
+         errno = save;
+
+         /* Advertise successful initialization if new_num_ifs is
+            positive (and no updates to ifaddrs are permitted after
+            that).  Otherwise, num_ifs remains unchanged, at zero.
+            This store synchronizes with the initial acquire MO
+            load.  */
+         atomic_store_release (&num_ifs, new_num_ifs);
+         /* Keep the local copy current, to save another load.  */
+         num_ifs_local = new_num_ifs;
+       }
 
-    cleanup:
-      /* Release lock, preserve error value, and close socket.  */
-      save = errno;
       __libc_lock_unlock (lock);
+
       __close (sd);
     }
 
-  if (num_ifs == 0)
+  /* num_ifs_local cannot be negative because the if statement above
+     covered this case.  It can still be zero if we just performed
+     initialization, but could not find any interfaces.  */
+  if (num_ifs_local == 0)
     return;
 
+  /* The code below accesses ifaddrs, so we need to ensure that the
+     initialization happens-before this point.
+
+     The actual initialization is sequenced-before the release store
+     to num_ifs, and sequenced-before the end of the critical section.
+
+     This means there are three possible executions:
+
+     (1) The thread that initialized the data also uses it, so
+         sequenced-before is sufficient to ensure happens-before.
+
+     (2) The release MO store of num_ifs synchronizes-with the acquire
+         MO load, and the acquire MO load is sequenced before the use
+         of the initialized data below.
+
+     (3) We enter the critical section, and the relaxed MO load of
+         num_ifs yields a positive value.  The write to ifaddrs is
+         sequenced-before leaving the critical section.  Leaving the
+         critical section happens-before we entered the critical
+         section ourselves, which means that the write to ifaddrs
+         happens-before this point.
+
+     Consequently, all potential writes to ifaddrs (and the data it
+     points to) happens-before this point.  */
+
   /* Find an address for which we have a direct connection.  */
   for (i = 0; hp->h_addr_list[i]; ++i)
     {
       struct in_addr *haddr = (struct in_addr *) hp->h_addr_list[i];
 
-      for (j = 0; j < num_ifs; ++j)
+      for (j = 0; j < num_ifs_local; ++j)
        {
-         u_int32_t if_addr    = ifaddrs[j].u.ipv4.addr;
-         u_int32_t if_netmask = ifaddrs[j].u.ipv4.mask;
+         uint32_t if_addr    = ifaddrs[j].u.ipv4.addr;
+         uint32_t if_netmask = ifaddrs[j].u.ipv4.mask;
 
          if (((haddr->s_addr ^ if_addr) & if_netmask) == 0)
            {
@@ -553,13 +569,4 @@ _res_hconf_trim_domains (struct hostent *hp)
   for (i = 0; hp->h_aliases[i]; ++i)
     _res_hconf_trim_domain (hp->h_aliases[i]);
 }
-
-
-/* Free all resources if necessary.  */
-static void __attribute__ ((unused))
-free_mem (void)
-{
-  free (ifaddrs);
-}
-
-text_set_element (__libc_subfreeres, free_mem);
+#endif