xref: /netbsd-src/external/gpl2/texinfo/dist/lib/tempname.c (revision 29619d2afe564e54d657b83e5a3ae89584f83720)
1*29619d2aSchristos /*	$NetBSD: tempname.c,v 1.1.1.1 2016/01/14 00:11:29 christos Exp $	*/
2*29619d2aSchristos 
3*29619d2aSchristos /* tempname.c - generate the name of a temporary file.
4*29619d2aSchristos 
5*29619d2aSchristos    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
6*29619d2aSchristos    2000, 2001, 2002, 2003 Free Software Foundation, Inc.
7*29619d2aSchristos 
8*29619d2aSchristos    This program is free software; you can redistribute it and/or modify
9*29619d2aSchristos    it under the terms of the GNU General Public License as published by
10*29619d2aSchristos    the Free Software Foundation; either version 2, or (at your option)
11*29619d2aSchristos    any later version.
12*29619d2aSchristos 
13*29619d2aSchristos    This program is distributed in the hope that it will be useful,
14*29619d2aSchristos    but WITHOUT ANY WARRANTY; without even the implied warranty of
15*29619d2aSchristos    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16*29619d2aSchristos    GNU General Public License for more details.
17*29619d2aSchristos 
18*29619d2aSchristos    You should have received a copy of the GNU General Public License along
19*29619d2aSchristos    with this program; if not, write to the Free Software Foundation,
20*29619d2aSchristos    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
21*29619d2aSchristos 
22*29619d2aSchristos #if HAVE_CONFIG_H
23*29619d2aSchristos # include <config.h>
24*29619d2aSchristos #endif
25*29619d2aSchristos 
26*29619d2aSchristos #include <sys/types.h>
27*29619d2aSchristos #include <assert.h>
28*29619d2aSchristos 
29*29619d2aSchristos #include <errno.h>
30*29619d2aSchristos #ifndef __set_errno
31*29619d2aSchristos # define __set_errno(Val) errno = (Val)
32*29619d2aSchristos #endif
33*29619d2aSchristos 
34*29619d2aSchristos #include <stdio.h>
35*29619d2aSchristos #ifndef P_tmpdir
36*29619d2aSchristos # define P_tmpdir "/tmp"
37*29619d2aSchristos #endif
38*29619d2aSchristos #ifndef TMP_MAX
39*29619d2aSchristos # define TMP_MAX 238328
40*29619d2aSchristos #endif
41*29619d2aSchristos #ifndef __GT_FILE
42*29619d2aSchristos # define __GT_FILE	0
43*29619d2aSchristos # define __GT_BIGFILE	1
44*29619d2aSchristos # define __GT_DIR	2
45*29619d2aSchristos # define __GT_NOCREATE	3
46*29619d2aSchristos #endif
47*29619d2aSchristos 
48*29619d2aSchristos #include <stddef.h>
49*29619d2aSchristos #include <stdlib.h>
50*29619d2aSchristos #include <string.h>
51*29619d2aSchristos 
52*29619d2aSchristos #if HAVE_FCNTL_H || _LIBC
53*29619d2aSchristos # include <fcntl.h>
54*29619d2aSchristos #endif
55*29619d2aSchristos 
56*29619d2aSchristos #if HAVE_SYS_TIME_H || _LIBC
57*29619d2aSchristos # include <sys/time.h>
58*29619d2aSchristos #endif
59*29619d2aSchristos 
60*29619d2aSchristos #if HAVE_STDINT_H || _LIBC
61*29619d2aSchristos # include <stdint.h>
62*29619d2aSchristos #endif
63*29619d2aSchristos #if HAVE_INTTYPES_H
64*29619d2aSchristos # include <inttypes.h>
65*29619d2aSchristos #endif
66*29619d2aSchristos 
67*29619d2aSchristos #if HAVE_UNISTD_H || _LIBC
68*29619d2aSchristos # include <unistd.h>
69*29619d2aSchristos #endif
70*29619d2aSchristos 
71*29619d2aSchristos #include <sys/stat.h>
72*29619d2aSchristos #if STAT_MACROS_BROKEN
73*29619d2aSchristos # undef S_ISDIR
74*29619d2aSchristos #endif
75*29619d2aSchristos #if !defined S_ISDIR && defined S_IFDIR
76*29619d2aSchristos # define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
77*29619d2aSchristos #endif
78*29619d2aSchristos #if !S_IRUSR && S_IREAD
79*29619d2aSchristos # define S_IRUSR S_IREAD
80*29619d2aSchristos #endif
81*29619d2aSchristos #if !S_IRUSR
82*29619d2aSchristos # define S_IRUSR 00400
83*29619d2aSchristos #endif
84*29619d2aSchristos #if !S_IWUSR && S_IWRITE
85*29619d2aSchristos # define S_IWUSR S_IWRITE
86*29619d2aSchristos #endif
87*29619d2aSchristos #if !S_IWUSR
88*29619d2aSchristos # define S_IWUSR 00200
89*29619d2aSchristos #endif
90*29619d2aSchristos #if !S_IXUSR && S_IEXEC
91*29619d2aSchristos # define S_IXUSR S_IEXEC
92*29619d2aSchristos #endif
93*29619d2aSchristos #if !S_IXUSR
94*29619d2aSchristos # define S_IXUSR 00100
95*29619d2aSchristos #endif
96*29619d2aSchristos 
97*29619d2aSchristos #if _LIBC
98*29619d2aSchristos # define struct_stat64 struct stat64
99*29619d2aSchristos #else
100*29619d2aSchristos # define struct_stat64 struct stat
101*29619d2aSchristos # define __getpid getpid
102*29619d2aSchristos # define __gettimeofday gettimeofday
103*29619d2aSchristos # define __mkdir mkdir
104*29619d2aSchristos # define __open open
105*29619d2aSchristos # define __open64 open
106*29619d2aSchristos # define __lxstat64(version, path, buf) lstat (path, buf)
107*29619d2aSchristos # define __xstat64(version, path, buf) stat (path, buf)
108*29619d2aSchristos #endif
109*29619d2aSchristos 
110*29619d2aSchristos #if ! (HAVE___SECURE_GETENV || _LIBC)
111*29619d2aSchristos # define __secure_getenv getenv
112*29619d2aSchristos #endif
113*29619d2aSchristos 
114*29619d2aSchristos #ifdef _LIBC
115*29619d2aSchristos # include <hp-timing.h>
116*29619d2aSchristos # if HP_TIMING_AVAIL
117*29619d2aSchristos #  define RANDOM_BITS(Var) \
118*29619d2aSchristos   if (__builtin_expect (value == UINT64_C (0), 0))			      \
119*29619d2aSchristos     {									      \
120*29619d2aSchristos       /* If this is the first time this function is used initialize	      \
121*29619d2aSchristos 	 the variable we accumulate the value in to some somewhat	      \
122*29619d2aSchristos 	 random value.  If we'd not do this programs at startup time	      \
123*29619d2aSchristos 	 might have a reduced set of possible names, at least on slow	      \
124*29619d2aSchristos 	 machines.  */							      \
125*29619d2aSchristos       struct timeval tv;						      \
126*29619d2aSchristos       __gettimeofday (&tv, NULL);					      \
127*29619d2aSchristos       value = ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec;		      \
128*29619d2aSchristos     }									      \
129*29619d2aSchristos   HP_TIMING_NOW (Var)
130*29619d2aSchristos # endif
131*29619d2aSchristos #endif
132*29619d2aSchristos 
133*29619d2aSchristos /* Use the widest available unsigned type if uint64_t is not
134*29619d2aSchristos    available.  The algorithm below extracts a number less than 62**6
135*29619d2aSchristos    (approximately 2**35.725) from uint64_t, so ancient hosts where
136*29619d2aSchristos    uintmax_t is only 32 bits lose about 3.725 bits of randomness,
137*29619d2aSchristos    which is better than not having mkstemp at all.  */
138*29619d2aSchristos #if !defined UINT64_MAX && !defined uint64_t
139*29619d2aSchristos # define uint64_t uintmax_t
140*29619d2aSchristos #endif
141*29619d2aSchristos 
142*29619d2aSchristos /* Return nonzero if DIR is an existent directory.  */
143*29619d2aSchristos static int
direxists(const char * dir)144*29619d2aSchristos direxists (const char *dir)
145*29619d2aSchristos {
146*29619d2aSchristos   struct_stat64 buf;
147*29619d2aSchristos   return __xstat64 (_STAT_VER, dir, &buf) == 0 && S_ISDIR (buf.st_mode);
148*29619d2aSchristos }
149*29619d2aSchristos 
150*29619d2aSchristos /* Path search algorithm, for tmpnam, tmpfile, etc.  If DIR is
151*29619d2aSchristos    non-null and exists, uses it; otherwise uses the first of $TMPDIR,
152*29619d2aSchristos    P_tmpdir, /tmp that exists.  Copies into TMPL a template suitable
153*29619d2aSchristos    for use with mk[s]temp.  Will fail (-1) if DIR is non-null and
154*29619d2aSchristos    doesn't exist, none of the searched dirs exists, or there's not
155*29619d2aSchristos    enough space in TMPL. */
156*29619d2aSchristos int
__path_search(char * tmpl,size_t tmpl_len,const char * dir,const char * pfx,int try_tmpdir)157*29619d2aSchristos __path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx,
158*29619d2aSchristos 	       int try_tmpdir)
159*29619d2aSchristos {
160*29619d2aSchristos   const char *d;
161*29619d2aSchristos   size_t dlen, plen;
162*29619d2aSchristos 
163*29619d2aSchristos   if (!pfx || !pfx[0])
164*29619d2aSchristos     {
165*29619d2aSchristos       pfx = "file";
166*29619d2aSchristos       plen = 4;
167*29619d2aSchristos     }
168*29619d2aSchristos   else
169*29619d2aSchristos     {
170*29619d2aSchristos       plen = strlen (pfx);
171*29619d2aSchristos       if (plen > 5)
172*29619d2aSchristos 	plen = 5;
173*29619d2aSchristos     }
174*29619d2aSchristos 
175*29619d2aSchristos   if (try_tmpdir)
176*29619d2aSchristos     {
177*29619d2aSchristos       d = __secure_getenv ("TMPDIR");
178*29619d2aSchristos       if (d != NULL && direxists (d))
179*29619d2aSchristos 	dir = d;
180*29619d2aSchristos       else if (dir != NULL && direxists (dir))
181*29619d2aSchristos 	/* nothing */ ;
182*29619d2aSchristos       else
183*29619d2aSchristos 	dir = NULL;
184*29619d2aSchristos     }
185*29619d2aSchristos   if (dir == NULL)
186*29619d2aSchristos     {
187*29619d2aSchristos       if (direxists (P_tmpdir))
188*29619d2aSchristos 	dir = P_tmpdir;
189*29619d2aSchristos       else if (strcmp (P_tmpdir, "/tmp") != 0 && direxists ("/tmp"))
190*29619d2aSchristos 	dir = "/tmp";
191*29619d2aSchristos       else
192*29619d2aSchristos 	{
193*29619d2aSchristos 	  __set_errno (ENOENT);
194*29619d2aSchristos 	  return -1;
195*29619d2aSchristos 	}
196*29619d2aSchristos     }
197*29619d2aSchristos 
198*29619d2aSchristos   dlen = strlen (dir);
199*29619d2aSchristos   while (dlen > 1 && dir[dlen - 1] == '/')
200*29619d2aSchristos     dlen--;			/* remove trailing slashes */
201*29619d2aSchristos 
202*29619d2aSchristos   /* check we have room for "${dir}/${pfx}XXXXXX\0" */
203*29619d2aSchristos   if (tmpl_len < dlen + 1 + plen + 6 + 1)
204*29619d2aSchristos     {
205*29619d2aSchristos       __set_errno (EINVAL);
206*29619d2aSchristos       return -1;
207*29619d2aSchristos     }
208*29619d2aSchristos 
209*29619d2aSchristos   sprintf (tmpl, "%.*s/%.*sXXXXXX", (int) dlen, dir, (int) plen, pfx);
210*29619d2aSchristos   return 0;
211*29619d2aSchristos }
212*29619d2aSchristos 
213*29619d2aSchristos /* These are the characters used in temporary filenames.  */
214*29619d2aSchristos static const char letters[] =
215*29619d2aSchristos "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
216*29619d2aSchristos 
217*29619d2aSchristos /* Generate a temporary file name based on TMPL.  TMPL must match the
218*29619d2aSchristos    rules for mk[s]temp (i.e. end in "XXXXXX").  The name constructed
219*29619d2aSchristos    does not exist at the time of the call to __gen_tempname.  TMPL is
220*29619d2aSchristos    overwritten with the result.
221*29619d2aSchristos 
222*29619d2aSchristos    KIND may be one of:
223*29619d2aSchristos    __GT_NOCREATE:	simply verify that the name does not exist
224*29619d2aSchristos 			at the time of the call.
225*29619d2aSchristos    __GT_FILE:		create the file using open(O_CREAT|O_EXCL)
226*29619d2aSchristos 			and return a read-write fd.  The file is mode 0600.
227*29619d2aSchristos    __GT_BIGFILE:	same as __GT_FILE but use open64().
228*29619d2aSchristos    __GT_DIR:		create a directory, which will be mode 0700.
229*29619d2aSchristos 
230*29619d2aSchristos    We use a clever algorithm to get hard-to-predict names. */
231*29619d2aSchristos int
__gen_tempname(char * tmpl,int kind)232*29619d2aSchristos __gen_tempname (char *tmpl, int kind)
233*29619d2aSchristos {
234*29619d2aSchristos   int len;
235*29619d2aSchristos   char *XXXXXX;
236*29619d2aSchristos   static uint64_t value;
237*29619d2aSchristos   uint64_t random_time_bits;
238*29619d2aSchristos   unsigned int count;
239*29619d2aSchristos   int fd = -1;
240*29619d2aSchristos   int save_errno = errno;
241*29619d2aSchristos   struct_stat64 st;
242*29619d2aSchristos 
243*29619d2aSchristos   /* A lower bound on the number of temporary files to attempt to
244*29619d2aSchristos      generate.  The maximum total number of temporary file names that
245*29619d2aSchristos      can exist for a given template is 62**6.  It should never be
246*29619d2aSchristos      necessary to try all these combinations.  Instead if a reasonable
247*29619d2aSchristos      number of names is tried (we define reasonable as 62**3) fail to
248*29619d2aSchristos      give the system administrator the chance to remove the problems.  */
249*29619d2aSchristos   unsigned int attempts_min = 62 * 62 * 62;
250*29619d2aSchristos 
251*29619d2aSchristos   /* The number of times to attempt to generate a temporary file.  To
252*29619d2aSchristos      conform to POSIX, this must be no smaller than TMP_MAX.  */
253*29619d2aSchristos   unsigned int attempts = attempts_min < TMP_MAX ? TMP_MAX : attempts_min;
254*29619d2aSchristos 
255*29619d2aSchristos   len = strlen (tmpl);
256*29619d2aSchristos   if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
257*29619d2aSchristos     {
258*29619d2aSchristos       __set_errno (EINVAL);
259*29619d2aSchristos       return -1;
260*29619d2aSchristos     }
261*29619d2aSchristos 
262*29619d2aSchristos   /* This is where the Xs start.  */
263*29619d2aSchristos   XXXXXX = &tmpl[len - 6];
264*29619d2aSchristos 
265*29619d2aSchristos   /* Get some more or less random data.  */
266*29619d2aSchristos #ifdef RANDOM_BITS
267*29619d2aSchristos   RANDOM_BITS (random_time_bits);
268*29619d2aSchristos #else
269*29619d2aSchristos # if HAVE_GETTIMEOFDAY || _LIBC
270*29619d2aSchristos   {
271*29619d2aSchristos     struct timeval tv;
272*29619d2aSchristos     __gettimeofday (&tv, NULL);
273*29619d2aSchristos     random_time_bits = ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec;
274*29619d2aSchristos   }
275*29619d2aSchristos # else
276*29619d2aSchristos   random_time_bits = time (NULL);
277*29619d2aSchristos # endif
278*29619d2aSchristos #endif
279*29619d2aSchristos   value += random_time_bits ^ __getpid ();
280*29619d2aSchristos 
281*29619d2aSchristos   for (count = 0; count < attempts; value += 7777, ++count)
282*29619d2aSchristos     {
283*29619d2aSchristos       uint64_t v = value;
284*29619d2aSchristos 
285*29619d2aSchristos       /* Fill in the random bits.  */
286*29619d2aSchristos       XXXXXX[0] = letters[v % 62];
287*29619d2aSchristos       v /= 62;
288*29619d2aSchristos       XXXXXX[1] = letters[v % 62];
289*29619d2aSchristos       v /= 62;
290*29619d2aSchristos       XXXXXX[2] = letters[v % 62];
291*29619d2aSchristos       v /= 62;
292*29619d2aSchristos       XXXXXX[3] = letters[v % 62];
293*29619d2aSchristos       v /= 62;
294*29619d2aSchristos       XXXXXX[4] = letters[v % 62];
295*29619d2aSchristos       v /= 62;
296*29619d2aSchristos       XXXXXX[5] = letters[v % 62];
297*29619d2aSchristos 
298*29619d2aSchristos       switch (kind)
299*29619d2aSchristos 	{
300*29619d2aSchristos 	case __GT_FILE:
301*29619d2aSchristos 	  fd = __open (tmpl, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
302*29619d2aSchristos 	  break;
303*29619d2aSchristos 
304*29619d2aSchristos 	case __GT_BIGFILE:
305*29619d2aSchristos 	  fd = __open64 (tmpl, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
306*29619d2aSchristos 	  break;
307*29619d2aSchristos 
308*29619d2aSchristos 	case __GT_DIR:
309*29619d2aSchristos 	  fd = __mkdir (tmpl, S_IRUSR | S_IWUSR | S_IXUSR);
310*29619d2aSchristos 	  break;
311*29619d2aSchristos 
312*29619d2aSchristos 	case __GT_NOCREATE:
313*29619d2aSchristos 	  /* This case is backward from the other three.  __gen_tempname
314*29619d2aSchristos 	     succeeds if __xstat fails because the name does not exist.
315*29619d2aSchristos 	     Note the continue to bypass the common logic at the bottom
316*29619d2aSchristos 	     of the loop.  */
317*29619d2aSchristos 	  if (__lxstat64 (_STAT_VER, tmpl, &st) < 0)
318*29619d2aSchristos 	    {
319*29619d2aSchristos 	      if (errno == ENOENT)
320*29619d2aSchristos 		{
321*29619d2aSchristos 		  __set_errno (save_errno);
322*29619d2aSchristos 		  return 0;
323*29619d2aSchristos 		}
324*29619d2aSchristos 	      else
325*29619d2aSchristos 		/* Give up now. */
326*29619d2aSchristos 		return -1;
327*29619d2aSchristos 	    }
328*29619d2aSchristos 	  continue;
329*29619d2aSchristos 
330*29619d2aSchristos 	default:
331*29619d2aSchristos 	  assert (! "invalid KIND in __gen_tempname");
332*29619d2aSchristos 	}
333*29619d2aSchristos 
334*29619d2aSchristos       if (fd >= 0)
335*29619d2aSchristos 	{
336*29619d2aSchristos 	  __set_errno (save_errno);
337*29619d2aSchristos 	  return fd;
338*29619d2aSchristos 	}
339*29619d2aSchristos       else if (errno != EEXIST)
340*29619d2aSchristos 	return -1;
341*29619d2aSchristos     }
342*29619d2aSchristos 
343*29619d2aSchristos   /* We got out of the loop because we ran out of combinations to try.  */
344*29619d2aSchristos   __set_errno (EEXIST);
345*29619d2aSchristos   return -1;
346*29619d2aSchristos }
347