Debian Codegraph @

src/vendor/azure-uamqp-c/deps/azure-c-shared-utility/adapters/uniqueid_azsphere.c

raw
1 // Copyright (c) Microsoft. All rights reserved.
2 // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
4 #include <stdlib.h>
5 #include <stdint.h>
6 #include <string.h>
7 #include <sys/random.h>
8
9 #include "azure_macro_utils/macro_utils.h"
10 #include "azure_c_shared_utility/uniqueid.h"
11 #include "azure_c_shared_utility/xlogging.h"
12
13 #define UUID_LENGTH 36
14
15 MU_DEFINE_ENUM_STRINGS(UNIQUEID_RESULT, UNIQUEID_RESULT_VALUES);
16
17 // UUID fields as specified in RFC 4122
18 typedef struct UUID_TAG
19 {
20 uint32_t time_low;
21 uint16_t time_mid;
22 uint16_t time_hi_and_version;
23 uint16_t clock_seq_and_variant;
24 uint8_t node[6];
25 } UUID;
26
27 // lowercase uuid format expected by azure iot sdk
28 static const char* uuid_format =
29 "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x";
30
31 UNIQUEID_RESULT UniqueId_Generate(char* uid, size_t len)
32 {
33 UNIQUEID_RESULT result;
34
35 /* Codes_SRS_UNIQUEID_07_002: [If uid is NULL then UniqueId_Generate shall return UNIQUEID_INVALID_ARG] */
36 /* Codes_SRS_UNIQUEID_07_003: [If len is less then 37 then UniqueId_Generate shall return UNIQUEID_INVALID_ARG] */
37 if (uid == NULL || len < (UUID_LENGTH + 1)) // UUID_LENGTH + 1 to compensate "/0"
38 {
39 result = UNIQUEID_INVALID_ARG;
40 LogError("Buffer Size is Null or Shorter than 37 Characters. (result = %" PRI_MU_ENUM ")", MU_ENUM_VALUE(UNIQUEID_RESULT, result));
41 }
42 else
43 {
44 // generate version 4 uuid
45 UUID unique_id;
46
47 // get random bytes
48 ssize_t bytes_got = getrandom(&unique_id, sizeof(unique_id), GRND_NONBLOCK);
49 if (bytes_got != sizeof(unique_id))
50 {
51 LogError("Failed to obtain random numbers from getrandom.");
52 result = UNIQUEID_ERROR;
53 }
54 else
55 {
56 // format as version 4 (random) uuid variant 2
57 unique_id.clock_seq_and_variant = (unique_id.clock_seq_and_variant & 0x3FFF) | 0x8000;
58 unique_id.time_hi_and_version = (unique_id.time_hi_and_version & 0x0FFF) | 0x4000;
59
60 /* Codes_SRS_UNIQUEID_07_001: [UniqueId_Generate shall create a unique Id 36 character long string.] */
61 // write out unique_id as string
62 memset(uid, 0, len);
63 int chars_written = snprintf(uid, len, uuid_format,
64 unique_id.time_low, unique_id.time_mid, unique_id.time_hi_and_version,
65 unique_id.clock_seq_and_variant >> 8, unique_id.clock_seq_and_variant & 0xFF,
66 unique_id.node[0], unique_id.node[1], unique_id.node[2],
67 unique_id.node[3], unique_id.node[4], unique_id.node[5]);
68
69 if (chars_written != UUID_LENGTH)
70 {
71 LogError("Failed to convert binary uuid to string format.");
72 result = UNIQUEID_ERROR;
73 }
74 else
75 {
76 result = UNIQUEID_OK;
77 }
78 }
79 }
80 return result;
81 }