Update.
[glibc.git] / sysdeps / posix / tempname.c
blob82e024313276f91b1320855f5a530c4049f4141c
1 /* Copyright (C) 1991,92,93,94,95,96,97,98 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 Library General Public License as
6 published by the Free Software Foundation; either version 2 of the
7 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 Library General Public License for more details.
14 You should have received a copy of the GNU Library General Public
15 License along with the GNU C Library; see the file COPYING.LIB. If not,
16 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 Boston, MA 02111-1307, USA. */
19 #include <stddef.h>
20 #include <stdint.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <errno.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <sys/time.h>
31 #ifdef USE_IN_LIBIO
32 # include "libioP.h"
33 # include <libio.h>
34 #endif
36 /* Return nonzero if DIR is an existent directory. */
37 static int
38 diraccess (const char *dir)
40 struct stat buf;
41 return __stat (dir, &buf) == 0 && S_ISDIR (buf.st_mode);
44 /* Return nonzero if FILE exists. */
45 static int
46 exists (const char *file)
48 /* We can stat the file even if we can't read its data. */
49 struct stat st;
50 int save = errno;
51 if (__stat (file, &st) == 0)
52 return 1;
53 else
55 /* We report that the file exists if stat failed for a reason other
56 than nonexistence. In this case, it may or may not exist, and we
57 don't know; but reporting that it does exist will never cause any
58 trouble, while reporting that it doesn't exist when it does would
59 violate the interface of __stdio_gen_tempname. */
60 int exists = errno != ENOENT;
61 __set_errno (save);
62 return exists;
67 /* These are the characters used in temporary filenames. */
68 static const char letters[] =
69 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
71 /* Generate a temporary filename and return it (in a static buffer). If
72 STREAMPTR is not NULL, open a stream "w+b" on the file and set
73 *STREAMPTR to it. If DIR_SEARCH is nonzero, DIR and PFX are used as
74 described for tempnam. If not, a temporary filename in P_tmpdir with no
75 special prefix is generated. If LENPTR is not NULL, *LENPTR is set the
76 to length (including the terminating '\0') of the resultant filename,
77 which is returned. This goes through a cyclic pattern of all possible
78 filenames consisting of five decimal digits of the current pid and three
79 of the characters in `letters'. Data for tempnam and tmpnam is kept
80 separate, but when tempnam is using P_tmpdir and no prefix (i.e, it is
81 identical to tmpnam), the same data is used. Each potential filename is
82 tested for an already-existing file of the same name, and no name of an
83 existing file will be returned. When the cycle reaches its end
84 (12345ZZZ), NULL is returned. */
85 char *
86 __stdio_gen_tempname (char *buf, size_t bufsize, const char *dir,
87 const char *pfx, int dir_search, size_t *lenptr,
88 FILE **streamptr, int large_file)
90 int saverrno = errno;
91 static const char tmpdir[] = P_tmpdir;
92 size_t plen, dlen, len;
93 char *XXXXXX;
94 static uint64_t value;
95 struct timeval tv;
96 int count;
98 if (dir_search)
100 register const char *d = __secure_getenv ("TMPDIR");
101 if (d != NULL && !diraccess (d))
102 d = NULL;
103 if (d == NULL && dir != NULL && diraccess (dir))
104 d = dir;
105 if (d == NULL && diraccess (tmpdir))
106 d = tmpdir;
107 if (d == NULL && diraccess ("/tmp"))
108 d = "/tmp";
109 if (d == NULL)
111 __set_errno (ENOENT);
112 return NULL;
114 dir = d;
116 else
117 dir = tmpdir;
119 dlen = strlen (dir);
121 /* Remove trailing slashes from the directory name. */
122 while (dlen > 1 && dir[dlen - 1] == '/')
123 --dlen;
125 if (pfx != NULL && *pfx != '\0')
127 plen = strlen (pfx);
128 if (plen > 5)
129 plen = 5;
131 else
132 plen = 0;
134 len = __snprintf (buf, bufsize, "%.*s/%.*sXXXXXX",
135 (int) dlen, dir, (int) plen, pfx);
137 if (len < dlen + plen + 7)
139 __set_errno (EINVAL);
140 return NULL;
143 XXXXXX = &buf[dlen + plen + 1];
145 /* Get some more or less random data. */
146 __gettimeofday (&tv, NULL);
147 value += ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec ^ __getpid ();
149 for (count = 0; count < TMP_MAX; value += 7777, ++count)
151 uint64_t v = value;
153 /* Fill in the random bits. */
154 XXXXXX[0] = letters[v % 62];
155 v /= 62;
156 XXXXXX[1] = letters[v % 62];
157 v /= 62;
158 XXXXXX[2] = letters[v % 62];
159 v /= 62;
160 XXXXXX[3] = letters[v % 62];
161 v /= 62;
162 XXXXXX[4] = letters[v % 62];
163 v /= 62;
164 XXXXXX[5] = letters[v % 62];
166 if (streamptr != NULL)
168 /* Try to create the file atomically. */
169 #ifdef _G_OPEN64
170 int fd = (large_file
171 ? __open (buf, O_RDWR|O_CREAT|O_EXCL, 0666)
172 : _G_OPEN64 (buf, O_RDWR|O_CREAT|O_EXCL, 0666));
173 #else
174 int fd = __open (buf, O_RDWR|O_CREAT|O_EXCL, 0666);
175 #endif
176 if (fd >= 0)
178 /* We got a new file that did not previously exist.
179 Create a stream for it. */
180 #ifdef USE_IN_LIBIO
181 int save;
182 struct locked_FILE
184 struct _IO_FILE_plus fp;
185 #ifdef _IO_MTSAFE_IO
186 _IO_lock_t lock;
187 #endif
188 } *new_f;
189 struct _IO_FILE_plus *fp;
191 new_f = (struct locked_FILE *)
192 malloc (sizeof (struct locked_FILE));
193 if (new_f == NULL)
195 /* We lost trying to create a stream (out of memory?).
196 Nothing to do but remove the file, close the descriptor,
197 and return failure. */
198 save = errno;
199 lose:
200 (void) remove (buf);
201 (void) __close (fd);
202 __set_errno (save);
203 return NULL;
205 fp = &new_f->fp;
206 #ifdef _IO_MTSAFE_IO
207 fp->file._lock = &new_f->lock;
208 #endif
209 _IO_init (&fp->file, 0);
210 _IO_JUMPS (&fp->file) = &_IO_file_jumps;
211 _IO_file_init (&fp->file);
212 # if !_IO_UNIFIED_JUMPTABLES
213 fp->vtable = NULL;
214 # endif
215 if (_IO_file_attach (&fp->file, fd) == NULL)
217 save = errno;
218 free (fp);
219 goto lose;
221 fp->file._flags &= ~_IO_DELETE_DONT_CLOSE;
223 *streamptr = (FILE *) fp;
224 #else
225 *streamptr = __newstream ();
226 if (*streamptr == NULL)
228 /* We lost trying to create a stream (out of memory?).
229 Nothing to do but remove the file, close the descriptor,
230 and return failure. */
231 const int save = errno;
232 (void) remove (buf);
233 (void) __close (fd);
234 __set_errno (save);
235 return NULL;
237 (*streamptr)->__cookie = (__ptr_t) (long int) fd;
238 (*streamptr)->__mode.__write = 1;
239 (*streamptr)->__mode.__read = 1;
240 (*streamptr)->__mode.__binary = 1;
241 #endif
243 #if defined EMFILE || defined ENFILE || defined EINTR
244 else if (0
245 # ifdef EMFILE
246 || errno == EMFILE
247 # endif
248 # ifdef ENFILE
249 || errno == ENFILE
250 # endif
251 # ifdef EINTR
252 || errno == EINTR
253 # endif
255 /* We cannot open anymore files since all descriptors are
256 used or because we got a signal. */
257 return NULL;
258 #endif
259 else
260 continue;
262 else if (exists (buf))
263 continue;
265 /* If the file already existed we have continued the loop above,
266 so we only get here when we have a winning name to return. */
268 __set_errno (saverrno);
270 if (lenptr != NULL)
271 *lenptr = len + 1;
272 return buf;
275 /* We got out of the loop because we ran out of combinations to try. */
276 __set_errno (EEXIST); /* ? */
277 return NULL;