gen_uuid.c revision 5610f9924bfe506852701f1f11f6ca9f421e8a57
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/*
36 * Force inclusion of SVID stuff since we need it if we're compiling in
37 * gcc-wall wall mode
38 */
39#define _SVID_SOURCE
40
41#include <stdio.h>
42#ifdef HAVE_UNISTD_H
43#include <unistd.h>
44#endif
45#ifdef HAVE_STDLIB_H
46#include <stdlib.h>
47#endif
48#include <string.h>
49#include <fcntl.h>
50#include <errno.h>
51#include <sys/types.h>
52#include <sys/time.h>
53#include <sys/wait.h>
54#include <sys/stat.h>
55#include <sys/file.h>
56#ifdef HAVE_SYS_IOCTL_H
57#include <sys/ioctl.h>
58#endif
59#ifdef HAVE_SYS_SOCKET_H
60#include <sys/socket.h>
61#endif
62#include <sys/un.h>
63#ifdef HAVE_SYS_SOCKIO_H
64#include <sys/sockio.h>
65#endif
66#ifdef HAVE_NET_IF_H
67#include <net/if.h>
68#endif
69#ifdef HAVE_NETINET_IN_H
70#include <netinet/in.h>
71#endif
72#ifdef HAVE_NET_IF_DL_H
73#include <net/if_dl.h>
74#endif
75#ifdef __linux__
76#include <sys/syscall.h>
77#endif
78
79#include "uuidP.h"
80#include "uuidd.h"
81
82#ifdef HAVE_SRANDOM
83#define srand(x) 	srandom(x)
84#define rand() 		random()
85#endif
86
87#ifdef TLS
88#define THREAD_LOCAL static TLS
89#else
90#define THREAD_LOCAL static
91#endif
92
93#if defined(__linux__) && defined(__NR_gettid) && defined(HAVE_JRAND48)
94#define DO_JRAND_MIX
95THREAD_LOCAL unsigned short jrand_seed[3];
96#endif
97
98static int get_random_fd(void)
99{
100	struct timeval	tv;
101	static int	fd = -2;
102	int		i;
103
104	if (fd == -2) {
105		gettimeofday(&tv, 0);
106		fd = open("/dev/urandom", O_RDONLY);
107		if (fd == -1)
108			fd = open("/dev/random", O_RDONLY | O_NONBLOCK);
109		if (fd >= 0) {
110			i = fcntl(fd, F_GETFD);
111			if (i >= 0)
112				fcntl(fd, F_SETFD, i | FD_CLOEXEC);
113		}
114		srand((getpid() << 16) ^ getuid() ^ tv.tv_sec ^ tv.tv_usec);
115#ifdef DO_JRAND_MIX
116		jrand_seed[0] = getpid() ^ (tv.tv_sec & 0xFFFF);
117		jrand_seed[1] = getppid() ^ (tv.tv_usec & 0xFFFF);
118		jrand_seed[2] = (tv.tv_sec ^ tv.tv_usec) >> 16;
119#endif
120	}
121	/* Crank the random number generator a few times */
122	gettimeofday(&tv, 0);
123	for (i = (tv.tv_sec ^ tv.tv_usec) & 0x1F; i > 0; i--)
124		rand();
125	return fd;
126}
127
128
129/*
130 * Generate a series of random bytes.  Use /dev/urandom if possible,
131 * and if not, use srandom/random.
132 */
133static void get_random_bytes(void *buf, int nbytes)
134{
135	int i, n = nbytes, fd = get_random_fd();
136	int lose_counter = 0;
137	unsigned char *cp = (unsigned char *) buf;
138	unsigned short tmp_seed[3];
139
140	if (fd >= 0) {
141		while (n > 0) {
142			i = read(fd, cp, n);
143			if (i <= 0) {
144				if (lose_counter++ > 16)
145					break;
146				continue;
147			}
148			n -= i;
149			cp += i;
150			lose_counter = 0;
151		}
152	}
153
154	/*
155	 * We do this all the time, but this is the only source of
156	 * randomness if /dev/random/urandom is out to lunch.
157	 */
158	for (cp = buf, i = 0; i < nbytes; i++)
159		*cp++ ^= (rand() >> 7) & 0xFF;
160#ifdef DO_JRAND_MIX
161	memcpy(tmp_seed, jrand_seed, sizeof(tmp_seed));
162	jrand_seed[2] = jrand_seed[2] ^ syscall(__NR_gettid);
163	for (cp = buf, i = 0; i < nbytes; i++)
164		*cp++ ^= (jrand48(tmp_seed) >> 7) & 0xFF;
165	memcpy(jrand_seed, tmp_seed,
166	       sizeof(jrand_seed)-sizeof(unsigned short));
167#endif
168
169	return;
170}
171
172/*
173 * Get the ethernet hardware address, if we can find it...
174 */
175static int get_node_id(unsigned char *node_id)
176{
177#ifdef HAVE_NET_IF_H
178	int 		sd;
179	struct ifreq 	ifr, *ifrp;
180	struct ifconf 	ifc;
181	char buf[1024];
182	int		n, i;
183	unsigned char 	*a;
184#ifdef HAVE_NET_IF_DL_H
185	struct sockaddr_dl *sdlp;
186#endif
187
188/*
189 * BSD 4.4 defines the size of an ifreq to be
190 * max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
191 * However, under earlier systems, sa_len isn't present, so the size is
192 * just sizeof(struct ifreq)
193 */
194#ifdef HAVE_SA_LEN
195#ifndef max
196#define max(a,b) ((a) > (b) ? (a) : (b))
197#endif
198#define ifreq_size(i) max(sizeof(struct ifreq),\
199     sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
200#else
201#define ifreq_size(i) sizeof(struct ifreq)
202#endif /* HAVE_SA_LEN*/
203
204	sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
205	if (sd < 0) {
206		return -1;
207	}
208	memset(buf, 0, sizeof(buf));
209	ifc.ifc_len = sizeof(buf);
210	ifc.ifc_buf = buf;
211	if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0) {
212		close(sd);
213		return -1;
214	}
215	n = ifc.ifc_len;
216	for (i = 0; i < n; i+= ifreq_size(*ifrp) ) {
217		ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
218		strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
219#ifdef SIOCGIFHWADDR
220		if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
221			continue;
222		a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
223#else
224#ifdef SIOCGENADDR
225		if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
226			continue;
227		a = (unsigned char *) ifr.ifr_enaddr;
228#else
229#ifdef HAVE_NET_IF_DL_H
230		sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
231		if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
232			continue;
233		a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
234#else
235		/*
236		 * XXX we don't have a way of getting the hardware
237		 * address
238		 */
239		close(sd);
240		return 0;
241#endif /* HAVE_NET_IF_DL_H */
242#endif /* SIOCGENADDR */
243#endif /* SIOCGIFHWADDR */
244		if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5])
245			continue;
246		if (node_id) {
247			memcpy(node_id, a, 6);
248			close(sd);
249			return 1;
250		}
251	}
252	close(sd);
253#endif
254	return 0;
255}
256
257/* Assume that the gettimeofday() has microsecond granularity */
258#define MAX_ADJUSTMENT 10
259
260static int get_clock(uint32_t *clock_high, uint32_t *clock_low,
261		     uint16_t *ret_clock_seq, int *num)
262{
263	THREAD_LOCAL int		adjustment = 0;
264	THREAD_LOCAL struct timeval	last = {0, 0};
265	THREAD_LOCAL int		state_fd = -2;
266	THREAD_LOCAL FILE		*state_f;
267	THREAD_LOCAL uint16_t		clock_seq;
268	struct timeval 			tv;
269	unsigned long long		clock_reg;
270	mode_t				save_umask;
271
272	if (state_fd == -2) {
273		save_umask = umask(0);
274		state_fd = open("/var/lib/libuuid/clock.txt",
275				O_RDWR|O_CREAT, 0660);
276		(void) umask(save_umask);
277		state_f = fdopen(state_fd, "r+");
278		if (!state_f) {
279			close(state_fd);
280			state_fd = -1;
281		}
282	}
283	if (state_fd >= 0) {
284		rewind(state_f);
285		while (lockf(state_fd, F_LOCK, 0) < 0) {
286			if ((errno == EAGAIN) || (errno == EINTR))
287				continue;
288			fclose(state_f);
289			close(state_fd);
290			state_fd = -1;
291		}
292	}
293	if (state_fd >= 0) {
294		unsigned int cl;
295		unsigned long tv1, tv2;
296		int a;
297
298		if (fscanf(state_f, "clock: %04x tv: %lu %lu adj: %d\n",
299			   &cl, &tv1, &tv2, &a) == 4) {
300			clock_seq = cl & 0x3FFF;
301			last.tv_sec = tv1;
302			last.tv_usec = tv2;
303			adjustment = a;
304		}
305	}
306
307	if ((last.tv_sec == 0) && (last.tv_usec == 0)) {
308		get_random_bytes(&clock_seq, sizeof(clock_seq));
309		clock_seq &= 0x3FFF;
310		last = tv;
311		last.tv_sec--;
312	}
313
314try_again:
315	gettimeofday(&tv, 0);
316	if ((tv.tv_sec < last.tv_sec) ||
317	    ((tv.tv_sec == last.tv_sec) &&
318	     (tv.tv_usec < last.tv_usec))) {
319		clock_seq = (clock_seq+1) & 0x3FFF;
320		adjustment = 0;
321		last = tv;
322	} else if ((tv.tv_sec == last.tv_sec) &&
323	    (tv.tv_usec == last.tv_usec)) {
324		if (adjustment >= MAX_ADJUSTMENT)
325			goto try_again;
326		adjustment++;
327	} else {
328		adjustment = 0;
329		last = tv;
330	}
331
332	clock_reg = tv.tv_usec*10 + adjustment;
333	clock_reg += ((unsigned long long) tv.tv_sec)*10000000;
334	clock_reg += (((unsigned long long) 0x01B21DD2) << 32) + 0x13814000;
335
336	if (num && (*num > 1)) {
337		adjustment += *num - 1;
338		last.tv_usec += adjustment / 10;
339		adjustment = adjustment % 10;
340		last.tv_sec += last.tv_usec / 1000000;
341		last.tv_usec = last.tv_usec % 1000000;
342	}
343
344	if (state_fd > 0) {
345		rewind(state_f);
346		ftruncate(state_fd, 0);
347		fprintf(state_f, "clock: %04x tv: %lu %lu adj: %d\n",
348			clock_seq, last.tv_sec, last.tv_usec, adjustment);
349		fflush(state_f);
350		rewind(state_f);
351		lockf(state_fd, F_ULOCK, 0);
352	}
353
354	*clock_high = clock_reg >> 32;
355	*clock_low = clock_reg;
356	*ret_clock_seq = clock_seq;
357	return 0;
358}
359
360static ssize_t read_all(int fd, char *buf, size_t count)
361{
362	ssize_t ret;
363	ssize_t c = 0;
364
365	memset(buf, 0, count);
366	while (count > 0) {
367		ret = read(fd, buf, count);
368		if (ret < 0) {
369			if ((errno == EAGAIN) || (errno == EINTR))
370				continue;
371			return -1;
372		}
373		count -= ret;
374		buf += ret;
375		c += ret;
376	}
377	return c;
378}
379
380
381/*
382 * Try using the uuidd daemon to generate the UUID
383 *
384 * Returns 0 on success, non-zero on failure.
385 */
386static int get_uuid_via_daemon(int op, uuid_t out, int *num)
387{
388#ifdef USE_UUIDD
389	char op_buf[64];
390	int op_len;
391	int s;
392	ssize_t ret;
393	int32_t reply_len = 0, expected = 16;
394	struct sockaddr_un srv_addr;
395	pid_t pid;
396	static const char *uuidd_path = UUIDD_PATH;
397	static int access_ret = -2;
398	static int start_attempts = 0;
399
400	if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
401		return -1;
402
403	srv_addr.sun_family = AF_UNIX;
404	strcpy(srv_addr.sun_path, UUIDD_SOCKET_PATH);
405
406	if (connect(s, (const struct sockaddr *) &srv_addr,
407		    sizeof(struct sockaddr_un)) < 0) {
408		if (access_ret == -2)
409			access_ret = access(uuidd_path, X_OK);
410		if (access_ret == 0 && start_attempts++ < 5) {
411			if ((pid = fork()) == 0) {
412				execl(uuidd_path, "uuidd", "-qT", "300", 0);
413				exit(1);
414			}
415			(void) waitpid(pid, 0, 0);
416			if (connect(s, (const struct sockaddr *) &srv_addr,
417				    sizeof(struct sockaddr_un)) < 0)
418				goto fail;
419		} else
420			goto fail;
421	}
422	op_buf[0] = op;
423	op_len = 1;
424	if (op == UUIDD_OP_BULK_TIME_UUID) {
425		memcpy(op_buf+1, num, sizeof(*num));
426		op_len += sizeof(*num);
427		expected += sizeof(*num);
428	}
429
430	ret = write(s, op_buf, op_len);
431	if (ret < 1)
432		goto fail;
433
434	ret = read_all(s, (char *) &reply_len, sizeof(reply_len));
435	if (ret < 0)
436		goto fail;
437
438	if (reply_len != expected)
439		goto fail;
440
441	ret = read_all(s, op_buf, reply_len);
442
443	if (op == UUIDD_OP_BULK_TIME_UUID)
444		memcpy(op_buf+16, num, sizeof(int));
445
446	memcpy(out, op_buf, 16);
447
448	close(s);
449	return ((ret == expected) ? 0 : -1);
450
451fail:
452	close(s);
453#endif
454	return -1;
455}
456
457void uuid__generate_time(uuid_t out, int *num)
458{
459	static unsigned char node_id[6];
460	static int has_init = 0;
461	struct uuid uu;
462	uint32_t	clock_mid;
463
464	if (!has_init) {
465		if (get_node_id(node_id) <= 0) {
466			get_random_bytes(node_id, 6);
467			/*
468			 * Set multicast bit, to prevent conflicts
469			 * with IEEE 802 addresses obtained from
470			 * network cards
471			 */
472			node_id[0] |= 0x01;
473		}
474		has_init = 1;
475	}
476	get_clock(&clock_mid, &uu.time_low, &uu.clock_seq, num);
477	uu.clock_seq |= 0x8000;
478	uu.time_mid = (uint16_t) clock_mid;
479	uu.time_hi_and_version = ((clock_mid >> 16) & 0x0FFF) | 0x1000;
480	memcpy(uu.node, node_id, 6);
481	uuid_pack(&uu, out);
482}
483
484void uuid_generate_time(uuid_t out)
485{
486#ifdef TLS
487	THREAD_LOCAL int		num = 0;
488	THREAD_LOCAL struct uuid	uu;
489	THREAD_LOCAL time_t		last_time = 0;
490	time_t				now;
491
492	if (num > 0) {
493		now = time(0);
494		if (now > last_time+1)
495			num = 0;
496	}
497	if (num <= 0) {
498		num = 1000;
499		if (get_uuid_via_daemon(UUIDD_OP_BULK_TIME_UUID,
500					out, &num) == 0) {
501			last_time = time(0);
502			uuid_unpack(out, &uu);
503			num--;
504			return;
505		}
506		num = 0;
507	}
508	if (num > 0) {
509		uu.time_low++;
510		if (uu.time_low == 0) {
511			uu.time_mid++;
512			if (uu.time_mid == 0)
513				uu.time_hi_and_version++;
514		}
515		num--;
516		uuid_pack(&uu, out);
517		return;
518	}
519#else
520	if (get_uuid_via_daemon(UUIDD_OP_TIME_UUID, out, 0) == 0)
521		return;
522#endif
523
524	uuid__generate_time(out, 0);
525}
526
527
528void uuid__generate_random(uuid_t out, int *num)
529{
530	uuid_t	buf;
531	struct uuid uu;
532	int i, n;
533
534	if (!num || !*num)
535		n = 1;
536	else
537		n = *num;
538
539	for (i = 0; i < n; i++) {
540		get_random_bytes(buf, sizeof(buf));
541		uuid_unpack(buf, &uu);
542
543		uu.clock_seq = (uu.clock_seq & 0x3FFF) | 0x8000;
544		uu.time_hi_and_version = (uu.time_hi_and_version & 0x0FFF)
545			| 0x4000;
546		uuid_pack(&uu, out);
547		out += sizeof(uuid_t);
548	}
549}
550
551void uuid_generate_random(uuid_t out)
552{
553	int	num = 1;
554	/* No real reason to use the daemon for random uuid's -- yet */
555
556	uuid__generate_random(out, &num);
557}
558
559
560/*
561 * This is the generic front-end to uuid_generate_random and
562 * uuid_generate_time.  It uses uuid_generate_random only if
563 * /dev/urandom is available, since otherwise we won't have
564 * high-quality randomness.
565 */
566void uuid_generate(uuid_t out)
567{
568	if (get_random_fd() >= 0)
569		uuid_generate_random(out);
570	else
571		uuid_generate_time(out);
572}
573