Opened 8 years ago

Closed 7 years ago

#10980 closed Bugs (fixed)

boost::random::random_device bug with /dev/random

Reported by: Bastiaan Stougie <bastiaan.stougie@…> Owned by: No-Maintainer
Milestone: To Be Determined Component: random
Version: Boost 1.56.0 Severity: Problem
Keywords: random_device Cc:

Description

There is a bug in boost 1.56 random_device implementation where it can fail to read from /dev/random with an exception

"boost::random_device: EOF while reading random-number pseudo-device /dev/random: Success"

The boost random_device code attempts to read 4 bytes from /dev/random, gets fewer but >0 bytes because /dev/random temporarily runs out of random data, and boost random_device incorrectly concludes that end of file has been reached and throws an exception, where it should just try to read more bytes.

Change History (2)

comment:1 by Bastiaan Stougie <bastiaan.stougie@…>, 8 years ago

Here's a patch:

diff --git a/libs/random/src/random_device.cpp b/libs/random/src/random_device.cpp
--- a/libs/random/src/random_device.cpp
+++ b/libs/random/src/random_device.cpp
@@ -168,13 +168,17 @@

   unsigned int next() {
         unsigned int result;
    -    long sz = read(fd, reinterpret_cast<char *>(&result), sizeof(result));
    -    if(sz == -1)
    -      error("error while reading");
    -    else if(sz != sizeof(result)) {
    -      errno = 0;
    -      error("EOF while reading");
    -    }
    +    size_t offset = 0;
    +    do {
    +      long sz = read(fd, reinterpret_cast<char *>(&result) + offset, sizeof(result) - offset);
    +      if(sz == -1)
    +        error("error while reading");
    +      else if(sz == 0) {
    +        errno = 0;
    +        error("EOF while reading");
    +      }
    +      offset += sz;
    +    } while (offset < sizeof(result));
         return result;
       }

comment:2 by Steven Watanabe, 7 years ago

Resolution: fixed
Status: newclosed
Note: See TracTickets for help on using tickets.