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 //! Implementation for Linux / Android
10
11 extern crate libc;
12
13 use rand_core::{Error, ErrorKind};
14 use super::random_device;
15 use super::OsRngImpl;
16
17 use std::io;
18 use std::io::Read;
19 use std::fs::{File, OpenOptions};
20 use std::os::unix::fs::OpenOptionsExt;
21 use std::sync::atomic::{AtomicBool, Ordering};
22 #[allow(deprecated)] // Required for compatibility with Rust < 1.24.
23 use std::sync::atomic::ATOMIC_BOOL_INIT;
24 use std::sync::{Once, ONCE_INIT};
25
26 #[derive(Clone, Debug)]
27 pub struct OsRng {
28 method: OsRngMethod,
29 initialized: bool,
30 }
31
32 #[derive(Clone, Debug)]
33 enum OsRngMethod {
34 GetRandom,
35 RandomDevice,
36 }
37
38 impl OsRngImpl for OsRng {
new() -> Result<OsRng, Error>39 fn new() -> Result<OsRng, Error> {
40 if is_getrandom_available() {
41 return Ok(OsRng { method: OsRngMethod::GetRandom,
42 initialized: false });
43 }
44 random_device::open("/dev/urandom", &|p| File::open(p))?;
45 Ok(OsRng { method: OsRngMethod::RandomDevice, initialized: false })
46 }
47
fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error>48 fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> {
49 match self.method {
50 OsRngMethod::GetRandom => getrandom_try_fill(dest, false),
51 OsRngMethod::RandomDevice => random_device::read(dest),
52 }
53 }
54
test_initialized(&mut self, dest: &mut [u8], blocking: bool) -> Result<usize, Error>55 fn test_initialized(&mut self, dest: &mut [u8], blocking: bool)
56 -> Result<usize, Error>
57 {
58 #[allow(deprecated)]
59 static OS_RNG_INITIALIZED: AtomicBool = ATOMIC_BOOL_INIT;
60 if !self.initialized {
61 self.initialized = OS_RNG_INITIALIZED.load(Ordering::Relaxed);
62 }
63 if self.initialized { return Ok(0); }
64
65 let result = match self.method {
66 OsRngMethod::GetRandom => {
67 getrandom_try_fill(dest, blocking)?;
68 Ok(dest.len())
69 }
70 OsRngMethod::RandomDevice => {
71 info!("OsRng: testing random device /dev/random");
72 let mut file = OpenOptions::new()
73 .read(true)
74 .custom_flags(if blocking { 0 } else { libc::O_NONBLOCK })
75 .open("/dev/random")
76 .map_err(random_device::map_err)?;
77 file.read(&mut dest[..1]).map_err(random_device::map_err)?;
78 Ok(1)
79 }
80 };
81 OS_RNG_INITIALIZED.store(true, Ordering::Relaxed);
82 self.initialized = true;
83 result
84 }
85
method_str(&self) -> &'static str86 fn method_str(&self) -> &'static str {
87 match self.method {
88 OsRngMethod::GetRandom => "getrandom",
89 OsRngMethod::RandomDevice => "/dev/urandom",
90 }
91 }
92 }
93
94 #[cfg(target_arch = "x86_64")]
95 const NR_GETRANDOM: libc::c_long = 318;
96 #[cfg(target_arch = "x86")]
97 const NR_GETRANDOM: libc::c_long = 355;
98 #[cfg(target_arch = "arm")]
99 const NR_GETRANDOM: libc::c_long = 384;
100 #[cfg(target_arch = "aarch64")]
101 const NR_GETRANDOM: libc::c_long = 278;
102 #[cfg(target_arch = "s390x")]
103 const NR_GETRANDOM: libc::c_long = 349;
104 #[cfg(target_arch = "powerpc")]
105 const NR_GETRANDOM: libc::c_long = 359;
106 #[cfg(target_arch = "powerpc64")]
107 const NR_GETRANDOM: libc::c_long = 359;
108 #[cfg(target_arch = "mips")] // old ABI
109 const NR_GETRANDOM: libc::c_long = 4353;
110 #[cfg(target_arch = "mips64")]
111 const NR_GETRANDOM: libc::c_long = 5313;
112 #[cfg(target_arch = "sparc")]
113 const NR_GETRANDOM: libc::c_long = 347;
114 #[cfg(target_arch = "sparc64")]
115 const NR_GETRANDOM: libc::c_long = 347;
116 #[cfg(not(any(target_arch = "x86_64", target_arch = "x86",
117 target_arch = "arm", target_arch = "aarch64",
118 target_arch = "s390x", target_arch = "powerpc",
119 target_arch = "powerpc64", target_arch = "mips",
120 target_arch = "mips64", target_arch = "sparc",
121 target_arch = "sparc64")))]
122 const NR_GETRANDOM: libc::c_long = 0;
123
getrandom(buf: &mut [u8], blocking: bool) -> libc::c_long124 fn getrandom(buf: &mut [u8], blocking: bool) -> libc::c_long {
125 const GRND_NONBLOCK: libc::c_uint = 0x0001;
126
127 if NR_GETRANDOM == 0 { return -1 };
128
129 unsafe {
130 libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(),
131 if blocking { 0 } else { GRND_NONBLOCK })
132 }
133 }
134
getrandom_try_fill(dest: &mut [u8], blocking: bool) -> Result<(), Error>135 fn getrandom_try_fill(dest: &mut [u8], blocking: bool) -> Result<(), Error> {
136 let mut read = 0;
137 while read < dest.len() {
138 let result = getrandom(&mut dest[read..], blocking);
139 if result == -1 {
140 let err = io::Error::last_os_error();
141 let kind = err.kind();
142 if kind == io::ErrorKind::Interrupted {
143 continue;
144 } else if kind == io::ErrorKind::WouldBlock {
145 return Err(Error::with_cause(
146 ErrorKind::NotReady,
147 "getrandom not ready",
148 err,
149 ));
150 } else {
151 return Err(Error::with_cause(
152 ErrorKind::Unavailable,
153 "unexpected getrandom error",
154 err,
155 ));
156 }
157 } else {
158 read += result as usize;
159 }
160 }
161 Ok(())
162 }
163
is_getrandom_available() -> bool164 fn is_getrandom_available() -> bool {
165 static CHECKER: Once = ONCE_INIT;
166 #[allow(deprecated)]
167 static AVAILABLE: AtomicBool = ATOMIC_BOOL_INIT;
168
169 if NR_GETRANDOM == 0 { return false };
170
171 CHECKER.call_once(|| {
172 debug!("OsRng: testing getrandom");
173 let mut buf: [u8; 0] = [];
174 let result = getrandom(&mut buf, false);
175 let available = if result == -1 {
176 let err = io::Error::last_os_error().raw_os_error();
177 err != Some(libc::ENOSYS)
178 } else {
179 true
180 };
181 AVAILABLE.store(available, Ordering::Relaxed);
182 info!("OsRng: using {}", if available { "getrandom" } else { "/dev/urandom" });
183 });
184
185 AVAILABLE.load(Ordering::Relaxed)
186 }
187