Sync from coreutils.
[gnulib.git] / lib / tempname.c
1 /* tempname.c - generate the name of a temporary file.
2
3    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4    2000, 2001, 2002, 2003, 2005 Free Software Foundation, Inc.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2, or (at your option)
9    any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License along
17    with this program; if not, write to the Free Software Foundation,
18    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
19
20 #if HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
24 #include <sys/types.h>
25 #include <assert.h>
26
27 #include <errno.h>
28 #ifndef __set_errno
29 # define __set_errno(Val) errno = (Val)
30 #endif
31
32 #include <stdio.h>
33 #ifndef P_tmpdir
34 # define P_tmpdir "/tmp"
35 #endif
36 #ifndef TMP_MAX
37 # define TMP_MAX 238328
38 #endif
39 #ifndef __GT_FILE
40 # define __GT_FILE      0
41 # define __GT_BIGFILE   1
42 # define __GT_DIR       2
43 # define __GT_NOCREATE  3
44 #endif
45
46 #include <stddef.h>
47 #include <stdlib.h>
48 #include <string.h>
49
50 #if HAVE_FCNTL_H || _LIBC
51 # include <fcntl.h>
52 #endif
53
54 #if HAVE_SYS_TIME_H || _LIBC
55 # include <sys/time.h>
56 #endif
57
58 #if HAVE_STDINT_H || _LIBC
59 # include <stdint.h>
60 #endif
61 #if HAVE_INTTYPES_H
62 # include <inttypes.h>
63 #endif
64
65 #if HAVE_UNISTD_H || _LIBC
66 # include <unistd.h>
67 #endif
68
69 #include <sys/stat.h>
70
71 #if _LIBC
72 # define struct_stat64 struct stat64
73 #else
74 # include "stat-macros.h"
75 # define struct_stat64 struct stat
76 # define __getpid getpid
77 # define __gettimeofday gettimeofday
78 # define __mkdir mkdir
79 # define __open open
80 # define __open64 open
81 # define __lxstat64(version, file, buf) lstat (file, buf)
82 # define __xstat64(version, file, buf) stat (file, buf)
83 #endif
84
85 #if ! (HAVE___SECURE_GETENV || _LIBC)
86 # define __secure_getenv getenv
87 #endif
88
89 #ifdef _LIBC
90 # include <hp-timing.h>
91 # if HP_TIMING_AVAIL
92 #  define RANDOM_BITS(Var) \
93   if (__builtin_expect (value == UINT64_C (0), 0))                            \
94     {                                                                         \
95       /* If this is the first time this function is used initialize           \
96          the variable we accumulate the value in to some somewhat             \
97          random value.  If we'd not do this programs at startup time          \
98          might have a reduced set of possible names, at least on slow         \
99          machines.  */                                                        \
100       struct timeval tv;                                                      \
101       __gettimeofday (&tv, NULL);                                             \
102       value = ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec;                      \
103     }                                                                         \
104   HP_TIMING_NOW (Var)
105 # endif
106 #endif
107
108 /* Use the widest available unsigned type if uint64_t is not
109    available.  The algorithm below extracts a number less than 62**6
110    (approximately 2**35.725) from uint64_t, so ancient hosts where
111    uintmax_t is only 32 bits lose about 3.725 bits of randomness,
112    which is better than not having mkstemp at all.  */
113 #if !defined UINT64_MAX && !defined uint64_t
114 # define uint64_t uintmax_t
115 #endif
116
117 /* Return nonzero if DIR is an existent directory.  */
118 static int
119 direxists (const char *dir)
120 {
121   struct_stat64 buf;
122   return __xstat64 (_STAT_VER, dir, &buf) == 0 && S_ISDIR (buf.st_mode);
123 }
124
125 /* Path search algorithm, for tmpnam, tmpfile, etc.  If DIR is
126    non-null and exists, uses it; otherwise uses the first of $TMPDIR,
127    P_tmpdir, /tmp that exists.  Copies into TMPL a template suitable
128    for use with mk[s]temp.  Will fail (-1) if DIR is non-null and
129    doesn't exist, none of the searched dirs exists, or there's not
130    enough space in TMPL. */
131 int
132 __path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx,
133                int try_tmpdir)
134 {
135   const char *d;
136   size_t dlen, plen;
137
138   if (!pfx || !pfx[0])
139     {
140       pfx = "file";
141       plen = 4;
142     }
143   else
144     {
145       plen = strlen (pfx);
146       if (plen > 5)
147         plen = 5;
148     }
149
150   if (try_tmpdir)
151     {
152       d = __secure_getenv ("TMPDIR");
153       if (d != NULL && direxists (d))
154         dir = d;
155       else if (dir != NULL && direxists (dir))
156         /* nothing */ ;
157       else
158         dir = NULL;
159     }
160   if (dir == NULL)
161     {
162       if (direxists (P_tmpdir))
163         dir = P_tmpdir;
164       else if (strcmp (P_tmpdir, "/tmp") != 0 && direxists ("/tmp"))
165         dir = "/tmp";
166       else
167         {
168           __set_errno (ENOENT);
169           return -1;
170         }
171     }
172
173   dlen = strlen (dir);
174   while (dlen > 1 && dir[dlen - 1] == '/')
175     dlen--;                     /* remove trailing slashes */
176
177   /* check we have room for "${dir}/${pfx}XXXXXX\0" */
178   if (tmpl_len < dlen + 1 + plen + 6 + 1)
179     {
180       __set_errno (EINVAL);
181       return -1;
182     }
183
184   sprintf (tmpl, "%.*s/%.*sXXXXXX", (int) dlen, dir, (int) plen, pfx);
185   return 0;
186 }
187
188 /* These are the characters used in temporary file names.  */
189 static const char letters[] =
190 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
191
192 /* Generate a temporary file name based on TMPL.  TMPL must match the
193    rules for mk[s]temp (i.e. end in "XXXXXX").  The name constructed
194    does not exist at the time of the call to __gen_tempname.  TMPL is
195    overwritten with the result.
196
197    KIND may be one of:
198    __GT_NOCREATE:       simply verify that the name does not exist
199                         at the time of the call.
200    __GT_FILE:           create the file using open(O_CREAT|O_EXCL)
201                         and return a read-write fd.  The file is mode 0600.
202    __GT_BIGFILE:        same as __GT_FILE but use open64().
203    __GT_DIR:            create a directory, which will be mode 0700.
204
205    We use a clever algorithm to get hard-to-predict names. */
206 int
207 __gen_tempname (char *tmpl, int kind)
208 {
209   int len;
210   char *XXXXXX;
211   static uint64_t value;
212   uint64_t random_time_bits;
213   unsigned int count;
214   int fd = -1;
215   int save_errno = errno;
216   struct_stat64 st;
217
218   /* A lower bound on the number of temporary files to attempt to
219      generate.  The maximum total number of temporary file names that
220      can exist for a given template is 62**6.  It should never be
221      necessary to try all these combinations.  Instead if a reasonable
222      number of names is tried (we define reasonable as 62**3) fail to
223      give the system administrator the chance to remove the problems.  */
224   unsigned int attempts_min = 62 * 62 * 62;
225
226   /* The number of times to attempt to generate a temporary file.  To
227      conform to POSIX, this must be no smaller than TMP_MAX.  */
228   unsigned int attempts = attempts_min < TMP_MAX ? TMP_MAX : attempts_min;
229
230   len = strlen (tmpl);
231   if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
232     {
233       __set_errno (EINVAL);
234       return -1;
235     }
236
237   /* This is where the Xs start.  */
238   XXXXXX = &tmpl[len - 6];
239
240   /* Get some more or less random data.  */
241 #ifdef RANDOM_BITS
242   RANDOM_BITS (random_time_bits);
243 #else
244 # if HAVE_GETTIMEOFDAY || _LIBC
245   {
246     struct timeval tv;
247     __gettimeofday (&tv, NULL);
248     random_time_bits = ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec;
249   }
250 # else
251   random_time_bits = time (NULL);
252 # endif
253 #endif
254   value += random_time_bits ^ __getpid ();
255
256   for (count = 0; count < attempts; value += 7777, ++count)
257     {
258       uint64_t v = value;
259
260       /* Fill in the random bits.  */
261       XXXXXX[0] = letters[v % 62];
262       v /= 62;
263       XXXXXX[1] = letters[v % 62];
264       v /= 62;
265       XXXXXX[2] = letters[v % 62];
266       v /= 62;
267       XXXXXX[3] = letters[v % 62];
268       v /= 62;
269       XXXXXX[4] = letters[v % 62];
270       v /= 62;
271       XXXXXX[5] = letters[v % 62];
272
273       switch (kind)
274         {
275         case __GT_FILE:
276           fd = __open (tmpl, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
277           break;
278
279         case __GT_BIGFILE:
280           fd = __open64 (tmpl, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
281           break;
282
283         case __GT_DIR:
284           fd = __mkdir (tmpl, S_IRUSR | S_IWUSR | S_IXUSR);
285           break;
286
287         case __GT_NOCREATE:
288           /* This case is backward from the other three.  __gen_tempname
289              succeeds if __xstat fails because the name does not exist.
290              Note the continue to bypass the common logic at the bottom
291              of the loop.  */
292           if (__lxstat64 (_STAT_VER, tmpl, &st) < 0)
293             {
294               if (errno == ENOENT)
295                 {
296                   __set_errno (save_errno);
297                   return 0;
298                 }
299               else
300                 /* Give up now. */
301                 return -1;
302             }
303           continue;
304
305         default:
306           assert (! "invalid KIND in __gen_tempname");
307         }
308
309       if (fd >= 0)
310         {
311           __set_errno (save_errno);
312           return fd;
313         }
314       else if (errno != EEXIST)
315         return -1;
316     }
317
318   /* We got out of the loop because we ran out of combinations to try.  */
319   __set_errno (EEXIST);
320   return -1;
321 }