2 * gen_uuid.c --- generate a DCE-compatible uuid
4 * Copyright (C) 1996, 1997, 1998, 1999 Theodore Ts'o.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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
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
36 * Force inclusion of SVID stuff since we need it if we're compiling in
40 #define _DEFAULT_SOURCE /* since glibc 2.20 _SVID_SOURCE is deprecated */
45 #define _WIN32_WINNT 0x0500
59 #include <sys/types.h>
60 #ifdef HAVE_SYS_TIME_H
63 #ifdef HAVE_SYS_WAIT_H
67 #ifdef HAVE_SYS_FILE_H
70 #ifdef HAVE_SYS_IOCTL_H
71 #include <sys/ioctl.h>
73 #ifdef HAVE_SYS_RANDOM_H
74 #include <sys/random.h>
76 #ifdef HAVE_SYS_SOCKET_H
77 #include <sys/socket.h>
82 #ifdef HAVE_SYS_SOCKIO_H
83 #include <sys/sockio.h>
88 #ifdef HAVE_NETINET_IN_H
89 #include <netinet/in.h>
91 #ifdef HAVE_NET_IF_DL_H
92 #include <net/if_dl.h>
94 #if defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)
95 #include <sys/syscall.h>
97 #ifdef HAVE_SYS_RESOURCE_H
98 #include <sys/resource.h>
105 #define srand(x) srandom(x)
106 #define rand() random()
110 #define THREAD_LOCAL static TLS
112 #define THREAD_LOCAL static
115 #if defined(__linux__) && defined(__NR_gettid) && defined(HAVE_JRAND48)
117 THREAD_LOCAL unsigned short jrand_seed[3];
120 static int get_random_fd(void)
127 gettimeofday(&tv, 0);
129 fd = open("/dev/urandom", O_RDONLY);
131 fd = open("/dev/random", O_RDONLY | O_NONBLOCK);
133 i = fcntl(fd, F_GETFD);
135 fcntl(fd, F_SETFD, i | FD_CLOEXEC);
138 srand(((unsigned)getpid() << 16) ^ getuid() ^ tv.tv_sec ^ tv.tv_usec);
140 jrand_seed[0] = getpid() ^ (tv.tv_sec & 0xFFFF);
141 jrand_seed[1] = getppid() ^ (tv.tv_usec & 0xFFFF);
142 jrand_seed[2] = (tv.tv_sec ^ tv.tv_usec) >> 16;
145 /* Crank the random number generator a few times */
146 gettimeofday(&tv, 0);
147 for (i = (tv.tv_sec ^ tv.tv_usec) & 0x1F; i > 0; i--)
154 * Generate a series of random bytes. Use /dev/urandom if possible,
155 * and if not, use srandom/random.
157 static void get_random_bytes(void *buf, int nbytes)
159 int i, n = nbytes, fd;
160 int lose_counter = 0;
161 unsigned char *cp = buf;
163 #ifdef HAVE_GETRANDOM
164 i = getrandom(buf, nbytes, 0);
168 #ifdef HAVE_GETENTROPY
169 if (getentropy(buf, nbytes) == 0)
173 fd = get_random_fd();
178 if (lose_counter++ > 16)
189 * We do this all the time, but this is the only source of
190 * randomness if /dev/random/urandom is out to lunch.
192 for (cp = buf, i = 0; i < nbytes; i++)
193 *cp++ ^= (rand() >> 7) & 0xFF;
196 unsigned short tmp_seed[3];
198 memcpy(tmp_seed, jrand_seed, sizeof(tmp_seed));
199 jrand_seed[2] = jrand_seed[2] ^ syscall(__NR_gettid);
200 for (cp = buf, i = 0; i < nbytes; i++)
201 *cp++ ^= (jrand48(tmp_seed) >> 7) & 0xFF;
202 memcpy(jrand_seed, tmp_seed,
203 sizeof(jrand_seed) - sizeof(unsigned short));
211 * Get the ethernet hardware address, if we can find it...
213 * XXX for a windows version, probably should use GetAdaptersInfo:
214 * http://www.codeguru.com/cpp/i-n/network/networkinformation/article.php/c5451
215 * commenting out get_node_id just to get gen_uuid to compile under windows
216 * is not the right way to go!
218 static int get_node_id(unsigned char *node_id)
222 struct ifreq ifr, *ifrp;
227 #ifdef HAVE_NET_IF_DL_H
228 struct sockaddr_dl *sdlp;
232 * BSD 4.4 defines the size of an ifreq to be
233 * max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
234 * However, under earlier systems, sa_len isn't present, so the size is
235 * just sizeof(struct ifreq)
239 #define max(a,b) ((a) > (b) ? (a) : (b))
241 #define ifreq_size(i) max(sizeof(struct ifreq),\
242 sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
244 #define ifreq_size(i) sizeof(struct ifreq)
245 #endif /* HAVE_SA_LEN*/
247 sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
251 memset(buf, 0, sizeof(buf));
252 ifc.ifc_len = sizeof(buf);
254 if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0) {
259 for (i = 0; i < n; i+= ifreq_size(*ifrp) ) {
260 ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
261 strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
263 if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
265 a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
268 if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
270 a = (unsigned char *) ifr.ifr_enaddr;
272 #ifdef HAVE_NET_IF_DL_H
273 sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
274 if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
276 a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
279 * XXX we don't have a way of getting the hardware
284 #endif /* HAVE_NET_IF_DL_H */
285 #endif /* SIOCGENADDR */
286 #endif /* SIOCGIFHWADDR */
287 if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5])
290 memcpy(node_id, a, 6);
300 /* Assume that the gettimeofday() has microsecond granularity */
301 #define MAX_ADJUSTMENT 10
303 static int get_clock(uint32_t *clock_high, uint32_t *clock_low,
304 uint16_t *ret_clock_seq, int *num)
306 THREAD_LOCAL int adjustment = 0;
307 THREAD_LOCAL struct timeval last = {0, 0};
308 THREAD_LOCAL int state_fd = -2;
309 THREAD_LOCAL FILE *state_f;
310 THREAD_LOCAL uint16_t clock_seq;
319 if (state_fd == -2) {
320 save_umask = umask(0);
321 state_fd = open("/var/lib/libuuid/clock.txt",
322 O_RDWR|O_CREAT, 0660);
323 (void) umask(save_umask);
325 state_f = fdopen(state_fd, "r+");
334 fl.l_whence = SEEK_SET;
340 while (fcntl(state_fd, F_SETLKW, &fl) < 0) {
341 if ((errno == EAGAIN) || (errno == EINTR))
351 unsigned long tv1, tv2;
354 if (fscanf(state_f, "clock: %04x tv: %lu %lu adj: %d\n",
355 &cl, &tv1, &tv2, &a) == 4) {
356 clock_seq = cl & 0x3FFF;
363 if ((last.tv_sec == 0) && (last.tv_usec == 0)) {
364 get_random_bytes(&clock_seq, sizeof(clock_seq));
366 gettimeofday(&last, 0);
371 gettimeofday(&tv, 0);
372 if ((tv.tv_sec < last.tv_sec) ||
373 ((tv.tv_sec == last.tv_sec) &&
374 (tv.tv_usec < last.tv_usec))) {
375 clock_seq = (clock_seq+1) & 0x3FFF;
378 } else if ((tv.tv_sec == last.tv_sec) &&
379 (tv.tv_usec == last.tv_usec)) {
380 if (adjustment >= MAX_ADJUSTMENT)
388 clock_reg = tv.tv_usec*10 + adjustment;
389 clock_reg += ((uint64_t) tv.tv_sec)*10000000;
390 clock_reg += (((uint64_t) 0x01B21DD2) << 32) + 0x13814000;
392 if (num && (*num > 1)) {
393 adjustment += *num - 1;
394 last.tv_usec += adjustment / 10;
395 adjustment = adjustment % 10;
396 last.tv_sec += last.tv_usec / 1000000;
397 last.tv_usec = last.tv_usec % 1000000;
402 len = fprintf(state_f,
403 "clock: %04x tv: %016lu %08lu adj: %08d\n",
404 clock_seq, (unsigned long)last.tv_sec,
405 (unsigned long)last.tv_usec, adjustment);
407 if (ftruncate(state_fd, len) < 0) {
408 fprintf(state_f, " \n");
414 if (fcntl(state_fd, F_SETLK, &fl) < 0) {
421 *clock_high = clock_reg >> 32;
422 *clock_low = clock_reg;
423 *ret_clock_seq = clock_seq;
427 #if defined(USE_UUIDD) && defined(HAVE_SYS_UN_H)
428 static ssize_t read_all(int fd, char *buf, size_t count)
434 memset(buf, 0, count);
436 ret = read(fd, buf, count);
438 if ((errno == EAGAIN || errno == EINTR || ret == 0) &&
453 * Close all file descriptors
455 static void close_all_fds(void)
459 #if defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX)
460 max = sysconf(_SC_OPEN_MAX);
461 #elif defined(HAVE_GETDTABLESIZE)
462 max = getdtablesize();
463 #elif defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
466 getrlimit(RLIMIT_NOFILE, &rl);
472 for (i=0; i < max; i++) {
475 open("/dev/null", O_RDWR);
478 #endif /* defined(USE_UUIDD) && defined(HAVE_SYS_UN_H) */
480 #if __GNUC_PREREQ (4, 6)
481 #pragma GCC diagnostic push
482 #if !defined(USE_UUIDD) || !defined(HAVE_SYS_UN_H)
483 #pragma GCC diagnostic ignored "-Wunused-parameter"
487 * Try using the uuidd daemon to generate the UUID
489 * Returns 0 on success, non-zero on failure.
491 static int get_uuid_via_daemon(int op, uuid_t out, int *num)
493 #if defined(USE_UUIDD) && defined(HAVE_SYS_UN_H)
498 int32_t reply_len = 0, expected = 16;
499 struct sockaddr_un srv_addr;
502 static const char *uuidd_path = UUIDD_PATH;
503 static int access_ret = -2;
504 static int start_attempts = 0;
506 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
509 srv_addr.sun_family = AF_UNIX;
510 strcpy(srv_addr.sun_path, UUIDD_SOCKET_PATH);
512 if (connect(s, (const struct sockaddr *) &srv_addr,
513 sizeof(struct sockaddr_un)) < 0) {
514 if (access_ret == -2)
515 access_ret = access(uuidd_path, X_OK);
517 access_ret = stat(uuidd_path, &st);
518 if (access_ret == 0 && (st.st_mode & (S_ISUID | S_ISGID)) == 0)
519 access_ret = access(UUIDD_DIR, W_OK);
520 if (access_ret == 0 && start_attempts++ < 5) {
521 if ((pid = fork()) == 0) {
523 execl(uuidd_path, "uuidd", "-qT", "300",
527 (void) waitpid(pid, 0, 0);
528 if (connect(s, (const struct sockaddr *) &srv_addr,
529 sizeof(struct sockaddr_un)) < 0)
536 if (op == UUIDD_OP_BULK_TIME_UUID) {
537 memcpy(op_buf+1, num, sizeof(*num));
538 op_len += sizeof(*num);
539 expected += sizeof(*num);
542 ret = write(s, op_buf, op_len);
546 ret = read_all(s, (char *) &reply_len, sizeof(reply_len));
550 if (reply_len != expected)
553 ret = read_all(s, op_buf, reply_len);
555 if (op == UUIDD_OP_BULK_TIME_UUID)
556 memcpy(op_buf+16, num, sizeof(int));
558 memcpy(out, op_buf, 16);
561 return ((ret == expected) ? 0 : -1);
568 #if __GNUC_PREREQ (4, 6)
569 #pragma GCC diagnostic pop
572 void uuid__generate_time(uuid_t out, int *num)
574 static unsigned char node_id[6];
575 static int has_init = 0;
580 if (get_node_id(node_id) <= 0) {
581 get_random_bytes(node_id, 6);
583 * Set multicast bit, to prevent conflicts
584 * with IEEE 802 addresses obtained from
591 get_clock(&clock_mid, &uu.time_low, &uu.clock_seq, num);
592 uu.clock_seq |= 0x8000;
593 uu.time_mid = (uint16_t) clock_mid;
594 uu.time_hi_and_version = ((clock_mid >> 16) & 0x0FFF) | 0x1000;
595 memcpy(uu.node, node_id, 6);
599 void uuid_generate_time(uuid_t out)
602 THREAD_LOCAL int num = 0;
603 THREAD_LOCAL struct uuid uu;
604 THREAD_LOCAL time_t last_time = 0;
609 if (now > last_time+1)
614 if (get_uuid_via_daemon(UUIDD_OP_BULK_TIME_UUID,
617 uuid_unpack(out, &uu);
625 if (uu.time_low == 0) {
627 if (uu.time_mid == 0)
628 uu.time_hi_and_version++;
635 if (get_uuid_via_daemon(UUIDD_OP_TIME_UUID, out, 0) == 0)
639 uuid__generate_time(out, 0);
643 void uuid__generate_random(uuid_t out, int *num)
654 for (i = 0; i < n; i++) {
655 get_random_bytes(buf, sizeof(buf));
656 uuid_unpack(buf, &uu);
658 uu.clock_seq = (uu.clock_seq & 0x3FFF) | 0x8000;
659 uu.time_hi_and_version = (uu.time_hi_and_version & 0x0FFF)
662 out += sizeof(uuid_t);
666 void uuid_generate_random(uuid_t out)
669 /* No real reason to use the daemon for random uuid's -- yet */
671 uuid__generate_random(out, &num);
676 * This is the generic front-end to uuid_generate_random and
677 * uuid_generate_time. It uses uuid_generate_random only if
678 * /dev/urandom is available, since otherwise we won't have
679 * high-quality randomness.
681 void uuid_generate(uuid_t out)
683 if (get_random_fd() >= 0)
684 uuid_generate_random(out);
686 uuid_generate_time(out);