viruuid.c 7.1 KB
Newer Older
1
/*
2 3
 * viruuid.h: helper APIs for dealing with UUIDs
 *
E
Eric Blake 已提交
4
 * Copyright (C) 2007-2012 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library.  If not, see
O
Osier Yang 已提交
18
 * <http://www.gnu.org/licenses/>.
19 20 21 22 23
 *
 * Authors:
 *     Mark McLoughlin <markmc@redhat.com>
 */

24
#include <config.h>
25

26
#include "viruuid.h"
27 28 29 30

#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
31
#include <stdio.h>
32 33 34 35 36 37
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>

J
Jim Meyering 已提交
38
#include "c-ctype.h"
39
#include "internal.h"
40
#include "virutil.h"
41
#include "virterror_internal.h"
42
#include "virlog.h"
43
#include "viralloc.h"
E
Eric Blake 已提交
44
#include "virfile.h"
45
#include "virrandom.h"
46

47
#ifndef ENODATA
48
# define ENODATA EIO
49 50
#endif

51 52
static unsigned char host_uuid[VIR_UUID_BUFLEN];

53
static int
D
Daniel P. Berrange 已提交
54 55
virUUIDGenerateRandomBytes(unsigned char *buf,
                           int buflen)
56 57 58 59 60 61 62 63 64 65 66 67
{
    int fd;

    if ((fd = open("/dev/urandom", O_RDONLY)) < 0)
        return errno;

    while (buflen > 0) {
        int n;

        if ((n = read(fd, buf, buflen)) <= 0) {
            if (errno == EINTR)
                continue;
68
            VIR_FORCE_CLOSE(fd);
69 70 71 72 73 74 75
            return n < 0 ? errno : ENODATA;
        }

        buf += n;
        buflen -= n;
    }

76
    VIR_FORCE_CLOSE(fd);
77 78 79 80 81

    return 0;
}

static int
D
Daniel P. Berrange 已提交
82 83
virUUIDGeneratePseudoRandomBytes(unsigned char *buf,
                                 int buflen)
84 85
{
    while (buflen > 0) {
86
        *buf++ = virRandomBits(8);
87 88 89 90 91 92
        buflen--;
    }

    return 0;
}

93 94
/**
 * virUUIDGenerate:
95
 * @uuid: array of VIR_UUID_BUFLEN bytes to store the new UUID
96 97 98 99 100
 *
 * Generates a randomized unique identifier.
 *
 * Returns 0 in case of success and -1 in case of failure
 */
101
int
D
Daniel P. Berrange 已提交
102
virUUIDGenerate(unsigned char *uuid)
103 104 105
{
    int err;

106
    if (uuid == NULL)
107
        return -1;
108

109 110
    if ((err = virUUIDGenerateRandomBytes(uuid, VIR_UUID_BUFLEN))) {
        char ebuf[1024];
111 112
        VIR_WARN("Falling back to pseudorandom UUID,"
                 " failed to generate random bytes: %s",
113
                 virStrerror(err, ebuf, sizeof(ebuf)));
114
        err = virUUIDGeneratePseudoRandomBytes(uuid, VIR_UUID_BUFLEN);
115
    }
116

117
    return err;
118 119
}

120 121
/**
 * virUUIDParse:
122 123
 * @uuidstr: zero terminated string representation of the UUID
 * @uuid: array of VIR_UUID_BUFLEN bytes to store the raw UUID
124 125 126 127 128 129
 *
 * Parses the external string representation, allowing spaces and '-'
 * character in the sequence, and storing the result as a raw UUID
 *
 * Returns 0 in case of success and -1 in case of error.
 */
130
int
131
virUUIDParse(const char *uuidstr, unsigned char *uuid) {
132 133 134 135 136
    const char *cur;
    int i;

    /*
     * do a liberal scan allowing '-' and ' ' anywhere between character
137 138
     * pairs, and surrounding whitespace, as long as there are exactly
     * 32 hexadecimal digits the end.
139
     */
140
    cur = uuidstr;
141 142 143
    while (c_isspace(*cur))
        cur++;

144 145
    for (i = 0;i < VIR_UUID_BUFLEN;) {
        uuid[i] = 0;
146 147 148 149 150 151
        if (*cur == 0)
            goto error;
        if ((*cur == '-') || (*cur == ' ')) {
            cur++;
            continue;
        }
J
Jim Meyering 已提交
152
        if (!c_isxdigit(*cur))
153
            goto error;
154
        uuid[i] = virHexToBin(*cur);
155
        uuid[i] *= 16;
156 157 158
        cur++;
        if (*cur == 0)
            goto error;
J
Jim Meyering 已提交
159
        if (!c_isxdigit(*cur))
160
            goto error;
161
        uuid[i] += virHexToBin(*cur);
162 163 164 165
        i++;
        cur++;
    }

166 167 168 169 170 171
    while (*cur) {
        if (!c_isspace(*cur))
            goto error;
        cur++;
    }

172 173 174 175 176 177
    return 0;

 error:
    return -1;
}

