2 This file is part of systemd.
4 Copyright 2011 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
27 #include "hexdecoct.h"
28 #include "id128-util.h"
31 #include "random-util.h"
34 _public_ char *sd_id128_to_string(sd_id128_t id, char s[SD_ID128_STRING_MAX]) {
37 assert_return(s, NULL);
39 for (n = 0; n < 16; n++) {
40 s[n*2] = hexchar(id.bytes[n] >> 4);
41 s[n*2+1] = hexchar(id.bytes[n] & 0xF);
49 _public_ int sd_id128_from_string(const char s[], sd_id128_t *ret) {
54 assert_return(s, -EINVAL);
56 for (n = 0, i = 0; n < 16;) {
60 /* Is this a GUID? Then be nice, and skip over
65 else if (i == 13 || i == 18 || i == 23) {
75 a = unhexchar(s[i++]);
79 b = unhexchar(s[i++]);
83 t.bytes[n++] = (a << 4) | b;
86 if (i != (is_guid ? 36 : 32))
97 _public_ int sd_id128_get_machine(sd_id128_t *ret) {
98 static thread_local sd_id128_t saved_machine_id = {};
101 assert_return(ret, -EINVAL);
103 if (sd_id128_is_null(saved_machine_id)) {
104 r = id128_read("/etc/machine-id", ID128_PLAIN, &saved_machine_id);
108 if (sd_id128_is_null(saved_machine_id))
112 *ret = saved_machine_id;
116 _public_ int sd_id128_get_boot(sd_id128_t *ret) {
117 static thread_local sd_id128_t saved_boot_id = {};
120 assert_return(ret, -EINVAL);
122 if (sd_id128_is_null(saved_boot_id)) {
123 r = id128_read("/proc/sys/kernel/random/boot_id", ID128_UUID, &saved_boot_id);
128 *ret = saved_boot_id;
132 static sd_id128_t make_v4_uuid(sd_id128_t id) {
133 /* Stolen from generate_random_uuid() of drivers/char/random.c
134 * in the kernel sources */
136 /* Set UUID version to 4 --- truly random generation */
137 id.bytes[6] = (id.bytes[6] & 0x0F) | 0x40;
139 /* Set the UUID variant to DCE */
140 id.bytes[8] = (id.bytes[8] & 0x3F) | 0x80;
145 _public_ int sd_id128_randomize(sd_id128_t *ret) {
149 assert_return(ret, -EINVAL);
151 r = dev_urandom(&t, sizeof(t));
155 /* Turn this into a valid v4 UUID, to be nice. Note that we
156 * only guarantee this for newly generated UUIDs, not for
157 * pre-existing ones. */
159 *ret = make_v4_uuid(t);