xref: /titanic_41/usr/src/lib/libc/port/gen/mktemp.c (revision c138f478d2bc94e73ab8f6a084e323bec25e62f5)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*	Copyright (c) 1988 AT&T	*/
30 /*	  All Rights Reserved  	*/
31 
32 
33 /*
34  *	mktemp() expects a string with up to six trailing 'X's.
35  *	These will be overlaid with letters, digits and symbols from
36  *	the portable filename character set.  If every combination thus
37  *	inserted leads to an existing file name, the string is shortened
38  *	to length zero and a pointer to a null string is returned.
39  *
40  *	The guarantee made by mktime() to the caller is that the
41  *	generated file name string will not match the string
42  *	produced by any other concurrent process using mktemp().
43  *	To guarantee uniqueness across the process-id space,
44  *	the process-id of the caller is encoded into the string.
45  *	To allow repeated calls within the same process to generate
46  *	different strings on each call, a sequence number is encoded
47  *	into the string along with process-id.
48  *
49  *	The encoding is performed using radix-64 (6 bits per character),
50  *	with 64 characters taken from the portable file name character set.
51  *	This allows the six X's to be a representation of a 36-bit integer
52  *	composed of bit fields:
53  *		( pid | seq )
54  *	where the process-id occupies the high-order bits and the sequence
55  *	number occupies the low-order bits.  The size of the pid field is
56  *	not fixed at the traditional 15 bits (MAXPID = 30000); the system
57  *	now allows a larger process-id space and MAXPID is obtained from
58  *	the system with a call to sysconf(_SC_MAXPID).
59  *
60  *	mktime() should fail if fewer than six X's are presented to it.
61  *	However, this has been traditionally accepted and is preserved
62  *	in the present code.  The consequence is that the 36-bit integer
63  *	is reduced to a (6*N)-bit integer, where N is the number of X's.
64  *	mktime() fails immediately if the resulting integer is not large
65  *	enough to contain MAXPID.
66  *
67  *	In an attempt to confuse and thwart hackers, the starting
68  *	sequence number is randomized using the current time.
69  */
70 
71 #define	XCNT  6
72 #pragma weak mktemp = _mktemp
73 
74 #include "synonyms.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 mktemp(char *as)
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 	s = as + (len - 1);
171 	while ((len != 0) && (xcnt < XCNT) && (*s == 'X')) {
172 		xcnt++;
173 		len--;
174 		--s;
175 	}
176 	first_x = s + 1;	/* Remember pointer to the first X */
177 
178 	/* fail if we don't have enough X's to represent MAXPID */
179 	if ((tryshift = xcnt * 6 - pidshift) < 0) {
180 		/*
181 		 * Some broken programs call mktemp() repeatedly,
182 		 * passing the same string without reinserting the X's.
183 		 * Check to see if this is such a call by testing
184 		 * the trailing characters of the string for a
185 		 * match with the process-id.
186 		 */
187 		uint64_t xpid = 0;		/* reconstructed pid */
188 
189 		s = as + len;
190 		for (xcnt = previous_xcnt; xcnt && s > as; xcnt--) {
191 			int c;
192 			int i;
193 
194 			c = *--s;
195 			for (i = 0; i < 64; i++)
196 				if (c == chars[i])
197 					break;
198 			if (i == 64)
199 				goto fail;
200 			xpid = xpid * 64 + i;
201 		}
202 		xpid >>= (previous_xcnt * 6 - pidshift);
203 		xpid &= ((1 << pidshift) - 1);
204 
205 		if (xpid == pid &&
206 		    lstat64(as, &buf) == -1 && errno == ENOENT) {
207 			lmutex_unlock(&mktemp_lock);
208 			return (as);
209 		}
210 
211 		goto fail;
212 	}
213 
214 	/* we can try sequence numbers in the range 0 <= try < max_try */
215 	max_try = 1 << tryshift;
216 	if (previous_try >= max_try)
217 		previous_try = 0;
218 
219 	try = previous_try;
220 	for (;;) {
221 		/* num is up to a 36-bit integer ... */
222 		uint64_t num = ((uint64_t)pid << tryshift) + (uint64_t)try;
223 		int i;
224 
225 		/* ... which we represent backwards in base 64 */
226 		for (i = 0, s = first_x; i < xcnt; i++) {
227 			*s++ = chars[num & 077];
228 			num >>= 6;
229 		}
230 
231 		if (lstat64(as, &buf) == -1) {
232 			if (errno != ENOENT)
233 				break;		/* unrecoverable error */
234 			/* remember where we left off for the next call */
235 			previous_try = try + 1;
236 			previous_xcnt = xcnt;
237 			lmutex_unlock(&mktemp_lock);
238 			return (as);
239 		}
240 
241 		if (++try == max_try)
242 			try = 0;
243 		if (try == previous_try)
244 			break;
245 	}
246 
247 fail:
248 	lmutex_unlock(&mktemp_lock);
249 	*as = '\0';
250 	return (as);
251 }
252