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