1 // Copyright 2018 Developers of the Rand project.
2 //
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.
8 
9 //! Implementations that just need to read from a file
10 use crate::{
11     util::LazyUsize,
12     util_libc::{open_readonly, sys_fill_exact},
13     Error,
14 };
15 use core::{
16     cell::UnsafeCell,
17     sync::atomic::{AtomicUsize, Ordering::Relaxed},
18 };
19 
20 #[cfg(target_os = "redox")]
21 const FILE_PATH: &str = "rand:\0";
22 #[cfg(any(
23     target_os = "dragonfly",
24     target_os = "emscripten",
25     target_os = "haiku",
26     target_os = "macos",
27     target_os = "solaris",
28     target_os = "illumos"
29 ))]
30 const FILE_PATH: &str = "/dev/random\0";
31 #[cfg(any(target_os = "android", target_os = "linux"))]
32 const FILE_PATH: &str = "/dev/urandom\0";
33 
getrandom_inner(dest: &mut [u8]) -> Result<(), Error>34 pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
35     let fd = get_rng_fd()?;
36     let read = |buf: &mut [u8]| unsafe { libc::read(fd, buf.as_mut_ptr() as *mut _, buf.len()) };
37 
38     if cfg!(target_os = "emscripten") {
39         // `Crypto.getRandomValues` documents `dest` should be at most 65536 bytes.
40         for chunk in dest.chunks_mut(65536) {
41             sys_fill_exact(chunk, read)?;
42         }
43     } else {
44         sys_fill_exact(dest, read)?;
45     }
46     Ok(())
47 }
48 
49 // Returns the file descriptor for the device file used to retrieve random
50 // bytes. The file will be opened exactly once. All successful calls will
51 // return the same file descriptor. This file descriptor is never closed.
get_rng_fd() -> Result<libc::c_int, Error>52 fn get_rng_fd() -> Result<libc::c_int, Error> {
53     static FD: AtomicUsize = AtomicUsize::new(LazyUsize::UNINIT);
54     fn get_fd() -> Option<libc::c_int> {
55         match FD.load(Relaxed) {
56             LazyUsize::UNINIT => None,
57             val => Some(val as libc::c_int),
58         }
59     }
60 
61     // Use double-checked locking to avoid acquiring the lock if possible.
62     if let Some(fd) = get_fd() {
63         return Ok(fd);
64     }
65 
66     // SAFETY: We use the mutex only in this method, and we always unlock it
67     // before returning, making sure we don't violate the pthread_mutex_t API.
68     static MUTEX: Mutex = Mutex::new();
69     unsafe { MUTEX.lock() };
70     let _guard = DropGuard(|| unsafe { MUTEX.unlock() });
71 
72     if let Some(fd) = get_fd() {
73         return Ok(fd);
74     }
75 
76     // On Linux, /dev/urandom might return insecure values.
77     #[cfg(any(target_os = "android", target_os = "linux"))]
78     wait_until_rng_ready()?;
79 
80     let fd = unsafe { open_readonly(FILE_PATH)? };
81     // The fd always fits in a usize without conflicting with UNINIT.
82     debug_assert!(fd >= 0 && (fd as usize) < LazyUsize::UNINIT);
83     FD.store(fd as usize, Relaxed);
84 
85     Ok(fd)
86 }
87 
88 // Succeeds once /dev/urandom is safe to read from
89 #[cfg(any(target_os = "android", target_os = "linux"))]
wait_until_rng_ready() -> Result<(), Error>90 fn wait_until_rng_ready() -> Result<(), Error> {
91     // Poll /dev/random to make sure it is ok to read from /dev/urandom.
92     let fd = unsafe { open_readonly("/dev/random\0")? };
93     let mut pfd = libc::pollfd {
94         fd,
95         events: libc::POLLIN,
96         revents: 0,
97     };
98     let _guard = DropGuard(|| unsafe {
99         libc::close(fd);
100     });
101 
102     loop {
103         // A negative timeout means an infinite timeout.
104         let res = unsafe { libc::poll(&mut pfd, 1, -1) };
105         if res >= 0 {
106             debug_assert_eq!(res, 1); // We only used one fd, and cannot timeout.
107             return Ok(());
108         }
109         let err = crate::util_libc::last_os_error();
110         match err.raw_os_error() {
111             Some(libc::EINTR) | Some(libc::EAGAIN) => continue,
112             _ => return Err(err),
113         }
114     }
115 }
116 
117 struct Mutex(UnsafeCell<libc::pthread_mutex_t>);
118 
119 impl Mutex {
new() -> Self120     const fn new() -> Self {
121         Self(UnsafeCell::new(libc::PTHREAD_MUTEX_INITIALIZER))
122     }
lock(&self)123     unsafe fn lock(&self) {
124         let r = libc::pthread_mutex_lock(self.0.get());
125         debug_assert_eq!(r, 0);
126     }
unlock(&self)127     unsafe fn unlock(&self) {
128         let r = libc::pthread_mutex_unlock(self.0.get());
129         debug_assert_eq!(r, 0);
130     }
131 }
132 
133 unsafe impl Sync for Mutex {}
134 
135 struct DropGuard<F: FnMut()>(F);
136 
137 impl<F: FnMut()> Drop for DropGuard<F> {
drop(&mut self)138     fn drop(&mut self) {
139         self.0()
140     }
141 }
142