summaryrefslogtreecommitdiff
path: root/src/libnm-glib-aux/nm-uuid.c
blob: ff0649d0fe5d3ba390a483fe605d14ee011246c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
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
277
278
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/* SPDX-License-Identifier: LGPL-2.1-or-later */

#include "libnm-glib-aux/nm-default-glib.h"

#include "nm-uuid.h"

#include "libnm-glib-aux/nm-random-utils.h"
#include "libnm-glib-aux/nm-str-buf.h"

/*****************************************************************************/

const NMUuid nm_uuid_ns_zero =
    NM_UUID_INIT(00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00);

/* arbitrarily chosen namespace UUID for nm_uuid_generate_from_strings() */
const NMUuid nm_uuid_ns_1 =
    NM_UUID_INIT(b4, 25, e9, fb, 75, 98, 44, b4, 9e, 3b, 5a, 2e, 3a, aa, 49, 05);

char *
nm_uuid_unparse_case(const NMUuid *uuid, char out_str[static 37], gboolean upper_case)
{
    char *s;
    int   i;

    nm_assert(uuid);
    nm_assert(out_str);

    s = out_str;
    for (i = 0; i < 16; i++) {
        const guint8 c = uuid->uuid[i];

        if (NM_IN_SET(i, 4, 6, 8, 10))
            *(s++) = '-';
        *(s++) = nm_hexchar(c >> 4, upper_case);
        *(s++) = nm_hexchar(c, upper_case);
    }
    *s = '\0';

    return out_str;
}

/*****************************************************************************/

gboolean
nm_uuid_parse_full(const char *str, NMUuid *out_uuid, gboolean *out_is_normalized)
{
    NMUuid   uuid;
    guint8  *p;
    int      i;
    gboolean is_normalized = TRUE;

    nm_assert(str);

    p = uuid.uuid;

    for (i = 0; TRUE;) {
        int v0;
        int v1;

        if (NM_IN_SET(i, 8, 13, 18, 23)) {
            if (str[i] != '-')
                return FALSE;
            i++;
            continue;
        }

        if (i == 36) {
            if (str[i] != '\0')
                return FALSE;

            NM_SET_OUT(out_is_normalized, is_normalized);
            NM_SET_OUT(out_uuid, uuid);
            return TRUE;
        }

#define _hexchar(ch, out_is_normalized2)                                    \
    ({                                                                      \
        const char _ch     = (ch);                                          \
        int        _result = -1;                                            \
                                                                            \
        if (_ch >= '0') {                                                   \
            if (_ch <= '9')                                                 \
                _result = (_ch - '0');                                      \
            else if (_ch >= 'A') {                                          \
                if (_ch <= 'F') {                                           \
                    *(out_is_normalized2) = FALSE;                          \
                    _result               = ((int) _ch) + (10 - (int) 'A'); \
                } else if (_ch >= 'a' && _ch <= 'f')                        \
                    _result = ((int) _ch) + (10 - (int) 'a');               \
            }                                                               \
        }                                                                   \
                                                                            \
        _result;                                                            \
    })

        v0 = _hexchar(str[i++], &is_normalized);
        if (v0 < 0)
            return FALSE;
        v1 = _hexchar(str[i++], &is_normalized);
        if (v1 < 0)
            return FALSE;

        *(p++) = (v0 << 4) + v1;
    }
}

/*****************************************************************************/

NMUuid *
nm_uuid_generate_random(NMUuid *out_uuid)
{
    nm_assert(out_uuid);

    /* https://tools.ietf.org/html/rfc4122#section-4.4 */

    /* See also, systemd's id128_make_v4_uuid() */

    /* nm_utils_random_bytes() is supposed to try hard to give good
     * randomness. If it fails, it still makes an effort to fill
     * random data into the buffer. There is not much we can do about
     * that case, except making sure that it does not happen in the
     * first place. */
    nm_utils_random_bytes(out_uuid, sizeof(*out_uuid));

    /* Set the four most significant bits (bits 12 through 15) of the
     * time_hi_and_version field to the 4-bit version number from
     * Section 4.1.3. */
    out_uuid->uuid[6] = (out_uuid->uuid[6] & 0x0Fu) | 0x40u;

    /* Set the two most significant bits (bits 6 and 7) of the
     * clock_seq_hi_and_reserved to zero and one, respectively. */
    out_uuid->uuid[8] = (out_uuid->uuid[8] & 0x3Fu) | 0x80u;

    return out_uuid;
}

/*****************************************************************************/

gboolean
nm_uuid_is_normalized_full(const char *str)
{
    /* The only reason why this exists is that nm_uuid_is_normalized() is an inline function.
     * If you need to forward declare the function, that won't work.
     *
     * Usually, you wouldn't use this variant! */
    return nm_uuid_is_normalized(str);
}

/*****************************************************************************/

