Joel Galenson | 4be0c6d | 2020-07-07 13:20:14 -0700 | [diff] [blame] | 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 FreeBSD and NetBSD |
ThiƩbaud Weksteen | 9791b30 | 2021-03-03 16:30:20 +0100 | [diff] [blame] | 10 | use crate::{util_libc::sys_fill_exact, Error}; |
Joel Galenson | 4be0c6d | 2020-07-07 13:20:14 -0700 | [diff] [blame] | 11 | use core::ptr; |
| 12 | |
| 13 | fn kern_arnd(buf: &mut [u8]) -> libc::ssize_t { |
| 14 | static MIB: [libc::c_int; 2] = [libc::CTL_KERN, libc::KERN_ARND]; |
| 15 | let mut len = buf.len(); |
| 16 | let ret = unsafe { |
| 17 | libc::sysctl( |
| 18 | MIB.as_ptr(), |
| 19 | MIB.len() as libc::c_uint, |
| 20 | buf.as_mut_ptr() as *mut _, |
| 21 | &mut len, |
| 22 | ptr::null(), |
| 23 | 0, |
| 24 | ) |
| 25 | }; |
| 26 | if ret == -1 { |
Joel Galenson | 4be0c6d | 2020-07-07 13:20:14 -0700 | [diff] [blame] | 27 | -1 |
| 28 | } else { |
| 29 | len as libc::ssize_t |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { |
Jeff Vander Stoep | 4d7867d | 2022-12-12 11:02:41 +0100 | [diff] [blame] | 34 | // getrandom(2) was introduced in FreeBSD 12.0 and NetBSD 10.0 |
Joel Galenson | 4be0c6d | 2020-07-07 13:20:14 -0700 | [diff] [blame] | 35 | #[cfg(target_os = "freebsd")] |
| 36 | { |
| 37 | use crate::util_libc::Weak; |
| 38 | static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") }; |
| 39 | type GetRandomFn = |
| 40 | unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::ssize_t; |
| 41 | |
| 42 | if let Some(fptr) = GETRANDOM.ptr() { |
| 43 | let func: GetRandomFn = unsafe { core::mem::transmute(fptr) }; |
| 44 | return sys_fill_exact(dest, |buf| unsafe { func(buf.as_mut_ptr(), buf.len(), 0) }); |
| 45 | } |
| 46 | } |
ThiƩbaud Weksteen | 9791b30 | 2021-03-03 16:30:20 +0100 | [diff] [blame] | 47 | // Both FreeBSD and NetBSD will only return up to 256 bytes at a time, and |
| 48 | // older NetBSD kernels will fail on longer buffers. |
| 49 | for chunk in dest.chunks_mut(256) { |
| 50 | sys_fill_exact(chunk, kern_arnd)? |
| 51 | } |
| 52 | Ok(()) |
Joel Galenson | 4be0c6d | 2020-07-07 13:20:14 -0700 | [diff] [blame] | 53 | } |