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