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