Fills buffer with cryptographically random data obtained from /dev/(u)random
| 113 | |
| 114 | //! Fills buffer with cryptographically random data obtained from /dev/(u)random |
| 115 | int fill_random_dev_random(void* buf, std::size_t len) |
| 116 | { |
| 117 | boost::scope::unique_fd file; |
| 118 | while (true) |
| 119 | { |
| 120 | file.reset(::open("/dev/urandom", O_RDONLY | O_CLOEXEC)); |
| 121 | if (!file) |
| 122 | { |
| 123 | if (errno == EINTR) |
| 124 | continue; |
| 125 | } |
| 126 | |
| 127 | break; |
| 128 | } |
| 129 | |
| 130 | if (!file) |
| 131 | { |
| 132 | while (true) |
| 133 | { |
| 134 | file.reset(::open("/dev/random", O_RDONLY | O_CLOEXEC)); |
| 135 | if (!file) |
| 136 | { |
| 137 | const int err = errno; |
| 138 | if (err == EINTR) |
| 139 | continue; |
| 140 | return err; |
| 141 | } |
| 142 | |
| 143 | break; |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | std::size_t bytes_read = 0u; |
| 148 | while (bytes_read < len) |
| 149 | { |
| 150 | ssize_t n = ::read(file.get(), buf, len - bytes_read); |
| 151 | if (BOOST_UNLIKELY(n < 0)) |
| 152 | { |
| 153 | const int err = errno; |
| 154 | if (err == EINTR) |
| 155 | continue; |
| 156 | return err; |
| 157 | } |
| 158 | |
| 159 | bytes_read += n; |
| 160 | buf = static_cast< char* >(buf) + n; |
| 161 | } |
| 162 | |
| 163 | return 0; |
| 164 | } |
| 165 | |
| 166 | #if defined(BOOST_FILESYSTEM_HAS_GETRANDOM) || defined(BOOST_FILESYSTEM_HAS_GETRANDOM_SYSCALL) |
| 167 |
no test coverage detected