rand/noise.c (noise_devrandom): Refactor internals.
authorMark Wooding <mdw@distorted.org.uk>
Thu, 26 May 2016 08:26:09 +0000 (09:26 +0100)
committerMark Wooding <mdw@distorted.org.uk>
Sat, 4 Jun 2016 13:55:30 +0000 (14:55 +0100)
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

index ee2adcc..5421bc1 100644 (file)
@@ -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);
 }