Changeset

8444:adb079840714

util.crand: Only keep return value of getrandom() as the others don't return partial results
author Kim Alvefur <zash@zash.se>
date Sat, 02 Dec 2017 11:11:32 +0100
parents 8443:980885ba062c
children 8445:2d3a3d12ec87
files util-src/crand.c
diffstat 1 files changed, 6 insertions(+), 14 deletions(-) [+]
line wrap: on
line diff
--- a/util-src/crand.c	Sat Dec 02 10:58:37 2017 +0100
+++ b/util-src/crand.c	Sat Dec 02 11:11:32 2017 +0100
@@ -59,8 +59,7 @@
 #endif
 
 int Lrandom(lua_State *L) {
-	int ret = 0;
-	size_t len = (size_t)luaL_checkinteger(L, 1);
+	const size_t len = (size_t)luaL_checkinteger(L, 1);
 	void *buf = lua_newuserdata(L, len);
 
 #if defined(WITH_GETRANDOM)
@@ -69,25 +68,22 @@
 	 * *does* block if the entropy pool is not yet initialized.
 	 */
 	int left = len;
-	char *b = buf;
+	char *p = buf;
 
 	do {
-		ret = getrandom(b, left, 0);
+		int ret = getrandom(p, left, 0);
 
 		if(ret < 0) {
 			lua_pushstring(L, strerror(errno));
 			return lua_error(L);
 		}
 
-		b += ret;
+		p += ret;
 		left -= ret;
 	} while(left > 0);
 
-	ret = len;
-
 #elif defined(WITH_ARC4RANDOM)
 	arc4random_buf(buf, len);
-	ret = len;
 #elif defined(WITH_OPENSSL)
 
 	if(!RAND_status()) {
@@ -95,11 +91,7 @@
 		return lua_error(L);
 	}
 
-	ret = RAND_bytes(buf, len);
-
-	if(ret == 1) {
-		ret = len;
-	} else {
+	if(RAND_bytes(buf, len) != 1) {
 		/* TODO ERR_get_error() */
 		lua_pushstring(L, "RAND_bytes() failed");
 		return lua_error(L);
@@ -107,7 +99,7 @@
 
 #endif
 
-	lua_pushlstring(L, buf, ret);
+	lua_pushlstring(L, buf, len);
 	return 1;
 }