Line data Source code
1 : /* SPDX-License-Identifier: MIT OR GPL-3.0-only */
2 : /* uuid.c
3 : * strophe XMPP client library -- UUID generation
4 : *
5 : * Copyright (C) 2015 Dmitry Podgorny <pasis.ua@gmail.com>
6 : *
7 : * This software is provided AS-IS with no warranty, either express
8 : * or implied.
9 : *
10 : * This program is dual licensed under the MIT or GPLv3 licenses.
11 : */
12 :
13 : /** @file
14 : * Generation of UUID version 4 according to RFC4122.
15 : */
16 :
17 : #include "strophe.h"
18 : #include "common.h"
19 :
20 : /** @def XMPP_UUID_LEN
21 : * UUID length in string representation excluding '\0'.
22 : */
23 : #define XMPP_UUID_LEN 36
24 :
25 : /** Generate UUID version 4 in pre-allocated buffer.
26 : *
27 : * @param ctx a Strophe context object
28 : * @param uuid pre-allocated buffer of size (XMPP_UUID_LEN + 1)
29 : */
30 0 : static void crypto_uuid_gen(xmpp_ctx_t *ctx, char *uuid)
31 : {
32 0 : unsigned char buf[16];
33 0 : int i = 0; /* uuid iterator */
34 0 : int j = 0; /* buf iterator */
35 :
36 0 : static const char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7',
37 : '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
38 :
39 0 : xmpp_rand_bytes(ctx->rand, buf, sizeof(buf));
40 0 : buf[8] &= 0x3f;
41 0 : buf[8] |= 0x80;
42 0 : buf[6] &= 0x0f;
43 0 : buf[6] |= 0x40;
44 0 : while (i < XMPP_UUID_LEN) {
45 0 : if (i == 8 || i == 13 || i == 18 || i == 23)
46 0 : uuid[i++] = '-';
47 : else {
48 0 : uuid[i++] = hex[buf[j] >> 4];
49 0 : uuid[i++] = hex[buf[j] & 0x0f];
50 0 : ++j;
51 : }
52 : }
53 0 : uuid[XMPP_UUID_LEN] = '\0';
54 0 : }
55 :
56 : /** Generate UUID version 4.
57 : * This function allocates memory for the resulting string and must be freed
58 : * with xmpp_free().
59 : *
60 : * @param ctx a Strophe context object
61 : *
62 : * @return ASCIIZ string
63 : */
64 0 : char *xmpp_uuid_gen(xmpp_ctx_t *ctx)
65 : {
66 0 : char *uuid;
67 :
68 0 : uuid = strophe_alloc(ctx, XMPP_UUID_LEN + 1);
69 0 : if (uuid != NULL) {
70 0 : crypto_uuid_gen(ctx, uuid);
71 : }
72 0 : return uuid;
73 : }
|