hurd: Stop mapping AT_NO_AUTOMOUNT to O_NOTRANS
[glibc.git] / sysdeps / posix / tempname.c
blobc00fe0c18110fef74495e9cd3155a97775350d5a
1 /* Copyright (C) 1991-2024 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 <https://www.gnu.org/licenses/>. */
18 #if !_LIBC
19 # include <libc-config.h>
20 # include "tempname.h"
21 #endif
23 #include <errno.h>
25 #include <stdio.h>
26 #ifndef TMP_MAX
27 # define TMP_MAX 238328
28 #endif
29 #ifndef __GT_FILE
30 # define __GT_FILE 0
31 # define __GT_DIR 1
32 # define __GT_NOCREATE 2
33 #endif
34 #if !_LIBC && (GT_FILE != __GT_FILE || GT_DIR != __GT_DIR \
35 || GT_NOCREATE != __GT_NOCREATE)
36 # error report this to bug-gnulib@gnu.org
37 #endif
39 #include <stdlib.h>
40 #include <string.h>
42 #include <fcntl.h>
43 #include <stdint.h>
44 #include <sys/random.h>
45 #include <sys/stat.h>
46 #include <time.h>
48 #if _LIBC
49 # define struct_stat64 struct __stat64_t64
50 #else
51 # define struct_stat64 struct stat
52 # define __gen_tempname gen_tempname
53 # define __mkdir mkdir
54 # define __open open
55 # define __lstat64_time64(file, buf) lstat (file, buf)
56 # define __getrandom getrandom
57 # define __clock_gettime64 clock_gettime
58 # define __timespec64 timespec
59 #endif
61 /* Use getrandom if it works, falling back on a 64-bit linear
62 congruential generator that starts with Var's value
63 mixed in with a clock's low-order bits if available. */
64 typedef uint_fast64_t random_value;
65 #define RANDOM_VALUE_MAX UINT_FAST64_MAX
66 #define BASE_62_DIGITS 10 /* 62**10 < UINT_FAST64_MAX */
67 #define BASE_62_POWER (62LL * 62 * 62 * 62 * 62 * 62 * 62 * 62 * 62 * 62)
69 /* Return the result of mixing the entropy from R and S.
70 Assume that R and S are not particularly random,
71 and that the result should look randomish to an untrained eye. */
73 static random_value
74 mix_random_values (random_value r, random_value s)
76 /* As this code is used only when high-quality randomness is neither
77 available nor necessary, there is no need for fancier polynomials
78 such as those in the Linux kernel's 'random' driver. */
79 return (2862933555777941757 * r + 3037000493) ^ s;
82 /* Set *R to a random value.
83 Return true if *R is set to high-quality value taken from getrandom.
84 Otherwise return false, falling back to a low-quality *R that might
85 depend on S.
87 This function returns false only when getrandom fails.
88 On GNU systems this should happen only early in the boot process,
89 when the fallback should be good enough for programs using tempname
90 because any attacker likely has root privileges already. */
92 static bool
93 random_bits (random_value *r, random_value s)
95 /* Without GRND_NONBLOCK it can be blocked for minutes on some systems. */
96 if (__getrandom (r, sizeof *r, GRND_NONBLOCK) == sizeof *r)
97 return true;
99 /* If getrandom did not work, use ersatz entropy based on low-order
100 clock bits. On GNU systems getrandom should fail only
101 early in booting, when ersatz should be good enough.
102 Do not use ASLR-based entropy, as that would leak ASLR info into
103 the resulting file name which is typically public.
105 Of course we are in a state of sin here. */
107 random_value v = s;
109 #if _LIBC || (defined CLOCK_REALTIME && HAVE_CLOCK_GETTIME)
110 struct __timespec64 tv;
111 __clock_gettime64 (CLOCK_REALTIME, &tv);
112 v = mix_random_values (v, tv.tv_sec);
113 v = mix_random_values (v, tv.tv_nsec);
114 #endif
116 /* In glibc, clock_gettime with CLOCK_REALTIME is expected to always
117 succeed. */
118 #if !_LIBC
119 *r = mix_random_values (v, clock ());
120 #endif
121 return false;
124 #if _LIBC
125 static int try_tempname_len (char *, int, void *, int (*) (char *, void *),
126 size_t);
127 #endif
129 static int
130 try_file (char *tmpl, void *flags)
132 int *openflags = flags;
133 return __open (tmpl,
134 (*openflags & ~O_ACCMODE)
135 | O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
138 static int
139 try_dir (char *tmpl, _GL_UNUSED void *flags)
141 return __mkdir (tmpl, S_IRUSR | S_IWUSR | S_IXUSR);
144 static int
145 try_nocreate (char *tmpl, _GL_UNUSED void *flags)
147 struct_stat64 st;
149 if (__lstat64_time64 (tmpl, &st) == 0 || errno == EOVERFLOW)
150 __set_errno (EEXIST);
151 return errno == ENOENT ? 0 : -1;
154 /* These are the characters used in temporary file names. */
155 static const char letters[] =
156 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
158 /* Generate a temporary file name based on TMPL. TMPL must match the
159 rules for mk[s]temp (i.e., end in at least X_SUFFIX_LEN "X"s,
160 possibly with a suffix).
161 The name constructed does not exist at the time of the call to
162 this function. TMPL is overwritten with the result.
164 KIND may be one of:
165 __GT_NOCREATE: simply verify that the name does not exist
166 at the time of the call.
167 __GT_FILE: create the file using open(O_CREAT|O_EXCL)
168 and return a read-write fd. The file is mode 0600.
169 __GT_DIR: create a directory, which will be mode 0700.
172 #ifdef _LIBC
173 static
174 #endif
176 gen_tempname_len (char *tmpl, int suffixlen, int flags, int kind,
177 size_t x_suffix_len)
179 static int (*const tryfunc[]) (char *, void *) =
181 [__GT_FILE] = try_file,
182 [__GT_DIR] = try_dir,
183 [__GT_NOCREATE] = try_nocreate
185 return try_tempname_len (tmpl, suffixlen, &flags, tryfunc[kind],
186 x_suffix_len);
189 #ifdef _LIBC
190 static
191 #endif
193 try_tempname_len (char *tmpl, int suffixlen, void *args,
194 int (*tryfunc) (char *, void *), size_t x_suffix_len)
196 size_t len;
197 char *XXXXXX;
198 unsigned int count;
199 int fd = -1;
200 int saved_errno = errno;
202 /* A lower bound on the number of temporary files to attempt to
203 generate. The maximum total number of temporary file names that
204 can exist for a given template is 62**6. It should never be
205 necessary to try all of these combinations. Instead if a reasonable
206 number of names is tried (we define reasonable as 62**3) fail to
207 give the system administrator the chance to remove the problems.
208 This value requires that X_SUFFIX_LEN be at least 3. */
209 #define ATTEMPTS_MIN (62 * 62 * 62)
211 /* The number of times to attempt to generate a temporary file. To
212 conform to POSIX, this must be no smaller than TMP_MAX. */
213 #if ATTEMPTS_MIN < TMP_MAX
214 unsigned int attempts = TMP_MAX;
215 #else
216 unsigned int attempts = ATTEMPTS_MIN;
217 #endif
219 /* A random variable. */
220 random_value v = 0;
222 /* A value derived from the random variable, and how many random
223 base-62 digits can currently be extracted from VDIGBUF. */
224 random_value vdigbuf;
225 int vdigits = 0;
227 /* Least biased value for V. If V is less than this, V can generate
228 BASE_62_DIGITS unbiased digits. Otherwise the digits are biased. */
229 random_value const biased_min
230 = RANDOM_VALUE_MAX - RANDOM_VALUE_MAX % BASE_62_POWER;
232 len = strlen (tmpl);
233 if (len < x_suffix_len + suffixlen
234 || strspn (&tmpl[len - x_suffix_len - suffixlen], "X") < x_suffix_len)
236 __set_errno (EINVAL);
237 return -1;
240 /* This is where the Xs start. */
241 XXXXXX = &tmpl[len - x_suffix_len - suffixlen];
243 for (count = 0; count < attempts; ++count)
245 for (size_t i = 0; i < x_suffix_len; i++)
247 if (vdigits == 0)
249 /* Worry about bias only if the bits are high quality. */
250 while (random_bits (&v, v) && biased_min <= v)
251 continue;
253 vdigbuf = v;
254 vdigits = BASE_62_DIGITS;
257 XXXXXX[i] = letters[vdigbuf % 62];
258 vdigbuf /= 62;
259 vdigits--;
262 fd = tryfunc (tmpl, args);
263 if (fd >= 0)
265 __set_errno (saved_errno);
266 return fd;
268 else if (errno != EEXIST)
269 return -1;
272 /* We got out of the loop because we ran out of combinations to try. */
273 __set_errno (EEXIST);
274 return -1;
278 __gen_tempname (char *tmpl, int suffixlen, int flags, int kind)
280 return gen_tempname_len (tmpl, suffixlen, flags, kind, 6);
283 #if !_LIBC
285 try_tempname (char *tmpl, int suffixlen, void *args,
286 int (*tryfunc) (char *, void *))
288 return try_tempname_len (tmpl, suffixlen, args, tryfunc, 6);
290 #endif