libcoap 4.3.0
coap_prng.c
Go to the documentation of this file.
1/*
2 * coap_prng.c -- random number generation
3 *
4 * Copyright (C) 2020 Olaf Bergmann <bergmann@tzi.org>
5 *
6 * SPDX-License-Identifier: BSD-2-Clause
7 *
8 * This file is part of the CoAP library libcoap. Please see README
9 * for terms of use.
10 */
11
12#include "coap3/coap_internal.h"
13
14#ifdef HAVE_GETRANDOM
15#include <sys/random.h>
16#else /* !HAVE_GETRANDOM */
17#include <stdlib.h>
18#endif /* !HAVE_GETRANDOM */
19
20#if defined(_WIN32)
21
22errno_t __cdecl rand_s( _Out_ unsigned int* _RandomValue );
29coap_prng_impl( unsigned char *buf, size_t len ) {
30 while ( len != 0 ) {
31 uint32_t r = 0;
32 size_t i;
33 if ( rand_s( &r ) != 0 )
34 return 0;
35 for ( i = 0; i < len && i < 4; i++ ) {
36 *buf++ = (uint8_t)r;
37 r >>= 8;
38 }
39 len -= i;
40 }
41 return 1;
42}
43
44#endif /* _WIN32 */
45
46static int
47coap_prng_default(void *buf, size_t len) {
48#ifdef HAVE_GETRANDOM
49 return getrandom(buf, len, 0);
50#else /* !HAVE_GETRANDOM */
51#if defined(_WIN32)
52 return coap_prng_impl(buf,len);
53#else /* !_WIN32 */
54 unsigned char *dst = (unsigned char *)buf;
55 while (len--)
56 *dst++ = rand() & 0xFF;
57 return 1;
58#endif /* !_WIN32 */
59#endif /* !HAVE_GETRANDOM */
60}
61
63
64#if defined(WITH_CONTIKI)
65
66#elif defined(WITH_LWIP) && defined(LWIP_RAND)
67
68#else
69
70void
72 rand_func = rng;
73}
74
75void
76coap_prng_init(unsigned int seed) {
77#ifdef HAVE_GETRANDOM
78 /* No seed to seed the random source if getrandom() is used,
79 * see dtls_prng(). */
80 (void)seed;
81#else /* !HAVE_GETRANDOM */
82 srand(seed);
83#endif /* !HAVE_GETRANDOM */
84}
85
86int
87coap_prng(void *buf, size_t len) {
88 if (!rand_func) {
89 return 0;
90 }
91
92 rand_func(buf, len);
93 return 1;
94}
95
96#endif
Pulls together all the internal only header files.
static int coap_prng_default(void *buf, size_t len)
Definition: coap_prng.c:47
static coap_rand_func_t rand_func
Definition: coap_prng.c:62
int(* coap_rand_func_t)(void *out, size_t len)
Data type for random number generator function.
Definition: coap_prng.h:77
void coap_set_prng(coap_rand_func_t rng)
Replaces the current random number generation function with the default function rng.
Definition: coap_prng.c:71
int coap_prng(void *buf, size_t len)
Fills buf with len random bytes using the default pseudo random number generator.
Definition: coap_prng.c:87
void coap_prng_init(unsigned int seed)
Seeds the default random number generation function with the given seed.
Definition: coap_prng.c:76
#define COAP_STATIC_INLINE
Definition: libcoap.h:40