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