1 /* Copyright (C) 1991-2021 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 General Public
6 License as published by the Free Software Foundation; either
7 version 3 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 General Public License for more details.
14 You should have received a copy of the GNU General Public
15 License along with the GNU C Library; if not, see
16 <https://www.gnu.org/licenses/>. */
19 # include <libc-config.h>
20 # include "tempname.h"
23 #include <sys/types.h>
31 # define P_tmpdir "/tmp"
34 # define TMP_MAX 238328
39 # define __GT_NOCREATE 2
41 #if !_LIBC && (GT_FILE != __GT_FILE || GT_DIR != __GT_DIR \
42 || GT_NOCREATE != __GT_NOCREATE)
43 # error report this to bug-gnulib@gnu.org
53 #include <sys/random.h>
58 # define struct_stat64 struct stat64
59 # define __secure_getenv __libc_secure_getenv
61 # define struct_stat64 struct stat
62 # define __gen_tempname gen_tempname
63 # define __mkdir mkdir
65 # define __lstat64(file, buf) lstat (file, buf)
66 # define __stat64(file, buf) stat (file, buf)
67 # define __getrandom getrandom
68 # define __clock_gettime64 clock_gettime
69 # define __timespec64 timespec
72 /* Use getrandom if it works, falling back on a 64-bit linear
73 congruential generator that starts with Var's value
74 mixed in with a clock's low-order bits if available. */
75 typedef uint_fast64_t random_value;
76 #define RANDOM_VALUE_MAX UINT_FAST64_MAX
77 #define BASE_62_DIGITS 10 /* 62**10 < UINT_FAST64_MAX */
78 #define BASE_62_POWER (62LL * 62 * 62 * 62 * 62 * 62 * 62 * 62 * 62 * 62)
81 random_bits (random_value var, bool use_getrandom)
84 /* Without GRND_NONBLOCK it can be blocked for minutes on some systems. */
85 if (use_getrandom && __getrandom (&r, sizeof r, GRND_NONBLOCK) == sizeof r)
87 #if _LIBC || (defined CLOCK_MONOTONIC && HAVE_CLOCK_GETTIME)
88 /* Add entropy if getrandom did not work. */
89 struct __timespec64 tv;
90 __clock_gettime64 (CLOCK_MONOTONIC, &tv);
93 return 2862933555777941757 * var + 3037000493;
97 /* Return nonzero if DIR is an existent directory. */
99 direxists (const char *dir)
102 return __stat64 (dir, &buf) == 0 && S_ISDIR (buf.st_mode);
105 /* Path search algorithm, for tmpnam, tmpfile, etc. If DIR is
106 non-null and exists, uses it; otherwise uses the first of $TMPDIR,
107 P_tmpdir, /tmp that exists. Copies into TMPL a template suitable
108 for use with mk[s]temp. Will fail (-1) if DIR is non-null and
109 doesn't exist, none of the searched dirs exists, or there's not
110 enough space in TMPL. */
112 __path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx,
132 d = __secure_getenv ("TMPDIR");
133 if (d != NULL && direxists (d))
135 else if (dir != NULL && direxists (dir))
142 if (direxists (P_tmpdir))
144 else if (strcmp (P_tmpdir, "/tmp") != 0 && direxists ("/tmp"))
148 __set_errno (ENOENT);
154 while (dlen > 1 && dir[dlen - 1] == '/')
155 dlen--; /* remove trailing slashes */
157 /* check we have room for "${dir}/${pfx}XXXXXX\0" */
158 if (tmpl_len < dlen + 1 + plen + 6 + 1)
160 __set_errno (EINVAL);
164 sprintf (tmpl, "%.*s/%.*sXXXXXX", (int) dlen, dir, (int) plen, pfx);
170 static int try_tempname_len (char *, int, void *, int (*) (char *, void *),
175 try_file (char *tmpl, void *flags)
177 int *openflags = flags;
179 (*openflags & ~O_ACCMODE)
180 | O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
184 try_dir (char *tmpl, void *flags _GL_UNUSED)
186 return __mkdir (tmpl, S_IRUSR | S_IWUSR | S_IXUSR);
190 try_nocreate (char *tmpl, void *flags _GL_UNUSED)
194 if (__lstat64 (tmpl, &st) == 0 || errno == EOVERFLOW)
195 __set_errno (EEXIST);
196 return errno == ENOENT ? 0 : -1;
199 /* These are the characters used in temporary file names. */
200 static const char letters[] =
201 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
203 /* Generate a temporary file name based on TMPL. TMPL must match the
204 rules for mk[s]temp (i.e., end in at least X_SUFFIX_LEN "X"s,
205 possibly with a suffix).
206 The name constructed does not exist at the time of the call to
207 this function. TMPL is overwritten with the result.
210 __GT_NOCREATE: simply verify that the name does not exist
211 at the time of the call.
212 __GT_FILE: create the file using open(O_CREAT|O_EXCL)
213 and return a read-write fd. The file is mode 0600.
214 __GT_DIR: create a directory, which will be mode 0700.
216 We use a clever algorithm to get hard-to-predict names. */
221 gen_tempname_len (char *tmpl, int suffixlen, int flags, int kind,
224 static int (*const tryfunc[]) (char *, void *) =
226 [__GT_FILE] = try_file,
227 [__GT_DIR] = try_dir,
228 [__GT_NOCREATE] = try_nocreate
230 return try_tempname_len (tmpl, suffixlen, &flags, tryfunc[kind],
238 try_tempname_len (char *tmpl, int suffixlen, void *args,
239 int (*tryfunc) (char *, void *), size_t x_suffix_len)
245 int save_errno = errno;
247 /* A lower bound on the number of temporary files to attempt to
248 generate. The maximum total number of temporary file names that
249 can exist for a given template is 62**6. It should never be
250 necessary to try all of these combinations. Instead if a reasonable
251 number of names is tried (we define reasonable as 62**3) fail to
252 give the system administrator the chance to remove the problems.
253 This value requires that X_SUFFIX_LEN be at least 3. */
254 #define ATTEMPTS_MIN (62 * 62 * 62)
256 /* The number of times to attempt to generate a temporary file. To
257 conform to POSIX, this must be no smaller than TMP_MAX. */
258 #if ATTEMPTS_MIN < TMP_MAX
259 unsigned int attempts = TMP_MAX;
261 unsigned int attempts = ATTEMPTS_MIN;
264 /* A random variable. The initial value is used only the for fallback path
265 on 'random_bits' on 'getrandom' failure. Its initial value tries to use
266 some entropy from the ASLR and ignore possible bits from the stack
268 random_value v = ((uintptr_t) &v) / alignof (max_align_t);
270 /* How many random base-62 digits can currently be extracted from V. */
273 /* Whether to consume entropy when acquiring random bits. On the
274 first try it's worth the entropy cost with __GT_NOCREATE, which
275 is inherently insecure and can use the entropy to make it a bit
276 less secure. On the (rare) second and later attempts it might
277 help against DoS attacks. */
278 bool use_getrandom = tryfunc == try_nocreate;
280 /* Least unfair value for V. If V is less than this, V can generate
281 BASE_62_DIGITS digits fairly. Otherwise it might be biased. */
282 random_value const unfair_min
283 = RANDOM_VALUE_MAX - RANDOM_VALUE_MAX % BASE_62_POWER;
286 if (len < x_suffix_len + suffixlen
287 || strspn (&tmpl[len - x_suffix_len - suffixlen], "X") < x_suffix_len)
289 __set_errno (EINVAL);
293 /* This is where the Xs start. */
294 XXXXXX = &tmpl[len - x_suffix_len - suffixlen];
296 for (count = 0; count < attempts; ++count)
298 for (size_t i = 0; i < x_suffix_len; i++)
304 v = random_bits (v, use_getrandom);
305 use_getrandom = true;
307 while (unfair_min <= v);
309 vdigits = BASE_62_DIGITS;
312 XXXXXX[i] = letters[v % 62];
317 fd = tryfunc (tmpl, args);
320 __set_errno (save_errno);
323 else if (errno != EEXIST)
327 /* We got out of the loop because we ran out of combinations to try. */
328 __set_errno (EEXIST);
333 __gen_tempname (char *tmpl, int suffixlen, int flags, int kind)
335 return gen_tempname_len (tmpl, suffixlen, flags, kind, 6);
340 try_tempname (char *tmpl, int suffixlen, void *args,
341 int (*tryfunc) (char *, void *))
343 return try_tempname_len (tmpl, suffixlen, args, tryfunc, 6);