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