about summary refs log tree commit diff
path: root/sysdeps/posix/mktemp.c
diff options
context:
space:
mode:
Diffstat (limited to 'sysdeps/posix/mktemp.c')
-rw-r--r--sysdeps/posix/mktemp.c46
1 files changed, 35 insertions, 11 deletions
diff --git a/sysdeps/posix/mktemp.c b/sysdeps/posix/mktemp.c
index f7a1783c8f..6bbc4c0ce9 100644
--- a/sysdeps/posix/mktemp.c
+++ b/sysdeps/posix/mktemp.c
@@ -1,4 +1,4 @@
-/* Copyright (C) 1991, 1992, 1993, 1996 Free Software Foundation, Inc.
+/* Copyright (C) 1991, 1992, 1993, 1996, 1998 Free Software Foundation, Inc.
    This file is part of the GNU C Library.
 
    The GNU C Library is free software; you can redistribute it and/or
@@ -16,13 +16,15 @@
    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.  */
 
+#include <errno.h>
+#include <stdint.h>
+#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <errno.h>
 #include <unistd.h>
-#include <stdio.h>
-#include <sys/types.h>
 #include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/types.h>
 
 /* Generate a unique temporary file name from TEMPLATE.
    The last six characters of TEMPLATE must be "XXXXXX";
@@ -33,8 +35,11 @@ mktemp (template)
 {
   static const char letters[]
     = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+  static uint32_t value;
+  struct timeval tv;
+  char *XXXXXX;
   size_t len;
-  size_t i;
+  int count;
 
   len = strlen (template);
   if (len < 6 || strcmp (&template[len - 6], "XXXXXX"))
@@ -43,20 +48,39 @@ mktemp (template)
       return NULL;
     }
 
-  if (sprintf (&template[len - 5], "%.5u",
-	       (unsigned int) getpid () % 100000) != 5)
-    /* Inconceivable lossage.  */
-    return NULL;
+  /* This is where the Xs start.  */
+  XXXXXX = &template[len - 6];
 
-  for (i = 0; i < sizeof (letters); ++i)
+  /* Get some more or less random data.  */
+  __gettimeofday (&tv, NULL);
+  value += tv.tv_usec | getpid ();
+
+  for (count = 0; count < TMP_MAX; ++count)
     {
       struct stat ignored;
+      uint32_t v = value;
 
-      template[len - 6] = letters[i];
+      /* Fill in the random bits.  */
+      XXXXXX[0] = letters[v % 62];
+      v /= 62;
+      XXXXXX[1] = letters[v % 62];
+      v /= 62;
+      XXXXXX[2] = letters[v % 62];
+      v /= 62;
+      XXXXXX[3] = letters[v % 62];
+      v /= 62;
+      XXXXXX[4] = letters[v % 62];
+      v /= 62;
+      XXXXXX[5] = letters[v % 62];
 
       if (stat (template, &ignored) < 0 && errno == ENOENT)
 	/* The file does not exist.  So return this name.  */
 	return template;
+
+      /* This is a random value.  It is only necessary that the next
+	 TMP_MAX values generated by adding 7777 to VALUE are different
+	 with (module 2^32).  */
+      value += 7777;
     }
 
   /* We return the null string if we can't find a unique file name.  */