]> git.ipfire.org Git - thirdparty/glibc.git/blame - sysdeps/posix/tempname.c
Update copyright dates with scripts/update-copyrights.
[thirdparty/glibc.git] / sysdeps / posix / tempname.c
CommitLineData
d614a753 1/* Copyright (C) 1991-2020 Free Software Foundation, Inc.
478b92f0 2 This file is part of the GNU C Library.
28f540f4 3
478b92f0 4 The GNU C Library is free software; you can redistribute it and/or
41bdb6e2
AJ
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.
28f540f4 8
478b92f0
UD
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
41bdb6e2 12 Lesser General Public License for more details.
28f540f4 13
41bdb6e2 14 You should have received a copy of the GNU Lesser General Public
59ba27a6 15 License along with the GNU C Library; if not, see
5a82c748 16 <https://www.gnu.org/licenses/>. */
28f540f4 17
c7aec4be 18#if !_LIBC
46c3f8cd 19# include <config.h>
c7aec4be 20# include "tempname.h"
46c3f8cd
UD
21#endif
22
28f540f4 23#include <sys/types.h>
2e65ca2b 24#include <assert.h>
28f540f4 25
46c3f8cd
UD
26#include <errno.h>
27#ifndef __set_errno
28# define __set_errno(Val) errno = (Val)
29#endif
30
31#include <stdio.h>
32#ifndef P_tmpdir
33# define P_tmpdir "/tmp"
34#endif
35#ifndef TMP_MAX
36# define TMP_MAX 238328
37#endif
38#ifndef __GT_FILE
39# define __GT_FILE 0
d7e23b02
UD
40# define __GT_DIR 1
41# define __GT_NOCREATE 2
46c3f8cd 42#endif
c7aec4be
WN
43#if !_LIBC && (GT_FILE != __GT_FILE || GT_DIR != __GT_DIR \
44 || GT_NOCREATE != __GT_NOCREATE)
45# error report this to bug-gnulib@gnu.org
46c3f8cd
UD
46#endif
47
c7aec4be
WN
48#include <stddef.h>
49#include <stdlib.h>
50#include <string.h>
46c3f8cd 51
c7aec4be 52#include <fcntl.h>
4a39c34c 53#include <time.h>
c7aec4be
WN
54#include <stdint.h>
55#include <unistd.h>
46c3f8cd
UD
56
57#include <sys/stat.h>
46c3f8cd
UD
58
59#if _LIBC
60# define struct_stat64 struct stat64
c7aec4be 61# define __secure_getenv __libc_secure_getenv
46c3f8cd
UD
62#else
63# define struct_stat64 struct stat
c7aec4be 64# define __gen_tempname gen_tempname
46c3f8cd 65# define __getpid getpid
46c3f8cd
UD
66# define __mkdir mkdir
67# define __open open
c7aec4be
WN
68# define __lxstat64(version, file, buf) lstat (file, buf)
69# define __secure_getenv secure_getenv
46c3f8cd
UD
70#endif
71
3b5c1b57 72#ifdef _LIBC
359653aa
AZ
73# include <random-bits.h>
74# define RANDOM_BITS(Var) ((Var) = random_bits ())
75# else
76# define RANDOM_BITS(Var) \
77 { \
4a39c34c
ZW
78 struct timespec ts; \
79 clock_gettime (CLOCK_REALTIME, &ts); \
80 (Var) = ((uint64_t) tv.tv_nsec << 16) ^ tv.tv_sec; \
359653aa 81 }
3b5c1b57
UD
82#endif
83
f2615995
UD
84/* Use the widest available unsigned type if uint64_t is not
85 available. The algorithm below extracts a number less than 62**6
86 (approximately 2**35.725) from uint64_t, so ancient hosts where
87 uintmax_t is only 32 bits lose about 3.725 bits of randomness,
88 which is better than not having mkstemp at all. */
89#if !defined UINT64_MAX && !defined uint64_t
90# define uint64_t uintmax_t
91#endif
92
c7aec4be 93#if _LIBC
28f540f4
RM
94/* Return nonzero if DIR is an existent directory. */
95static int
7cabd57c 96direxists (const char *dir)
28f540f4 97{
46c3f8cd 98 struct_stat64 buf;
8edf6e0d 99 return __xstat64 (_STAT_VER, dir, &buf) == 0 && S_ISDIR (buf.st_mode);
28f540f4
RM
100}
101
7cabd57c
UD
102/* Path search algorithm, for tmpnam, tmpfile, etc. If DIR is
103 non-null and exists, uses it; otherwise uses the first of $TMPDIR,
104 P_tmpdir, /tmp that exists. Copies into TMPL a template suitable
105 for use with mk[s]temp. Will fail (-1) if DIR is non-null and
106 doesn't exist, none of the searched dirs exists, or there's not
107 enough space in TMPL. */
108int
60876a75
UD
109__path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx,
110 int try_tmpdir)
28f540f4 111{
7cabd57c
UD
112 const char *d;
113 size_t dlen, plen;
114
115 if (!pfx || !pfx[0])
116 {
117 pfx = "file";
118 plen = 4;
119 }
28f540f4
RM
120 else
121 {
7cabd57c
UD
122 plen = strlen (pfx);
123 if (plen > 5)
124 plen = 5;
28f540f4 125 }
28f540f4 126
60876a75
UD
127 if (try_tmpdir)
128 {
c7aec4be 129 d = __secure_getenv ("TMPDIR");
60876a75
UD
130 if (d != NULL && direxists (d))
131 dir = d;
132 else if (dir != NULL && direxists (dir))
133 /* nothing */ ;
5a7cb1a2
UD
134 else
135 dir = NULL;
60876a75 136 }
e9dcb080 137 if (dir == NULL)
28f540f4 138 {
b61af6fc
UD
139 if (direxists (P_tmpdir))
140 dir = P_tmpdir;
141 else if (strcmp (P_tmpdir, "/tmp") != 0 && direxists ("/tmp"))
142 dir = "/tmp";
143 else
144 {
145 __set_errno (ENOENT);
146 return -1;
147 }
28f540f4 148 }
28f540f4
RM
149
150 dlen = strlen (dir);
28f540f4 151 while (dlen > 1 && dir[dlen - 1] == '/')
7cabd57c 152 dlen--; /* remove trailing slashes */
28f540f4 153
7cabd57c
UD
154 /* check we have room for "${dir}/${pfx}XXXXXX\0" */
155 if (tmpl_len < dlen + 1 + plen + 6 + 1)
28f540f4 156 {
7cabd57c
UD
157 __set_errno (EINVAL);
158 return -1;
28f540f4 159 }
28f540f4 160
04166d6e 161 sprintf (tmpl, "%.*s/%.*sXXXXXX", (int) dlen, dir, (int) plen, pfx);
7cabd57c
UD
162 return 0;
163}
c7aec4be 164#endif /* _LIBC */
7cabd57c 165
c7aec4be 166/* These are the characters used in temporary file names. */
7cabd57c
UD
167static const char letters[] =
168"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
169
170/* Generate a temporary file name based on TMPL. TMPL must match the
7f3146e7
UD
171 rules for mk[s]temp (i.e. end in "XXXXXX", possibly with a suffix).
172 The name constructed does not exist at the time of the call to
173 __gen_tempname. TMPL is overwritten with the result.
2e65ca2b
UD
174
175 KIND may be one of:
176 __GT_NOCREATE: simply verify that the name does not exist
177 at the time of the call.
178 __GT_FILE: create the file using open(O_CREAT|O_EXCL)
179 and return a read-write fd. The file is mode 0600.
2e65ca2b 180 __GT_DIR: create a directory, which will be mode 0700.
7cabd57c
UD
181
182 We use a clever algorithm to get hard-to-predict names. */
183int
7f3146e7 184__gen_tempname (char *tmpl, int suffixlen, int flags, int kind)
7cabd57c
UD
185{
186 int len;
187 char *XXXXXX;
8e9b2075
UD
188 unsigned int count;
189 int fd = -1;
7cabd57c 190 int save_errno = errno;
46c3f8cd 191 struct_stat64 st;
28f540f4 192
8e9b2075
UD
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
c7aec4be 196 necessary to try all of these combinations. Instead if a reasonable
8e9b2075
UD
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. */
cec40916 199#define ATTEMPTS_MIN (62 * 62 * 62)
8e9b2075
UD
200
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. */
cec40916
UD
203#if ATTEMPTS_MIN < TMP_MAX
204 unsigned int attempts = TMP_MAX;
205#else
206 unsigned int attempts = ATTEMPTS_MIN;
207#endif
8e9b2075 208
7cabd57c 209 len = strlen (tmpl);
7f3146e7 210 if (len < 6 + suffixlen || memcmp (&tmpl[len - 6 - suffixlen], "XXXXXX", 6))
7cabd57c 211 {
a7ab2023 212 __set_errno (EINVAL);
7cabd57c
UD
213 return -1;
214 }
28f540f4 215
7cabd57c 216 /* This is where the Xs start. */
7f3146e7 217 XXXXXX = &tmpl[len - 6 - suffixlen];
d68171ed 218
e1df30fb
AZ
219 uint64_t pid = (uint64_t) __getpid () << 32;
220 for (count = 0; count < attempts; ++count)
a7ab2023 221 {
e1df30fb
AZ
222 uint64_t v;
223 /* Get some more or less random data. */
224 RANDOM_BITS (v);
225 v ^= pid;
a7ab2023
UD
226
227 /* Fill in the random bits. */
228 XXXXXX[0] = letters[v % 62];
229 v /= 62;
230 XXXXXX[1] = letters[v % 62];
231 v /= 62;
232 XXXXXX[2] = letters[v % 62];
233 v /= 62;
234 XXXXXX[3] = letters[v % 62];
235 v /= 62;
236 XXXXXX[4] = letters[v % 62];
237 v /= 62;
238 XXXXXX[5] = letters[v % 62];
28f540f4 239
2e65ca2b 240 switch (kind)
7cabd57c 241 {
2e65ca2b 242 case __GT_FILE:
d7e23b02 243 fd = __open (tmpl,
e8a32126 244 (flags & ~O_ACCMODE)
d7e23b02 245 | O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
2e65ca2b
UD
246 break;
247
248 case __GT_DIR:
46c3f8cd 249 fd = __mkdir (tmpl, S_IRUSR | S_IWUSR | S_IXUSR);
2e65ca2b
UD
250 break;
251
252 case __GT_NOCREATE:
253 /* This case is backward from the other three. __gen_tempname
254 succeeds if __xstat fails because the name does not exist.
255 Note the continue to bypass the common logic at the bottom
256 of the loop. */
72c65ff4 257 if (__lxstat64 (_STAT_VER, tmpl, &st) < 0)
7cabd57c
UD
258 {
259 if (errno == ENOENT)
28f540f4 260 {
7cabd57c
UD
261 __set_errno (save_errno);
262 return 0;
28f540f4 263 }
7cabd57c
UD
264 else
265 /* Give up now. */
266 return -1;
28f540f4 267 }
2e65ca2b
UD
268 continue;
269
270 default:
271 assert (! "invalid KIND in __gen_tempname");
c7aec4be 272 abort ();
2e65ca2b
UD
273 }
274
275 if (fd >= 0)
276 {
277 __set_errno (save_errno);
278 return fd;
28f540f4 279 }
2e65ca2b
UD
280 else if (errno != EEXIST)
281 return -1;
28f540f4
RM
282 }
283
284 /* We got out of the loop because we ran out of combinations to try. */
7cabd57c
UD
285 __set_errno (EEXIST);
286 return -1;
28f540f4 287}