xref: /freebsd/lib/libc/stdio/mktemp.c (revision 6829dae12bb055451fa467da4589c43bd03b1e64)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1987, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #if defined(LIBC_SCCS) && !defined(lint)
33 static char sccsid[] = "@(#)mktemp.c	8.1 (Berkeley) 6/4/93";
34 #endif /* LIBC_SCCS and not lint */
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include "namespace.h"
39 #include <sys/param.h>
40 #include <sys/stat.h>
41 #include <fcntl.h>
42 #include <errno.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <ctype.h>
47 #include <unistd.h>
48 #include "un-namespace.h"
49 
50 char *_mktemp(char *);
51 
52 static int _gettemp(char *, int *, int, int, int);
53 
54 static const unsigned char padchar[] =
55 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
56 
57 int
58 mkostemps(char *path, int slen, int oflags)
59 {
60 	int fd;
61 
62 	return (_gettemp(path, &fd, 0, slen, oflags) ? fd : -1);
63 }
64 
65 int
66 mkstemps(char *path, int slen)
67 {
68 	int fd;
69 
70 	return (_gettemp(path, &fd, 0, slen, 0) ? fd : -1);
71 }
72 
73 int
74 mkostemp(char *path, int oflags)
75 {
76 	int fd;
77 
78 	return (_gettemp(path, &fd, 0, 0, oflags) ? fd : -1);
79 }
80 
81 int
82 mkstemp(char *path)
83 {
84 	int fd;
85 
86 	return (_gettemp(path, &fd, 0, 0, 0) ? fd : -1);
87 }
88 
89 char *
90 mkdtemp(char *path)
91 {
92 	return (_gettemp(path, (int *)NULL, 1, 0, 0) ? path : (char *)NULL);
93 }
94 
95 char *
96 _mktemp(char *path)
97 {
98 	return (_gettemp(path, (int *)NULL, 0, 0, 0) ? path : (char *)NULL);
99 }
100 
101 __warn_references(mktemp,
102     "warning: mktemp() possibly used unsafely; consider using mkstemp()");
103 
104 char *
105 mktemp(char *path)
106 {
107 	return (_mktemp(path));
108 }
109 
110 static int
111 _gettemp(char *path, int *doopen, int domkdir, int slen, int oflags)
112 {
113 	char *start, *trv, *suffp, *carryp;
114 	char *pad;
115 	struct stat sbuf;
116 	int rval;
117 	uint32_t rand;
118 	char carrybuf[MAXPATHLEN];
119 
120 	if ((doopen != NULL && domkdir) || slen < 0 ||
121 	    (oflags & ~(O_APPEND | O_DIRECT | O_SHLOCK | O_EXLOCK | O_SYNC |
122 	    O_CLOEXEC)) != 0) {
123 		errno = EINVAL;
124 		return (0);
125 	}
126 
127 	for (trv = path; *trv != '\0'; ++trv)
128 		;
129 	if (trv - path >= MAXPATHLEN) {
130 		errno = ENAMETOOLONG;
131 		return (0);
132 	}
133 	trv -= slen;
134 	suffp = trv;
135 	--trv;
136 	if (trv < path || NULL != strchr(suffp, '/')) {
137 		errno = EINVAL;
138 		return (0);
139 	}
140 
141 	/* Fill space with random characters */
142 	while (trv >= path && *trv == 'X') {
143 		rand = arc4random_uniform(sizeof(padchar) - 1);
144 		*trv-- = padchar[rand];
145 	}
146 	start = trv + 1;
147 
148 	/* save first combination of random characters */
149 	memcpy(carrybuf, start, suffp - start);
150 
151 	/*
152 	 * check the target directory.
153 	 */
154 	if (doopen != NULL || domkdir) {
155 		for (; trv > path; --trv) {
156 			if (*trv == '/') {
157 				*trv = '\0';
158 				rval = stat(path, &sbuf);
159 				*trv = '/';
160 				if (rval != 0)
161 					return (0);
162 				if (!S_ISDIR(sbuf.st_mode)) {
163 					errno = ENOTDIR;
164 					return (0);
165 				}
166 				break;
167 			}
168 		}
169 	}
170 
171 	for (;;) {
172 		if (doopen) {
173 			if ((*doopen =
174 			    _open(path, O_CREAT|O_EXCL|O_RDWR|oflags, 0600)) >=
175 			    0)
176 				return (1);
177 			if (errno != EEXIST)
178 				return (0);
179 		} else if (domkdir) {
180 			if (mkdir(path, 0700) == 0)
181 				return (1);
182 			if (errno != EEXIST)
183 				return (0);
184 		} else if (lstat(path, &sbuf))
185 			return (errno == ENOENT);
186 
187 		/* If we have a collision, cycle through the space of filenames */
188 		for (trv = start, carryp = carrybuf;;) {
189 			/* have we tried all possible permutations? */
190 			if (trv == suffp)
191 				return (0); /* yes - exit with EEXIST */
192 			pad = strchr(padchar, *trv);
193 			if (pad == NULL) {
194 				/* this should never happen */
195 				errno = EIO;
196 				return (0);
197 			}
198 			/* increment character */
199 			*trv = (*++pad == '\0') ? padchar[0] : *pad;
200 			/* carry to next position? */
201 			if (*trv == *carryp) {
202 				/* increment position and loop */
203 				++trv;
204 				++carryp;
205 			} else {
206 				/* try with new name */
207 				break;
208 			}
209 		}
210 	}
211 	/*NOTREACHED*/
212 }
213