2 * Copyright (c) 2001, 2003, 2004, 2008-2011, 2013
3 * Todd C. Miller <Todd.Miller@courtesan.com>
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 #if !defined(HAVE_MKSTEMPS) || !defined(HAVE_MKDTEMP)
22 #include <sys/types.h>
32 #endif /* HAVE_STDLIB_H */
36 #endif /* HAVE_UNISTD_H */
37 #if TIME_WITH_SYS_TIME
46 #define TEMPCHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
47 #define NUM_CHARS (sizeof(TEMPCHARS) - 1)
50 #define INT_MAX 0x7fffffff
55 # define SRAND srandom
56 # define SEED_T unsigned int
60 # define SRAND srand48
65 # define SEED_T unsigned int
76 * Seed from time of day and process id multiplied by small primes.
78 (void) gettimeofday(&tv, NULL);
79 seed = (tv.tv_sec % 10000) * 523 + tv.tv_usec * 13 +
80 (getpid() % 1000) * 983;
87 static int initialized;
94 return RAND() & 0xffffffff;
98 mktemp_internal(char *path, int slen, int mode)
100 char *start, *cp, *ep;
101 const char *tempchars = TEMPCHARS;
102 unsigned int r, tries;
105 for (ep = path; *ep; ep++)
107 if (path + slen >= ep) {
114 for (start = ep; start > path && start[-1] == 'X'; start--) {
115 if (tries < INT_MAX / NUM_CHARS)
121 for (cp = start; *cp; cp++) {
122 r = get_random() % NUM_CHARS;
128 fd = open(path, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
129 if (fd != -1 || errno != EEXIST)
133 if (mkdir(path, S_IRWXU) == 0)
145 #ifndef HAVE_MKSTEMPS
147 mkstemps(char *path, int slen)
149 return mktemp_internal(path, slen, MKTEMP_FILE);
151 #endif /* HAVE_MKSTEMPS */
157 if (mktemp_internal(path, 0, MKTEMP_DIR) == -1)
161 #endif /* HAVE_MKDTEMP */
162 #endif /* !HAVE_MKSTEMPS || !HAVE_MKDTEMP */