1 /*
2  * Copyright (c) 2010-2012 Balabit
3  * Copyright (c) 2010-2012 Balázs Scheidler
4  * Copyright (c) 2012 Gergely Nagy <algernon@balabit.hu>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As an additional exemption you are allowed to compile & link against the
21  * OpenSSL libraries as published by the OpenSSL project. See the file
22  * COPYING for details.
23  */
24 
25 #include "uuid.h"
26 
27 #include <openssl/rand.h>
28 #include <arpa/inet.h>
29 
30 void
uuid_gen_random(gchar * buf,gsize buflen)31 uuid_gen_random(gchar *buf, gsize buflen)
32 {
33   union
34   {
35     struct
36     {
37       guint32 time_low;
38       guint16 time_mid;
39       guint16 time_hi_and_version;
40       guint8  clk_seq_hi_res;
41       guint8  clk_seq_low;
42       guint8  node[6];
43       guint16 node_low;
44       guint32 node_hi;
45     };
46     guchar __rnd[16];
47   } uuid;
48 
49   RAND_bytes(uuid.__rnd, sizeof(uuid));
50 
51   uuid.clk_seq_hi_res = (uuid.clk_seq_hi_res & ~0xC0) | 0x80;
52   uuid.time_hi_and_version = htons((uuid.time_hi_and_version & ~0xF000) | 0x4000);
53 
54   g_snprintf(buf, buflen, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
55              uuid.time_low, uuid.time_mid, uuid.time_hi_and_version,
56              uuid.clk_seq_hi_res, uuid.clk_seq_low,
57              uuid.node[0], uuid.node[1], uuid.node[2],
58              uuid.node[3], uuid.node[4], uuid.node[5]);
59 
60 }
61