Fix compilation on ancient Linux distros without sys/random.h

This commit is contained in:
Kovid Goyal 2021-02-16 12:39:18 +05:30
parent c244bcd978
commit 9ad5ef8b2d
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C

View File

@ -9,8 +9,9 @@
#include <stdbool.h>
#if __linux__
#include <sys/random.h>
#include <errno.h>
#if __has_include(<sys/random.h>)
#include <sys/random.h>
static inline bool
secure_random_bytes(void *buf, size_t nbytes) {
@ -27,6 +28,25 @@ secure_random_bytes(void *buf, size_t nbytes) {
}
}
#else
#include "safe-wrappers.h"
static inline bool
secure_random_bytes(void *buf, size_t nbytes) {
int fd = safe_open("/dev/urandom", O_RDONLY, 0);
if (fd < 0) return false;
size_t bytes_read = 0;
while (bytes_read < nbytes) {
ssize_t n = read(fd, (uint8_t*)buf + bytes_read, nbytes - bytes_read);
if (n < 0) {
if (errno == EINTR) continue;
break;
}
bytes_read += n;
}
safe_close(fd, __FILE__, __LINE__);
return bytes_read == nbytes;
}
#endif
#else
static inline bool
secure_random_bytes(void *buf, size_t nbytes) {
arc4random_buf(buf, nbytes);