1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2011 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
30 char *sd_id128_to_string(sd_id128_t id, char s[33]) {
35 for (n = 0; n < 16; n++) {
36 s[n*2] = hexchar(id.bytes[n] >> 4);
37 s[n*2+1] = hexchar(id.bytes[n] & 0xF);
45 int sd_id128_from_string(const char s[33], sd_id128_t *ret) {
52 for (n = 0; n < 16; n++) {
55 a = unhexchar(s[n*2]);
59 b = unhexchar(s[n*2+1]);
63 t.bytes[n] = (a << 4) | b;
73 sd_id128_t sd_id128_make_v4_uuid(sd_id128_t id) {
74 /* Stolen from generate_random_uuid() of drivers/char/random.c
75 * in the kernel sources */
77 /* Set UUID version to 4 --- truly random generation */
78 id.bytes[6] = (id.bytes[6] & 0x0F) | 0x40;
80 /* Set the UUID variant to DCE */
81 id.bytes[8] = (id.bytes[8] & 0x3F) | 0x80;
86 int sd_id128_get_machine(sd_id128_t *ret) {
87 static __thread sd_id128_t saved_machine_id;
88 static __thread bool saved_machine_id_valid = false;
95 if (saved_machine_id_valid) {
96 *ret = saved_machine_id;
100 fd = open("/etc/machine-id", O_RDONLY|O_CLOEXEC|O_NOCTTY);
104 k = loop_read(fd, buf, 32, false);
105 close_nointr_nofail(fd);
113 for (j = 0; j < 16; j++) {
116 a = unhexchar(buf[j*2]);
117 b = unhexchar(buf[j*2+1]);
122 t.bytes[j] = a << 4 | b;
125 saved_machine_id = t;
126 saved_machine_id_valid = true;
132 int sd_id128_get_boot(sd_id128_t *ret) {
133 static __thread sd_id128_t saved_boot_id;
134 static __thread bool saved_boot_id_valid = false;
142 if (saved_boot_id_valid) {
143 *ret = saved_boot_id;
147 fd = open("/proc/sys/kernel/random/boot_id", O_RDONLY|O_CLOEXEC|O_NOCTTY);
151 k = loop_read(fd, buf, 36, false);
152 close_nointr_nofail(fd);
160 for (j = 0, p = buf; j < 16; j++) {
172 t.bytes[j] = a << 4 | b;
178 saved_boot_id_valid = true;
184 int sd_id128_randomize(sd_id128_t *ret) {
191 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
195 k = loop_read(fd, &t, 16, false);
196 close_nointr_nofail(fd);
204 /* Turn this into a valid v4 UUID, to be nice. Note that we
205 * only guarantee this for newly generated UUIDs, not for
206 * pre-existing ones.*/
208 *ret = sd_id128_make_v4_uuid(t);