xref: /illumos-gate/usr/src/lib/libc/port/gen/mktemp.c (revision 7257d1b4)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*	Copyright (c) 1988 AT&T	*/
28 /*	  All Rights Reserved  	*/
29 
30 #pragma ident	"%Z%%M%	%I%	%E% SMI"
31 
32 /*
33  *	mktemp() expects a string with up to six trailing 'X's.
34  *	These will be overlaid with letters, digits and symbols from
35  *	the portable filename character set.  If every combination thus
36  *	inserted leads to an existing file name, the string is shortened
37  *	to length zero and a pointer to a null string is returned.
38  *
39  *	The guarantee made by mktime() to the caller is that the
40  *	generated file name string will not match the string
41  *	produced by any other concurrent process using mktemp().
42  *	To guarantee uniqueness across the process-id space,
43  *	the process-id of the caller is encoded into the string.
44  *	To allow repeated calls within the same process to generate
45  *	different strings on each call, a sequence number is encoded
46  *	into the string along with process-id.
47  *
48  *	The encoding is performed using radix-64 (6 bits per character),
49  *	with 64 characters taken from the portable file name character set.
50  *	This allows the six X's to be a representation of a 36-bit integer
51  *	composed of bit fields:
52  *		( pid | seq )
53  *	where the process-id occupies the high-order bits and the sequence
54  *	number occupies the low-order bits.  The size of the pid field is
55  *	not fixed at the traditional 15 bits (MAXPID = 30000); the system
56  *	now allows a larger process-id space and MAXPID is obtained from
57  *	the system with a call to sysconf(_SC_MAXPID).
58  *
59  *	mktime() should fail if fewer than six X's are presented to it.
60  *	However, this has been traditionally accepted and is preserved
61  *	in the present code.  The consequence is that the 36-bit integer
62  *	is reduced to a (6*N)-bit integer, where N is the number of X's.
63  *	mktime() fails immediately if the resulting integer is not large
64  *	enough to contain MAXPID.
65  *
66  *	In an attempt to confuse and thwart hackers, the starting
67  *	sequence number is randomized using the current time.
68  */
69 
70 #pragma weak _mktemp = mktemp
71 
72 #define	XCNT  6
73 
74 #include "lint.h"
75 #include "mtlib.h"
76 #include <sys/types.h>
77 #include <string.h>
78 #include <unistd.h>
79 #include <thread.h>
80 #include <synch.h>
81 #include <sys/stat.h>
82 #include <errno.h>
83 #include <sys/time.h>
84 #include <stdlib.h>
85 #include <stdio.h>
86 #include <sys/param.h>
87 
88 /*
89  * 64-bit digits, must be from the POSIX "portable file name character set".
90  */
91 static char
92 chars[64] = {
93 	'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
94 	'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
95 	'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
96 	'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
97 	'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '_',
98 };
99 
100 /*
101  * Find highest one bit set.
102  * Returns bit number of highest bit that is set.
103  * Low order bit is number 0, high order bit is number 31.
104  */
105 static int
106 highbit(uint_t i)
107 {
108 	int h = 0;
109 
110 	if (i & 0xffff0000)
111 		h += 16, i >>= 16;
112 	if (i & 0xff00)
113 		h += 8, i >>= 8;
114 	if (i & 0xf0)
115 		h += 4, i >>= 4;
116 	if (i & 0xc)
117 		h += 2, i >>= 2;
118 	if (i & 0x2)
119 		h += 1;
120 	return (h);
121 }
122 
123 char *
124 libc_mktemps(char *as, int slen)
125 {
126 	/* statics are protected by this static mutex */
127 	static mutex_t	mktemp_lock = DEFAULTMUTEX;
128 	static int	pidshift = 0;
129 	static int	previous_try = 0;
130 	static pid_t	previous_pid = 0;
131 	static int	previous_xcnt = XCNT;
132 
133 	pid_t		pid;
134 	int		try;
135 	int		tryshift;
136 	int		max_try;
137 	char		*s;
138 	char		*first_x;
139 	int		len;
140 	uint_t		xcnt;
141 	struct stat64	buf;
142 
143 	if (as == NULL || *as == '\0')	/* If the string passed is null then */
144 		return (as);	/* a pointer to a null string is returned. */
145 
146 	lmutex_lock(&mktemp_lock);
147 
148 	pid = getpid();
149 	if (pid != previous_pid) {	/* first time or first after fork() */
150 		/*
151 		 * Randomize the starting sequence number in
152 		 * an attempt to confuse and thwart hackers.
153 		 * Use the low 12 bits of the time in milliseconds.
154 		 */
155 		struct timeval tm;
156 
157 		(void) gettimeofday(&tm, NULL);
158 		previous_try = (tm.tv_sec * 1000 + tm.tv_usec / 1000) & 0xfff;
159 		previous_pid = pid;
160 		previous_xcnt = XCNT;
161 	}
162 
163 	/* for all possible values of pid, 0 <= pid < (1 << pidshift) */
164 	if (pidshift == 0)	/* one-time initialization */
165 		pidshift = highbit((uint_t)MAXPID) + 1;
166 
167 	/* count the X's */
168 	xcnt = 0;
169 	len = (int)strlen(as);
170 	if (slen >= len || slen < 0)
171 		goto fail;
172 	len -= slen;
173 	s = as + (len - 1);
174 	while ((len != 0) && (xcnt < XCNT) && (*s == 'X')) {
175 		xcnt++;
176 		len--;
177 		--s;
178 	}
179 	first_x = s + 1;	/* Remember pointer to the first X */
180 
181 	/* fail if we don't have enough X's to represent MAXPID */
182 	if ((tryshift = xcnt * 6 - pidshift) < 0) {
183 		/*
184 		 * Some broken programs call mktemp() repeatedly,
185 		 * passing the same string without reinserting the X's.
186 		 * Check to see if this is such a call by testing
187 		 * the trailing characters of the string for a
188 		 * match with the process-id.
189 		 */
190 		uint64_t xpid = 0;		/* reconstructed pid */
191 
192 		s = as + len;
193 		for (xcnt = previous_xcnt; xcnt && s > as; xcnt--) {
194 			int c;
195 			int i;
196 
197 			c = *--s;
198 			for (i = 0; i < 64; i++)
199 				if (c == chars[i])
200 					break;
201 			if (i == 64)
202 				goto fail;
203 			xpid = xpid * 64 + i;
204 		}
205 		xpid >>= (previous_xcnt * 6 - pidshift);
206 		xpid &= ((1 << pidshift) - 1);
207 
208 		if (xpid == pid &&
209 		    lstat64(as, &buf) == -1 && errno == ENOENT) {
210 			lmutex_unlock(&mktemp_lock);
211 			return (as);
212 		}
213 
214 		goto fail;
215 	}
216 
217 	/* we can try sequence numbers in the range 0 <= try < max_try */
218 	max_try = 1 << tryshift;
219 	if (previous_try >= max_try)
220 		previous_try = 0;
221 
222 	try = previous_try;
223 	for (;;) {
224 		/* num is up to a 36-bit integer ... */
225 		uint64_t num = ((uint64_t)pid << tryshift) + (uint64_t)try;
226 		int i;
227 
228 		/* ... which we represent backwards in base 64 */
229 		for (i = 0, s = first_x; i < xcnt; i++) {
230 			*s++ = chars[num & 077];
231 			num >>= 6;
232 		}
233 
234 		if (lstat64(as, &buf) == -1) {
235 			if (errno != ENOENT)
236 				break;		/* unrecoverable error */
237 			/* remember where we left off for the next call */
238 			previous_try = try + 1;
239 			previous_xcnt = xcnt;
240 			lmutex_unlock(&mktemp_lock);
241 			return (as);
242 		}
243 
244 		if (++try == max_try)
245 			try = 0;
246 		if (try == previous_try)
247 			break;
248 	}
249 
250 fail:
251 	lmutex_unlock(&mktemp_lock);
252 	*as = '\0';
253 	return (as);
254 }
255 
256 char *
257 mktemp(char *template)
258 {
259 	return (libc_mktemps(template, 0));
260 }
261