Add ChangeLog ...
[glibc.git] / sysdeps / posix / tempname.c
bloba98f1d6e9b08c345b653c1906951ce6152569ff8
1 /* Copyright (C) 1991-2001, 2006, 2007, 2009 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
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 Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, see
16 <http://www.gnu.org/licenses/>. */
18 #if HAVE_CONFIG_H
19 # include <config.h>
20 #endif
22 #include <sys/types.h>
23 #include <assert.h>
25 #include <errno.h>
26 #ifndef __set_errno
27 # define __set_errno(Val) errno = (Val)
28 #endif
30 #include <stdio.h>
31 #ifndef P_tmpdir
32 # define P_tmpdir "/tmp"
33 #endif
34 #ifndef TMP_MAX
35 # define TMP_MAX 238328
36 #endif
37 #ifndef __GT_FILE
38 # define __GT_FILE 0
39 # define __GT_DIR 1
40 # define __GT_NOCREATE 2
41 #endif
43 #if STDC_HEADERS || _LIBC
44 # include <stddef.h>
45 # include <stdlib.h>
46 # include <string.h>
47 #endif
49 #if HAVE_FCNTL_H || _LIBC
50 # include <fcntl.h>
51 #endif
53 #if HAVE_SYS_TIME_H || _LIBC
54 # include <sys/time.h>
55 #endif
57 #if HAVE_STDINT_H || _LIBC
58 # include <stdint.h>
59 #endif
61 #if HAVE_UNISTD_H || _LIBC
62 # include <unistd.h>
63 #endif
65 #include <sys/stat.h>
66 #if STAT_MACROS_BROKEN
67 # undef S_ISDIR
68 #endif
69 #if !defined S_ISDIR && defined S_IFDIR
70 # define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
71 #endif
72 #if !S_IRUSR && S_IREAD
73 # define S_IRUSR S_IREAD
74 #endif
75 #if !S_IRUSR
76 # define S_IRUSR 00400
77 #endif
78 #if !S_IWUSR && S_IWRITE
79 # define S_IWUSR S_IWRITE
80 #endif
81 #if !S_IWUSR
82 # define S_IWUSR 00200
83 #endif
84 #if !S_IXUSR && S_IEXEC
85 # define S_IXUSR S_IEXEC
86 #endif
87 #if !S_IXUSR
88 # define S_IXUSR 00100
89 #endif
91 #if _LIBC
92 # define struct_stat64 struct stat64
93 #else
94 # define struct_stat64 struct stat
95 # define __getpid getpid
96 # define __gettimeofday gettimeofday
97 # define __mkdir mkdir
98 # define __open open
99 # define __open64 open
100 # define __lxstat64(version, path, buf) lstat (path, buf)
101 # define __xstat64(version, path, buf) stat (path, buf)
102 #endif
104 #if ! (HAVE___SECURE_GETENV || _LIBC)
105 # define __secure_getenv getenv
106 #endif
108 #ifdef _LIBC
109 # include <hp-timing.h>
110 # if HP_TIMING_AVAIL
111 # define RANDOM_BITS(Var) \
112 if (__builtin_expect (value == UINT64_C (0), 0)) \
114 /* If this is the first time this function is used initialize \
115 the variable we accumulate the value in to some somewhat \
116 random value. If we'd not do this programs at startup time \
117 might have a reduced set of possible names, at least on slow \
118 machines. */ \
119 struct timeval tv; \
120 __gettimeofday (&tv, NULL); \
121 value = ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec; \
123 HP_TIMING_NOW (Var)
124 # endif
125 #endif
127 /* Use the widest available unsigned type if uint64_t is not
128 available. The algorithm below extracts a number less than 62**6
129 (approximately 2**35.725) from uint64_t, so ancient hosts where
130 uintmax_t is only 32 bits lose about 3.725 bits of randomness,
131 which is better than not having mkstemp at all. */
132 #if !defined UINT64_MAX && !defined uint64_t
133 # define uint64_t uintmax_t
134 #endif
136 /* Return nonzero if DIR is an existent directory. */
137 static int
138 direxists (const char *dir)
140 struct_stat64 buf;
141 return __xstat64 (_STAT_VER, dir, &buf) == 0 && S_ISDIR (buf.st_mode);
144 /* Path search algorithm, for tmpnam, tmpfile, etc. If DIR is
145 non-null and exists, uses it; otherwise uses the first of $TMPDIR,
146 P_tmpdir, /tmp that exists. Copies into TMPL a template suitable
147 for use with mk[s]temp. Will fail (-1) if DIR is non-null and
148 doesn't exist, none of the searched dirs exists, or there's not
149 enough space in TMPL. */
151 __path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx,
152 int try_tmpdir)
154 const char *d;
155 size_t dlen, plen;
157 if (!pfx || !pfx[0])
159 pfx = "file";
160 plen = 4;
162 else
164 plen = strlen (pfx);
165 if (plen > 5)
166 plen = 5;
169 if (try_tmpdir)
171 d = __secure_getenv ("TMPDIR");
172 if (d != NULL && direxists (d))
173 dir = d;
174 else if (dir != NULL && direxists (dir))
175 /* nothing */ ;
176 else
177 dir = NULL;
179 if (dir == NULL)
181 if (direxists (P_tmpdir))
182 dir = P_tmpdir;
183 else if (strcmp (P_tmpdir, "/tmp") != 0 && direxists ("/tmp"))
184 dir = "/tmp";
185 else
187 __set_errno (ENOENT);
188 return -1;
192 dlen = strlen (dir);
193 while (dlen > 1 && dir[dlen - 1] == '/')
194 dlen--; /* remove trailing slashes */
196 /* check we have room for "${dir}/${pfx}XXXXXX\0" */
197 if (tmpl_len < dlen + 1 + plen + 6 + 1)
199 __set_errno (EINVAL);
200 return -1;
203 sprintf (tmpl, "%.*s/%.*sXXXXXX", (int) dlen, dir, (int) plen, pfx);
204 return 0;
207 /* These are the characters used in temporary filenames. */
208 static const char letters[] =
209 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
211 /* Generate a temporary file name based on TMPL. TMPL must match the
212 rules for mk[s]temp (i.e. end in "XXXXXX", possibly with a suffix).
213 The name constructed does not exist at the time of the call to
214 __gen_tempname. TMPL is overwritten with the result.
216 KIND may be one of:
217 __GT_NOCREATE: simply verify that the name does not exist
218 at the time of the call.
219 __GT_FILE: create the file using open(O_CREAT|O_EXCL)
220 and return a read-write fd. The file is mode 0600.
221 __GT_DIR: create a directory, which will be mode 0700.
223 We use a clever algorithm to get hard-to-predict names. */
225 __gen_tempname (char *tmpl, int suffixlen, int flags, int kind)
227 int len;
228 char *XXXXXX;
229 static uint64_t value;
230 uint64_t random_time_bits;
231 unsigned int count;
232 int fd = -1;
233 int save_errno = errno;
234 struct_stat64 st;
236 /* A lower bound on the number of temporary files to attempt to
237 generate. The maximum total number of temporary file names that
238 can exist for a given template is 62**6. It should never be
239 necessary to try all these combinations. Instead if a reasonable
240 number of names is tried (we define reasonable as 62**3) fail to
241 give the system administrator the chance to remove the problems. */
242 #define ATTEMPTS_MIN (62 * 62 * 62)
244 /* The number of times to attempt to generate a temporary file. To
245 conform to POSIX, this must be no smaller than TMP_MAX. */
246 #if ATTEMPTS_MIN < TMP_MAX
247 unsigned int attempts = TMP_MAX;
248 #else
249 unsigned int attempts = ATTEMPTS_MIN;
250 #endif
252 len = strlen (tmpl);
253 if (len < 6 + suffixlen || memcmp (&tmpl[len - 6 - suffixlen], "XXXXXX", 6))
255 __set_errno (EINVAL);
256 return -1;
259 /* This is where the Xs start. */
260 XXXXXX = &tmpl[len - 6 - suffixlen];
262 /* Get some more or less random data. */
263 #ifdef RANDOM_BITS
264 RANDOM_BITS (random_time_bits);
265 #else
266 # if HAVE_GETTIMEOFDAY || _LIBC
268 struct timeval tv;
269 __gettimeofday (&tv, NULL);
270 random_time_bits = ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec;
272 # else
273 random_time_bits = time (NULL);
274 # endif
275 #endif
276 value += random_time_bits ^ __getpid ();
278 for (count = 0; count < attempts; value += 7777, ++count)
280 uint64_t v = value;
282 /* Fill in the random bits. */
283 XXXXXX[0] = letters[v % 62];
284 v /= 62;
285 XXXXXX[1] = letters[v % 62];
286 v /= 62;
287 XXXXXX[2] = letters[v % 62];
288 v /= 62;
289 XXXXXX[3] = letters[v % 62];
290 v /= 62;
291 XXXXXX[4] = letters[v % 62];
292 v /= 62;
293 XXXXXX[5] = letters[v % 62];
295 switch (kind)
297 case __GT_FILE:
298 fd = __open (tmpl,
299 (flags & ~O_ACCMODE)
300 | O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
301 break;
303 case __GT_DIR:
304 fd = __mkdir (tmpl, S_IRUSR | S_IWUSR | S_IXUSR);
305 break;
307 case __GT_NOCREATE:
308 /* This case is backward from the other three. __gen_tempname
309 succeeds if __xstat fails because the name does not exist.
310 Note the continue to bypass the common logic at the bottom
311 of the loop. */
312 if (__lxstat64 (_STAT_VER, tmpl, &st) < 0)
314 if (errno == ENOENT)
316 __set_errno (save_errno);
317 return 0;
319 else
320 /* Give up now. */
321 return -1;
323 continue;
325 default:
326 assert (! "invalid KIND in __gen_tempname");
329 if (fd >= 0)
331 __set_errno (save_errno);
332 return fd;
334 else if (errno != EEXIST)
335 return -1;
338 /* We got out of the loop because we ran out of combinations to try. */
339 __set_errno (EEXIST);
340 return -1;