Skip to content

Commit

Permalink
refactor(random): on linux+bsd use api instead of /dev/urandom
Browse files Browse the repository at this point in the history
the api is faster and equally good
  • Loading branch information
Tieske committed Feb 6, 2025
1 parent dc0e2c5 commit fc855a0
Showing 1 changed file with 30 additions and 6 deletions.
36 changes: 30 additions & 6 deletions src/random.c
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,17 @@
#include <fcntl.h>

#ifdef _WIN32
#include "windows.h"
#include "wincrypt.h"
#include "windows.h"
#include "wincrypt.h"
#else
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#if defined(__linux__)
#include <sys/random.h> // getrandom()
#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
#include <stdlib.h> // arc4random_buf()
#endif
#endif


Expand Down Expand Up @@ -53,15 +58,34 @@ static int lua_get_random_bytes(lua_State* L) {
ssize_t total_read = 0;

#ifdef _WIN32
// Use BCryptGenRandom() on Windows
if (!BCRYPT_SUCCESS(BCryptGenRandom(NULL, buffer, num_bytes, BCRYPT_USE_SYSTEM_PREFERRED_RNG))) {
DWORD error = GetLastError();
lua_pushnil(L);
lua_pushfstring(L, "failed to get random data: %lu", error);
return 2;
}

#elif defined(__linux__)
// Use getrandom() on Linux (Kernel 3.17+, 2014)
ssize_t total_read = 0;
while (total_read < num_bytes) {
ssize_t n = getrandom(buffer + total_read, num_bytes - total_read, 0);
if (n < 0) {
if (errno == EINTR) continue; // Retry on interrupt
lua_pushnil(L);
lua_pushfstring(L, "getrandom() failed: %s", strerror(errno));
return 2;
}
total_read += n;
}

#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
// Use arc4random_buf() on BSD/macOS
arc4random_buf(buffer, num_bytes);

#else
// for macOS/unixes use /dev/urandom for non-blocking
// fall back to /dev/urandom for anything else
int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
if (fd < 0) {
lua_pushnil(L);
Expand Down

0 comments on commit fc855a0

Please sign in to comment.