Add vendor/fmt
[lttng-tools.git] / src / common / uuid.cpp
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
c9e313bc 9#include <common/compat/string.hpp>
c70636a7
MJ
10#include <stddef.h>
11#include <stdint.h>
12#include <stdio.h>
13#include <stdlib.h>
14#include <string.h>
15#include <time.h>
16
c9e313bc 17#include "uuid.hpp"
c70636a7 18
328c2fe7
JG
19namespace {
20const lttng_uuid nil_uuid = {};
21bool lttng_uuid_is_init;
22} /* namespace */
c70636a7 23
328c2fe7 24void lttng_uuid_to_str(const lttng_uuid& uuid, char *uuid_str)
c70636a7
MJ
25{
26 sprintf(uuid_str, LTTNG_UUID_FMT, LTTNG_UUID_FMT_VALUES(uuid));
27}
28
328c2fe7 29int lttng_uuid_from_str(const char *str_in, lttng_uuid& uuid_out)
c70636a7
MJ
30{
31 int ret = 0;
32 lttng_uuid uuid_scan;
33
328c2fe7 34 if (str_in == nullptr) {
c70636a7
MJ
35 ret = -1;
36 goto end;
37 }
38
a1298db6 39 if (lttng_strnlen(str_in, LTTNG_UUID_STR_LEN) != LTTNG_UUID_STR_LEN - 1) {
c70636a7
MJ
40 ret = -1;
41 goto end;
42 }
43
44 /* Scan to a temporary location in case of a partial match. */
45 if (sscanf(str_in, LTTNG_UUID_FMT, LTTNG_UUID_SCAN_VALUES(uuid_scan)) !=
46 LTTNG_UUID_LEN) {
47 ret = -1;
48 }
49
328c2fe7 50 uuid_out = uuid_scan;
c70636a7
MJ
51end:
52 return ret;
53}
54
328c2fe7 55bool lttng_uuid_is_nil(const lttng_uuid& uuid)
c70636a7 56{
328c2fe7 57 return uuid == nil_uuid;
c70636a7
MJ
58}
59
60/*
61 * Generate a random UUID according to RFC4122, section 4.4.
62 */
328c2fe7 63int lttng_uuid_generate(lttng_uuid& uuid_out)
c70636a7
MJ
64{
65 int i, ret = 0;
66
c70636a7
MJ
67 if (!lttng_uuid_is_init) {
68 /*
69 * We don't need cryptographic quality randomness to
70 * generate UUIDs, seed rand with the epoch.
71 */
72 const time_t epoch = time(NULL);
73
74 if (epoch == (time_t) -1) {
75 ret = -1;
76 goto end;
77 }
c70636a7 78
aeeb48c6 79 srand(epoch);
c70636a7
MJ
80 lttng_uuid_is_init = true;
81 }
82
83 /*
84 * Generate 16 bytes of random bits.
85 */
86 for (i = 0; i < LTTNG_UUID_LEN; i++) {
87 uuid_out[i] = (uint8_t) rand();
88 }
89
90 /*
91 * Set the two most significant bits (bits 6 and 7) of the
92 * clock_seq_hi_and_reserved to zero and one, respectively.
93 */
94 uuid_out[8] &= ~(1 << 6);
95 uuid_out[8] |= (1 << 7);
96
97 /*
98 * Set the four most significant bits (bits 12 through 15) of the
99 * time_hi_and_version field to the 4-bit version number from
100 * Section 4.1.3.
101 */
102 uuid_out[6] &= 0x0f;
103 uuid_out[6] |= (LTTNG_UUID_VER << 4);
104
105end:
106 return ret;
107}
This page took 0.046405 seconds and 4 git commands to generate.