1 // Copyright 2018 Developers of the Rand project.
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
9 //! Implementations that just need to read from a file
10 use crate::util
::LazyUsize
;
11 use crate::util_libc
::{open_readonly, sys_fill_exact}
;
13 use core
::cell
::UnsafeCell
;
14 use core
::sync
::atomic
::{AtomicUsize, Ordering::Relaxed}
;
16 #[cfg(target_os = "redox")]
17 const FILE_PATH
: &str = "rand:\0";
19 target_os
= "dragonfly",
20 target_os
= "emscripten",
23 target_os
= "solaris",
26 const FILE_PATH
: &str = "/dev/random\0";
27 #[cfg(any(target_os = "android", target_os = "linux"))]
28 const FILE_PATH
: &str = "/dev/urandom\0";
30 pub fn getrandom_inner(dest
: &mut [u8]) -> Result
<(), Error
> {
31 let fd
= get_rng_fd()?
;
32 let read
= |buf
: &mut [u8]| unsafe { libc::read(fd, buf.as_mut_ptr() as *mut _, buf.len()) }
;
34 if cfg
!(target_os
= "emscripten") {
35 // `Crypto.getRandomValues` documents `dest` should be at most 65536 bytes.
36 for chunk
in dest
.chunks_mut(65536) {
37 sys_fill_exact(chunk
, read
)?
;
40 sys_fill_exact(dest
, read
)?
;
45 // Returns the file descriptor for the device file used to retrieve random
46 // bytes. The file will be opened exactly once. All successful calls will
47 // return the same file descriptor. This file descriptor is never closed.
48 fn get_rng_fd() -> Result
<libc
::c_int
, Error
> {
49 static FD
: AtomicUsize
= AtomicUsize
::new(LazyUsize
::UNINIT
);
50 fn get_fd() -> Option
<libc
::c_int
> {
51 match FD
.load(Relaxed
) {
52 LazyUsize
::UNINIT
=> None
,
53 val
=> Some(val
as libc
::c_int
),
57 // Use double-checked locking to avoid acquiring the lock if possible.
58 if let Some(fd
) = get_fd() {
62 // SAFETY: We use the mutex only in this method, and we always unlock it
63 // before returning, making sure we don't violate the pthread_mutex_t API.
64 static MUTEX
: Mutex
= Mutex
::new();
65 unsafe { MUTEX.lock() }
;
66 let _guard
= DropGuard(|| unsafe { MUTEX.unlock() }
);
68 if let Some(fd
) = get_fd() {
72 // On Linux, /dev/urandom might return insecure values.
73 #[cfg(any(target_os = "android", target_os = "linux"))]
74 wait_until_rng_ready()?
;
76 let fd
= unsafe { open_readonly(FILE_PATH)? }
;
77 // The fd always fits in a usize without conflicting with UNINIT.
78 debug_assert
!(fd
>= 0 && (fd
as usize) < LazyUsize
::UNINIT
);
79 FD
.store(fd
as usize, Relaxed
);
84 // Succeeds once /dev/urandom is safe to read from
85 #[cfg(any(target_os = "android", target_os = "linux"))]
86 fn wait_until_rng_ready() -> Result
<(), Error
> {
87 // Poll /dev/random to make sure it is ok to read from /dev/urandom.
88 let fd
= unsafe { open_readonly("/dev/random\0")? }
;
89 let mut pfd
= libc
::pollfd
{
94 let _guard
= DropGuard(|| unsafe {
99 // A negative timeout means an infinite timeout.
100 let res
= unsafe { libc::poll(&mut pfd, 1, -1) }
;
102 assert_eq
!(res
, 1); // We only used one fd, and cannot timeout.
105 let err
= crate::util_libc
::last_os_error();
106 match err
.raw_os_error() {
107 Some(libc
::EINTR
) | Some(libc
::EAGAIN
) => continue,
108 _
=> return Err(err
),
113 struct Mutex(UnsafeCell
<libc
::pthread_mutex_t
>);
116 const fn new() -> Self {
117 Self(UnsafeCell
::new(libc
::PTHREAD_MUTEX_INITIALIZER
))
119 unsafe fn lock(&self) {
120 let r
= libc
::pthread_mutex_lock(self.0.get());
121 debug_assert_eq
!(r
, 0);
123 unsafe fn unlock(&self) {
124 let r
= libc
::pthread_mutex_unlock(self.0.get());
125 debug_assert_eq
!(r
, 0);
129 unsafe impl Sync
for Mutex {}
131 struct DropGuard
<F
: FnMut()>(F
);
133 impl<F
: FnMut()> Drop
for DropGuard
<F
> {