1 /* SPDX-License-Identifier: LGPL-2.1+ */
11 #include "hexdecoct.h"
12 #include "id128-util.h"
14 #include "stdio-util.h"
16 char *id128_to_uuid_string(sd_id128_t id, char s[37]) {
21 /* Similar to sd_id128_to_string() but formats the result as UUID instead of plain hex chars */
23 for (n = 0; n < 16; n++) {
25 if (IN_SET(n, 4, 6, 8, 10))
28 s[k++] = hexchar(id.bytes[n] >> 4);
29 s[k++] = hexchar(id.bytes[n] & 0xF);
39 bool id128_is_valid(const char *s) {
47 /* Plain formatted 128bit hex string */
49 for (i = 0; i < l; i++) {
52 if (!(c >= '0' && c <= '9') &&
53 !(c >= 'a' && c <= 'z') &&
54 !(c >= 'A' && c <= 'Z'))
62 for (i = 0; i < l; i++) {
65 if (IN_SET(i, 8, 13, 18, 23)) {
69 if (!(c >= '0' && c <= '9') &&
70 !(c >= 'a' && c <= 'z') &&
71 !(c >= 'A' && c <= 'Z'))
82 int id128_read_fd(int fd, Id128Format f, sd_id128_t *ret) {
87 assert(f < _ID128_FORMAT_MAX);
89 /* Reads an 128bit ID from a file, which may either be in plain format (32 hex digits), or in UUID format, both
90 * optionally followed by a newline and nothing else. ID files should really be newline terminated, but if they
91 * aren't that's OK too, following the rule of "Be conservative in what you send, be liberal in what you
94 l = loop_read(fd, buffer, sizeof(buffer), false); /* we expect a short read of either 32/33 or 36/37 chars */
97 if (l == 0) /* empty? */
102 case 33: /* plain UUID with trailing newline */
103 if (buffer[32] != '\n')
107 case 32: /* plain UUID without trailing newline */
114 case 37: /* RFC UUID with trailing newline */
115 if (buffer[36] != '\n')
119 case 36: /* RFC UUID without trailing newline */
120 if (f == ID128_PLAIN)
130 return sd_id128_from_string(buffer, ret);
133 int id128_read(const char *p, Id128Format f, sd_id128_t *ret) {
134 _cleanup_close_ int fd = -1;
136 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY);
140 return id128_read_fd(fd, f, ret);
143 int id128_write_fd(int fd, Id128Format f, sd_id128_t id, bool do_sync) {
149 assert(f < _ID128_FORMAT_MAX);
151 if (f != ID128_UUID) {
152 sd_id128_to_string(id, buffer);
156 id128_to_uuid_string(id, buffer);
161 r = loop_write(fd, buffer, sz, false);
169 r = fsync_directory_of_file(fd);
177 #if 0 /// UNNEEDED by elogind
178 int id128_write(const char *p, Id128Format f, sd_id128_t id, bool do_sync) {
179 _cleanup_close_ int fd = -1;
181 fd = open(p, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_TRUNC, 0444);
185 return id128_write_fd(fd, f, id, do_sync);
188 void id128_hash_func(const void *p, struct siphash *state) {
189 siphash24_compress(p, 16, state);
192 int id128_compare_func(const void *a, const void *b) {
193 return memcmp(a, b, 16);
196 const struct hash_ops id128_hash_ops = {
197 .hash = id128_hash_func,
198 .compare = id128_compare_func,