openssl/
util.rs

1use crate::error::ErrorStack;
2use crate::util;
3use foreign_types::{ForeignType, ForeignTypeRef};
4use libc::{c_char, c_int, c_void};
5use std::any::Any;
6use std::panic::{self, AssertUnwindSafe};
7use std::slice;
8
9/// Wraps a user-supplied callback and a slot for panics thrown inside the callback (while FFI
10/// frames are on the stack).
11///
12/// When dropped, checks if the callback has panicked, and resumes unwinding if so.
13pub struct CallbackState<F> {
14    /// The user callback. Taken out of the `Option` when called.
15    cb: Option<F>,
16    /// If the callback panics, we place the panic object here, to be re-thrown once OpenSSL
17    /// returns.
18    panic: Option<Box<dyn Any + Send + 'static>>,
19}
20
21impl<F> CallbackState<F> {
22    pub fn new(callback: F) -> Self {
23        CallbackState {
24            cb: Some(callback),
25            panic: None,
26        }
27    }
28}
29
30impl<F> Drop for CallbackState<F> {
31    fn drop(&mut self) {
32        if let Some(panic) = self.panic.take() {
33            panic::resume_unwind(panic);
34        }
35    }
36}
37
38/// Password callback function, passed to private key loading functions.
39///
40/// `cb_state` is expected to be a pointer to a `CallbackState`.
41pub unsafe extern "C" fn invoke_passwd_cb<F>(
42    buf: *mut c_char,
43    size: c_int,
44    _rwflag: c_int,
45    cb_state: *mut c_void,
46) -> c_int
47where
48    F: FnOnce(&mut [u8]) -> Result<usize, ErrorStack>,
49{
50    let callback = &mut *(cb_state as *mut CallbackState<F>);
51
52    let result = panic::catch_unwind(AssertUnwindSafe(|| {
53        let pass_slice = util::from_raw_parts_mut(buf as *mut u8, size as usize);
54        callback.cb.take().unwrap()(pass_slice)
55    }));
56
57    match result {
58        Ok(Ok(len)) if len > size as usize => 0,
59        Ok(Ok(len)) => len as c_int,
60        Ok(Err(_)) => {
61            // FIXME restore error stack
62            0
63        }
64        Err(err) => {
65            callback.panic = Some(err);
66            0
67        }
68    }
69}
70
71pub trait ForeignTypeExt: ForeignType {
72    unsafe fn from_ptr_opt(ptr: *mut Self::CType) -> Option<Self> {
73        if ptr.is_null() {
74            None
75        } else {
76            Some(Self::from_ptr(ptr))
77        }
78    }
79}
80impl<FT: ForeignType> ForeignTypeExt for FT {}
81
82pub trait ForeignTypeRefExt: ForeignTypeRef {
83    unsafe fn from_const_ptr<'a>(ptr: *const Self::CType) -> &'a Self {
84        Self::from_ptr(ptr as *mut Self::CType)
85    }
86
87    unsafe fn from_const_ptr_opt<'a>(ptr: *const Self::CType) -> Option<&'a Self> {
88        if ptr.is_null() {
89            None
90        } else {
91            Some(Self::from_const_ptr(ptr as *mut Self::CType))
92        }
93    }
94}
95impl<FT: ForeignTypeRef> ForeignTypeRefExt for FT {}
96
97/// The same as `slice::from_raw_parts`, except that `data` may be `NULL` if
98/// `len` is 0.
99pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
100    if len == 0 {
101        &[]
102    } else {
103        // Using this to implement the preferred API
104        #[allow(clippy::disallowed_methods)]
105        slice::from_raw_parts(data, len)
106    }
107}
108
109/// The same as `slice::from_raw_parts_mut`, except that `data` may be `NULL`
110/// if `len` is 0.
111pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
112    if len == 0 {
113        &mut []
114    } else {
115        // Using this to implement the preferred API
116        #[allow(clippy::disallowed_methods)]
117        slice::from_raw_parts_mut(data, len)
118    }
119}