1 /* THIS FILE HAS BEEN MODIFIED FROM THE ORIGINAL OPENBSD SOURCE */
2 /* Changes: Removed mktemp */
4 /* $OpenBSD: mktemp.c,v 1.30 2010/03/21 23:09:30 schwarze Exp $ */
6 * Copyright (c) 1996-1998, 2008 Theo de Raadt
7 * Copyright (c) 1997, 2008-2009 Todd C. Miller
9 * Permission to use, copy, modify, and distribute this software for any
10 * purpose with or without fee is hereby granted, provided that the above
11 * copyright notice and this permission notice appear in all copies.
13 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22 /* OPENBSD ORIGINAL: lib/libc/stdio/mktemp.c */
26 #include <sys/types.h>
37 #if !defined(HAVE_MKDTEMP) || defined(HAVE_STRICT_MKSTEMP)
43 #define TEMPCHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
44 #define NUM_CHARS (sizeof(TEMPCHARS) - 1)
47 mktemp_internal(char *path, int slen, int mode)
49 char *start, *cp, *ep;
50 const char *tempchars = TEMPCHARS;
51 unsigned int r, tries;
57 if (len == 0 || slen < 0 || (size_t)slen >= len) {
61 ep = path + len - slen;
64 for (start = ep; start > path && start[-1] == 'X'; start--) {
65 if (tries < INT_MAX / NUM_CHARS)
71 for (cp = start; cp != ep; cp++) {
72 r = arc4random_uniform(NUM_CHARS);
78 if (lstat(path, &sb) != 0)
79 return(errno == ENOENT ? 0 : -1);
82 fd = open(path, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
83 if (fd != -1 || errno != EEXIST)
87 if (mkdir(path, S_IRUSR|S_IWUSR|S_IXUSR) == 0)
100 char *_mktemp(char *);
105 if (mktemp_internal(path, 0, MKTEMP_NAME) == -1)
110 __warn_references(mktemp,
111 "warning: mktemp() possibly used unsafely; consider using mkstemp()");
116 return(_mktemp(path));
123 return(mktemp_internal(path, 0, MKTEMP_FILE));
127 mkstemps(char *path, int slen)
129 return(mktemp_internal(path, slen, MKTEMP_FILE));
137 error = mktemp_internal(path, 0, MKTEMP_DIR);
138 return(error ? NULL : path);
141 #endif /* !defined(HAVE_MKDTEMP) || defined(HAVE_STRICT_MKSTEMP) */