Clean-up: coverity warns of uncaught exception during logging
[lttng-tools.git] / src / common / uuid.cpp
1 /*
2 * Copyright (C) 2018 Jérémie Galarneau <jeremie.galarneau@efficios.com>
3 * Copyright (C) 2019 Michael Jeanson <mjeanson@efficios.com>
4 *
5 * SPDX-License-Identifier: LGPL-2.1-only
6 *
7 */
8
9 #include <common/compat/string.hpp>
10 #include <common/error.hpp>
11 #include <common/format.hpp>
12 #include <common/random.hpp>
13
14 #include <stddef.h>
15 #include <stdint.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <time.h>
20
21 #include "uuid.hpp"
22
23 namespace {
24 const lttng_uuid nil_uuid = {};
25 bool lttng_uuid_is_init;
26 } /* namespace */
27
28 void lttng_uuid_to_str(const lttng_uuid& uuid, char *uuid_str)
29 {
30 sprintf(uuid_str, LTTNG_UUID_FMT, LTTNG_UUID_FMT_VALUES(uuid));
31 }
32
33 std::string lttng::utils::uuid_to_str(const lttng_uuid& uuid)
34 {
35 std::string uuid_str(LTTNG_UUID_STR_LEN, '\0');
36
37 ::lttng_uuid_to_str(uuid, &uuid_str[0]);
38
39 /* Don't include '\0' in the C++ string. */
40 uuid_str.resize(uuid_str.size() - 1);
41
42 return uuid_str;
43 }
44
45 int lttng_uuid_from_str(const char *str_in, lttng_uuid& uuid_out)
46 {
47 int ret = 0;
48 lttng_uuid uuid_scan;
49
50 if (str_in == nullptr) {
51 ret = -1;
52 goto end;
53 }
54
55 if (lttng_strnlen(str_in, LTTNG_UUID_STR_LEN) != LTTNG_UUID_STR_LEN - 1) {
56 ret = -1;
57 goto end;
58 }
59
60 /* Scan to a temporary location in case of a partial match. */
61 if (sscanf(str_in, LTTNG_UUID_FMT, LTTNG_UUID_SCAN_VALUES(uuid_scan)) !=
62 LTTNG_UUID_LEN) {
63 ret = -1;
64 goto end;
65 }
66
67 uuid_out = uuid_scan;
68 end:
69 return ret;
70 }
71
72 bool lttng_uuid_is_nil(const lttng_uuid& uuid)
73 {
74 return uuid == nil_uuid;
75 }
76
77 /*
78 * Generate a random UUID according to RFC4122, section 4.4.
79 */
80 int lttng_uuid_generate(lttng_uuid& uuid_out)
81 {
82 int i, ret = 0;
83
84 if (!lttng_uuid_is_init) {
85 try {
86 srand(lttng::random::produce_best_effort_random_seed());
87 } catch (std::exception& e) {
88 ERR("Failed to initialize random seed during generation of UUID: %s",
89 e.what());
90 ret = -1;
91 goto end;
92 }
93
94 lttng_uuid_is_init = true;
95 }
96
97 /*
98 * Generate 16 bytes of random bits.
99 */
100 for (i = 0; i < LTTNG_UUID_LEN; i++) {
101 uuid_out[i] = (uint8_t) rand();
102 }
103
104 /*
105 * Set the two most significant bits (bits 6 and 7) of the
106 * clock_seq_hi_and_reserved to zero and one, respectively.
107 */
108 uuid_out[8] &= ~(1 << 6);
109 uuid_out[8] |= (1 << 7);
110
111 /*
112 * Set the four most significant bits (bits 12 through 15) of the
113 * time_hi_and_version field to the 4-bit version number from
114 * Section 4.1.3.
115 */
116 uuid_out[6] &= 0x0f;
117 uuid_out[6] |= (LTTNG_UUID_VER << 4);
118
119 end:
120 return ret;
121 }
This page took 0.03137 seconds and 4 git commands to generate.