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