b95404
commit 4dddd7e9cbecad4aa03ee5a9b9edb596e3d4e909
b95404
Author: Adhemerval Zanella <adhemerval.zanella@linaro.org>
b95404
Date:   Tue Sep 29 08:56:07 2020 -0300
b95404
b95404
    posix: Sync tempname with gnulib [BZ #26648]
b95404
b95404
    It syncs with gnulib commit b1268f22f443e8e4b9e.  The try_tempname_len
b95404
    now uses getrandom on each iteration to get entropy and only uses the
b95404
    clock plus ASLR as source of entropy if getrandom fails.
b95404
b95404
    Checked on x86_64-linux-gnu and i686-linux-gnu.
b95404
b95404
Conflicts:
b95404
	sysdeps/posix/tempname.c
b95404
	  (Missing tree-wide __gettimeofday to clock_gettime change,
b95404
	  commit 4a39c34c4f85de57fb4e648cfa1e774437d69680 upstream.
b95404
	  File was rebased to the upstream version.)
b95404
b95404
diff --git a/sysdeps/posix/tempname.c b/sysdeps/posix/tempname.c
b95404
index a7b404cf4410cb00..f199b25a7a227751 100644
b95404
--- a/sysdeps/posix/tempname.c
b95404
+++ b/sysdeps/posix/tempname.c
b95404
@@ -1,4 +1,4 @@
b95404
-/* Copyright (C) 1991-2018 Free Software Foundation, Inc.
b95404
+/* Copyright (C) 1991-2021 Free Software Foundation, Inc.
b95404
    This file is part of the GNU C Library.
b95404
 
b95404
    The GNU C Library is free software; you can redistribute it and/or
b95404
@@ -13,10 +13,10 @@
b95404
 
b95404
    You should have received a copy of the GNU Lesser General Public
b95404
    License along with the GNU C Library; if not, see
b95404
-   <http://www.gnu.org/licenses/>.  */
b95404
+   <https://www.gnu.org/licenses/>.  */
b95404
 
b95404
 #if !_LIBC
b95404
-# include <config.h>
b95404
+# include <libc-config.h>
b95404
 # include "tempname.h"
b95404
 #endif
b95404
 
b95404
@@ -24,9 +24,6 @@
b95404
 #include <assert.h>
b95404
 
b95404
 #include <errno.h>
b95404
-#ifndef __set_errno
b95404
-# define __set_errno(Val) errno = (Val)
b95404
-#endif
b95404
 
b95404
 #include <stdio.h>
b95404
 #ifndef P_tmpdir
b95404
@@ -36,12 +33,12 @@
b95404
 # define TMP_MAX 238328
b95404
 #endif
b95404
 #ifndef __GT_FILE
b95404
-# define __GT_FILE	0
b95404
-# define __GT_DIR	1
b95404
-# define __GT_NOCREATE	2
b95404
+# define __GT_FILE      0
b95404
+# define __GT_DIR       1
b95404
+# define __GT_NOCREATE  2
b95404
 #endif
b95404
-#if !_LIBC && (GT_FILE != __GT_FILE || GT_DIR != __GT_DIR	\
b95404
-	       || GT_NOCREATE != __GT_NOCREATE)
b95404
+#if !_LIBC && (GT_FILE != __GT_FILE || GT_DIR != __GT_DIR       \
b95404
+               || GT_NOCREATE != __GT_NOCREATE)
b95404
 # error report this to bug-gnulib@gnu.org
b95404
 #endif
b95404
 
b95404
@@ -50,11 +47,11 @@
b95404
 #include <string.h>
b95404
 
b95404
 #include <fcntl.h>
b95404
-#include <sys/time.h>
b95404
+#include <stdalign.h>
b95404
 #include <stdint.h>
b95404
-#include <unistd.h>
b95404
-
b95404
+#include <sys/random.h>
b95404
 #include <sys/stat.h>
b95404
+#include <time.h>
b95404
 
b95404
 #if _LIBC
b95404
 # define struct_stat64 struct stat64
