1 | /* |
2 | * This Source Code Form is subject to the terms of the Mozilla Public |
3 | * License, v. 2.0. If a copy of the MPL was not distributed with this |
4 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. |
5 | * |
6 | * Copyright 1997 - July 2008 CWI, August 2008 - 2019 MonetDB B.V. |
7 | */ |
8 | |
9 | /* NOTE: for this file to work correctly, the random number generator |
10 | * must have been seeded (srand) with something like the current time */ |
11 | |
12 | #include "monetdb_config.h" |
13 | #include "muuid.h" |
14 | #include <string.h> /* strdup */ |
15 | #ifdef HAVE_UUID_UUID_H |
16 | # include <uuid/uuid.h> |
17 | #endif |
18 | #ifndef HAVE_UUID |
19 | #ifdef HAVE_OPENSSL |
20 | # include <openssl/rand.h> |
21 | #else |
22 | #ifdef HAVE_COMMONCRYPTO |
23 | #include <CommonCrypto/CommonCrypto.h> |
24 | #include <CommonCrypto/CommonRandom.h> |
25 | #endif |
26 | #endif |
27 | #endif |
28 | |
29 | /** |
30 | * Shallow wrapper around uuid, that comes up with some random pseudo |
31 | * uuid if uuid is not available |
32 | */ |
33 | char * |
34 | generateUUID(void) |
35 | { |
36 | #ifdef HAVE_UUID |
37 | # ifdef UUID_PRINTABLE_STRING_LENGTH |
38 | /* Solaris */ |
39 | char out[UUID_PRINTABLE_STRING_LENGTH]; |
40 | # else |
41 | char out[37]; |
42 | # endif |
43 | uuid_t uuid; |
44 | uuid_generate(uuid); |
45 | uuid_unparse(uuid, out); |
46 | #else |
47 | /* try to do some pseudo interesting stuff, and stash it in the |
48 | * format of a UUID to at least return some uniform answer */ |
49 | char out[37]; |
50 | #ifdef HAVE_OPENSSL |
51 | unsigned char randbuf[16]; |
52 | if (RAND_bytes(randbuf, 16) >= 0) |
53 | snprintf(out, sizeof(out), |
54 | "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-" |
55 | "%02x%02x%02x%02x%02x%02x" , |
56 | randbuf[0], randbuf[1], randbuf[2], randbuf[3], |
57 | randbuf[4], randbuf[5], randbuf[6], randbuf[7], |
58 | randbuf[8], randbuf[9], randbuf[10], randbuf[11], |
59 | randbuf[12], randbuf[13], randbuf[14], randbuf[15]); |
60 | else |
61 | #else |
62 | #ifdef HAVE_COMMONCRYPTO |
63 | unsigned char randbuf[16]; |
64 | if (CCRandomGenerateBytes(randbuf, 16) == kCCSuccess) |
65 | snprintf(out, sizeof(out), |
66 | "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-" |
67 | "%02x%02x%02x%02x%02x%02x" , |
68 | randbuf[0], randbuf[1], randbuf[2], randbuf[3], |
69 | randbuf[4], randbuf[5], randbuf[6], randbuf[7], |
70 | randbuf[8], randbuf[9], randbuf[10], randbuf[11], |
71 | randbuf[12], randbuf[13], randbuf[14], randbuf[15]); |
72 | else |
73 | #endif |
74 | #endif |
75 | /* generate something like this: |
76 | * cefa7a9c-1dd2-11b2-8350-880020adbeef |
77 | * ("%08x-%04x-%04x-%04x-%012x") */ |
78 | snprintf(out, sizeof(out), |
79 | "%04x%04x-%04x-%04x-%04x-%04x%04x%04x" , |
80 | rand() % 65536, rand() % 65536, |
81 | rand() % 65536, rand() % 65536, |
82 | rand() % 65536, rand() % 65536, |
83 | rand() % 65536, rand() % 65536); |
84 | #endif |
85 | return strdup(out); |
86 | } |
87 | |