util: add support for getrandom()
Add support for the Linux getrandom() system call, which is available in glibc since 2.25.
This commit is contained in:
parent
db93180ce1
commit
c5735ebfe9
3 changed files with 42 additions and 0 deletions
5
configure
vendored
5
configure
vendored
|
@ -633,6 +633,11 @@ if test_code 'arc4random_buf()' 'stdlib.h' '' '' 'arc4random_buf(NULL, 0);'; the
|
||||||
add_def HAVE_ARC4RANDOM
|
add_def HAVE_ARC4RANDOM
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if test_code 'getrandom()' 'stdlib.h sys/random.h' '' '' \
|
||||||
|
'getrandom(NULL, 256, 0);'; then
|
||||||
|
add_def HAVE_GETRANDOM
|
||||||
|
fi
|
||||||
|
|
||||||
RECVMMSG_CODE='
|
RECVMMSG_CODE='
|
||||||
struct mmsghdr hdr;
|
struct mmsghdr hdr;
|
||||||
return !recvmmsg(0, &hdr, 1, MSG_DONTWAIT, 0);'
|
return !recvmmsg(0, &hdr, 1, MSG_DONTWAIT, 0);'
|
||||||
|
|
|
@ -76,4 +76,8 @@
|
||||||
#include <arpa/inet.h>
|
#include <arpa/inet.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#ifdef HAVE_GETRANDOM
|
||||||
|
#include <sys/random.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
#endif /* GOT_SYSINCL_H */
|
#endif /* GOT_SYSINCL_H */
|
||||||
|
|
33
util.c
33
util.c
|
@ -1195,11 +1195,44 @@ UTI_GetRandomBytesUrandom(void *buf, unsigned int len)
|
||||||
|
|
||||||
/* ================================================== */
|
/* ================================================== */
|
||||||
|
|
||||||
|
#ifdef HAVE_GETRANDOM
|
||||||
|
static void
|
||||||
|
get_random_bytes_getrandom(char *buf, unsigned int len)
|
||||||
|
{
|
||||||
|
static char rand_buf[256];
|
||||||
|
static unsigned int available = 0, disabled = 0;
|
||||||
|
unsigned int i;
|
||||||
|
|
||||||
|
for (i = 0; i < len; i++) {
|
||||||
|
if (!available) {
|
||||||
|
if (disabled)
|
||||||
|
break;
|
||||||
|
|
||||||
|
if (getrandom(rand_buf, sizeof (rand_buf), 0) != sizeof (rand_buf)) {
|
||||||
|
disabled = 1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
available = sizeof (rand_buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
buf[i] = rand_buf[--available];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (i < len)
|
||||||
|
UTI_GetRandomBytesUrandom(buf, len);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* ================================================== */
|
||||||
|
|
||||||
void
|
void
|
||||||
UTI_GetRandomBytes(void *buf, unsigned int len)
|
UTI_GetRandomBytes(void *buf, unsigned int len)
|
||||||
{
|
{
|
||||||
#ifdef HAVE_ARC4RANDOM
|
#ifdef HAVE_ARC4RANDOM
|
||||||
arc4random_buf(buf, len);
|
arc4random_buf(buf, len);
|
||||||
|
#elif defined(HAVE_GETRANDOM)
|
||||||
|
get_random_bytes_getrandom(buf, len);
|
||||||
#else
|
#else
|
||||||
UTI_GetRandomBytesUrandom(buf, len);
|
UTI_GetRandomBytesUrandom(buf, len);
|
||||||
#endif
|
#endif
|
||||||
|
|
Loading…
Reference in a new issue