openssl/ssl/
bio.rs

1use cfg_if::cfg_if;
2use ffi::{
3    self, BIO_clear_retry_flags, BIO_new, BIO_set_retry_read, BIO_set_retry_write, BIO,
4    BIO_CTRL_DGRAM_QUERY_MTU, BIO_CTRL_FLUSH,
5};
6use libc::{c_char, c_int, c_long, c_void, strlen};
7use std::any::Any;
8use std::io;
9use std::io::prelude::*;
10use std::panic::{catch_unwind, AssertUnwindSafe};
11use std::ptr;
12
13use crate::error::ErrorStack;
14use crate::{cvt_p, util};
15
16pub struct StreamState<S> {
17    pub stream: S,
18    pub error: Option<io::Error>,
19    pub panic: Option<Box<dyn Any + Send>>,
20    pub dtls_mtu_size: c_long,
21}
22
23/// Safe wrapper for `BIO_METHOD`
24pub struct BioMethod(BIO_METHOD);
25
26impl BioMethod {
27    fn new<S: Read + Write>() -> Result<BioMethod, ErrorStack> {
28        BIO_METHOD::new::<S>().map(BioMethod)
29    }
30}
31
32unsafe impl Sync for BioMethod {}
33unsafe impl Send for BioMethod {}
34
35pub fn new<S: Read + Write>(stream: S) -> Result<(*mut BIO, BioMethod), ErrorStack> {
36    let method = BioMethod::new::<S>()?;
37
38    let state = Box::new(StreamState {
39        stream,
40        error: None,
41        panic: None,
42        dtls_mtu_size: 0,
43    });
44
45    unsafe {
46        let bio = cvt_p(BIO_new(method.0.get()))?;
47        BIO_set_data(bio, Box::into_raw(state) as *mut _);
48        BIO_set_init(bio, 1);
49
50        Ok((bio, method))
51    }
52}
53
54pub unsafe fn take_error<S>(bio: *mut BIO) -> Option<io::Error> {
55    let state = state::<S>(bio);
56    state.error.take()
57}
58
59pub unsafe fn take_panic<S>(bio: *mut BIO) -> Option<Box<dyn Any + Send>> {
60    let state = state::<S>(bio);
61    state.panic.take()
62}
63
64pub unsafe fn get_ref<'a, S: 'a>(bio: *mut BIO) -> &'a S {
65    let state = &*(BIO_get_data(bio) as *const StreamState<S>);
66    &state.stream
67}
68
69pub unsafe fn get_mut<'a, S: 'a>(bio: *mut BIO) -> &'a mut S {
70    &mut state(bio).stream
71}
72
73pub unsafe fn set_dtls_mtu_size<S>(bio: *mut BIO, mtu_size: usize) {
74    if mtu_size as u64 > c_long::MAX as u64 {
75        panic!(
76            "Given MTU size {} can't be represented in a positive `c_long` range",
77            mtu_size
78        )
79    }
80    state::<S>(bio).dtls_mtu_size = mtu_size as c_long;
81}
82
83unsafe fn state<'a, S: 'a>(bio: *mut BIO) -> &'a mut StreamState<S> {
84    &mut *(BIO_get_data(bio) as *mut _)
85}
86
87unsafe extern "C" fn bwrite<S: Write>(bio: *mut BIO, buf: *const c_char, len: c_int) -> c_int {
88    BIO_clear_retry_flags(bio);
89
90    let state = state::<S>(bio);
91    let buf = util::from_raw_parts(buf as *const _, len as usize);
92
93    match catch_unwind(AssertUnwindSafe(|| state.stream.write(buf))) {
94        Ok(Ok(len)) => len as c_int,
95        Ok(Err(err)) => {
96            if retriable_error(&err) {
97                BIO_set_retry_write(bio);
98            }
99            state.error = Some(err);
100            -1
101        }
102        Err(err) => {
103            state.panic = Some(err);
104            -1
105        }
106    }
107}
108
109unsafe extern "C" fn bread<S: Read>(bio: *mut BIO, buf: *mut c_char, len: c_int) -> c_int {
110    BIO_clear_retry_flags(bio);
111
112    let state = state::<S>(bio);
113    let buf = util::from_raw_parts_mut(buf as *mut _, len as usize);
114
115    match catch_unwind(AssertUnwindSafe(|| state.stream.read(buf))) {
116        Ok(Ok(len)) => len as c_int,
117        Ok(Err(err)) => {
118            if retriable_error(&err) {
119                BIO_set_retry_read(bio);
120            }
121            state.error = Some(err);
122            -1
123        }
124        Err(err) => {
125            state.panic = Some(err);
126            -1
127        }
128    }
129}
130
131#[allow(clippy::match_like_matches_macro)] // matches macro requires rust 1.42.0
132fn retriable_error(err: &io::Error) -> bool {
133    match err.kind() {
134        io::ErrorKind::WouldBlock | io::ErrorKind::NotConnected => true,
135        _ => false,
136    }
137}
138
139unsafe extern "C" fn bputs<S: Write>(bio: *mut BIO, s: *const c_char) -> c_int {
140    bwrite::<S>(bio, s, strlen(s) as c_int)
141}
142
143unsafe extern "C" fn ctrl<S: Write>(
144    bio: *mut BIO,
145    cmd: c_int,
146    _num: c_long,
147    _ptr: *mut c_void,
148) -> c_long {
149    let state = state::<S>(bio);
150
151    if cmd == BIO_CTRL_FLUSH {
152        match catch_unwind(AssertUnwindSafe(|| state.stream.flush())) {
153            Ok(Ok(())) => 1,
154            Ok(Err(err)) => {
155                state.error = Some(err);
156                0
157            }
158            Err(err) => {
159                state.panic = Some(err);
160                0
161            }
162        }
163    } else if cmd == BIO_CTRL_DGRAM_QUERY_MTU {
164        state.dtls_mtu_size
165    } else {
166        0
167    }
168}
169
170unsafe extern "C" fn create(bio: *mut BIO) -> c_int {
171    BIO_set_init(bio, 0);
172    BIO_set_num(bio, 0);
173    BIO_set_data(bio, ptr::null_mut());
174    BIO_set_flags(bio, 0);
175    1
176}
177
178unsafe extern "C" fn destroy<S>(bio: *mut BIO) -> c_int {
179    if bio.is_null() {
180        return 0;
181    }
182
183    let data = BIO_get_data(bio);
184    assert!(!data.is_null());
185    let _ = Box::<StreamState<S>>::from_raw(data as *mut _);
186    BIO_set_data(bio, ptr::null_mut());
187    BIO_set_init(bio, 0);
188    1
189}
190
191cfg_if! {
192    if #[cfg(any(ossl110, libressl273, boringssl))] {
193        use ffi::{BIO_get_data, BIO_set_data, BIO_set_flags, BIO_set_init};
194        use crate::cvt;
195
196        #[allow(bad_style)]
197        unsafe fn BIO_set_num(_bio: *mut ffi::BIO, _num: c_int) {}
198
199        #[allow(bad_style, clippy::upper_case_acronyms)]
200        struct BIO_METHOD(*mut ffi::BIO_METHOD);
201
202        impl BIO_METHOD {
203            fn new<S: Read + Write>() -> Result<BIO_METHOD, ErrorStack> {
204                #[cfg(not(boringssl))]
205                use ffi::{
206                    BIO_meth_set_write__fixed_rust as BIO_meth_set_write,
207                    BIO_meth_set_read__fixed_rust as BIO_meth_set_read,
208                    BIO_meth_set_puts__fixed_rust as BIO_meth_set_puts,
209                    BIO_meth_set_ctrl__fixed_rust as BIO_meth_set_ctrl,
210                    BIO_meth_set_create__fixed_rust as BIO_meth_set_create,
211                    BIO_meth_set_destroy__fixed_rust as BIO_meth_set_destroy,
212                };
213                #[cfg(boringssl)]
214                use ffi::{
215                    BIO_meth_set_write,
216                    BIO_meth_set_read,
217                    BIO_meth_set_puts,
218                    BIO_meth_set_ctrl,
219                    BIO_meth_set_create,
220                    BIO_meth_set_destroy,
221                };
222
223                unsafe {
224                    let ptr = cvt_p(ffi::BIO_meth_new(ffi::BIO_TYPE_NONE, b"rust\0".as_ptr() as *const _))?;
225                    let method = BIO_METHOD(ptr);
226                    cvt(BIO_meth_set_write(method.0, Some(bwrite::<S>)))?;
227                    cvt(BIO_meth_set_read(method.0, Some(bread::<S>)))?;
228                    cvt(BIO_meth_set_puts(method.0, Some(bputs::<S>)))?;
229                    cvt(BIO_meth_set_ctrl(method.0, Some(ctrl::<S>)))?;
230                    cvt(BIO_meth_set_create(method.0, Some(create)))?;
231                    cvt(BIO_meth_set_destroy(method.0, Some(destroy::<S>)))?;
232                    Ok(method)
233                }
234            }
235
236            fn get(&self) -> *mut ffi::BIO_METHOD {
237                self.0
238            }
239        }
240
241        impl Drop for BIO_METHOD {
242            fn drop(&mut self) {
243                unsafe {
244                    ffi::BIO_meth_free(self.0);
245                }
246            }
247        }
248    } else {
249        #[allow(bad_style, clippy::upper_case_acronyms)]
250        struct BIO_METHOD(*mut ffi::BIO_METHOD);
251
252        impl BIO_METHOD {
253            fn new<S: Read + Write>() -> Result<BIO_METHOD, ErrorStack> {
254                let ptr = Box::new(ffi::BIO_METHOD {
255                    type_: ffi::BIO_TYPE_NONE,
256                    name: b"rust\0".as_ptr() as *const _,
257                    bwrite: Some(bwrite::<S>),
258                    bread: Some(bread::<S>),
259                    bputs: Some(bputs::<S>),
260                    bgets: None,
261                    ctrl: Some(ctrl::<S>),
262                    create: Some(create),
263                    destroy: Some(destroy::<S>),
264                    callback_ctrl: None,
265                });
266
267                Ok(BIO_METHOD(Box::into_raw(ptr)))
268            }
269
270            fn get(&self) -> *mut ffi::BIO_METHOD {
271                self.0
272            }
273        }
274
275        impl Drop for BIO_METHOD {
276            fn drop(&mut self) {
277                unsafe {
278                    let _ = Box::<ffi::BIO_METHOD>::from_raw(self.0);
279                }
280            }
281        }
282
283        #[allow(bad_style)]
284        unsafe fn BIO_set_init(bio: *mut ffi::BIO, init: c_int) {
285            (*bio).init = init;
286        }
287
288        #[allow(bad_style)]
289        unsafe fn BIO_set_flags(bio: *mut ffi::BIO, flags: c_int) {
290            (*bio).flags = flags;
291        }
292
293        #[allow(bad_style)]
294        unsafe fn BIO_get_data(bio: *mut ffi::BIO) -> *mut c_void {
295            (*bio).ptr
296        }
297
298        #[allow(bad_style)]
299        unsafe fn BIO_set_data(bio: *mut ffi::BIO, data: *mut c_void) {
300            (*bio).ptr = data;
301        }
302
303        #[allow(bad_style)]
304        unsafe fn BIO_set_num(bio: *mut ffi::BIO, num: c_int) {
305            (*bio).num = num;
306        }
307    }
308}