Merge 0.10->trunk
[prosody.git] / util / random.lua
index 5938a94f820ac4e3379c1f56594d3abe07810a15..574e2e1cdf384cf7d893530fdcd97c80843aaba7 100644 (file)
@@ -6,35 +6,22 @@
 -- COPYING file in the source package for more information.
 --
 
-local tostring = tostring;
-local os_time = os.time;
-local os_clock = os.clock;
-local ceil = math.ceil;
-local H = require "util.hashes".sha512;
+local ok, crand = pcall(require, "util.crand");
+if ok then return crand; end
 
-local last_uniq_time = 0;
-local function uniq_time()
-       local new_uniq_time = os_time();
-       if last_uniq_time >= new_uniq_time then new_uniq_time = last_uniq_time + 1; end
-       last_uniq_time = new_uniq_time;
-       return new_uniq_time;
-end
+local urandom, urandom_err = io.open("/dev/urandom", "r");
 
-local function new_random(x)
-       return H(x..os_clock()..tostring({}));
+local function seed()
 end
 
-local buffer = new_random(uniq_time());
-
-local function seed(x)
-       buffer = new_random(buffer..x);
+local function bytes(n)
+       return urandom:read(n);
 end
 
-local function bytes(n)
-       if #buffer < n+4 then seed(uniq_time()); end
-       local r = buffer:sub(1, n);
-       buffer = buffer:sub(n+1);
-       return r;
+if not urandom then
+       function bytes()
+               error("Unable to obtain a secure random number generator, please see https://prosody.im/doc/random ("..urandom_err..")");
+       end
 end
 
 return {