xio: add nacl's randombyte function
authorDaniel Borkmann <dborkman@redhat.com>
Mon, 28 Jan 2013 16:55:43 +0000 (28 17:55 +0100)
committerDaniel Borkmann <dborkman@redhat.com>
Mon, 28 Jan 2013 16:55:43 +0000 (28 17:55 +0100)
Signed-off-by: Daniel Borkmann <dborkman@redhat.com>
xio.c
xio.h

diff --git a/xio.c b/xio.c
index df92213..bb5fe38 100644 (file)
--- a/xio.c
+++ b/xio.c
@@ -156,3 +156,44 @@ ssize_t write_exact(int fd, void *buf, size_t len, int mayexit)
 
        return num;
 }
+
+static int fd_rnd = -1;
+
+static void randombytes(unsigned char *x, unsigned long long xlen)
+{
+       int ret;
+
+       if (fd_rnd < 0) {
+               for (;;) {
+                       fd_rnd = open("/dev/urandom", O_RDONLY);
+                       if (fd_rnd < 0)
+                               break;
+                       sleep(1);
+               }
+       }
+
+       while (xlen > 0) {
+               if (xlen < 1048576)
+                       ret = xlen;
+               else
+                       ret = 1048576;
+
+               ret = read(fd_rnd, x, ret);
+               if (ret < 1) {
+                       sleep(1);
+                       continue;
+               }
+
+               x += ret;
+               xlen -= ret;
+       }
+}
+
+int secrand(void)
+{
+       int ret;
+
+       randombytes((void *) &ret, sizeof(ret));
+
+       return ret;
+}
diff --git a/xio.h b/xio.h
index cdda6b8..a144da2 100644 (file)
--- a/xio.h
+++ b/xio.h
@@ -17,10 +17,6 @@ extern ssize_t read_or_die(int fd, void *buf, size_t count);
 extern ssize_t write_or_die(int fd, const void *buf, size_t count);
 extern ssize_t read_exact(int fd, void *buf, size_t len, int mayexit);
 extern ssize_t write_exact(int fd, void *buf, size_t len, int mayexit);
-
-static inline int secrand(void)
-{
-       return rand();
-}
+extern int secrand(void);
 
 #endif /* XIO_H */