/**
 * nm_uuid_is_valid_nmlegacy()
 * @str: the string to check whether it's a valid UUID.
 *
 * Note that this does not perform a strict check.
 * Instead, it checks a more relaxed format (including
 * non valid UUID strings). This is for backward compatibility,
 * where older code did not perform a strict check.
 *
 * Returns: %TRUE, if the string is a valid legacy format.
 *   This may not be a valid UUID!
 */
gboolean
nm_uuid_is_valid_nmlegacy(const char *str)
{
    const char *p          = str;
    int         num_dashes = 0;

    if (!p)
        return FALSE;

    while (*p) {
        if (*p == '-')
            num_dashes++;
        else if (!g_ascii_isxdigit(*p))
            return FALSE;
        p++;
    }

    /* While we accept here bogus strings as UUIDs, they must contain only
     * hexdigits and '-', and they must be either 36 or 40 chars long. */

    if ((num_dashes == 4) && (p - str == 36))
        return TRUE;

    /* Backwards compat for older configurations */
    if ((num_dashes == 0) && (p - str == 40))
        return TRUE;

    return FALSE;
}

/*****************************************************************************/

gboolean
nm_uuid_is_valid_nm(const char *str,
                    gboolean   *out_normalized,
                    char       *out_normalized_str /* [static 37] */)
{
    NMUuid   uuid;
    gboolean is_normalized;

    /* @out_normalized_str is only set, if normalization was necessary
     * and possible. The caller cannot request @out_normalized_str, without
     * also getting @out_normalized. */
    nm_assert(!out_normalized_str || out_normalized);

    if (!str)
        return FALSE;

    if (nm_uuid_parse_full(str, &uuid, &is_normalized)) {
        /* Note that:
         *   @is_normalized means that "str" contains a normalized UUID
         *   @out_normalized: indicates whether str requires normalization
         *     and whether @out_normalized_str was set to contain the normalized
         *     UUID.
         * With this, we get the slightly odd assignment: */
        NM_SET_OUT(out_normalized, !is_normalized);

        if (!is_normalized && out_normalized_str) {
            /* we need to normalize the UUID */
            nm_uuid_unparse(&uuid, out_normalized_str);
        }

        /* regardless whether normalization was necessary, the UUID is
         * essentially valid. */
        return TRUE;
    }

    if (nm_uuid_is_valid_nmlegacy(str)) {
        /* This is not a valid UUID, but something that we used to
         * accept according to nm_uuid_is_valid_nmlegacy().
         *
         * Normalize it by sha1 hashing the string. Upper case characters
         * are made lower case first. */
        NM_SET_OUT(out_normalized, TRUE);
        if (out_normalized_str) {
            char str_lower[40 + 1];
            int  i;

            nm_assert(strlen(str) < G_N_ELEMENTS(str_lower));

            /* normalize first to lower-case. */
            for (i = 0; str[i]; i++) {
                nm_assert(i < G_N_ELEMENTS(str_lower));
                str_lower[i] = g_ascii_tolower(str[i]);
            }
            nm_assert(i < G_N_ELEMENTS(str_lower));
            str_lower[i] = '\0';

            /* The namespace UUID is chosen randomly. */
            nm_uuid_generate_from_string(
                &uuid,
                str_lower,
                -1,
                NM_UUID_TYPE_VERSION5,
                &NM_UUID_INIT(4e, 72, f7, 09, ca, 95, 44, 05, 90, 53, 1f, 43, 29, 4a, 61, 8c));
            nm_uuid_unparse(&uuid, out_normalized_str);
        }
        return TRUE;
    }

    /* UUID is not valid. */
    return FALSE;
}

/*****************************************************************************/

gboolean
nm_uuid_is_null(const NMUuid *uuid)
{
    int i;

    if (!uuid)
        return TRUE;

    for (i = 0; i < (int) G_N_ELEMENTS(uuid->uuid); i++) {
        if (uuid->uuid[i])
            return FALSE;
    }
    return TRUE;
}

char *
nm_uuid_generate_random_str(char buf[static 37])
{
    NMUuid uuid;

    nm_assert(buf);

    nm_uuid_generate_random(&uuid);
    return nm_uuid_unparse(&uuid, buf);
}

/*****************************************************************************/

/**
 * nm_uuid_generate_from_string:
 * @uuid: the UUID to update inplace. This function cannot
 *   fail to succeed.
 * @s: a string to use as the seed for the UUID
 * @slen: if negative, treat @s as zero terminated C string.
 *   Otherwise, assume the length as given (and allow @s to be
 *   non-null terminated or contain '\0').
 * @uuid_type: a type identifier which UUID format to generate.
 * @type_args: additional arguments, depending on the uuid_type
 *
 * For a given @s, this function will always return the same UUID.
 *
 * Returns: the input @uuid. This function cannot fail.
 **/
