]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/rand.rs
Improve type size assertions
[rust.git] / src / libstd / sys / unix / rand.rs
1 use crate::mem;
2 use crate::slice;
3
4 pub fn hashmap_random_keys() -> (u64, u64) {
5     let mut v = (0, 0);
6     unsafe {
7         let view = slice::from_raw_parts_mut(&mut v as *mut _ as *mut u8,
8                                              mem::size_of_val(&v));
9         imp::fill_bytes(view);
10     }
11     return v
12 }
13
14 #[cfg(all(unix,
15           not(target_os = "ios"),
16           not(target_os = "openbsd"),
17           not(target_os = "freebsd"),
18           not(target_os = "fuchsia")))]
19 mod imp {
20     use crate::fs::File;
21     use crate::io::Read;
22
23     #[cfg(any(target_os = "linux", target_os = "android"))]
24     fn getrandom(buf: &mut [u8]) -> libc::c_long {
25         unsafe {
26             libc::syscall(libc::SYS_getrandom, buf.as_mut_ptr(), buf.len(), libc::GRND_NONBLOCK)
27         }
28     }
29
30     #[cfg(not(any(target_os = "linux", target_os = "android")))]
31     fn getrandom_fill_bytes(_buf: &mut [u8]) -> bool { false }
32
33     #[cfg(any(target_os = "linux", target_os = "android"))]
34     fn getrandom_fill_bytes(v: &mut [u8]) -> bool {
35         use crate::sync::atomic::{AtomicBool, Ordering};
36         use crate::sys::os::errno;
37
38         static GETRANDOM_UNAVAILABLE: AtomicBool = AtomicBool::new(false);
39         if GETRANDOM_UNAVAILABLE.load(Ordering::Relaxed) {
40             return false;
41         }
42
43         let mut read = 0;
44         while read < v.len() {
45             let result = getrandom(&mut v[read..]);
46             if result == -1 {
47                 let err = errno() as libc::c_int;
48                 if err == libc::EINTR {
49                     continue;
50                 } else if err == libc::ENOSYS {
51                     GETRANDOM_UNAVAILABLE.store(true, Ordering::Relaxed);
52                     return false;
53                 } else if err == libc::EAGAIN {
54                     return false;
55                 } else {
56                     panic!("unexpected getrandom error: {}", err);
57                 }
58             } else {
59                 read += result as usize;
60             }
61         }
62         true
63     }
64
65     pub fn fill_bytes(v: &mut [u8]) {
66         // getrandom_fill_bytes here can fail if getrandom() returns EAGAIN,
67         // meaning it would have blocked because the non-blocking pool (urandom)
68         // has not initialized in the kernel yet due to a lack of entropy. The
69         // fallback we do here is to avoid blocking applications which could
70         // depend on this call without ever knowing they do and don't have a
71         // work around. The PRNG of /dev/urandom will still be used but over a
72         // possibly predictable entropy pool.
73         if getrandom_fill_bytes(v) {
74             return;
75         }
76
77         // getrandom failed because it is permanently or temporarily (because
78         // of missing entropy) unavailable. Open /dev/urandom, read from it,
79         // and close it again.
80         let mut file = File::open("/dev/urandom").expect("failed to open /dev/urandom");
81         file.read_exact(v).expect("failed to read /dev/urandom")
82     }
83 }
84
85 #[cfg(target_os = "openbsd")]
86 mod imp {
87     use crate::sys::os::errno;
88
89     pub fn fill_bytes(v: &mut [u8]) {
90         // getentropy(2) permits a maximum buffer size of 256 bytes
91         for s in v.chunks_mut(256) {
92             let ret = unsafe {
93                 libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len())
94             };
95             if ret == -1 {
96                 panic!("unexpected getentropy error: {}", errno());
97             }
98         }
99     }
100 }
101
102 // On iOS and MacOS `SecRandomCopyBytes` calls `CCRandomCopyBytes` with
103 // `kCCRandomDefault`. `CCRandomCopyBytes` manages a CSPRNG which is seeded
104 // from `/dev/random` and which runs on its own thread accessed via GCD.
105 // This seems needlessly heavyweight for the purposes of generating two u64s
106 // once per thread in `hashmap_random_keys`. Therefore `SecRandomCopyBytes` is
107 // only used on iOS where direct access to `/dev/urandom` is blocked by the
108 // sandbox.
109 #[cfg(target_os = "ios")]
110 mod imp {
111     use crate::io;
112     use crate::ptr;
113     use libc::{c_int, size_t};
114
115     enum SecRandom {}
116
117     #[allow(non_upper_case_globals)]
118     const kSecRandomDefault: *const SecRandom = ptr::null();
119
120     extern {
121         fn SecRandomCopyBytes(rnd: *const SecRandom,
122                               count: size_t,
123                               bytes: *mut u8) -> c_int;
124     }
125
126     pub fn fill_bytes(v: &mut [u8]) {
127         let ret = unsafe {
128             SecRandomCopyBytes(kSecRandomDefault,
129                                v.len(),
130                                v.as_mut_ptr())
131         };
132         if ret == -1 {
133             panic!("couldn't generate random bytes: {}",
134                    io::Error::last_os_error());
135         }
136     }
137 }
138
139 #[cfg(target_os = "freebsd")]
140 mod imp {
141     use crate::ptr;
142
143     pub fn fill_bytes(v: &mut [u8]) {
144         let mib = [libc::CTL_KERN, libc::KERN_ARND];
145         // kern.arandom permits a maximum buffer size of 256 bytes
146         for s in v.chunks_mut(256) {
147             let mut s_len = s.len();
148             let ret = unsafe {
149                 libc::sysctl(mib.as_ptr(), mib.len() as libc::c_uint,
150                              s.as_mut_ptr() as *mut _, &mut s_len,
151                              ptr::null(), 0)
152             };
153             if ret == -1 || s_len != s.len() {
154                 panic!("kern.arandom sysctl failed! (returned {}, s.len() {}, oldlenp {})",
155                        ret, s.len(), s_len);
156             }
157         }
158     }
159 }
160
161 #[cfg(target_os = "fuchsia")]
162 mod imp {
163     #[link(name = "zircon")]
164     extern {
165         fn zx_cprng_draw(buffer: *mut u8, len: usize);
166     }
167
168     pub fn fill_bytes(v: &mut [u8]) {
169         unsafe { zx_cprng_draw(v.as_mut_ptr(), v.len()) }
170     }
171 }