OSDN Git Service

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