b95404
@@ -62,33 +59,38 @@
b95404
 #else
b95404
 # define struct_stat64 struct stat
b95404
 # define __gen_tempname gen_tempname
b95404
-# define __getpid getpid
b95404
-# define __gettimeofday gettimeofday
b95404
 # define __mkdir mkdir
b95404
 # define __open open
b95404
-# define __secure_getenv secure_getenv
b95404
+# define __lstat64(file, buf) lstat (file, buf)
b95404
+# define __stat64(file, buf) stat (file, buf)
b95404
+# define __getrandom getrandom
b95404
+# define __clock_gettime64 clock_gettime
b95404
+# define __timespec64 timespec
b95404
 #endif
b95404
 
b95404
-#ifdef _LIBC
b95404
-# include <random-bits.h>
b95404
-# define RANDOM_BITS(Var) ((Var) = random_bits ())
b95404
-# else
b95404
-# define RANDOM_BITS(Var) \
b95404
-    {                                                                         \
b95404
-      struct timeval tv;                                                      \
b95404
-      __gettimeofday (&tv, NULL);                                             \
b95404
-      (Var) = ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec;                      \
b95404
-    }
b95404
-#endif
b95404
+/* Use getrandom if it works, falling back on a 64-bit linear
b95404
+   congruential generator that starts with Var's value
b95404
+   mixed in with a clock's low-order bits if available.  */
b95404
+typedef uint_fast64_t random_value;
b95404
+#define RANDOM_VALUE_MAX UINT_FAST64_MAX
b95404
+#define BASE_62_DIGITS 10 /* 62**10 < UINT_FAST64_MAX */
b95404
+#define BASE_62_POWER (62LL * 62 * 62 * 62 * 62 * 62 * 62 * 62 * 62 * 62)
b95404
 
b95404
-/* Use the widest available unsigned type if uint64_t is not
b95404
-   available.  The algorithm below extracts a number less than 62**6
b95404
-   (approximately 2**35.725) from uint64_t, so ancient hosts where
b95404
-   uintmax_t is only 32 bits lose about 3.725 bits of randomness,
b95404
-   which is better than not having mkstemp at all.  */
b95404
-#if !defined UINT64_MAX && !defined uint64_t
b95404
-# define uint64_t uintmax_t
b95404
+static random_value
b95404
+random_bits (random_value var)
b95404
+{
b95404
+  random_value r;
b95404
+  /* Without GRND_NONBLOCK it can be blocked for minutes on some systems.  */
b95404
+  if (__getrandom (&r, sizeof r, GRND_NONBLOCK) == sizeof r)
b95404
+    return r;
b95404
+#if _LIBC || (defined CLOCK_MONOTONIC && HAVE_CLOCK_GETTIME)
b95404
+  /* Add entropy if getrandom did not work.  */
b95404
+  struct __timespec64 tv;
b95404
+  __clock_gettime64 (CLOCK_MONOTONIC, &tv;;
b95404
+  var ^= tv.tv_nsec;
b95404
 #endif
b95404
+  return 2862933555777941757 * var + 3037000493;
b95404
+}
b95404
 
b95404
 #if _LIBC
b95404
 /* Return nonzero if DIR is an existent directory.  */
b95404
@@ -107,7 +109,7 @@ direxists (const char *dir)
b95404
    enough space in TMPL. */
b95404
 int
b95404
 __path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx,
b95404
-	       int try_tmpdir)
b95404
+               int try_tmpdir)
b95404
 {
b95404
   const char *d;
b95404
   size_t dlen, plen;
b95404
@@ -121,35 +123,35 @@ __path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx,
b95404
     {
b95404
       plen = strlen (pfx);
b95404
       if (plen > 5)
b95404
-	plen = 5;
b95404
+        plen = 5;
b95404
     }
b95404
 
b95404
   if (try_tmpdir)
b95404
     {
b95404
       d = __secure_getenv ("TMPDIR");
b95404
       if (d != NULL && direxists (d))
b95404
-	dir = d;
b95404
+        dir = d;
b95404
       else if (dir != NULL && direxists (dir))
b95404
-	/* nothing */ ;
b95404
+        /* nothing */ ;
b95404
       else
b95404
-	dir = NULL;
b95404
+        dir = NULL;
b95404
     }
b95404
   if (dir == NULL)
b95404
     {
b95404
       if (direxists (P_tmpdir))
b95404
-	dir = P_tmpdir;
b95404
+        dir = P_tmpdir;
b95404
       else if (strcmp (P_tmpdir, "/tmp") != 0 && direxists ("/tmp"))
b95404
-	dir = "/tmp";
b95404
+        dir = "/tmp";
b95404
       else
b95404
-	{
b95404
-	  __set_errno (ENOENT);
b95404
-	  return -1;
b95404
-	}
b95404
+        {
b95404
+          __set_errno (ENOENT);
b95404
+          return -1;
b95404
+        }
b95404
     }
b95404
 
b95404
   dlen = strlen (dir);
b95404
   while (dlen > 1 && dir[dlen - 1] == '/')
b95404
-    dlen--;			/* remove trailing slashes */
b95404
+    dlen--;                     /* remove trailing slashes */
b95404
 
b95404
   /* check we have room for "${dir}/${pfx}XXXXXX\0" */
b95404
   if (tmpl_len < dlen + 1 + plen + 6 + 1)
b95404
@@ -163,39 +165,91 @@ __path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx,
b95404
 }
