Update copyright notices with scripts/update-copyrights
[glibc.git] / sysdeps / posix / tempname.c
blob1f86549df3cd2a4c50abd7e37554edd9d739c5ce
1 /* Copyright (C) 1991-2014 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 # ifdef HAVE___SECURE_GETENV
106 # define __libc_secure_getenv __secure_getenv
107 # else
108 # define __libc_secure_getenv getenv
109 # endif
110 #endif
112 #ifdef _LIBC
113 # include <hp-timing.h>
114 # if HP_TIMING_AVAIL
115 # define RANDOM_BITS(Var) \
116 if (__builtin_expect (value == UINT64_C (0), 0)) \
118 /* If this is the first time this function is used initialize \
119 the variable we accumulate the value in to some somewhat \
120 random value. If we'd not do this programs at startup time \
121 might have a reduced set of possible names, at least on slow \
122 machines. */ \
123 struct timeval tv; \
124 __gettimeofday (&tv, NULL); \
125 value = ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec; \
127 HP_TIMING_NOW (Var)
128 # endif
129 #endif
131 /* Use the widest available unsigned type if uint64_t is not
132 available. The algorithm below extracts a number less than 62**6
133 (approximately 2**35.725) from uint64_t, so ancient hosts where
134 uintmax_t is only 32 bits lose about 3.725 bits of randomness,
135 which is better than not having mkstemp at all. */
136 #if !defined UINT64_MAX && !defined uint64_t
137 # define uint64_t uintmax_t
138 #endif
140 /* Return nonzero if DIR is an existent directory. */
141 static int
142 direxists (const char *dir)
144 struct_stat64 buf;
145 return __xstat64 (_STAT_VER, dir, &buf) == 0 && S_ISDIR (buf.st_mode);
148 /* Path search algorithm, for tmpnam, tmpfile, etc. If DIR is
149 non-null and exists, uses it; otherwise uses the first of $TMPDIR,
150 P_tmpdir, /tmp that exists. Copies into TMPL a template suitable
151 for use with mk[s]temp. Will fail (-1) if DIR is non-null and
152 doesn't exist, none of the searched dirs exists, or there's not
153 enough space in TMPL. */
155 __path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx,
156 int try_tmpdir)
158 const char *d;
159 size_t dlen, plen;
161 if (!pfx || !pfx[0])
163 pfx = "file";
164 plen = 4;
166 else
168 plen = strlen (pfx);
169 if (plen > 5)
170 plen = 5;
173 if (try_tmpdir)
175 d = __libc_secure_getenv ("TMPDIR");
176 if (d != NULL && direxists (d))
177 dir = d;
178 else if (dir != NULL && direxists (dir))
179 /* nothing */ ;
180 else
181 dir = NULL;
183 if (dir == NULL)
185 if (direxists (P_tmpdir))
186 dir = P_tmpdir;
187 else if (strcmp (P_tmpdir, "/tmp") != 0 && direxists ("/tmp"))
188 dir = "/tmp";
189 else
191 __set_errno (ENOENT);
192 return -1;
196 dlen = strlen (dir);
197 while (dlen > 1 && dir[dlen - 1] == '/')
198 dlen--; /* remove trailing slashes */
200 /* check we have room for "${dir}/${pfx}XXXXXX\0" */
201 if (tmpl_len < dlen + 1 + plen + 6 + 1)
203 __set_errno (EINVAL);
204 return -1;
207 sprintf (tmpl, "%.*s/%.*sXXXXXX", (int) dlen, dir, (int) plen, pfx);
208 return 0;
211 /* These are the characters used in temporary filenames. */
212 static const char letters[] =
213 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
215 /* Generate a temporary file name based on TMPL. TMPL must match the
216 rules for mk[s]temp (i.e. end in "XXXXXX", possibly with a suffix).
217 The name constructed does not exist at the time of the call to
218 __gen_tempname. TMPL is overwritten with the result.
220 KIND may be one of:
221 __GT_NOCREATE: simply verify that the name does not exist
222 at the time of the call.
223 __GT_FILE: create the file using open(O_CREAT|O_EXCL)
224 and return a read-write fd. The file is mode 0600.
225 __GT_DIR: create a directory, which will be mode 0700.
227 We use a clever algorithm to get hard-to-predict names. */
229 __gen_tempname (char *tmpl, int suffixlen, int flags, int kind)
231 int len;
232 char *XXXXXX;
233 static uint64_t value;
234 uint64_t random_time_bits;
235 unsigned int count;
236 int fd = -1;
237 int save_errno = errno;
238 struct_stat64 st;
240 /* A lower bound on the number of temporary files to attempt to
241 generate. The maximum total number of temporary file names that
242 can exist for a given template is 62**6. It should never be
243 necessary to try all these combinations. Instead if a reasonable
244 number of names is tried (we define reasonable as 62**3) fail to
245 give the system administrator the chance to remove the problems. */
246 #define ATTEMPTS_MIN (62 * 62 * 62)
248 /* The number of times to attempt to generate a temporary file. To
249 conform to POSIX, this must be no smaller than TMP_MAX. */
250 #if ATTEMPTS_MIN < TMP_MAX
251 unsigned int attempts = TMP_MAX;
252 #else
253 unsigned int attempts = ATTEMPTS_MIN;
254 #endif
256 len = strlen (tmpl);
257 if (len < 6 + suffixlen || memcmp (&tmpl[len - 6 - suffixlen], "XXXXXX", 6))
259 __set_errno (EINVAL);
260 return -1;
263 /* This is where the Xs start. */
264 XXXXXX = &tmpl[len - 6 - suffixlen];
266 /* Get some more or less random data. */
267 #ifdef RANDOM_BITS
268 RANDOM_BITS (random_time_bits);
269 #else
270 # if HAVE_GETTIMEOFDAY || _LIBC
272 struct timeval tv;
273 __gettimeofday (&tv, NULL);
274 random_time_bits = ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec;
276 # else
277 random_time_bits = time (NULL);
278 # endif
279 #endif
280 value += random_time_bits ^ __getpid ();
282 for (count = 0; count < attempts; value += 7777, ++count)
284 uint64_t v = value;
286 /* Fill in the random bits. */
287 XXXXXX[0] = letters[v % 62];
288 v /= 62;
289 XXXXXX[1] = letters[v % 62];
290 v /= 62;
291 XXXXXX[2] = letters[v % 62];
292 v /= 62;
293 XXXXXX[3] = letters[v % 62];
294 v /= 62;
295 XXXXXX[4] = letters[v % 62];
296 v /= 62;
297 XXXXXX[5] = letters[v % 62];
299 switch (kind)
301 case __GT_FILE:
302 fd = __open (tmpl,
303 (flags & ~O_ACCMODE)
304 | O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
305 break;
307 case __GT_DIR:
308 fd = __mkdir (tmpl, S_IRUSR | S_IWUSR | S_IXUSR);
309 break;
311 case __GT_NOCREATE:
312 /* This case is backward from the other three. __gen_tempname
313 succeeds if __xstat fails because the name does not exist.
314 Note the continue to bypass the common logic at the bottom
315 of the loop. */
316 if (__lxstat64 (_STAT_VER, tmpl, &st) < 0)
318 if (errno == ENOENT)
320 __set_errno (save_errno);
321 return 0;
323 else
324 /* Give up now. */
325 return -1;
327 continue;
329 default:
330 assert (! "invalid KIND in __gen_tempname");
333 if (fd >= 0)
335 __set_errno (save_errno);
336 return fd;
338 else if (errno != EEXIST)
339 return -1;
342 /* We got out of the loop because we ran out of combinations to try. */
343 __set_errno (EEXIST);
344 return -1;