Add function to get a stream of random numbers into a buffer from /dev/urandom if possible, and falling back to random() if not.

This commit is contained in:
Con Kolivas 2011-03-15 12:56:23 +11:00
parent e26d0d1381
commit 0ffa041f36
2 changed files with 21 additions and 0 deletions

20
util.c
View file

@ -45,7 +45,11 @@
# define PAGE_SIZE (4096) # define PAGE_SIZE (4096)
#endif #endif
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "lrzip_private.h" #include "lrzip_private.h"
#include "liblrzip.h"
static const char *infile = NULL; static const char *infile = NULL;
static char delete_infile = 0; static char delete_infile = 0;
@ -122,3 +126,19 @@ void round_to_page(i64 *size)
if (unlikely(!*size)) if (unlikely(!*size))
*size = PAGE_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");
}
}

1
util.h
View file

@ -28,5 +28,6 @@ void register_outputfile(FILE *f);
void fatal(const char *format, ...); void fatal(const char *format, ...);
void failure(const char *format, ...); void failure(const char *format, ...);
void round_to_page(i64 *size); void round_to_page(i64 *size);
void get_rand(uchar *buf, int len);
#endif #endif