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