b95404
 #endif /* _LIBC */
b95404
 
b95404
+#if _LIBC
b95404
+static int try_tempname_len (char *, int, void *, int (*) (char *, void *),
b95404
+                             size_t);
b95404
+#endif
b95404
+
b95404
+static int
b95404
+try_file (char *tmpl, void *flags)
b95404
+{
b95404
+  int *openflags = flags;
b95404
+  return __open (tmpl,
b95404
+                 (*openflags & ~O_ACCMODE)
b95404
+                 | O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
b95404
+}
b95404
+
b95404
+static int
b95404
+try_dir (char *tmpl, void *flags _GL_UNUSED)
b95404
+{
b95404
+  return __mkdir (tmpl, S_IRUSR | S_IWUSR | S_IXUSR);
b95404
+}
b95404
+
b95404
+static int
b95404
+try_nocreate (char *tmpl, void *flags _GL_UNUSED)
b95404
+{
b95404
+  struct_stat64 st;
b95404
+
b95404
+  if (__lstat64 (tmpl, &st) == 0 || errno == EOVERFLOW)
b95404
+    __set_errno (EEXIST);
b95404
+  return errno == ENOENT ? 0 : -1;
b95404
+}
b95404
+
b95404
 /* These are the characters used in temporary file names.  */
b95404
 static const char letters[] =
b95404
 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
b95404
 
b95404
 /* Generate a temporary file name based on TMPL.  TMPL must match the
b95404
-   rules for mk[s]temp (i.e. end in "XXXXXX", possibly with a suffix).
b95404
+   rules for mk[s]temp (i.e., end in at least X_SUFFIX_LEN "X"s,
b95404
+   possibly with a suffix).
b95404
    The name constructed does not exist at the time of the call to
b95404
-   __gen_tempname.  TMPL is overwritten with the result.
b95404
+   this function.  TMPL is overwritten with the result.
b95404
 
b95404
    KIND may be one of:
b95404
-   __GT_NOCREATE:	simply verify that the name does not exist
b95404
-			at the time of the call.
b95404
-   __GT_FILE:		create the file using open(O_CREAT|O_EXCL)
b95404
-			and return a read-write fd.  The file is mode 0600.
b95404
-   __GT_DIR:		create a directory, which will be mode 0700.
b95404
+   __GT_NOCREATE:       simply verify that the name does not exist
b95404
+                        at the time of the call.
b95404
+   __GT_FILE:           create the file using open(O_CREAT|O_EXCL)
b95404
+                        and return a read-write fd.  The file is mode 0600.
b95404
+   __GT_DIR:            create a directory, which will be mode 0700.
b95404
 
b95404
    We use a clever algorithm to get hard-to-predict names. */
b95404
+#ifdef _LIBC
b95404
+static
b95404
+#endif
b95404
 int
b95404
-__gen_tempname (char *tmpl, int suffixlen, int flags, int kind)
b95404
+gen_tempname_len (char *tmpl, int suffixlen, int flags, int kind,
b95404
+                  size_t x_suffix_len)
b95404
 {
b95404
-  int len;
b95404
+  static int (*const tryfunc[]) (char *, void *) =
b95404
+    {
b95404
+      [__GT_FILE] = try_file,
b95404
+      [__GT_DIR] = try_dir,
b95404
+      [__GT_NOCREATE] = try_nocreate
b95404
+    };
b95404
+  return try_tempname_len (tmpl, suffixlen, &flags, tryfunc[kind],
b95404
+                           x_suffix_len);
b95404
+}
b95404
+
b95404
+#ifdef _LIBC
b95404
+static
b95404
+#endif
b95404
+int
b95404
+try_tempname_len (char *tmpl, int suffixlen, void *args,
b95404
+                  int (*tryfunc) (char *, void *), size_t x_suffix_len)
b95404
+{
b95404
+  size_t len;
b95404
   char *XXXXXX;
b95404
   unsigned int count;
b95404
   int fd = -1;
b95404
   int save_errno = errno;
b95404
-  struct_stat64 st;
b95404
 
b95404
   /* A lower bound on the number of temporary files to attempt to
b95404
      generate.  The maximum total number of temporary file names that
b95404
      can exist for a given template is 62**6.  It should never be
b95404
      necessary to try all of these combinations.  Instead if a reasonable
b95404
      number of names is tried (we define reasonable as 62**3) fail to
b95404
-     give the system administrator the chance to remove the problems.  */
b95404
+     give the system administrator the chance to remove the problems.
b95404
+     This value requires that X_SUFFIX_LEN be at least 3.  */
b95404
 #define ATTEMPTS_MIN (62 * 62 * 62)
b95404
 
b95404
   /* The number of times to attempt to generate a temporary file.  To
b95404
@@ -206,82 +260,75 @@ __gen_tempname (char *tmpl, int suffixlen, int flags, int kind)
b95404
   unsigned int attempts = ATTEMPTS_MIN;
b95404
 #endif
b95404
 
b95404
+  /* A random variable.  The initial value is used only the for fallback path
b95404
+     on 'random_bits' on 'getrandom' failure.  Its initial value tries to use
b95404
+     some entropy from the ASLR and ignore possible bits from the stack
b95404
+     alignment.  */
b95404
+  random_value v = ((uintptr_t) &v) / alignof (max_align_t);
b95404
+
b95404
+  /* How many random base-62 digits can currently be extracted from V.  */
b95404
+  int vdigits = 0;
b95404
+
b95404
+  /* Least unfair value for V.  If V is less than this, V can generate
b95404
+     BASE_62_DIGITS digits fairly.  Otherwise it might be biased.  */
b95404
+  random_value const unfair_min
b95404
+    = RANDOM_VALUE_MAX - RANDOM_VALUE_MAX % BASE_62_POWER;
b95404
+
b95404
   len = strlen (tmpl);
b95404
-  if (len < 6 + suffixlen || memcmp (&tmpl[len - 6 - suffixlen], "XXXXXX", 6))
b95404
+  if (len < x_suffix_len + suffixlen
b95404
+      || strspn (&tmpl[len - x_suffix_len - suffixlen], "X") < x_suffix_len)
b95404
     {
b95404
       __set_errno (EINVAL);
b95404
       return -1;
b95404
     }
b95404
 
b95404
   /* This is where the Xs start.  */
b95404
-  XXXXXX = &tmpl[len - 6 - suffixlen];
b95404
+  XXXXXX = &tmpl[len - x_suffix_len - suffixlen];
b95404
 
b95404
-  uint64_t pid = (uint64_t) __getpid () << 32;
b95404
   for (count = 0; count < attempts; ++count)
b95404
     {
b95404
-      uint64_t v;
b95404
-      /* Get some more or less random data.  */
b95404
-      RANDOM_BITS (v);
b95404
-      v ^= pid;
b95404
-
b95404
-      /* Fill in the random bits.  */
b95404
-      XXXXXX[0] = letters[v % 62];
b95404
-      v /= 62;
b95404
-      XXXXXX[1] = letters[v % 62];
b95404
-      v /= 62;
b95404
-      XXXXXX[2] = letters[v % 62];
b95404
-      v /= 62;
b95404
-      XXXXXX[3] = letters[v % 62];
b95404
-      v /= 62;
b95404
-      XXXXXX[4] = letters[v % 62];
b95404
-      v /= 62;
b95404
-      XXXXXX[5] = letters[v % 62];
b95404
-
b95404
-      switch (kind)
b95404
-	{
b95404
-	case __GT_FILE:
b95404
-	  fd = __open (tmpl,
b95404
-		       (flags & ~O_ACCMODE)
b95404
-		       | O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
b95404
-	  break;
b95404
-
b95404
-	case __GT_DIR:
b95404
-	  fd = __mkdir (tmpl, S_IRUSR | S_IWUSR | S_IXUSR);
b95404
-	  break;
b95404
-
b95404
-	case __GT_NOCREATE:
b95404
-	  /* This case is backward from the other three.  __gen_tempname
b95404
-	     succeeds if lstat fails because the name does not exist.
b95404
-	     Note the continue to bypass the common logic at the bottom
b95404
-	     of the loop.  */
b95404
-	  if (__lstat64 (tmpl, &st) < 0)
b95404
-	    {
b95404
-	      if (errno == ENOENT)
b95404
-		{
b95404
-		  __set_errno (save_errno);
b95404
-		  return 0;
b95404
-		}
b95404
-	      else
b95404
-		/* Give up now. */
b95404
-		return -1;
b95404
-	    }
b95404
-	  continue;
b95404
-
b95404
-	default:
b95404
-	  assert (! "invalid KIND in __gen_tempname");
b95404
-	  abort ();
b95404
-	}
b95404
-
b95404
+      for (size_t i = 0; i < x_suffix_len; i++)
b95404
+        {
b95404
+          if (vdigits == 0)
b95404
+            {
b95404
+              do
b95404
+                v = random_bits (v);
b95404
+              while (unfair_min <= v);
b95404
+
b95404
+              vdigits = BASE_62_DIGITS;
b95404
+            }
b95404
+
b95404
+          XXXXXX[i] = letters[v % 62];
b95404
+          v /= 62;
b95404
+          vdigits--;
b95404
+        }
b95404
+
b95404
+      fd = tryfunc (tmpl, args);
b95404
       if (fd >= 0)
b95404
-	{
b95404
-	  __set_errno (save_errno);
b95404
-	  return fd;
b95404
-	}
b95404
+        {
b95404
+          __set_errno (save_errno);
b95404
+          return fd;
b95404
+        }
b95404
       else if (errno != EEXIST)
b95404
-	return -1;
b95404
+        return -1;
b95404
     }
b95404
 
b95404
   /* We got out of the loop because we ran out of combinations to try.  */
b95404
   __set_errno (EEXIST);
b95404
   return -1;
b95404
 }
b95404
+
b95404
+int
b95404
+__gen_tempname (char *tmpl, int suffixlen, int flags, int kind)
b95404
+{
b95404
+  return gen_tempname_len (tmpl, suffixlen, flags, kind, 6);
b95404
+}
b95404
+
b95404
+#if !_LIBC
b95404
+int
b95404
+try_tempname (char *tmpl, int suffixlen, void *args,
b95404
+              int (*tryfunc) (char *, void *))
b95404
+{
b95404
+  return try_tempname_len (tmpl, suffixlen, args, tryfunc, 6);
b95404
+}
b95404
+#endif