OSDN Git Service

mkostemp: fix implementation
[uclinux-h8/uClibc.git] / libc / misc / internals / tempname.c
1 /* Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3
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.
8
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.
13
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    see <http://www.gnu.org/licenses/>.  */
17
18 /* March 11, 2002       Manuel Novoa III
19  *
20  * Modify code to remove dependency on libgcc long long arith support funcs.
21  */
22
23 /* June 6, 2004       Erik Andersen
24  *
25  * Don't use brain damaged getpid() based randomness.
26  */
27
28 /* April 15, 2005     Mike Frysinger
29  *
30  * Use brain damaged getpid() if real random fails.
31  */
32
33 #include <stddef.h>
34 #include <stdint.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <unistd.h>
41 #include <assert.h>
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #include <sys/time.h>
45 #include "tempname.h"
46
47 /* Return nonzero if DIR is an existent directory.  */
48 static int direxists (const char *dir)
49 {
50     struct stat buf;
51     return stat(dir, &buf) == 0 && S_ISDIR (buf.st_mode);
52 }
53
54 /* Path search algorithm, for tmpnam, tmpfile, etc.  If DIR is
55    non-null and exists, uses it; otherwise uses the first of $TMPDIR,
56    P_tmpdir, /tmp that exists.  Copies into TMPL a template suitable
57    for use with mk[s]temp.  Will fail (-1) if DIR is non-null and
58    doesn't exist, none of the searched dirs exists, or there's not
59    enough space in TMPL. */
60 int ___path_search (char *tmpl, size_t tmpl_len, const char *dir,
61         const char *pfx /*, int try_tmpdir*/)
62 {
63     /*const char *d; */
64     /* dir and pfx lengths should always fit into an int,
65        so don't bother using size_t here.  Especially since
66        the printf func requires an int for precision (%*s).  */
67     int dlen, plen;
68
69     if (!pfx || !pfx[0])
70     {
71         pfx = "file";
72         plen = 4;
73     }
74     else
75     {
76         plen = strlen (pfx);
77         if (plen > 5)
78             plen = 5;
79     }
80
81     /* Disable support for $TMPDIR */
82 #if 0
83     if (try_tmpdir)
84     {
85         d = __secure_getenv ("TMPDIR");
86         if (d != NULL && direxists (d))
87             dir = d;
88         else if (dir != NULL && direxists (dir))
89             /* nothing */ ;
90         else
91             dir = NULL;
92     }
93 #endif
94     if (dir == NULL)
95     {
96         if (direxists (P_tmpdir))
97             dir = P_tmpdir;
98         else if (strcmp (P_tmpdir, "/tmp") != 0 && direxists ("/tmp"))
99             dir = "/tmp";
100         else
101         {
102             __set_errno (ENOENT);
103             return -1;
104         }
105     }
106
107     dlen = strlen (dir);
108     while (dlen > 1 && dir[dlen - 1] == '/')
109         dlen--;                 /* remove trailing slashes */
110
111     /* check we have room for "${dir}/${pfx}XXXXXX\0" */
112     if (tmpl_len < (size_t)dlen + 1 + plen + 6 + 1)
113     {
114         __set_errno (EINVAL);
115         return -1;
116     }
117
118     sprintf (tmpl, "%.*s/%.*sXXXXXX", dlen, dir, plen, pfx);
119     return 0;
120 }
121
122 /* These are the characters used in temporary filenames.  */
123 static const char letters[] =
124 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
125 #define NUM_LETTERS (62)
126
127 static unsigned int fillrand(unsigned char *buf, unsigned int len)
128 {
129     int fd;
130     unsigned int result = -1;
131     fd = open("/dev/urandom", O_RDONLY);
132     if (fd < 0) {
133         fd = open("/dev/random", O_RDONLY | O_NONBLOCK);
134     }
135     if (fd >= 0) {
136         result = read(fd, buf, len);
137         close(fd);
138     }
139     return result;
140 }
141
142 static void brain_damaged_fillrand(unsigned char *buf, unsigned int len)
143 {
144         unsigned int i, k;
145         struct timeval tv;
146         uint32_t high, low, rh;
147         static uint64_t value;
148         gettimeofday(&tv, NULL);
149         value += ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec ^ getpid();
150         low = value & UINT32_MAX;
151         high = value >> 32;
152         for (i = 0; i < len; ++i) {
153                 rh = high % NUM_LETTERS;
154                 high /= NUM_LETTERS;
155 #define L ((UINT32_MAX % NUM_LETTERS + 1) % NUM_LETTERS)
156                 k = (low % NUM_LETTERS) + (L * rh);
157 #undef L
158 #define H ((UINT32_MAX / NUM_LETTERS) + ((UINT32_MAX % NUM_LETTERS + 1) / NUM_LETTERS))
159                 low = (low / NUM_LETTERS) + (H * rh) + (k / NUM_LETTERS);
160 #undef H
161                 k %= NUM_LETTERS;
162                 buf[i] = letters[k];
163         }
164 }
165
166 /* Generate a temporary file name based on TMPL.  TMPL must match the
167    rules for mk[s]temp (i.e. end in "XXXXXX").  The name constructed
168    does not exist at the time of the call to __gen_tempname.  TMPL is
169    overwritten with the result.
170
171    KIND may be one of:
172    __GT_NOCREATE:       simply verify that the name does not exist
173                         at the time of the call. mode argument is ignored.
174    __GT_FILE:           create the file using open(O_CREAT|O_EXCL)
175                         and return a read-write fd with given mode.
176    __GT_BIGFILE:        same as __GT_FILE but use open64().
177    __GT_DIR:            create a directory with given mode.
178
179 */
180 int attribute_hidden __gen_tempname (char *tmpl, int kind, int flags, mode_t mode)
181 {
182     char *XXXXXX;
183     unsigned int i;
184     int fd, save_errno = errno;
185     unsigned char randomness[6];
186     size_t len;
187
188     len = strlen (tmpl);
189     /* This is where the Xs start.  */
190     XXXXXX = tmpl + len - 6;
191     if (len < 6 || strcmp (XXXXXX, "XXXXXX"))
192     {
193         __set_errno (EINVAL);
194         return -1;
195     }
196
197     for (i = 0; i < TMP_MAX; ++i) {
198         unsigned char j;
199         /* Get some random data.  */
200         if (fillrand(randomness, sizeof(randomness)) != sizeof(randomness)) {
201             /* if random device nodes failed us, lets use the braindamaged ver */
202             brain_damaged_fillrand(randomness, sizeof(randomness));
203         }
204         for (j = 0; j < sizeof(randomness); ++j)
205             XXXXXX[j] = letters[randomness[j] % NUM_LETTERS];
206
207         switch (kind) {
208             case __GT_NOCREATE:
209                 {
210                     struct stat st;
211                     if (stat (tmpl, &st) < 0) {
212                         if (errno == ENOENT) {
213                             fd = 0;
214                             goto restore_and_ret;
215                         } else
216                             /* Give up now. */
217                             return -1;
218                     } else
219                         fd = 0;
220                 }
221             case __GT_FILE:
222                 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | flags, mode);
223                 break;
224 #if defined __UCLIBC_HAS_LFS__
225             case __GT_BIGFILE:
226                 fd = open64 (tmpl, O_RDWR | O_CREAT | O_EXCL | flags, mode);
227                 break;
228 #endif
229             case __GT_DIR:
230                 fd = mkdir (tmpl, mode);
231                 break;
232             default:
233                 fd = -1;
234                 assert (! "invalid KIND in __gen_tempname");
235         }
236
237         if (fd >= 0) {
238 restore_and_ret:
239             __set_errno (save_errno);
240             return fd;
241         }
242         else if (errno != EEXIST)
243             /* Any other error will apply also to other names we might
244                try, and there are 2^32 or so of them, so give up now. */
245             return -1;
246     }
247
248     /* We got out of the loop because we ran out of combinations to try.  */
249     __set_errno (EEXIST);
250     return -1;
251 }