| OLD | NEW |
| 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
| 4 | 4 |
| 5 #include "base/rand_util.h" | 5 #include "base/rand_util.h" |
| 6 | 6 |
| 7 #include <errno.h> | 7 #include <errno.h> |
| 8 #include <fcntl.h> | 8 #include <fcntl.h> |
| 9 #include <stddef.h> | 9 #include <stddef.h> |
| 10 #include <stdint.h> | 10 #include <stdint.h> |
| 11 #include <unistd.h> | 11 #include <unistd.h> |
| 12 | 12 |
| 13 #include "base/files/file_util.h" | 13 #include "base/files/file_util.h" |
| 14 #include "base/lazy_instance.h" | 14 #include "base/lazy_instance.h" |
| 15 #include "base/logging.h" | 15 #include "base/logging.h" |
| 16 #include "base/posix/eintr_wrapper.h" |
| 16 | 17 |
| 17 namespace { | 18 namespace { |
| 18 | 19 |
| 19 // We keep the file descriptor for /dev/urandom around so we don't need to | 20 // We keep the file descriptor for /dev/urandom around so we don't need to |
| 20 // reopen it (which is expensive), and since we may not even be able to reopen | 21 // reopen it (which is expensive), and since we may not even be able to reopen |
| 21 // it if we are later put in a sandbox. This class wraps the file descriptor so | 22 // it if we are later put in a sandbox. This class wraps the file descriptor so |
| 22 // we can use LazyInstance to handle opening it on the first access. | 23 // we can use LazyInstance to handle opening it on the first access. |
| 23 class URandomFd { | 24 class URandomFd { |
| 24 public: | 25 public: |
| 25 URandomFd() : fd_(open("/dev/urandom", O_RDONLY)) { | 26 URandomFd() : fd_(HANDLE_EINTR(open("/dev/urandom", O_RDONLY | O_CLOEXEC))) { |
| 26 DCHECK_GE(fd_, 0) << "Cannot open /dev/urandom: " << errno; | 27 DCHECK_GE(fd_, 0) << "Cannot open /dev/urandom: " << errno; |
| 27 } | 28 } |
| 28 | 29 |
| 29 ~URandomFd() { close(fd_); } | 30 ~URandomFd() { close(fd_); } |
| 30 | 31 |
| 31 int fd() const { return fd_; } | 32 int fd() const { return fd_; } |
| 32 | 33 |
| 33 private: | 34 private: |
| 34 const int fd_; | 35 const int fd_; |
| 35 }; | 36 }; |
| (...skipping 16 matching lines...) Expand all Loading... |
| 52 const bool success = | 53 const bool success = |
| 53 ReadFromFD(urandom_fd, static_cast<char*>(output), output_length); | 54 ReadFromFD(urandom_fd, static_cast<char*>(output), output_length); |
| 54 CHECK(success); | 55 CHECK(success); |
| 55 } | 56 } |
| 56 | 57 |
| 57 int GetUrandomFD(void) { | 58 int GetUrandomFD(void) { |
| 58 return g_urandom_fd.Pointer()->fd(); | 59 return g_urandom_fd.Pointer()->fd(); |
| 59 } | 60 } |
| 60 | 61 |
| 61 } // namespace base | 62 } // namespace base |
| OLD | NEW |