Debian Codegraph @

libuuid/src/gen_uuid.c

raw
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 #ifdef _WIN32
36 #define _WIN32_WINNT 0x0500
37 #include <windows.h>
38 #define UUID MYUUID
39 #endif
40 #include <stdio.h>
41 #ifdef HAVE_UNISTD_H
42 #include <unistd.h>
43 #endif
44 #ifdef HAVE_STDLIB_H
45 #include <stdlib.h>
46 #endif
47 #include <string.h>
48 #include <fcntl.h>
49 #include <errno.h>
50 #include <limits.h>
51 #include <sys/types.h>
52 #ifdef HAVE_SYS_TIME_H
53 #include <sys/time.h>
54 #endif
55 #include <sys/stat.h>
56 #ifdef HAVE_SYS_FILE_H
57 #include <sys/file.h>
58 #endif
59 #ifdef HAVE_SYS_IOCTL_H
60 #include <sys/ioctl.h>
61 #endif
62 #ifdef HAVE_SYS_SOCKET_H
63 #include <sys/socket.h>
64 #endif
65 #ifdef HAVE_SYS_UN_H
66 #include <sys/un.h>
67 #endif
68 #ifdef HAVE_SYS_SOCKIO_H
69 #include <sys/sockio.h>
70 #endif
71 #ifdef HAVE_NET_IF_H
72 #include <net/if.h>
73 #endif
74 #ifdef HAVE_NETINET_IN_H
75 #include <netinet/in.h>
76 #endif
77 #ifdef HAVE_NET_IF_DL_H
78 #include <net/if_dl.h>
79 #endif
80 #if defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)
81 #include <sys/syscall.h>
82 #endif
83 #ifdef HAVE_LIBPTHREAD
84 # include <pthread.h>
85 #endif
86
87 #include <signal.h>
88
89 #include "all-io.h"
90 #include "uuidP.h"
91 #include "uuidd.h"
92 #include "randutils.h"
93 #include "strutils.h"
94 #include "c.h"
95 #include "md5.h"
96 #include "sha1.h"
97 #include "timeutils.h"
98
99
100 #ifdef _WIN32
101 static void gettimeofday (struct timeval *tv, void *dummy)
102 {
103 FILETIME ftime;
104 uint64_t n;
105
106 GetSystemTimeAsFileTime (&ftime);
107 n = (((uint64_t) ftime.dwHighDateTime << 32)
108 + (uint64_t) ftime.dwLowDateTime);
109 if (n) {
110 n /= 10;
111 n -= ((369 * 365 + 89) * (uint64_t) 86400) * 1000000;
112 }
113
114 tv->tv_sec = n / 1000000;
115 tv->tv_usec = n % 1000000;
116 }
117
118 static int getuid (void)
119 {
120 return 1;
121 }
122 #endif
123
124 #ifdef TEST_PROGRAM
125 #define gettimeofday gettimeofday_fixed
126
127 static int gettimeofday_fixed(struct timeval *tv, void *tz __attribute__((unused)))
128 {
129 tv->tv_sec = 1645557742;
130 tv->tv_usec = 123456;
131 return 0;
132 }
133 #endif
134
135 /*
136 * Get the ethernet hardware address, if we can find it...
137 *
138 * XXX for a windows version, probably should use GetAdaptersInfo:
139 * http://www.codeguru.com/cpp/i-n/network/networkinformation/article.php/c5451
140 * commenting out get_node_id just to get gen_uuid to compile under windows
141 * is not the right way to go!
142 */
143 static int get_node_id(unsigned char *node_id)
144 {
145 #ifdef HAVE_NET_IF_H
146 int sd;
147 struct ifreq ifr, *ifrp;
148 struct ifconf ifc;
149 char buf[1024];
150 int n, i;
151 unsigned char *a = NULL;
152 #ifdef HAVE_NET_IF_DL_H
153 struct sockaddr_dl *sdlp;
154 #endif
155
156 /*
157 * BSD 4.4 defines the size of an ifreq to be
158 * max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
159 * However, under earlier systems, sa_len isn't present, so the size is
160 * just sizeof(struct ifreq)
161 */
162 #ifdef HAVE_SA_LEN
163 #define ifreq_size(i) max(sizeof(struct ifreq),\
164 sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
165 #else
166 #define ifreq_size(i) sizeof(struct ifreq)
167 #endif /* HAVE_SA_LEN */
168
169 sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
170 if (sd < 0) {
171 return -1;
172 }
173 memset(buf, 0, sizeof(buf));
174 ifc.ifc_len = sizeof(buf);
175 ifc.ifc_buf = buf;
176 if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0) {
177 close(sd);
178 return -1;
179 }
180 n = ifc.ifc_len;
181 for (i = 0; i < n; i+= ifreq_size(*ifrp) ) {
182 ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
183 strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
184 #ifdef SIOCGIFHWADDR
185 if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
186 continue;
187 a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
188 #else
189 #ifdef SIOCGENADDR
190 if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
191 continue;
192 a = (unsigned char *) ifr.ifr_enaddr;
193 #else
194 #ifdef HAVE_NET_IF_DL_H
195 sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
196 if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
197 continue;
198 a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
199 #else
200 /*
201 * XXX we don't have a way of getting the hardware
202 * address
203 */
204 close(sd);
205 return 0;
206 #endif /* HAVE_NET_IF_DL_H */
207 #endif /* SIOCGENADDR */
208 #endif /* SIOCGIFHWADDR */
209 if (a == NULL || (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]))
210 continue;
211 if (node_id) {
212 memcpy(node_id, a, 6);
213 close(sd);
214 return 1;
215 }
216 }
217 close(sd);
218 #endif
219 return 0;
220 }
221
222 enum { STATE_FD_ERROR = -1, STATE_FD_INIT = -2 };
223
224 static int state_fd_init(const char *clock_file, FILE **fp)
225 {
226 mode_t save_umask;
227 int state_fd;
228 FILE *state_f;
229
230 save_umask = umask(0);
231 state_fd = open(clock_file, O_RDWR|O_CREAT|O_CLOEXEC, 0660);
232 (void) umask(save_umask);
233 if (state_fd != -1) {
234 state_f = fdopen(state_fd, "r+" UL_CLOEXECSTR);
235 if (!state_f) {
236 close(state_fd);
237 state_fd = STATE_FD_ERROR;
238 } else
239 *fp = state_f;
240 }
241 return state_fd;
242 }
243
244 /* Assume that the gettimeofday() has microsecond granularity */
245 #define MAX_ADJUSTMENT 10
246 /* Reserve a clock_seq value for the 'continuous clock' implementation */
247 #define CLOCK_SEQ_CONT 0
248
249 /*
250 * Get clock from global sequence clock counter.
251 *
252 * Return -1 if the clock counter could not be opened/locked (in this case
253 * pseudorandom value is returned in @ret_clock_seq), otherwise return 0.
254 */
255 static int get_clock(uint32_t *clock_high, uint32_t *clock_low,
256 uint16_t *ret_clock_seq, int *num)
257 {
258 THREAD_LOCAL int adjustment = 0;
259 THREAD_LOCAL struct timeval last = {0, 0};
260 THREAD_LOCAL int state_fd = STATE_FD_INIT;
261 THREAD_LOCAL FILE *state_f;
262 THREAD_LOCAL uint16_t clock_seq;
263 struct timeval tv;
264 uint64_t clock_reg;
265 int ret = 0;
266
267 if (state_fd == STATE_FD_INIT)
268 state_fd = state_fd_init(LIBUUID_CLOCK_FILE, &state_f);
269
270 if (state_fd >= 0) {
271 rewind(state_f);
272 while (flock(state_fd, LOCK_EX) < 0) {
273 if ((errno == EAGAIN) || (errno == EINTR))
274 continue;
275 fclose(state_f);
276 close(state_fd);
277 state_fd = STATE_FD_ERROR;
278 ret = -1;
279 break;
280 }
281 } else
282 ret = -1;
283
284 if (state_fd >= 0) {
285 unsigned int cl;
286 unsigned long tv1, tv2;
287 int a;
288
289 if (fscanf(state_f, "clock: %04x tv: %lu %lu adj: %d\n",
290 &cl, &tv1, &tv2, &a) == 4) {
291 clock_seq = cl & 0x3FFF;
292 last.tv_sec = tv1;
293 last.tv_usec = tv2;
294 adjustment = a;
295 }
296 // reset in case of reserved CLOCK_SEQ_CONT
297 if (clock_seq == CLOCK_SEQ_CONT) {
298 last.tv_sec = 0;
299 last.tv_usec = 0;
300 }
301 }
302
303 if ((last.tv_sec == 0) && (last.tv_usec == 0)) {
304 do {
305 ul_random_get_bytes(&clock_seq, sizeof(clock_seq));
306 clock_seq &= 0x3FFF;
307 } while (clock_seq == CLOCK_SEQ_CONT);
308 gettimeofday(&last, NULL);
309 last.tv_sec--;
310 }
311
312 try_again:
313 gettimeofday(&tv, NULL);
314 if ((tv.tv_sec < last.tv_sec) ||
315 ((tv.tv_sec == last.tv_sec) &&
316 (tv.tv_usec < last.tv_usec))) {
317 do {
318 clock_seq = (clock_seq+1) & 0x3FFF;
319 } while (clock_seq == CLOCK_SEQ_CONT);
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 += ((uint64_t) tv.tv_sec)*10000000;
334 clock_reg += (((uint64_t) 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 fprintf(state_f,
347 "clock: %04x tv: %016ld %08ld adj: %08d \n",
348 clock_seq, (long)last.tv_sec, (long)last.tv_usec, adjustment);
349 fflush(state_f);
350 rewind(state_f);
351 flock(state_fd, LOCK_UN);
352 }
353
354 *clock_high = clock_reg >> 32;
355 *clock_low = clock_reg;
356 *ret_clock_seq = clock_seq;
357 return ret;
358 }
359
360 /*
361 * Get current time in 100ns ticks.
362 */
363 static uint64_t get_clock_counter(void)
364 {
365 struct timeval tv;
366 uint64_t clock_reg;
367
368 gettimeofday(&tv, NULL);
369 clock_reg = tv.tv_usec*10;
370 clock_reg += ((uint64_t) tv.tv_sec) * 10000000ULL;
371
372 return clock_reg;
373 }
374
375 /*
376 * Get continuous clock value.
377 *
378 * Return -1 if there is no valid clock counter available,
379 * otherwise return 0.
380 *
381 * This implementation doesn't deliver clock counters based on
382 * the current time because last_clock_reg is only incremented
383 * by the number of requested UUIDs.
384 * max_clock_offset is used to limit the offset of last_clock_reg.
385 * used/reserved UUIDs are written to LIBUUID_CLOCK_CONT_FILE.
386 */
387 static int get_clock_cont(uint32_t *clock_high,
388 uint32_t *clock_low,
389 int num,
390 uint32_t max_clock_offset)
391 {
392 /* all 64bit clock_reg values in this function represent '100ns ticks'
393 * due to the combination of tv_usec + MAX_ADJUSTMENT */
394
395 /* time offset according to RFC 4122. 4.1.4. */
396 const uint64_t reg_offset = (((uint64_t) 0x01B21DD2) << 32) + 0x13814000;
397 static uint64_t last_clock_reg = 0;
398 static uint64_t saved_clock_reg = 0;
399 static int state_fd = STATE_FD_INIT;
400 static FILE *state_f = NULL;
401 uint64_t clock_reg, next_clock_reg;
402
403 if (state_fd == STATE_FD_ERROR)
404 return -1;
405
406 clock_reg = get_clock_counter();
407
408 if (state_fd == STATE_FD_INIT) {
409 struct stat st;
410
411 state_fd = state_fd_init(LIBUUID_CLOCK_CONT_FILE, &state_f);
412 if (state_fd == STATE_FD_ERROR)
413 return -1;
414
415 if (fstat(state_fd, &st))
416 goto error;
417
418 if (st.st_size) {
419 rewind(state_f);
420 if (fscanf(state_f, "cont: %"SCNu64"\n", &last_clock_reg) != 1)
421 goto error;
422 /* don't use old timestamps, reset to current time */
423 if (last_clock_reg < clock_reg)
424 last_clock_reg = clock_reg;
425 } else
426 last_clock_reg = clock_reg;
427
428 saved_clock_reg = last_clock_reg;
429 }
430
431 if (max_clock_offset) {
432 uint64_t co = 10000000ULL * (uint64_t)max_clock_offset; // clock_offset in [100ns]
433
434 if ((last_clock_reg + co) < clock_reg)
435 last_clock_reg = clock_reg - co;
436 }
437
438 clock_reg += MAX_ADJUSTMENT;
439
440 next_clock_reg = last_clock_reg + (uint64_t)num;
441 if (next_clock_reg >= clock_reg)
442 return -1;
443
444 if (next_clock_reg >= saved_clock_reg) {
445 uint64_t cl = next_clock_reg + 100000000ULL; // 10s interval in [100ns]
446 int l;
447
448 rewind(state_f);
449 l = fprintf(state_f, "cont: %020"PRIu64" \n", cl);
450 if (l < 30 || fflush(state_f))
451 goto error;
452 saved_clock_reg = cl;
453 }
454
455 *clock_high = (last_clock_reg + reg_offset) >> 32;
456 *clock_low = last_clock_reg + reg_offset;
457 last_clock_reg = next_clock_reg;
458
459 return 0;
460
461 error:
462 if (state_fd >= 0)
463 close(state_fd);
464 if (state_f)
465 fclose(state_f);
466 state_fd = STATE_FD_ERROR;
467 state_f = NULL;
468 return -1;
469 }
470
471 #if defined(HAVE_UUIDD) && defined(HAVE_SYS_UN_H) && !defined(TEST_PROGRAM)
472
473 /*
474 * Try using the uuidd daemon to generate the UUID
475 *
476 * Returns 0 on success, non-zero on failure.
477 */
478 static int get_uuid_via_daemon(int op, uuid_t out, int *num)
479 {
480 char op_buf[64];
481 int op_len;
482 int s;
483 ssize_t ret;
484 int32_t reply_len = 0, expected = 16;
485 struct sockaddr_un srv_addr;
486
487 if (sizeof(UUIDD_SOCKET_PATH) > sizeof(srv_addr.sun_path))
488 return -1;
489
490 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
491 return -1;
492
493 srv_addr.sun_family = AF_UNIX;
494 xstrncpy(srv_addr.sun_path, UUIDD_SOCKET_PATH, sizeof(srv_addr.sun_path));
495
496 if (connect(s, (const struct sockaddr *) &srv_addr,
497 sizeof(struct sockaddr_un)) < 0)
498 goto fail;
499
500 op_buf[0] = op;
501 op_len = 1;
502 if (op == UUIDD_OP_BULK_TIME_UUID) {
503 memcpy(op_buf+1, num, sizeof(*num));
504 op_len += sizeof(*num);
505 expected += sizeof(*num);
506 }
507
508 ret = write(s, op_buf, op_len);
509 if (ret < 1)
510 goto fail;
511
512 ret = read_all(s, (char *) &reply_len, sizeof(reply_len));
513 if (ret < 0)
514 goto fail;
515
516 if (reply_len != expected)
517 goto fail;
518
519 ret = read_all(s, op_buf, reply_len);
520
521 if (op == UUIDD_OP_BULK_TIME_UUID)
522 memcpy(op_buf+16, num, sizeof(int));
523
524 memcpy(out, op_buf, 16);
525
526 close(s);
527 return ((ret == expected) ? 0 : -1);
528
529 fail:
530 close(s);
531 return -1;
532 }
533
534 #else /* !defined(HAVE_UUIDD) && defined(HAVE_SYS_UN_H) */
535 static int get_uuid_via_daemon(int op __attribute__((__unused__)),
536 uuid_t out __attribute__((__unused__)),
537 int *num __attribute__((__unused__)))
538 {
539 return -1;
540 }
541 #endif
542
543 static int __uuid_generate_time_internal(uuid_t out, int *num, uint32_t cont_offset)
544 {
545 static unsigned char node_id[6];
546 static int has_init = 0;
547 struct uuid uu;
548 uint32_t clock_mid;
549 int ret;
550
551 if (!has_init) {
552 if (get_node_id(node_id) <= 0) {
553 ul_random_get_bytes(node_id, 6);
554 /*
555 * Set multicast bit, to prevent conflicts
556 * with IEEE 802 addresses obtained from
557 * network cards
558 */
559 node_id[0] |= 0x01;
560 }
561 has_init = 1;
562 }
563 if (cont_offset) {
564 ret = get_clock_cont(&clock_mid, &uu.time_low, *num, cont_offset);
565 uu.clock_seq = CLOCK_SEQ_CONT;
566 if (ret != 0) /* fallback to previous implpementation */
567 ret = get_clock(&clock_mid, &uu.time_low, &uu.clock_seq, num);
568 } else {
569 ret = get_clock(&clock_mid, &uu.time_low, &uu.clock_seq, num);
570 }
571 uu.clock_seq |= 0x8000;
572 uu.time_mid = (uint16_t) clock_mid;
573 uu.time_hi_and_version = ((clock_mid >> 16) & 0x0FFF) | 0x1000;
574 memcpy(uu.node, node_id, 6);
575 uuid_pack(&uu, out);
576 return ret;
577 }
578
579 int __uuid_generate_time(uuid_t out, int *num)
580 {
581 return __uuid_generate_time_internal(out, num, 0);
582 }
583
584 int __uuid_generate_time_cont(uuid_t out, int *num, uint32_t cont_offset)
585 {
586 return __uuid_generate_time_internal(out, num, cont_offset);
587 }
588
589 #define CS_MIN (1<<6)
590 #define CS_MAX (1<<18)
591 #define CS_FACTOR 2
592
593 static void __uuid_set_variant_and_version(uuid_t uuid, int version)
594 {
595 uuid[6] = (uuid[6] & UUID_TYPE_MASK) | version << UUID_TYPE_SHIFT;
596 /* only DCE is supported */
597 uuid[8] = (uuid[8] & 0x3F) | 0x80;
598 }
599
600 /*
601 * Generate time-based UUID and store it to @out
602 *
603 * Tries to guarantee uniqueness of the generated UUIDs by obtaining them from the uuidd daemon,
604 * or, if uuidd is not usable, by using the global clock state counter (see get_clock()).
605 * If neither of these is possible (e.g. because of insufficient permissions), it generates
606 * the UUID anyway, but returns -1. Otherwise, returns 0.
607 */
608 #ifdef HAVE_LIBPTHREAD
609 THREAD_LOCAL struct {
610 int num;
611 int cache_size;
612 int last_used;
613 struct uuid uu;
614 time_t last_time;
615 } uuidd_cache = {
616 .cache_size = CS_MIN,
617 };
618
619 static void reset_uuidd_cache(void)
620 {
621 memset(&uuidd_cache, 0, sizeof(uuidd_cache));
622 uuidd_cache.cache_size = CS_MIN;
623 }
624 #endif /* HAVE_LIBPTHREAD */
625
626 static int uuid_generate_time_generic(uuid_t out)
627 {
628 #ifdef HAVE_LIBPTHREAD
629 static volatile sig_atomic_t atfork_registered;
630 time_t now;
631
632 if (!atfork_registered) {
633 pthread_atfork(NULL, NULL, reset_uuidd_cache);
634 atfork_registered = 1;
635 }
636
637 if (uuidd_cache.num > 0) { /* expire cache */
638 now = time(NULL);
639 if (now > uuidd_cache.last_time+1) {
640 uuidd_cache.last_used = uuidd_cache.cache_size - uuidd_cache.num;
641 uuidd_cache.num = 0;
642 }
643 }
644 if (uuidd_cache.num <= 0) { /* fill cache */
645 /*
646 * num + OP_BULK provides a local cache in each application.
647 * Start with a small cache size to cover short running applications
648 * and adjust the cache size over the runtime.
649 */
650 if ((uuidd_cache.last_used == uuidd_cache.cache_size) && (uuidd_cache.cache_size < CS_MAX))
651 uuidd_cache.cache_size *= CS_FACTOR;
652 else if ((uuidd_cache.last_used < (uuidd_cache.cache_size / CS_FACTOR)) && (uuidd_cache.cache_size > CS_MIN))
653 uuidd_cache.cache_size /= CS_FACTOR;
654
655 uuidd_cache.num = uuidd_cache.cache_size;
656
657 if (get_uuid_via_daemon(UUIDD_OP_BULK_TIME_UUID,
658 out, &uuidd_cache.num) == 0) {
659 uuidd_cache.last_time = time(NULL);
660 uuid_unpack(out, &uuidd_cache.uu);
661 uuidd_cache.num--;
662 return 0;
663 }
664 /* request to daemon failed, reset cache */
665 reset_uuidd_cache();
666 }
667 if (uuidd_cache.num > 0) { /* serve uuid from cache */
668 uuidd_cache.uu.time_low++;
669 if (uuidd_cache.uu.time_low == 0) {
670 uuidd_cache.uu.time_mid++;
671 if (uuidd_cache.uu.time_mid == 0)
672 uuidd_cache.uu.time_hi_and_version++;
673 }
674 uuidd_cache.num--;
675 uuid_pack(&uuidd_cache.uu, out);
676 if (uuidd_cache.num == 0)
677 uuidd_cache.last_used = uuidd_cache.cache_size;
678 return 0;
679 }
680
681 #else /* !HAVE_LIBPTHREAD */
682 {
683 int num = 1;
684 if (get_uuid_via_daemon(UUIDD_OP_TIME_UUID, out, &num) == 0)
685 return 0;
686 }
687 #endif /* HAVE_LIBPTHREAD */
688
689 return __uuid_generate_time(out, NULL);
690 }
691
692 /*
693 * Generate time-based UUID and store it to @out.
694 *
695 * Discards return value from uuid_generate_time_generic()
696 */
697 void uuid_generate_time(uuid_t out)
698 {
699 (void)uuid_generate_time_generic(out);
700 }
701
702
703 int uuid_generate_time_safe(uuid_t out)
704 {
705 return uuid_generate_time_generic(out);
706 }
707
708 void uuid_generate_time_v6(uuid_t out)
709 {
710 uint32_t clock_high, clock_low;
711 uint16_t clock_seq;
712
713 get_clock(&clock_high, &clock_low, &clock_seq, NULL);
714
715 out[0] = clock_high >> 20;
716 out[1] = clock_high >> 12;
717 out[2] = clock_high >> 4;
718 out[3] = clock_high << 4;
719 out[3] |= clock_low >> 28;
720 out[4] = clock_low >> 20;
721 out[5] = clock_low >> 12;
722 out[6] = clock_low >> 8;
723 out[7] = clock_low >> 0;
724
725 ul_random_get_bytes(out + 8, 8);
726 __uuid_set_variant_and_version(out, UUID_TYPE_DCE_TIME_V6);
727 }
728
729 // FIXME variable additional information
730 void uuid_generate_time_v7(uuid_t out)
731 {
732 struct timeval tv;
733 uint64_t ms;
734
735 gettimeofday(&tv, NULL);
736
737 ms = tv.tv_sec * MSEC_PER_SEC + tv.tv_usec / USEC_PER_MSEC;
738
739 out[0] = ms >> 40;
740 out[1] = ms >> 32;
741 out[2] = ms >> 24;
742 out[3] = ms >> 16;
743 out[4] = ms >> 8;
744 out[5] = ms >> 0;
745 ul_random_get_bytes(out + 6, 10);
746 __uuid_set_variant_and_version(out, UUID_TYPE_DCE_TIME_V7);
747 }
748
749
750 int __uuid_generate_random(uuid_t out, int *num)
751 {
752 uuid_t buf;
753 struct uuid uu;
754 int i, n, r = 0;
755
756 if (!num || !*num)
757 n = 1;
758 else
759 n = *num;
760
761 for (i = 0; i < n; i++) {
762 if (ul_random_get_bytes(buf, sizeof(buf)))
763 r = -1;
764 uuid_unpack(buf, &uu);
765
766 uu.clock_seq = (uu.clock_seq & 0x3FFF) | 0x8000;
767 uu.time_hi_and_version = (uu.time_hi_and_version & 0x0FFF)
768 | 0x4000;
769 uuid_pack(&uu, out);
770 out += sizeof(uuid_t);
771 }
772
773 return r;
774 }
775
776 void uuid_generate_random(uuid_t out)
777 {
778 int num = 1;
779 /* No real reason to use the daemon for random uuid's -- yet */
780
781 __uuid_generate_random(out, &num);
782 }
783
784 /*
785 * This is the generic front-end to __uuid_generate_random and
786 * uuid_generate_time. It uses __uuid_generate_random output
787 * only if high-quality randomness is available.
788 */
789 void uuid_generate(uuid_t out)
790 {
791 int num = 1;
792
793 if (__uuid_generate_random(out, &num))
794 uuid_generate_time(out);
795 }
796
797 /*
798 * Generate an MD5 hashed (predictable) UUID based on a well-known UUID
799 * providing the namespace and an arbitrary binary string.
800 */
801 void uuid_generate_md5(uuid_t out, const uuid_t ns, const char *name, size_t len)
802 {
803 UL_MD5_CTX ctx;
804 char hash[UL_MD5LENGTH];
805 uuid_t buf;
806 struct uuid uu;
807
808 ul_MD5Init(&ctx);
809 ul_MD5Update(&ctx, ns, sizeof(uuid_t));
810 ul_MD5Update(&ctx, (const unsigned char *)name, len);
811 ul_MD5Final((unsigned char *)hash, &ctx);
812
813 assert(sizeof(buf) <= sizeof(hash));
814
815 memcpy(buf, hash, sizeof(buf));
816 uuid_unpack(buf, &uu);
817
818 uu.clock_seq = (uu.clock_seq & 0x3FFF) | 0x8000;
819 uu.time_hi_and_version = (uu.time_hi_and_version & 0x0FFF) | 0x3000;
820 uuid_pack(&uu, out);
821 }
822
823 /*
824 * Generate a SHA1 hashed (predictable) UUID based on a well-known UUID
825 * providing the namespace and an arbitrary binary string.
826 */
827 void uuid_generate_sha1(uuid_t out, const uuid_t ns, const char *name, size_t len)
828 {
829 UL_SHA1_CTX ctx;
830 char hash[UL_SHA1LENGTH];
831 uuid_t buf;
832 struct uuid uu;
833
834 ul_SHA1Init(&ctx);
835 ul_SHA1Update(&ctx, ns, sizeof(uuid_t));
836 ul_SHA1Update(&ctx, (const unsigned char *)name, len);
837 ul_SHA1Final((unsigned char *)hash, &ctx);
838
839 assert(sizeof(buf) <= sizeof(hash));
840
841 memcpy(buf, hash, sizeof(buf));
842 uuid_unpack(buf, &uu);
843
844 uu.clock_seq = (uu.clock_seq & 0x3FFF) | 0x8000;
845 uu.time_hi_and_version = (uu.time_hi_and_version & 0x0FFF) | 0x5000;
846 uuid_pack(&uu, out);
847 }
848
849 #ifdef TEST_PROGRAM
850 int main(void)
851 {
852 char buf[UUID_STR_LEN];
853 uuid_t uuid;
854
855 uuid_generate_time(uuid);
856 uuid_unparse(uuid, buf);
857 printf("%s\n", buf);
858
859 uuid_generate_time_v6(uuid);
860 uuid_unparse(uuid, buf);
861 printf("%s\n", buf);
862
863 uuid_generate_time_v7(uuid);
864 uuid_unparse(uuid, buf);
865 printf("%s\n", buf);
866
867 return 0;
868 }
869 #endif