2 -- Copyright (C) 2008-2016 Matthew Wild
3 -- Copyright (C) 2008-2016 Waqas Hussain
4 -- Copyright (C) 2016 Kim Alvefur
6 -- This project is MIT/X11 licensed. Please see the
7 -- COPYING file in the source package for more information.
23 * TODO: Decide on fixed size or dynamically allocated buffer
31 #if defined(WITH_GETRANDOM)
33 #include <sys/syscall.h>
34 #include <linux/random.h>
37 #error getrandom() requires Linux 3.17 or later
40 /* Was this not supposed to be a function? */
41 int getrandom(char *buf, size_t len, int flags) {
42 return syscall(SYS_getrandom, buf, len, flags);
45 #elif defined(WITH_ARC4RANDOM)
47 #elif defined(WITH_OPENSSL)
48 #include <openssl/rand.h>
50 #error util.crand compiled without a random source
53 int Lrandom(lua_State *L) {
55 unsigned char buf[BUFLEN];
60 size_t len = (size_t)luaL_checkint(L, 1);
62 len = len > BUFLEN ? BUFLEN : len;
68 lua_pushstring(L, "out of memory");
69 /* or it migth be better to
70 * return lua_error(L);
76 #if defined(WITH_GETRANDOM)
77 ret = getrandom(buf, len, 0);
84 lua_pushstring(L, strerror(errno));
85 lua_pushinteger(L, errno);
89 #elif defined(WITH_ARC4RANDOM)
90 arc4random_buf(buf, len);
92 #elif defined(WITH_OPENSSL)
93 ret = RAND_bytes(buf, len);
102 lua_pushstring(L, "failed");
103 /* lua_pushinteger(L, ERR_get_error()); */
109 lua_pushlstring(L, buf, ret);
116 #ifdef ENABLE_SEEDING
117 int Lseed(lua_State *L) {
119 const char *seed = lua_tolstring(L, 1, &len);
121 #if defined(WITH_OPENSSL)
122 RAND_add(seed, len, len);
126 lua_pushliteral(L, "not-supported");
132 int luaopen_util_crand(lua_State *L) {
134 lua_pushcfunction(L, Lrandom);
135 lua_setfield(L, -2, "bytes");
136 #ifdef ENABLE_SEEDING
137 lua_pushcfunction(L, Lseed);
138 lua_setfield(L, -2, "seed");
141 #if defined(WITH_GETRANDOM)
142 lua_pushstring(L, "Linux");
143 #elif defined(WITH_ARC4RANDOM)
144 lua_pushstring(L, "arc4random()");
145 #elif defined(WITH_OPENSSL)
146 lua_pushstring(L, "OpenSSL");
148 lua_setfield(L, -2, "_source");
150 #if defined(WITH_OPENSSL) && defined(_WIN32)
151 /* Do we need to seed this on Windows? */