178 179 180 181 182 183 184 185 186
/**
 * virUUIDFormat:
 * @uuid: array of VIR_UUID_RAW_LEN bytes to store the raw UUID
 * @uuidstr: array of VIR_UUID_STRING_BUFLEN bytes to store the
 * string representation of the UUID in. The resulting string
 * will be NULL terminated.
 *
 * Converts the raw UUID into printable format, with embedded '-'
 *
187
 * Returns a pointer to the resulting character string.
188
 */
189 190
const char *
virUUIDFormat(const unsigned char *uuid, char *uuidstr)
191 192 193 194 195 196 197 198
{
    snprintf(uuidstr, VIR_UUID_STRING_BUFLEN,
             "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
             uuid[0], uuid[1], uuid[2], uuid[3],
             uuid[4], uuid[5], uuid[6], uuid[7],
             uuid[8], uuid[9], uuid[10], uuid[11],
             uuid[12], uuid[13], uuid[14], uuid[15]);
    uuidstr[VIR_UUID_STRING_BUFLEN-1] = '\0';
199
    return uuidstr;
200
}
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228



/**
 * virUUIDIsValid
 *
 * @uuid: The UUID to test
 *
 * Do some basic tests to check whether the given UUID is
 * valid as a host UUID.
 * Basic tests:
 *  - Not all of the digits may be equal
 */
int
virUUIDIsValid(unsigned char *uuid)
{
    unsigned int i, ctr = 1;
    unsigned char c;

    if (!uuid)
        return 0;

    c = uuid[0];

    for (i = 1; i < VIR_UUID_BUFLEN; i++)
        if (uuid[i] == c)
            ctr++;

229
    return ctr != VIR_UUID_BUFLEN;
230 231 232 233 234 235 236 237 238 239 240 241 242 243
}

static int
getDMISystemUUID(char *uuid, int len)
{
    unsigned int i = 0;
    const char *paths[] = {
        "/sys/devices/virtual/dmi/id/product_uuid",
        "/sys/class/dmi/id/product_uuid",
        NULL
    };

    while (paths[i]) {
        int fd = open(paths[i], O_RDONLY);
E
Eric Blake 已提交
244
        if (fd >= 0) {
245 246
            if (saferead(fd, uuid, len - 1) == len - 1) {
                uuid[len - 1] = '\0';
247
                VIR_FORCE_CLOSE(fd);
248 249
                return 0;
            }
250
            VIR_FORCE_CLOSE(fd);
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
        }
        i++;
    }

    return -1;
}


/**
 * setHostUUID
 *
 * @host_uuid: UUID that the host is supposed to have
 *
 * Set the UUID of the host if it hasn't been set, yet
 * Returns 0 in case of success, an error code in case of error.
 */
int
virSetHostUUIDStr(const char *uuid)
{
    int rc;
    char dmiuuid[VIR_UUID_STRING_BUFLEN];

    if (virUUIDIsValid(host_uuid))
        return EEXIST;

    if (!uuid) {
C
Chris Lalancette 已提交
277
        memset(dmiuuid, 0, sizeof(dmiuuid));
278
        if (!getDMISystemUUID(dmiuuid, sizeof(dmiuuid))) {
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
            if (!virUUIDParse(dmiuuid, host_uuid))
                return 0;
        }

        if (!virUUIDIsValid(host_uuid))
            return virUUIDGenerate(host_uuid);
    } else {
        rc = virUUIDParse(uuid, host_uuid);
        if (rc)
            return rc;
        if (!virUUIDIsValid(host_uuid))
            return EINVAL;
    }

    return 0;
}

/**
 * getHostUUID:
 *
 * @host_uuid: memory to store the host_uuid into
 *
 * Get the UUID of the host. Returns 0 in case of success,
 * an error code otherwise.
 * Returns 0 in case of success, an error code in case of error.
 */
int virGetHostUUID(unsigned char *uuid)
{
    int ret = 0;

    if (!virUUIDIsValid(host_uuid))
        ret = virSetHostUUIDStr(NULL);

    memcpy(uuid, host_uuid, sizeof(host_uuid));

    return ret;
}