Software /
code /
prosody
Comparison
util-src/crand.c @ 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 |
parent | 8443:980885ba062c |
child | 8445:2d3a3d12ec87 |
comparison
equal
deleted
inserted
replaced
8443:980885ba062c | 8444:adb079840714 |
---|---|
57 #elif ! defined(WITH_ARC4RANDOM) | 57 #elif ! defined(WITH_ARC4RANDOM) |
58 #error util.crand compiled without a random source | 58 #error util.crand compiled without a random source |
59 #endif | 59 #endif |
60 | 60 |
61 int Lrandom(lua_State *L) { | 61 int Lrandom(lua_State *L) { |
62 int ret = 0; | 62 const size_t len = (size_t)luaL_checkinteger(L, 1); |
63 size_t len = (size_t)luaL_checkinteger(L, 1); | |
64 void *buf = lua_newuserdata(L, len); | 63 void *buf = lua_newuserdata(L, len); |
65 | 64 |
66 #if defined(WITH_GETRANDOM) | 65 #if defined(WITH_GETRANDOM) |
67 /* | 66 /* |
68 * This acts like a read from /dev/urandom with the exception that it | 67 * This acts like a read from /dev/urandom with the exception that it |
69 * *does* block if the entropy pool is not yet initialized. | 68 * *does* block if the entropy pool is not yet initialized. |
70 */ | 69 */ |
71 int left = len; | 70 int left = len; |
72 char *b = buf; | 71 char *p = buf; |
73 | 72 |
74 do { | 73 do { |
75 ret = getrandom(b, left, 0); | 74 int ret = getrandom(p, left, 0); |
76 | 75 |
77 if(ret < 0) { | 76 if(ret < 0) { |
78 lua_pushstring(L, strerror(errno)); | 77 lua_pushstring(L, strerror(errno)); |
79 return lua_error(L); | 78 return lua_error(L); |
80 } | 79 } |
81 | 80 |
82 b += ret; | 81 p += ret; |
83 left -= ret; | 82 left -= ret; |
84 } while(left > 0); | 83 } while(left > 0); |
85 | 84 |
86 ret = len; | |
87 | |
88 #elif defined(WITH_ARC4RANDOM) | 85 #elif defined(WITH_ARC4RANDOM) |
89 arc4random_buf(buf, len); | 86 arc4random_buf(buf, len); |
90 ret = len; | |
91 #elif defined(WITH_OPENSSL) | 87 #elif defined(WITH_OPENSSL) |
92 | 88 |
93 if(!RAND_status()) { | 89 if(!RAND_status()) { |
94 lua_pushliteral(L, "OpenSSL PRNG not seeded"); | 90 lua_pushliteral(L, "OpenSSL PRNG not seeded"); |
95 return lua_error(L); | 91 return lua_error(L); |
96 } | 92 } |
97 | 93 |
98 ret = RAND_bytes(buf, len); | 94 if(RAND_bytes(buf, len) != 1) { |
99 | |
100 if(ret == 1) { | |
101 ret = len; | |
102 } else { | |
103 /* TODO ERR_get_error() */ | 95 /* TODO ERR_get_error() */ |
104 lua_pushstring(L, "RAND_bytes() failed"); | 96 lua_pushstring(L, "RAND_bytes() failed"); |
105 return lua_error(L); | 97 return lua_error(L); |
106 } | 98 } |
107 | 99 |
108 #endif | 100 #endif |
109 | 101 |
110 lua_pushlstring(L, buf, ret); | 102 lua_pushlstring(L, buf, len); |
111 return 1; | 103 return 1; |
112 } | 104 } |
113 | 105 |
114 int luaopen_util_crand(lua_State *L) { | 106 int luaopen_util_crand(lua_State *L) { |
115 #if (LUA_VERSION_NUM > 501) | 107 #if (LUA_VERSION_NUM > 501) |