| 6 |
| 7 | #include <errno.h> |
| 8 | #include <fcntl.h> |
| 9 | #include <stddef.h> |
| 10 | #include <stdint.h> |
| 11 | #include <unistd.h> |
| 12 |
| 13 | #include "base/files/file_util.h" |
| 14 | #include "base/logging.h" |
| 15 | #include "base/no_destructor.h" |
| 16 | #include "base/posix/eintr_wrapper.h" |
| 17 |
| 18 | namespace { |
| 19 |
| 20 | // We keep the file descriptor for /dev/urandom around so we don't need to |
| 21 | // reopen it (which is expensive), and since we may not even be able to reopen |
| 22 | // it if we are later put in a sandbox. This class wraps the file descriptor so |
| 23 | // we can use a static-local variable to handle opening it on the first access. |
| 24 | class URandomFd { |
| 25 | public: |
| 26 | #if defined(OS_AIX) |
| 27 | // AIX has no 64-bit support for open falgs such as - |
| 28 | // O_CLOEXEC, O_NOFOLLOW and O_TTY_INIT |
| 29 | URandomFd() : fd_(HANDLE_EINTR(open("/dev/urandom", O_RDONLY))) { |
| 30 | DPCHECK(fd_ >= 0) << "Cannot open /dev/urandom"; |
| 31 | } |
| 32 | #else |
| 33 | URandomFd() : fd_(HANDLE_EINTR(open("/dev/urandom", O_RDONLY | O_CLOEXEC))) { |
| 34 | DPCHECK(fd_ >= 0) << "Cannot open /dev/urandom"; |
| 35 | } |
| 36 | #endif |
| 37 |
| 38 | ~URandomFd() { close(fd_); } |
| 39 |
| 40 | int fd() const { return fd_; } |
| 41 |
| 42 | private: |
| 43 | const int fd_; |
| 44 | }; |
| 45 |
| 46 | } // namespace |
| 47 |
| 48 | namespace base { |
| 49 |
| 50 | void RandBytes(void* output, size_t output_length) { |
| 51 | const int urandom_fd = GetUrandomFD(); |
| 52 | const bool success = |
| 53 | ReadFromFD(urandom_fd, static_cast<char*>(output), output_length); |
| 54 | CHECK(success); |
| 55 | } |
| 56 |
| 57 | int GetUrandomFD() { |
| 58 | static NoDestructor<URandomFd> urandom_fd; |
| 59 | return urandom_fd->fd(); |
| 60 | } |
| 61 |
| 62 | } // namespace base |
| 63 |