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