Back to index

glibc  2.9
tempname.c
Go to the documentation of this file.
00001 /* Copyright (C) 1991-2001, 2006, 2007 Free Software Foundation, Inc.
00002    This file is part of the GNU C Library.
00003 
00004    The GNU C Library is free software; you can redistribute it and/or
00005    modify it under the terms of the GNU Lesser General Public
00006    License as published by the Free Software Foundation; either
00007    version 2.1 of the License, or (at your option) any later version.
00008 
00009    The GNU C Library is distributed in the hope that it will be useful,
00010    but WITHOUT ANY WARRANTY; without even the implied warranty of
00011    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012    Lesser General Public License for more details.
00013 
00014    You should have received a copy of the GNU Lesser General Public
00015    License along with the GNU C Library; if not, write to the Free
00016    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00017    02111-1307 USA.  */
00018 
00019 #if HAVE_CONFIG_H
00020 # include <config.h>
00021 #endif
00022 
00023 #include <sys/types.h>
00024 #include <assert.h>
00025 
00026 #include <errno.h>
00027 #ifndef __set_errno
00028 # define __set_errno(Val) errno = (Val)
00029 #endif
00030 
00031 #include <stdio.h>
00032 #ifndef P_tmpdir
00033 # define P_tmpdir "/tmp"
00034 #endif
00035 #ifndef TMP_MAX
00036 # define TMP_MAX 238328
00037 #endif
00038 #ifndef __GT_FILE
00039 # define __GT_FILE   0
00040 # define __GT_DIR    1
00041 # define __GT_NOCREATE      2
00042 #endif
00043 
00044 #if STDC_HEADERS || _LIBC
00045 # include <stddef.h>
00046 # include <stdlib.h>
00047 # include <string.h>
00048 #endif
00049 
00050 #if HAVE_FCNTL_H || _LIBC
00051 # include <fcntl.h>
00052 #endif
00053 
00054 #if HAVE_SYS_TIME_H || _LIBC
00055 # include <sys/time.h>
00056 #endif
00057 
00058 #if HAVE_STDINT_H || _LIBC
00059 # include <stdint.h>
00060 #endif
00061 
00062 #if HAVE_UNISTD_H || _LIBC
00063 # include <unistd.h>
00064 #endif
00065 
00066 #include <sys/stat.h>
00067 #if STAT_MACROS_BROKEN
00068 # undef S_ISDIR
00069 #endif
00070 #if !defined S_ISDIR && defined S_IFDIR
00071 # define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
00072 #endif
00073 #if !S_IRUSR && S_IREAD
00074 # define S_IRUSR S_IREAD
00075 #endif
00076 #if !S_IRUSR
00077 # define S_IRUSR 00400
00078 #endif
00079 #if !S_IWUSR && S_IWRITE
00080 # define S_IWUSR S_IWRITE
00081 #endif
00082 #if !S_IWUSR
00083 # define S_IWUSR 00200
00084 #endif
00085 #if !S_IXUSR && S_IEXEC
00086 # define S_IXUSR S_IEXEC
00087 #endif
00088 #if !S_IXUSR
00089 # define S_IXUSR 00100
00090 #endif
00091 
00092 #if _LIBC
00093 # define struct_stat64 struct stat64
00094 #else
00095 # define struct_stat64 struct stat
00096 # define __getpid getpid
00097 # define __gettimeofday gettimeofday
00098 # define __mkdir mkdir
00099 # define __open open
00100 # define __open64 open
00101 # define __lxstat64(version, path, buf) lstat (path, buf)
00102 # define __xstat64(version, path, buf) stat (path, buf)
00103 #endif
00104 
00105 #if ! (HAVE___SECURE_GETENV || _LIBC)
00106 # define __secure_getenv getenv
00107 #endif
00108 
00109 #ifdef _LIBC
00110 # include <hp-timing.h>
00111 # if HP_TIMING_AVAIL
00112 #  define RANDOM_BITS(Var) \
00113   if (__builtin_expect (value == UINT64_C (0), 0))                          \
00114     {                                                                \
00115       /* If this is the first time this function is used initialize         \
00116         the variable we accumulate the value in to some somewhat            \
00117         random value.  If we'd not do this programs at startup time         \
00118         might have a reduced set of possible names, at least on slow        \
00119         machines.  */                                                       \
00120       struct timeval tv;                                             \
00121       __gettimeofday (&tv, NULL);                                    \
00122       value = ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec;                    \
00123     }                                                                \
00124   HP_TIMING_NOW (Var)
00125 # endif
00126 #endif
00127 
00128 /* Use the widest available unsigned type if uint64_t is not
00129    available.  The algorithm below extracts a number less than 62**6
00130    (approximately 2**35.725) from uint64_t, so ancient hosts where
00131    uintmax_t is only 32 bits lose about 3.725 bits of randomness,
00132    which is better than not having mkstemp at all.  */
00133 #if !defined UINT64_MAX && !defined uint64_t
00134 # define uint64_t uintmax_t
00135 #endif
00136 
00137 /* Return nonzero if DIR is an existent directory.  */
00138 static int
00139 direxists (const char *dir)
00140 {
00141   struct_stat64 buf;
00142   return __xstat64 (_STAT_VER, dir, &buf) == 0 && S_ISDIR (buf.st_mode);
00143 }
00144 
00145 /* Path search algorithm, for tmpnam, tmpfile, etc.  If DIR is
00146    non-null and exists, uses it; otherwise uses the first of $TMPDIR,
00147    P_tmpdir, /tmp that exists.  Copies into TMPL a template suitable
00148    for use with mk[s]temp.  Will fail (-1) if DIR is non-null and
00149    doesn't exist, none of the searched dirs exists, or there's not
00150    enough space in TMPL. */
00151 int
00152 __path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx,
00153               int try_tmpdir)
00154 {
00155   const char *d;
00156   size_t dlen, plen;
00157 
00158   if (!pfx || !pfx[0])
00159     {
00160       pfx = "file";
00161       plen = 4;
00162     }
00163   else
00164     {
00165       plen = strlen (pfx);
00166       if (plen > 5)
00167        plen = 5;
00168     }
00169 
00170   if (try_tmpdir)
00171     {
00172       d = __secure_getenv ("TMPDIR");
00173       if (d != NULL && direxists (d))
00174        dir = d;
00175       else if (dir != NULL && direxists (dir))
00176        /* nothing */ ;
00177       else
00178        dir = NULL;
00179     }
00180   if (dir == NULL)
00181     {
00182       if (direxists (P_tmpdir))
00183        dir = P_tmpdir;
00184       else if (strcmp (P_tmpdir, "/tmp") != 0 && direxists ("/tmp"))
00185        dir = "/tmp";
00186       else
00187        {
00188          __set_errno (ENOENT);
00189          return -1;
00190        }
00191     }
00192 
00193   dlen = strlen (dir);
00194   while (dlen > 1 && dir[dlen - 1] == '/')
00195     dlen--;                 /* remove trailing slashes */
00196 
00197   /* check we have room for "${dir}/${pfx}XXXXXX\0" */
00198   if (tmpl_len < dlen + 1 + plen + 6 + 1)
00199     {
00200       __set_errno (EINVAL);
00201       return -1;
00202     }
00203 
00204   sprintf (tmpl, "%.*s/%.*sXXXXXX", (int) dlen, dir, (int) plen, pfx);
00205   return 0;
00206 }
00207 
00208 /* These are the characters used in temporary filenames.  */
00209 static const char letters[] =
00210 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
00211 
00212 /* Generate a temporary file name based on TMPL.  TMPL must match the
00213    rules for mk[s]temp (i.e. end in "XXXXXX").  The name constructed
00214    does not exist at the time of the call to __gen_tempname.  TMPL is
00215    overwritten with the result.
00216 
00217    KIND may be one of:
00218    __GT_NOCREATE:    simply verify that the name does not exist
00219                      at the time of the call.
00220    __GT_FILE:        create the file using open(O_CREAT|O_EXCL)
00221                      and return a read-write fd.  The file is mode 0600.
00222    __GT_DIR:         create a directory, which will be mode 0700.
00223 
00224    We use a clever algorithm to get hard-to-predict names. */
00225 int
00226 __gen_tempname (char *tmpl, int flags, int kind)
00227 {
00228   int len;
00229   char *XXXXXX;
00230   static uint64_t value;
00231   uint64_t random_time_bits;
00232   unsigned int count;
00233   int fd = -1;
00234   int save_errno = errno;
00235   struct_stat64 st;
00236 
00237   /* A lower bound on the number of temporary files to attempt to
00238      generate.  The maximum total number of temporary file names that
00239      can exist for a given template is 62**6.  It should never be
00240      necessary to try all these combinations.  Instead if a reasonable
00241      number of names is tried (we define reasonable as 62**3) fail to
00242      give the system administrator the chance to remove the problems.  */
00243 #define ATTEMPTS_MIN (62 * 62 * 62)
00244 
00245   /* The number of times to attempt to generate a temporary file.  To
00246      conform to POSIX, this must be no smaller than TMP_MAX.  */
00247 #if ATTEMPTS_MIN < TMP_MAX
00248   unsigned int attempts = TMP_MAX;
00249 #else
00250   unsigned int attempts = ATTEMPTS_MIN;
00251 #endif
00252 
00253   len = strlen (tmpl);
00254   if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
00255     {
00256       __set_errno (EINVAL);
00257       return -1;
00258     }
00259 
00260   /* This is where the Xs start.  */
00261   XXXXXX = &tmpl[len - 6];
00262 
00263   /* Get some more or less random data.  */
00264 #ifdef RANDOM_BITS
00265   RANDOM_BITS (random_time_bits);
00266 #else
00267 # if HAVE_GETTIMEOFDAY || _LIBC
00268   {
00269     struct timeval tv;
00270     __gettimeofday (&tv, NULL);
00271     random_time_bits = ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec;
00272   }
00273 # else
00274   random_time_bits = time (NULL);
00275 # endif
00276 #endif
00277   value += random_time_bits ^ __getpid ();
00278 
00279   for (count = 0; count < attempts; value += 7777, ++count)
00280     {
00281       uint64_t v = value;
00282 
00283       /* Fill in the random bits.  */
00284       XXXXXX[0] = letters[v % 62];
00285       v /= 62;
00286       XXXXXX[1] = letters[v % 62];
00287       v /= 62;
00288       XXXXXX[2] = letters[v % 62];
00289       v /= 62;
00290       XXXXXX[3] = letters[v % 62];
00291       v /= 62;
00292       XXXXXX[4] = letters[v % 62];
00293       v /= 62;
00294       XXXXXX[5] = letters[v % 62];
00295 
00296       switch (kind)
00297        {
00298        case __GT_FILE:
00299          fd = __open (tmpl,
00300                      (flags & ~O_ACCMODE)
00301                      | O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
00302          break;
00303 
00304        case __GT_DIR:
00305          fd = __mkdir (tmpl, S_IRUSR | S_IWUSR | S_IXUSR);
00306          break;
00307 
00308        case __GT_NOCREATE:
00309          /* This case is backward from the other three.  __gen_tempname
00310             succeeds if __xstat fails because the name does not exist.
00311             Note the continue to bypass the common logic at the bottom
00312             of the loop.  */
00313          if (__lxstat64 (_STAT_VER, tmpl, &st) < 0)
00314            {
00315              if (errno == ENOENT)
00316               {
00317                 __set_errno (save_errno);
00318                 return 0;
00319               }
00320              else
00321               /* Give up now. */
00322               return -1;
00323            }
00324          continue;
00325 
00326        default:
00327          assert (! "invalid KIND in __gen_tempname");
00328        }
00329 
00330       if (fd >= 0)
00331        {
00332          __set_errno (save_errno);
00333          return fd;
00334        }
00335       else if (errno != EEXIST)
00336        return -1;
00337     }
00338 
00339   /* We got out of the loop because we ran out of combinations to try.  */
00340   __set_errno (EEXIST);
00341   return -1;
00342 }