From 0ffa041f367f5aca58a0cbb0f3f82cd88a436c14 Mon Sep 17 00:00:00 2001 From: Con Kolivas Date: Tue, 15 Mar 2011 12:56:23 +1100 Subject: [PATCH] Add function to get a stream of random numbers into a buffer from /dev/urandom if possible, and falling back to random() if not. --- util.c | 20 ++++++++++++++++++++ util.h | 1 + 2 files changed, 21 insertions(+) diff --git a/util.c b/util.c index 50da3e1..6f207c4 100644 --- a/util.c +++ b/util.c @@ -45,7 +45,11 @@ # define PAGE_SIZE (4096) #endif +#include +#include +#include #include "lrzip_private.h" +#include "liblrzip.h" static const char *infile = NULL; static char delete_infile = 0; @@ -122,3 +126,19 @@ void round_to_page(i64 *size) if (unlikely(!*size)) *size = PAGE_SIZE; } + +void get_rand(uchar *buf, int len) +{ + int fd, i; + + fd = open("/dev/urandom", O_RDONLY); + if (fd == -1) { + for (i = 0; i < len; i++) + buf[i] = (uchar)random(); + } else { + if (unlikely(read(fd, buf, len) != len)) + fatal("Failed to read fd in get_rand\n"); + if (unlikely(close(fd))) + fatal("Failed to close fd in get_rand\n"); + } +} diff --git a/util.h b/util.h index 612517b..222d81d 100644 --- a/util.h +++ b/util.h @@ -28,5 +28,6 @@ void register_outputfile(FILE *f); void fatal(const char *format, ...); void failure(const char *format, ...); void round_to_page(i64 *size); +void get_rand(uchar *buf, int len); #endif