.
[glibc.git] / sysdeps / posix / tempname.c
blobc70a6e8d3588a182d5139fc4590fe39c4568bdae
1 /* Copyright (C) 1991, 1992, 1993, 1994, 1995 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
16 not, write to the Free Software Foundation, Inc., 675 Mass Ave,
17 Cambridge, MA 02139, USA. */
19 #include <ansidecl.h>
20 #include <errno.h>
21 #include <stddef.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #include <unistd.h>
30 #ifdef USE_IN_LIBIO
31 # include "libioP.h"
32 # include <libio.h>
33 #endif
35 /* Return nonzero if DIR is an existent directory. */
36 static int
37 DEFUN(diraccess, (dir), CONST char *dir)
39 struct stat buf;
40 return __stat (dir, &buf) == 0 && S_ISDIR (buf.st_mode);
43 /* Return nonzero if FILE exists. */
44 static int
45 DEFUN(exists, (file), CONST char *file)
47 /* We can stat the file even if we can't read its data. */
48 struct stat st;
49 int save = errno;
50 if (__stat (file, &st) == 0)
51 return 1;
52 else
54 /* We report that the file exists if stat failed for a reason other
55 than nonexistence. In this case, it may or may not exist, and we
56 don't know; but reporting that it does exist will never cause any
57 trouble, while reporting that it doesn't exist when it does would
58 violate the interface of __stdio_gen_tempname. */
59 int exists = errno != ENOENT;
60 errno = save;
61 return exists;
66 /* These are the characters used in temporary filenames. */
67 static CONST char letters[] =
68 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
70 /* Generate a temporary filename and return it (in a static buffer). If
71 STREAMPTR is not NULL, open a stream "w+b" on the file and set
72 *STREAMPTR to it. If DIR_SEARCH is nonzero, DIR and PFX are used as
73 described for tempnam. If not, a temporary filename in P_tmpdir with no
74 special prefix is generated. If LENPTR is not NULL, *LENPTR is set the
75 to length (including the terminating '\0') of the resultant filename,
76 which is returned. This goes through a cyclic pattern of all possible
77 filenames consisting of five decimal digits of the current pid and three
78 of the characters in `letters'. Data for tempnam and tmpnam is kept
79 separate, but when tempnam is using P_tmpdir and no prefix (i.e, it is
80 identical to tmpnam), the same data is used. Each potential filename is
81 tested for an already-existing file of the same name, and no name of an
82 existing file will be returned. When the cycle reaches its end
83 (12345ZZZ), NULL is returned. */
84 char *
85 DEFUN(__stdio_gen_tempname, (dir, pfx, dir_search, lenptr, streamptr),
86 CONST char *dir AND CONST char *pfx AND
87 int dir_search AND size_t *lenptr AND
88 FILE **streamptr)
90 int saverrno = errno;
91 static CONST char tmpdir[] = P_tmpdir;
92 static size_t indices[2];
93 size_t *idx;
94 static char buf[FILENAME_MAX];
95 static pid_t oldpid = (pid_t) 0;
96 pid_t pid = __getpid();
97 register size_t len, plen, dlen;
99 if (dir_search)
101 register CONST char *d = getenv ("TMPDIR");
102 if (d != NULL && !diraccess (d))
103 d = NULL;
104 if (d == NULL && dir != NULL && diraccess (dir))
105 d = dir;
106 if (d == NULL && diraccess (tmpdir))
107 d = tmpdir;
108 if (d == NULL && diraccess ("/tmp"))
109 d = "/tmp";
110 if (d == NULL)
112 errno = ENOENT;
113 return NULL;
115 dir = d;
117 else
118 dir = tmpdir;
120 dlen = strlen (dir);
122 /* Remove trailing slashes from the directory name. */
123 while (dlen > 1 && dir[dlen - 1] == '/')
124 --dlen;
126 if (pfx != NULL && *pfx != '\0')
128 plen = strlen (pfx);
129 if (plen > 5)
130 plen = 5;
132 else
133 plen = 0;
135 if (dir != tmpdir && !strcmp (dir, tmpdir))
136 dir = tmpdir;
137 idx = &indices[(plen == 0 && dir == tmpdir) ? 1 : 0];
139 if (pid != oldpid)
141 oldpid = pid;
142 indices[0] = indices[1] = 0;
145 len = dlen + 1 + plen + 5 + 3;
146 while (*idx < ((sizeof (letters) - 1) * (sizeof (letters) - 1) *
147 (sizeof (letters) - 1)))
149 const size_t i = (*idx)++;
151 /* Construct a file name and see if it already exists.
153 We use a single counter in *IDX to cycle each of three
154 character positions through each of 62 possible letters. */
156 if (sizeof (buf) < len ||
157 sprintf (buf, "%.*s/%.*s%.5d%c%c%c",
158 (int) dlen, dir, (int) plen,
159 pfx, pid % 100000,
160 letters[i % (sizeof (letters) - 1)],
161 letters[(i / (sizeof (letters) - 1))
162 % (sizeof (letters) - 1)],
163 letters[(i / ((sizeof (letters) - 1) *
164 (sizeof (letters) - 1)))
165 % (sizeof (letters) - 1)]
166 ) != (int) len)
167 return NULL;
169 if (streamptr != NULL)
171 /* Try to create the file atomically. */
172 int fd = __open (buf, O_RDWR|O_CREAT|O_EXCL, 0666);
173 if (fd >= 0)
175 /* We got a new file that did not previously exist.
176 Create a stream for it. */
177 #ifdef USE_IN_LIBIO
178 int save;
179 struct _IO_FILE_plus *fp;
181 fp = (struct _IO_FILE_plus *)
182 malloc(sizeof (struct _IO_FILE_plus));
183 if (fp == NULL)
185 /* We lost trying to create a stream (out of memory?).
186 Nothing to do but remove the file, close the descriptor,
187 and return failure. */
188 save = errno;
189 lose:
190 (void) remove (buf);
191 (void) __close (fd);
192 errno = save;
193 return NULL;
195 _IO_init (&fp->file, 0);
196 _IO_JUMPS (&fp->file) = &_IO_file_jumps;
197 _IO_file_init (&fp->file);
198 # if !_IO_UNIFIED_JUMPTABLES
199 fp->vtable = NULL;
200 # endif
201 if (_IO_file_attach (&fp->file, fd) == NULL)
203 save = errno;
204 free (fp);
205 goto lose;
207 fp->file._flags &= ~_IO_DELETE_DONT_CLOSE;
208 fp->file._IO_file_flags = 0;
210 *streamptr = (FILE *) fp;
211 #else
212 *streamptr = __newstream ();
213 if (*streamptr == NULL)
215 /* We lost trying to create a stream (out of memory?).
216 Nothing to do but remove the file, close the descriptor,
217 and return failure. */
218 const int save = errno;
219 (void) remove (buf);
220 (void) __close (fd);
221 errno = save;
222 return NULL;
224 (*streamptr)->__cookie = (PTR) (long int) fd;
225 (*streamptr)->__mode.__write = 1;
226 (*streamptr)->__mode.__read = 1;
227 (*streamptr)->__mode.__binary = 1;
228 #endif
230 else
231 continue;
233 else if (exists (buf))
234 continue;
236 /* If the file already existed we have continued the loop above,
237 so we only get here when we have a winning name to return. */
239 errno = saverrno;
241 if (lenptr != NULL)
242 *lenptr = len + 1;
243 return buf;
246 /* We got out of the loop because we ran out of combinations to try. */
247 errno = EEXIST; /* ? */
248 return NULL;