Permalink
Browse files

using non blocking call if possible to generate randomness

  • Loading branch information...
devnexen committed Feb 18, 2017
1 parent b6e41f7 commit b8338e2369383db1607540e49e2b59c5d447fc0c
Showing with 15 additions and 1 deletion.
  1. +15 −1 src/common/System.cpp
View
@@ -35,6 +35,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#ifdef __linux__
#include <linux/version.h>
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,17,0)
#include <sys/syscall.h>
#include <linux/random.h>
#define HAS_GETRANDOM_SYSCALL 1
#endif
#endif
#ifdef __native_client__
#include <nacl/nacl_exception.h>
#include <nacl/nacl_minidump.h>
@@ -345,13 +353,19 @@ void GenRandomBytes(void* dest, size_t size)
size_t bytes_written;
if (nacl_secure_random(dest, size, &bytes_written) != 0 || bytes_written != size)
Sys::Error("nacl_secure_random failed");
#else
#elif defined(__linux__) && defined(HAS_GETRANDOM_SYSCALL)
if (syscall(SYS_getrandom, dest, size, GRND_NONBLOCK) == -1)
Sys::Error("Failed getrandom syscall: %s", strerror(errno));
#elif defined(__linux__)
int fd = open("/dev/urandom", O_RDONLY);
if (fd == -1)
Sys::Error("Failed to open /dev/urandom: %s", strerror(errno));
if (read(fd, dest, size) != (ssize_t) size)
Sys::Error("Failed to read from /dev/urandom: %s", strerror(errno));
close(fd);
#else
arc4random_buf(dest, size);
#endif
}

0 comments on commit b8338e2

Please sign in to comment.