1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2016 Lennart Poettering
12 #include "hexdecoct.h"
13 #include "id128-util.h"
15 #include "stdio-util.h"
17 char *id128_to_uuid_string(sd_id128_t id, char s[37]) {
22 /* Similar to sd_id128_to_string() but formats the result as UUID instead of plain hex chars */
24 for (n = 0; n < 16; n++) {
26 if (IN_SET(n, 4, 6, 8, 10))
29 s[k++] = hexchar(id.bytes[n] >> 4);
30 s[k++] = hexchar(id.bytes[n] & 0xF);
40 bool id128_is_valid(const char *s) {
48 /* Plain formatted 128bit hex string */
50 for (i = 0; i < l; i++) {
53 if (!(c >= '0' && c <= '9') &&
54 !(c >= 'a' && c <= 'z') &&
55 !(c >= 'A' && c <= 'Z'))
63 for (i = 0; i < l; i++) {
66 if (IN_SET(i, 8, 13, 18, 23)) {
70 if (!(c >= '0' && c <= '9') &&
71 !(c >= 'a' && c <= 'z') &&
72 !(c >= 'A' && c <= 'Z'))
83 int id128_read_fd(int fd, Id128Format f, sd_id128_t *ret) {
88 assert(f < _ID128_FORMAT_MAX);
90 /* Reads an 128bit ID from a file, which may either be in plain format (32 hex digits), or in UUID format, both
91 * optionally followed by a newline and nothing else. ID files should really be newline terminated, but if they
92 * aren't that's OK too, following the rule of "Be conservative in what you send, be liberal in what you
95 l = loop_read(fd, buffer, sizeof(buffer), false); /* we expect a short read of either 32/33 or 36/37 chars */
98 if (l == 0) /* empty? */
103 case 33: /* plain UUID with trailing newline */
104 if (buffer[32] != '\n')
108 case 32: /* plain UUID without trailing newline */
115 case 37: /* RFC UUID with trailing newline */
116 if (buffer[36] != '\n')
120 case 36: /* RFC UUID without trailing newline */
121 if (f == ID128_PLAIN)
131 return sd_id128_from_string(buffer, ret);
134 int id128_read(const char *p, Id128Format f, sd_id128_t *ret) {
135 _cleanup_close_ int fd = -1;
137 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY);
141 return id128_read_fd(fd, f, ret);
144 int id128_write_fd(int fd, Id128Format f, sd_id128_t id, bool do_sync) {
150 assert(f < _ID128_FORMAT_MAX);
152 if (f != ID128_UUID) {
153 sd_id128_to_string(id, buffer);
157 id128_to_uuid_string(id, buffer);
162 r = loop_write(fd, buffer, sz, false);
170 r = fsync_directory_of_file(fd);
178 #if 0 /// UNNEEDED by elogind
179 int id128_write(const char *p, Id128Format f, sd_id128_t id, bool do_sync) {
180 _cleanup_close_ int fd = -1;
182 fd = open(p, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_TRUNC, 0444);
186 return id128_write_fd(fd, f, id, do_sync);
189 void id128_hash_func(const void *p, struct siphash *state) {
190 siphash24_compress(p, 16, state);
193 int id128_compare_func(const void *a, const void *b) {
194 return memcmp(a, b, 16);
197 const struct hash_ops id128_hash_ops = {
198 .hash = id128_hash_func,
199 .compare = id128_compare_func,