Merge branch 'milestone/monitoring' into jennifer/request_id
[trust_router.git] / common / tr_rand_id.c
1 /*
2  * Copyright (c) 2018, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
25  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
31  * OF THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  */
34
35 #include <stdio.h>
36 #include <string.h>
37 #include <openssl/rand.h>
38 #include <talloc.h>
39
40 #include <tr_rand_id.h>
41
42 static char *bytes_to_hex(TALLOC_CTX *mem_ctx, const unsigned char *bytes, size_t len)
43 {
44   char *hex = talloc_size(mem_ctx, 1 + len * 2 * sizeof(char));
45   char *p = NULL;
46
47   if (hex) {
48     p = hex;
49     while(len--) {
50       p += sprintf(p, "%02x", *(bytes++));
51     }
52   }
53
54   return hex;
55 }
56
57 /**
58  * Generate n random bytes of data
59  *
60  * @param dst destination buffer, at least n bytes long
61  * @param n number of bytes to generate
62  * @return -1 on error
63  */
64 static int random_bytes(unsigned char *dst, size_t n)
65 {
66   return RAND_pseudo_bytes(dst, n);
67 }
68
69 #define ID_LENGTH 15
70 /**
71  * Generate a random ID
72  *
73  * @param mem_ctx talloc context for the result
74  * @return random string of hex characters or null if it is unable to generate them
75  */
76 char *tr_random_id(TALLOC_CTX *mem_ctx)
77 {
78   unsigned char bytes[ID_LENGTH];
79   char *hex = NULL;
80
81   if (random_bytes(bytes, ID_LENGTH) >= 0)
82     hex = bytes_to_hex(mem_ctx, bytes, ID_LENGTH);
83
84   return hex;
85 }