NMUuid *
nm_uuid_generate_from_string(NMUuid       *uuid,
                             const char   *s,
                             gssize        slen,
                             NMUuidType    uuid_type,
                             const NMUuid *type_args)
{
    nm_auto_free_checksum GChecksum *sum = NULL;
    union {
        guint8 sha1[NM_UTILS_CHECKSUM_LENGTH_SHA1];
        guint8 md5[NM_UTILS_CHECKSUM_LENGTH_MD5];
        NMUuid uuid;
    } digest;
    gsize         digest_len;
    GChecksumType checksum_type;

    G_STATIC_ASSERT_EXPR(sizeof(digest.md5) >= sizeof(digest.uuid));
    G_STATIC_ASSERT_EXPR(sizeof(digest.sha1) >= sizeof(digest.uuid));

    g_return_val_if_fail(uuid, NULL);
    g_return_val_if_fail(slen <= 0 || s, NULL);

    if (slen < 0)
        slen = s ? strlen(s) : 0;

    switch (uuid_type) {
    case NM_UUID_TYPE_LEGACY:
        nm_assert(!type_args);
        type_args     = NULL;
        checksum_type = G_CHECKSUM_MD5;
        break;
    case NM_UUID_TYPE_VERSION3:
        if (!type_args)
            type_args = &nm_uuid_ns_zero;
        checksum_type = G_CHECKSUM_MD5;
        break;
    case NM_UUID_TYPE_VERSION5:
        if (!type_args)
            type_args = &nm_uuid_ns_zero;
        checksum_type = G_CHECKSUM_SHA1;
        break;
    default:
        g_return_val_if_reached(NULL);
    }

    sum = g_checksum_new(checksum_type);
    if (type_args)
        g_checksum_update(sum, (guchar *) type_args, sizeof(*type_args));
    g_checksum_update(sum, (guchar *) s, slen);

    digest_len = sizeof(digest);
    g_checksum_get_digest(sum, (guint8 *) &digest, &digest_len);

    nm_assert(digest_len >= sizeof(digest.uuid));
    nm_assert(digest_len
              == ((checksum_type == G_CHECKSUM_MD5 ? NM_UTILS_CHECKSUM_LENGTH_MD5
                                                   : NM_UTILS_CHECKSUM_LENGTH_SHA1)));

    *uuid = digest.uuid;

    if (uuid_type != NM_UUID_TYPE_LEGACY) {
        uuid->uuid[6] = (uuid->uuid[6] & 0x0F) | (uuid_type << 4);
        uuid->uuid[8] = (uuid->uuid[8] & 0x3F) | 0x80;
    }

    return uuid;
}

/**
 * nm_uuid_generate_from_string_str:
 * @s: a string to use as the seed for the UUID
 * @slen: if negative, treat @s as zero terminated C string.
 *   Otherwise, assume the length as given (and allow @s to be
 *   non-null terminated or contain '\0').
 * @uuid_type: a type identifier which UUID format to generate.
 * @type_args: additional arguments, depending on the uuid_type
 *
 * For a given @s, this function will always return the same UUID.
 *
 * Returns: a newly allocated UUID suitable for use as the #NMSettingConnection
 * object's #NMSettingConnection:id: property
 **/
char *
nm_uuid_generate_from_string_str(const char   *s,
                                 gssize        slen,
                                 NMUuidType    uuid_type,
                                 const NMUuid *type_args)
{
    NMUuid        uuid;
    const NMUuid *u;

    u = nm_uuid_generate_from_string(&uuid, s, slen, uuid_type, type_args);

    if (G_UNLIKELY(!u))
        return nm_assert_unreachable_val(NULL);
    nm_assert(u == &uuid);

    return nm_uuid_unparse(&uuid, g_new(char, 37));
}

/**
 * nm_uuid_generate_from_strings:
 * @string1: a variadic list of strings. Must be NULL terminated.
 *
 * Returns a variant3 UUID based on the concatenated C strings.
 * It does not simply concatenate them, but also includes the
 * terminating '\0' character. For example "a", "b", gives
 * "a\0b\0".
 *
 * This has the advantage, that the following invocations
 * all give different UUIDs: (NULL), (""), ("",""), ("","a"), ("a",""),
 * ("aa"), ("aa", ""), ("", "aa"), ...
 */
char *
nm_uuid_generate_from_strings(const char *string1, ...)
{
    if (!string1)
        return nm_uuid_generate_from_string_str(NULL, 0, NM_UUID_TYPE_VERSION3, &nm_uuid_ns_1);

    {
        nm_auto_str_buf NMStrBuf str = NM_STR_BUF_INIT(NM_UTILS_GET_NEXT_REALLOC_SIZE_104, FALSE);
        va_list                  args;
        const char              *s;

        nm_str_buf_append_len(&str, string1, strlen(string1) + 1u);

        va_start(args, string1);
        s = va_arg(args, const char *);
        while (s) {
            nm_str_buf_append_len(&str, s, strlen(s) + 1u);
            s = va_arg(args, const char *);
        }
        va_end(args);

        return nm_uuid_generate_from_string_str(nm_str_buf_get_str_unsafe(&str),
                                                str.len,
                                                NM_UUID_TYPE_VERSION3,
                                                &nm_uuid_ns_1);
    }
}