summaryrefslogtreecommitdiff
path: root/src/librandom/random_uint32.c
diff options
context:
space:
mode:
authorLaurent Bercot <ska-skaware@skarnet.org>2016-10-14 17:07:56 +0000
committerLaurent Bercot <ska-skaware@skarnet.org>2016-10-14 17:07:56 +0000
commita1933bd1847951b959016f59ee744d1b18a00142 (patch)
tree42392f2df048defd712fa12d290bf84a7a77df6d /src/librandom/random_uint32.c
parenteaf9404b22bba7be5092672144b867380c602beb (diff)
downloadskalibs-a1933bd1847951b959016f59ee744d1b18a00142.tar.xz
Clean up and modernize librandom.
Correct random number generation has historically been suprisingly painful to achieve. There was no standard, every system behaved in a subtly different way, and there were a few userland initiatives to get decent randomness, all incompatible of course. The situation is a bit better now, we're heading towards some standardization. The arc4random() series of functions is a good API, and available on a lot of systems - unfortunately not Linux, but on Linux the new getrandom() makes using /dev/random obsolete. So I removed the old crap in librandom, dropped EGD support, dropped dynamic backend selection, made a single API series (random_* instead of goodrandom_* and badrandom_*), added an arc4random backend and a getrandom backend, and defaulted to /dev/urandom backed up by SURF in the worst case. This should be much smaller and logical. However, it's a major API break, so the skarnet.org stack will be changed to adapt.
Diffstat (limited to 'src/librandom/random_uint32.c')
-rw-r--r--src/librandom/random_uint32.c56
1 files changed, 56 insertions, 0 deletions
diff --git a/src/librandom/random_uint32.c b/src/librandom/random_uint32.c
new file mode 100644
index 0000000..d011885
--- /dev/null
+++ b/src/librandom/random_uint32.c
@@ -0,0 +1,56 @@
+/* ISC license. */
+
+#include <skalibs/sysdeps.h>
+
+#ifdef SKALIBS_HASARC4RANDOM
+
+#include <stdlib.h>
+#include <skalibs/random.h>
+
+uint32 random_uint32 (uint32 n)
+{
+ return arc4random_uniform(n) ;
+}
+
+#else
+
+#include <skalibs/uint32.h>
+#include <skalibs/random.h>
+
+static inline uint32 random_mask2 (register uint32 n)
+{
+ for (;;)
+ {
+ register uint32 m = n | (n >> 1) ;
+ if (m == n) return n ;
+ n = m ;
+ }
+}
+
+static inline unsigned int random_nchars (register uint32 n)
+{
+ return n <= 0xff ? 1 :
+ n <= 0xffff ? 2 :
+ n <= 0xffffffUL ? 3 : 4 ;
+}
+
+uint32 random_uint32 (uint32 n)
+{
+ if (!n) return 0 ;
+ else
+ {
+ uint32 i = n, m = random_mask2(n-1) ;
+ unsigned int nchars = random_nchars(n) ;
+ char tmp[4] ;
+ while (i >= n)
+ {
+ random_string(tmp, nchars) ;
+ byte_zero(tmp + nchars, 4 - nchars) ;
+ uint32_unpack(tmp, &i) ;
+ i &= m ;
+ }
+ return i ;
+ }
+}
+
+#endif