gen_uuid.c revision ae91e64b
1/*
2 * gen_uuid.c --- generate a DCE-compatible uuid
3 *
4 * Copyright (C) 1996, 1997, 1998, 1999 Theodore Ts'o.
5 *
6 * %Begin-Header%
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, and the entire permission notice in its entirety,
12 *    including the disclaimer of warranties.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. The name of the author may not be used to endorse or promote
17 *    products derived from this software without specific prior
18 *    written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
21 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
23 * WHICH ARE HEREBY DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE
24 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
26 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
27 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
28 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
30 * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
31 * DAMAGE.
32 * %End-Header%
33 */
34
35#include <sys/param.h>
36#include <stdio.h>
37#ifdef HAVE_UNISTD_H
38#include <unistd.h>
39#endif
40#ifdef HAVE_STDLIB_H
41#include <stdlib.h>
42#endif
43#include <string.h>
44#include <fcntl.h>
45#include <errno.h>
46#include <limits.h>
47#include <sys/types.h>
48#ifdef HAVE_SYS_TIME_H
49#include <sys/time.h>
50#endif
51#include <sys/stat.h>
52#ifdef HAVE_SYS_FILE_H
53#include <sys/file.h>
54#endif
55#ifdef HAVE_SYS_IOCTL_H
56#include <sys/ioctl.h>
57#endif
58#ifdef HAVE_SYS_SOCKET_H
59#include <sys/socket.h>
60#endif
61#ifdef HAVE_SYS_UN_H
62#include <sys/un.h>
63#endif
64#ifdef HAVE_SYS_SOCKIO_H
65#include <sys/sockio.h>
66#endif
67#ifdef HAVE_NET_IF_H
68#include <net/if.h>
69#endif
70#ifdef HAVE_NETINET_IN_H
71#include <netinet/in.h>
72#endif
73#ifdef HAVE_NET_IF_DL_H
74#include <net/if_dl.h>
75#endif
76#if defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)
77#include <sys/syscall.h>
78#endif
79
80#include "uuidP.h"
81#include "randutils.h"
82
83#define read_all(a,b,c)	read(a,b,c)
84
85#ifdef HAVE_TLS
86#define THREAD_LOCAL static __thread
87#else
88#define THREAD_LOCAL static
89#endif
90
91/* index with UUID_VARIANT_xxx and shift 5 bits */
92static unsigned char variant_bits[] = { 0x00, 0x04, 0x06, 0x07 };
93
94/*
95 * Get the ethernet hardware address, if we can find it...
96 *
97 * XXX for a windows version, probably should use GetAdaptersInfo:
98 * http://www.codeguru.com/cpp/i-n/network/networkinformation/article.php/c5451
99 * commenting out get_node_id just to get gen_uuid to compile under windows
100 * is not the right way to go!
101 */
102static int get_node_id(unsigned char *node_id)
103{
104#ifdef HAVE_NET_IF_H
105	int		sd;
106	struct ifreq	ifr, *ifrp;
107	struct ifconf	ifc;
108	char buf[1024];
109	int		n, i;
110	unsigned char	*a;
111#ifdef HAVE_NET_IF_DL_H
112	struct sockaddr_dl *sdlp;
113#endif
114
115/*
116 * BSD 4.4 defines the size of an ifreq to be
117 * max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
118 * However, under earlier systems, sa_len isn't present, so the size is
119 * just sizeof(struct ifreq)
120 */
121#ifdef HAVE_SA_LEN
122#define ifreq_size(i) MAX(sizeof(struct ifreq),\
123     sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
124#else
125#define ifreq_size(i) sizeof(struct ifreq)
126#endif /* HAVE_SA_LEN */
127
128	sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
129	if (sd < 0) {
130		return -1;
131	}
132	memset(buf, 0, sizeof(buf));
133	ifc.ifc_len = sizeof(buf);
134	ifc.ifc_buf = buf;
135	if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0) {
136		close(sd);
137		return -1;
138	}
139	n = ifc.ifc_len;
140	for (i = 0; i < n; i+= ifreq_size(*ifrp) ) {
141		ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
142		strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
143#if defined(SIOCGIFHWADDR) && !defined(__sun)
144		if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
145			continue;
146		a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
147#else
148#ifdef SIOCGENADDR
149		if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
150			continue;
151		a = (unsigned char *) ifr.ifr_enaddr;
152#else
153#ifdef HAVE_NET_IF_DL_H
154		sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
155		if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
156			continue;
157		a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
158#else
159		/*
160		 * XXX we don't have a way of getting the hardware
161		 * address
162		 */
163		close(sd);
164		return 0;
165#endif /* HAVE_NET_IF_DL_H */
166#endif /* SIOCGENADDR */
167#endif /* SIOCGIFHWADDR */
168		if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5])
169			continue;
170		if (node_id) {
171			memcpy(node_id, a, 6);
172			close(sd);
173			return 1;
174		}
175	}
176	close(sd);
177#endif
178	return 0;
179}
180
181/* Assume that the gettimeofday() has microsecond granularity */
182#define MAX_ADJUSTMENT 10
183
184/*
185 * Get clock from global sequence clock counter.
186 *
187 * Return -1 if the clock counter could not be opened/locked (in this case
188 * pseudorandom value is returned in @ret_clock_seq), otherwise return 0.
189 */
190static int get_clock(uint32_t *clock_high, uint32_t *clock_low,
191		     uint16_t *ret_clock_seq, int *num)
192{
193	THREAD_LOCAL int		adjustment = 0;
194	THREAD_LOCAL struct timeval	last = {0, 0};
195	THREAD_LOCAL int		state_fd = -2;
196	THREAD_LOCAL FILE		*state_f;
197	THREAD_LOCAL uint16_t		clock_seq;
198	struct timeval			tv;
199	uint64_t			clock_reg;
200	mode_t				save_umask;
201	int				len;
202	int				ret = 0;
203
204	if (state_fd == -1)
205		ret = -1;
206
207	if (state_fd == -2) {
208		save_umask = umask(0);
209		state_fd = open(LIBUUID_CLOCK_FILE, O_RDWR|O_CREAT|O_CLOEXEC, 0660);
210		(void) umask(save_umask);
211		if (state_fd != -1) {
212			state_f = fdopen(state_fd, "r+" UL_CLOEXECSTR);
213			if (!state_f) {
214				close(state_fd);
215				state_fd = -1;
216				ret = -1;
217			}
218		}
219		else
220			ret = -1;
221	}
222	if (state_fd >= 0) {
223		rewind(state_f);
224		while (flock(state_fd, LOCK_EX) < 0) {
225			if ((errno == EAGAIN) || (errno == EINTR))
226				continue;
227			fclose(state_f);
228			close(state_fd);
229			state_fd = -1;
230			ret = -1;
231			break;
232		}
233	}
234	if (state_fd >= 0) {
235		unsigned int cl;
236		unsigned long tv1, tv2;
237		int a;
238
239		if (fscanf(state_f, "clock: %04x tv: %lu %lu adj: %d\n",
240			   &cl, &tv1, &tv2, &a) == 4) {
241			clock_seq = cl & 0x3FFF;
242			last.tv_sec = tv1;
243			last.tv_usec = tv2;
244			adjustment = a;
245		}
246	}
247
248	if ((last.tv_sec == 0) && (last.tv_usec == 0)) {
249		random_get_bytes(&clock_seq, sizeof(clock_seq));
250		clock_seq &= 0x3FFF;
251		gettimeofday(&last, NULL);
252		last.tv_sec--;
253	}
254
255try_again:
256	gettimeofday(&tv, NULL);
257	if ((tv.tv_sec < last.tv_sec) ||
258	    ((tv.tv_sec == last.tv_sec) &&
259	     (tv.tv_usec < last.tv_usec))) {
260		clock_seq = (clock_seq+1) & 0x3FFF;
261		adjustment = 0;
262		last = tv;
263	} else if ((tv.tv_sec == last.tv_sec) &&
264	    (tv.tv_usec == last.tv_usec)) {
265		if (adjustment >= MAX_ADJUSTMENT)
266			goto try_again;
267		adjustment++;
268	} else {
269		adjustment = 0;
270		last = tv;
271	}
272
273	clock_reg = tv.tv_usec*10 + adjustment;
274	clock_reg += ((uint64_t) tv.tv_sec)*10000000;
275	clock_reg += (((uint64_t) 0x01B21DD2) << 32) + 0x13814000;
276
277	if (num && (*num > 1)) {
278		adjustment += *num - 1;
279		last.tv_usec += adjustment / 10;
280		adjustment = adjustment % 10;
281		last.tv_sec += last.tv_usec / 1000000;
282		last.tv_usec = last.tv_usec % 1000000;
283	}
284
285	if (state_fd >= 0) {
286		rewind(state_f);
287		len = fprintf(state_f,
288			      "clock: %04x tv: %016ld %08ld adj: %08d\n",
289			      clock_seq, (long)last.tv_sec, (long)last.tv_usec, adjustment);
290		fflush(state_f);
291		if (ftruncate(state_fd, len) < 0) {
292			fprintf(state_f, "                   \n");
293			fflush(state_f);
294		}
295		rewind(state_f);
296		flock(state_fd, LOCK_UN);
297	}
298
299	*clock_high = clock_reg >> 32;
300	*clock_low = clock_reg;
301	*ret_clock_seq = clock_seq;
302	return ret;
303}
304
305static int __uuid_generate_time(uuid_t out, int *num)
306{
307	static unsigned char node_id[6];
308	static int has_init = 0;
309	struct uuid uu;
310	uint32_t	clock_mid;
311	int ret;
312
313	if (!has_init) {
314		if (get_node_id(node_id) <= 0) {
315			random_get_bytes(node_id, 6);
316			/*
317			 * Set multicast bit, to prevent conflicts
318			 * with IEEE 802 addresses obtained from
319			 * network cards
320			 */
321			node_id[0] |= 0x01;
322		}
323		has_init = 1;
324	}
325	ret = get_clock(&clock_mid, &uu.time_low, &uu.clock_seq, num);
326	uu.clock_seq |= 0x8000;
327	uu.time_mid = (uint16_t) clock_mid;
328	uu.time_hi_and_version = ((clock_mid >> 16) & 0x0FFF) | 0x1000;
329	memcpy(uu.node, node_id, 6);
330	uuid_pack(&uu, out);
331	return ret;
332}
333
334/*
335 * Generate time-based UUID and store it to @out
336 *
337 * Tries to guarantee uniqueness of the generated UUIDs by obtaining them from the uuidd daemon,
338 * or, if uuidd is not usable, by using the global clock state counter (see get_clock()).
339 * If neither of these is possible (e.g. because of insufficient permissions), it generates
340 * the UUID anyway, but returns -1. Otherwise, returns 0.
341 */
342static int uuid_generate_time_generic(uuid_t out) {
343	return __uuid_generate_time(out, NULL);
344}
345
346/*
347 * Generate time-based UUID and store it to @out.
348 *
349 * Discards return value from uuid_generate_time_generic()
350 */
351static void uuid_generate_time(uuid_t out)
352{
353	(void)uuid_generate_time_generic(out);
354}
355
356static void __uuid_generate_random(uuid_t out, int *num)
357{
358	uuid_t	buf;
359	struct uuid uu;
360	int i, n;
361
362	if (!num || !*num)
363		n = 1;
364	else
365		n = *num;
366
367	for (i = 0; i < n; i++) {
368		random_get_bytes(buf, sizeof(buf));
369		uuid_unpack(buf, &uu);
370
371		uu.clock_seq = (uu.clock_seq & 0x3FFF) | 0x8000;
372		uu.time_hi_and_version = (uu.time_hi_and_version & 0x0FFF)
373			| 0x4000;
374		uuid_pack(&uu, out);
375		out += sizeof(uuid_t);
376	}
377}
378
379void uuid_generate_random(uuid_t out)
380{
381	int	num = 1;
382	/* No real reason to use the daemon for random uuid's -- yet */
383
384	__uuid_generate_random(out, &num);
385}
386
387/*
388 * Check whether good random source (/dev/random or /dev/urandom)
389 * is available.
390 */
391static int have_random_source(void)
392{
393	return (access("/dev/random", R_OK) == 0 ||
394		access("/dev/urandom", R_OK) == 0);
395}
396
397
398/*
399 * This is the generic front-end to uuid_generate_random and
400 * uuid_generate_time.  It uses uuid_generate_random only if
401 * /dev/urandom is available, since otherwise we won't have
402 * high-quality randomness.
403 */
404void uuid_generate(uuid_t out)
405{
406	if (have_random_source())
407		uuid_generate_random(out);
408	else
409		uuid_generate_time(out);
410}
411