• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
22 errno_t __cdecl rand_s( _Out_ unsigned int* _RandomValue );
23 /**
24  * Fills \p buf with \p len random bytes. This is the default implementation for
25  * coap_prng(). You might want to change coap_prng_impl() to use a better
26  * PRNG on your specific platform.
27  */
28 COAP_STATIC_INLINE int
coap_prng_impl(unsigned char * buf,size_t len)29 coap_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 
46 static int
coap_prng_default(void * buf,size_t len)47 coap_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 
62 static coap_rand_func_t rand_func = coap_prng_default;
63 
64 #if defined(WITH_CONTIKI)
65 
66 #elif defined(WITH_LWIP) && defined(LWIP_RAND)
67 
68 #else
69 
70 void
coap_set_prng(coap_rand_func_t rng)71 coap_set_prng(coap_rand_func_t rng) {
72   rand_func = rng;
73 }
74 
75 void
coap_prng_init(unsigned int seed)76 coap_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 
86 int
coap_prng(void * buf,size_t len)87 coap_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
97