3 /* Copyright (C) 2001, 2003, 2004 Free Software Foundation, Inc.
4 Written by Werner Lemberg (wl@gnu.org)
6 This file is part of groff.
8 groff is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 2, or (at your option) any later
13 groff is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
18 You should have received a copy of the GNU General Public License along
19 with groff; see the file COPYING. If not, write to the Free Software
20 Foundation, 51 Franklin St - Fifth Floor, Boston, MA 02110-1301, USA. */
23 /* This file is heavily based on the function __gen_tempname() in the
24 file tempname.c which is part of the fileutils package. */
38 # define TMP_MAX 238328
42 # include <sys/time.h>
45 #ifdef HAVE_GETTIMEOFDAY
46 #ifdef NEED_DECLARATION_GETTIMEOFDAY
48 int gettimeofday(struct timeval
*, void *);
53 #if HAVE_CC_INTTYPES_H
54 # include <inttypes.h>
57 /* Use the widest available unsigned type if uint64_t is not
58 available. The algorithm below extracts a number less than 62**6
59 (approximately 2**35.725) from uint64_t, so ancient hosts where
60 uintmax_t is only 32 bits lose about 3.725 bits of randomness,
61 which is better than not having mkstemp at all. */
62 #if !defined UINT64_MAX && !defined uint64_t
63 # define uint64_t uintmax_t
66 /* These are the characters used in temporary filenames. */
67 static const char letters
[] =
68 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
70 int gen_tempname(char *tmpl
, int dir
)
72 static uint64_t value
;
74 size_t len
= strlen(tmpl
);
75 if (len
< 6 || strcmp(&tmpl
[len
- 6], "XXXXXX"))
76 return -1; /* EINVAL */
78 /* This is where the Xs start. */
79 char *XXXXXX
= &tmpl
[len
- 6];
81 /* Get some more or less random data. */
84 gettimeofday(&tv
, NULL
);
85 uint64_t random_time_bits
= ((uint64_t)tv
.tv_usec
<< 16) ^ tv
.tv_sec
;
87 uint64_t random_time_bits
= time(NULL
);
89 value
+= random_time_bits
^ getpid();
91 for (int count
= 0; count
< TMP_MAX
; value
+= 7777, ++count
) {
94 /* Fill in the random bits. */
95 XXXXXX
[0] = letters
[v
% 62];
97 XXXXXX
[1] = letters
[v
% 62];
99 XXXXXX
[2] = letters
[v
% 62];
101 XXXXXX
[3] = letters
[v
% 62];
103 XXXXXX
[4] = letters
[v
% 62];
105 XXXXXX
[5] = letters
[v
% 62];
107 int fd
= dir
? mkdir(tmpl
, S_IRUSR
| S_IWUSR
| S_IXUSR
)
108 : open(tmpl
, O_RDWR
| O_CREAT
| O_EXCL
, S_IRUSR
| S_IWUSR
);
112 else if (errno
!= EEXIST
)
116 /* We got out of the loop because we ran out of combinations to try. */
117 return -1; /* EEXIST */