From c22fa0c92e942bb1f7681cc6a28398ed1e6ddd49 Mon Sep 17 00:00:00 2001 From: Mark Wooding Date: Thu, 26 May 2016 09:26:09 +0100 Subject: [PATCH] rand/noise.c (noise_devrandom): Refactor internals. The objective is to make adding new ways of collecting high-quality system entropy easier. * Add labels for success and exit, to make sure that whatever we add whatever's in the buffer to the pool, and then clear out the buffer. * Initialize `fd' to `-1' at the top, and close it on the way out to make sure it doesn't leak. * Change the main `open' condition to allow something to have opened the right file already. This shouldn't change any observable behaviour, but it will make things easier in future. --- rand/noise.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/rand/noise.c b/rand/noise.c index ee2adcce..5421bc10 100644 --- a/rand/noise.c +++ b/rand/noise.c @@ -157,7 +157,7 @@ int noise_timer(rand_pool *r) int noise_devrandom(rand_pool *r) { - int fd; + int fd = -1; octet buf[RAND_POOLSZ]; ssize_t len; size_t n = 0; @@ -171,18 +171,24 @@ int noise_devrandom(rand_pool *r) * needs to get some more entropy from somewhere. */ - if ((fd = open("/dev/urandom", O_RDONLY | O_NONBLOCK)) >= 0 || + if (fd >= 0 || + (fd = open("/dev/urandom", O_RDONLY | O_NONBLOCK)) >= 0 || (fd = open("/dev/arandom", O_RDONLY | O_NONBLOCK)) >= 0 || (fd = open("/dev/random", O_RDONLY | O_NONBLOCK)) >= 0) { while (n < sizeof(buf)) { if ((len = read(fd, buf + n, sizeof(buf) - n)) <= 0) break; n += len; } - rand_add(r, buf, n, n * 8); - BURN(buf); - if (n == sizeof(buf)) ret = 1; - close(fd); + if (n == sizeof(buf)) goto win; } + goto done; + +win: + ret = 1; +done: + if (fd >= 0) close(fd); + rand_add(r, buf, n, 8*n); + BURN(buf); noise_timer(r); return (ret); } -- 2.11.0