# HG changeset patch # User Kim Alvefur # Date 1484909566 -3600 # Node ID 56552733742e2f315f25420116d929f874be56d4 # Parent 9b66ada1487cd3c32daa443e0f80d78b48a6baa0 util.crand: Let Lua handle allocation, freeing and error handling for buffer diff -r 9b66ada1487c -r 56552733742e util-src/crand.c --- a/util-src/crand.c Fri Jan 20 11:41:07 2017 +0100 +++ b/util-src/crand.c Fri Jan 20 11:52:46 2017 +0100 @@ -19,15 +19,6 @@ #include #include -/* - * TODO: Decide on fixed size or dynamically allocated buffer - */ -#if 1 -#include -#else -#define BUFLEN 256 -#endif - #if defined(WITH_GETRANDOM) #include #include @@ -38,7 +29,7 @@ #endif /* Was this not supposed to be a function? */ -int getrandom(char *buf, size_t len, int flags) { +int getrandom(void *buf, size_t len, int flags) { return syscall(SYS_getrandom, buf, len, flags); } @@ -51,36 +42,14 @@ #endif int Lrandom(lua_State *L) { -#ifdef BUFLEN - unsigned char buf[BUFLEN]; -#else - unsigned char *buf; -#endif int ret = 0; size_t len = (size_t)luaL_checkinteger(L, 1); -#ifdef BUFLEN - len = len > BUFLEN ? BUFLEN : len; -#else - buf = malloc(len); - - if(buf == NULL) { - lua_pushnil(L); - lua_pushstring(L, "out of memory"); - /* or it migth be better to - * return lua_error(L); - */ - return 2; - } - -#endif + void *buf = lua_newuserdata(L, len); #if defined(WITH_GETRANDOM) ret = getrandom(buf, len, 0); if(ret < 0) { -#ifndef BUFLEN - free(buf); -#endif lua_pushnil(L); lua_pushstring(L, strerror(errno)); lua_pushinteger(L, errno); @@ -96,9 +65,6 @@ if(ret == 1) { ret = len; } else { -#ifndef BUFLEN - free(buf); -#endif lua_pushnil(L); lua_pushstring(L, "failed"); /* lua_pushinteger(L, ERR_get_error()); */ @@ -107,10 +73,7 @@ #endif - lua_pushlstring(L, (const char *)buf, ret); -#ifndef BUFLEN - free(buf); -#endif + lua_pushlstring(L, buf, ret); return 1; }