Improve documentation of 'gnutls-verify-error'
[emacs.git] / lib / tempname.c
blob83e537a6940111f225a99d20bf602676641a5ad5
1 /* tempname.c - generate the name of a temporary file.
3 Copyright (C) 1991-2003, 2005-2007, 2009-2017 Free Software
4 Foundation, Inc.
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 3 of the License, or
9 (at your option) any later version.
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.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19 /* Extracted from glibc sysdeps/posix/tempname.c. See also tmpdir.c. */
21 #if !_LIBC
22 # include <config.h>
23 # include "tempname.h"
24 #endif
26 #include <sys/types.h>
27 #include <assert.h>
29 #include <errno.h>
30 #ifndef __set_errno
31 # define __set_errno(Val) errno = (Val)
32 #endif
34 #include <stdio.h>
35 #ifndef P_tmpdir
36 # define P_tmpdir "/tmp"
37 #endif
38 #ifndef TMP_MAX
39 # define TMP_MAX 238328
40 #endif
41 #ifndef __GT_FILE
42 # define __GT_FILE 0
43 # define __GT_DIR 1
44 # define __GT_NOCREATE 2
45 #endif
46 #if !_LIBC && (GT_FILE != __GT_FILE || GT_DIR != __GT_DIR \
47 || GT_NOCREATE != __GT_NOCREATE)
48 # error report this to bug-gnulib@gnu.org
49 #endif
51 #include <stddef.h>
52 #include <stdlib.h>
53 #include <string.h>
55 #include <fcntl.h>
56 #include <sys/time.h>
57 #include <stdint.h>
58 #include <unistd.h>
60 #include <sys/stat.h>
62 #if _LIBC
63 # define struct_stat64 struct stat64
64 #else
65 # define struct_stat64 struct stat
66 # define __try_tempname try_tempname
67 # define __gen_tempname gen_tempname
68 # define __getpid getpid
69 # define __gettimeofday gettimeofday
70 # define __mkdir mkdir
71 # define __open open
72 # define __lxstat64(version, file, buf) lstat (file, buf)
73 # define __secure_getenv secure_getenv
74 #endif
76 #ifdef _LIBC
77 # include <hp-timing.h>
78 # if HP_TIMING_AVAIL
79 # define RANDOM_BITS(Var) \
80 if (__builtin_expect (value == UINT64_C (0), 0)) \
81 { \
82 /* If this is the first time this function is used initialize \
83 the variable we accumulate the value in to some somewhat \
84 random value. If we'd not do this programs at startup time \
85 might have a reduced set of possible names, at least on slow \
86 machines. */ \
87 struct timeval tv; \
88 __gettimeofday (&tv, NULL); \
89 value = ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec; \
90 } \
91 HP_TIMING_NOW (Var)
92 # endif
93 #endif
95 /* Use the widest available unsigned type if uint64_t is not
96 available. The algorithm below extracts a number less than 62**6
97 (approximately 2**35.725) from uint64_t, so ancient hosts where
98 uintmax_t is only 32 bits lose about 3.725 bits of randomness,
99 which is better than not having mkstemp at all. */
100 #if !defined UINT64_MAX && !defined uint64_t
101 # define uint64_t uintmax_t
102 #endif
104 #if _LIBC
105 /* Return nonzero if DIR is an existent directory. */
106 static int
107 direxists (const char *dir)
109 struct_stat64 buf;
110 return __xstat64 (_STAT_VER, dir, &buf) == 0 && S_ISDIR (buf.st_mode);
113 /* Path search algorithm, for tmpnam, tmpfile, etc. If DIR is
114 non-null and exists, uses it; otherwise uses the first of $TMPDIR,
115 P_tmpdir, /tmp that exists. Copies into TMPL a template suitable
116 for use with mk[s]temp. Will fail (-1) if DIR is non-null and
117 doesn't exist, none of the searched dirs exists, or there's not
118 enough space in TMPL. */
120 __path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx,
121 int try_tmpdir)
123 const char *d;
124 size_t dlen, plen;
126 if (!pfx || !pfx[0])
128 pfx = "file";
129 plen = 4;
131 else
133 plen = strlen (pfx);
134 if (plen > 5)
135 plen = 5;
138 if (try_tmpdir)
140 d = __secure_getenv ("TMPDIR");
141 if (d != NULL && direxists (d))
142 dir = d;
143 else if (dir != NULL && direxists (dir))
144 /* nothing */ ;
145 else
146 dir = NULL;
148 if (dir == NULL)
150 if (direxists (P_tmpdir))
151 dir = P_tmpdir;
152 else if (strcmp (P_tmpdir, "/tmp") != 0 && direxists ("/tmp"))
153 dir = "/tmp";
154 else
156 __set_errno (ENOENT);
157 return -1;
161 dlen = strlen (dir);
162 while (dlen > 1 && dir[dlen - 1] == '/')
163 dlen--; /* remove trailing slashes */
165 /* check we have room for "${dir}/${pfx}XXXXXX\0" */
166 if (tmpl_len < dlen + 1 + plen + 6 + 1)
168 __set_errno (EINVAL);
169 return -1;
172 sprintf (tmpl, "%.*s/%.*sXXXXXX", (int) dlen, dir, (int) plen, pfx);
173 return 0;
175 #endif /* _LIBC */
177 /* These are the characters used in temporary file names. */
178 static const char letters[] =
179 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
182 __try_tempname (char *tmpl, int suffixlen, void *args,
183 int (*tryfunc) (char *, void *))
185 int len;
186 char *XXXXXX;
187 static uint64_t value;
188 uint64_t random_time_bits;
189 unsigned int count;
190 int fd = -1;
191 int save_errno = errno;
193 /* A lower bound on the number of temporary files to attempt to
194 generate. The maximum total number of temporary file names that
195 can exist for a given template is 62**6. It should never be
196 necessary to try all of these combinations. Instead if a reasonable
197 number of names is tried (we define reasonable as 62**3) fail to
198 give the system administrator the chance to remove the problems. */
199 #define ATTEMPTS_MIN (62 * 62 * 62)
201 /* The number of times to attempt to generate a temporary file. To
202 conform to POSIX, this must be no smaller than TMP_MAX. */
203 #if ATTEMPTS_MIN < TMP_MAX
204 unsigned int attempts = TMP_MAX;
205 #else
206 unsigned int attempts = ATTEMPTS_MIN;
207 #endif
209 len = strlen (tmpl);
210 if (len < 6 + suffixlen || memcmp (&tmpl[len - 6 - suffixlen], "XXXXXX", 6))
212 __set_errno (EINVAL);
213 return -1;
216 /* This is where the Xs start. */
217 XXXXXX = &tmpl[len - 6 - suffixlen];
219 /* Get some more or less random data. */
220 #ifdef RANDOM_BITS
221 RANDOM_BITS (random_time_bits);
222 #else
224 struct timeval tv;
225 __gettimeofday (&tv, NULL);
226 random_time_bits = ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec;
228 #endif
229 value += random_time_bits ^ __getpid ();
231 for (count = 0; count < attempts; value += 7777, ++count)
233 uint64_t v = value;
235 /* Fill in the random bits. */
236 XXXXXX[0] = letters[v % 62];
237 v /= 62;
238 XXXXXX[1] = letters[v % 62];
239 v /= 62;
240 XXXXXX[2] = letters[v % 62];
241 v /= 62;
242 XXXXXX[3] = letters[v % 62];
243 v /= 62;
244 XXXXXX[4] = letters[v % 62];
245 v /= 62;
246 XXXXXX[5] = letters[v % 62];
248 fd = tryfunc (tmpl, args);
249 if (fd >= 0)
251 __set_errno (save_errno);
252 return fd;
254 else if (errno != EEXIST)
255 return -1;
258 /* We got out of the loop because we ran out of combinations to try. */
259 __set_errno (EEXIST);
260 return -1;
263 static int
264 try_file (char *tmpl, void *flags)
266 int *openflags = flags;
267 return __open (tmpl,
268 (*openflags & ~O_ACCMODE)
269 | O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
272 static int
273 try_dir (char *tmpl, void *flags _GL_UNUSED)
275 return __mkdir (tmpl, S_IRUSR | S_IWUSR | S_IXUSR);
278 static int
279 try_nocreate (char *tmpl, void *flags _GL_UNUSED)
281 struct_stat64 st;
283 if (__lxstat64 (_STAT_VER, tmpl, &st) == 0)
284 __set_errno (EEXIST);
285 return errno == ENOENT ? 0 : -1;
288 /* Generate a temporary file name based on TMPL. TMPL must match the
289 rules for mk[s]temp (i.e. end in "XXXXXX", possibly with a suffix).
290 The name constructed does not exist at the time of the call to
291 __gen_tempname. TMPL is overwritten with the result.
293 KIND may be one of:
294 __GT_NOCREATE: simply verify that the name does not exist
295 at the time of the call.
296 __GT_FILE: create the file using open(O_CREAT|O_EXCL)
297 and return a read-write fd. The file is mode 0600.
298 __GT_DIR: create a directory, which will be mode 0700.
300 We use a clever algorithm to get hard-to-predict names. */
302 __gen_tempname (char *tmpl, int suffixlen, int flags, int kind)
304 int (*tryfunc) (char *, void *);
306 switch (kind)
308 case __GT_FILE:
309 tryfunc = try_file;
310 break;
312 case __GT_DIR:
313 tryfunc = try_dir;
314 break;
316 case __GT_NOCREATE:
317 tryfunc = try_nocreate;
318 break;
320 default:
321 assert (! "invalid KIND in __gen_tempname");
322 abort ();
324 return __try_tempname (tmpl, suffixlen, &flags, tryfunc);