]> git.proxmox.com Git - ceph.git/blob - ceph/src/pmdk/src/common/uuid.c
94fdd737cb8a85c0e83c6a034181b4328855bd42
[ceph.git] / ceph / src / pmdk / src / common / uuid.c
1 // SPDX-License-Identifier: BSD-3-Clause
2 /* Copyright 2014-2018, Intel Corporation */
3
4 /*
5 * uuid.c -- uuid utilities
6 */
7
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <string.h>
11 #include "uuid.h"
12 #include "out.h"
13
14 /*
15 * util_uuid_to_string -- generate a string form of the uuid
16 */
17 int
18 util_uuid_to_string(const uuid_t u, char *buf)
19 {
20 int len; /* size that is returned from sprintf call */
21
22 if (buf == NULL) {
23 LOG(2, "invalid buffer for uuid string");
24 return -1;
25 }
26
27 if (u == NULL) {
28 LOG(2, "invalid uuid structure");
29 return -1;
30 }
31
32 struct uuid *uuid = (struct uuid *)u;
33 len = snprintf(buf, POOL_HDR_UUID_STR_LEN,
34 "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
35 uuid->time_low, uuid->time_mid, uuid->time_hi_and_ver,
36 uuid->clock_seq_hi, uuid->clock_seq_low, uuid->node[0],
37 uuid->node[1], uuid->node[2], uuid->node[3], uuid->node[4],
38 uuid->node[5]);
39
40 if (len != POOL_HDR_UUID_STR_LEN - 1) {
41 LOG(2, "snprintf(uuid): %d", len);
42 return -1;
43 }
44
45 return 0;
46 }
47
48 /*
49 * util_uuid_from_string -- generate a binary form of the uuid
50 *
51 * uuid string read from /proc/sys/kernel/random/uuid. UUID string
52 * format example:
53 * f81d4fae-7dec-11d0-a765-00a0c91e6bf6
54 */
55 int
56 util_uuid_from_string(const char *uuid, struct uuid *ud)
57 {
58 if (strlen(uuid) != 36) {
59 LOG(2, "invalid uuid string");
60 return -1;
61 }
62
63 if (uuid[8] != '-' || uuid[13] != '-' || uuid[18] != '-' ||
64 uuid[23] != '-') {
65 LOG(2, "invalid uuid string");
66 return -1;
67 }
68
69 int n = sscanf(uuid,
70 "%08x-%04hx-%04hx-%02hhx%02hhx-"
71 "%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx",
72 &ud->time_low, &ud->time_mid, &ud->time_hi_and_ver,
73 &ud->clock_seq_hi, &ud->clock_seq_low, &ud->node[0],
74 &ud->node[1], &ud->node[2], &ud->node[3], &ud->node[4],
75 &ud->node[5]);
76
77 if (n != 11) {
78 LOG(2, "sscanf(uuid)");
79 return -1;
80 }
81
82 return 0;
83 }