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