1use ffi::{
2 self, BIO_clear_retry_flags, BIO_new, BIO_set_retry_read, BIO_set_retry_write, BIO,
3 BIO_CTRL_DGRAM_QUERY_MTU, BIO_CTRL_FLUSH,
4};
5use foreign_types::ForeignType;
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
23foreign_type_and_impl_send_sync! {
24 type CType = ffi::BIO_METHOD;
25 fn drop = ffi::BIO_meth_free;
26
27 pub struct BioMethod;
29 pub struct BioMethodRef;
31}
32
33pub fn new<S: Read + Write>(stream: S) -> Result<(*mut BIO, BioMethod), ErrorStack> {
34 let method = BioMethod::new::<S>()?;
35
36 let state = Box::new(StreamState {
37 stream,
38 error: None,
39 panic: None,
40 dtls_mtu_size: 0,
41 });
42
43 unsafe {
44 let bio = cvt_p(BIO_new(method.as_ptr()))?;
45 BIO_set_data(bio, Box::into_raw(state) as *mut _);
46 BIO_set_init(bio, 1);
47
48 Ok((bio, method))
49 }
50}
51
52pub unsafe fn take_error<S>(bio: *mut BIO) -> Option<io::Error> {
53 let state = state::<S>(bio);
54 state.error.take()
55}
56
57pub unsafe fn take_panic<S>(bio: *mut BIO) -> Option<Box<dyn Any + Send>> {
58 let state = state::<S>(bio);
59 state.panic.take()
60}
61
62pub unsafe fn get_ref<'a, S: 'a>(bio: *mut BIO) -> &'a S {
63 let state = &*(BIO_get_data(bio) as *const StreamState<S>);
64 &state.stream
65}
66
67pub unsafe fn get_mut<'a, S: 'a>(bio: *mut BIO) -> &'a mut S {
68 &mut state(bio).stream
69}
70
71pub unsafe fn set_dtls_mtu_size<S>(bio: *mut BIO, mtu_size: usize) {
72 if mtu_size as u64 > c_long::MAX as u64 {
73 panic!(
74 "Given MTU size {} can't be represented in a positive `c_long` range",
75 mtu_size
76 )
77 }
78 state::<S>(bio).dtls_mtu_size = mtu_size as c_long;
79}
80
81unsafe fn state<'a, S: 'a>(bio: *mut BIO) -> &'a mut StreamState<S> {
82 &mut *(BIO_get_data(bio) as *mut _)
83}
84
85unsafe extern "C" fn bwrite<S: Write>(bio: *mut BIO, buf: *const c_char, len: c_int) -> c_int {
86 BIO_clear_retry_flags(bio);
87
88 let state = state::<S>(bio);
89 let buf = util::from_raw_parts(buf as *const _, len as usize);
90
91 match catch_unwind(AssertUnwindSafe(|| state.stream.write(buf))) {
92 Ok(Ok(len)) => len as c_int,
93 Ok(Err(err)) => {
94 if retriable_error(&err) {
95 BIO_set_retry_write(bio);
96 }
97 state.error = Some(err);
98 -1
99 }
100 Err(err) => {
101 state.panic = Some(err);
102 -1
103 }
104 }
105}
106
107unsafe extern "C" fn bread<S: Read>(bio: *mut BIO, buf: *mut c_char, len: c_int) -> c_int {
108 BIO_clear_retry_flags(bio);
109
110 let state = state::<S>(bio);
111 let buf = util::from_raw_parts_mut(buf as *mut _, len as usize);
112
113 match catch_unwind(AssertUnwindSafe(|| state.stream.read(buf))) {
114 Ok(Ok(len)) => len as c_int,
115 Ok(Err(err)) => {
116 if retriable_error(&err) {
117 BIO_set_retry_read(bio);
118 }
119 state.error = Some(err);
120 -1
121 }
122 Err(err) => {
123 state.panic = Some(err);
124 -1
125 }
126 }
127}
128
129#[allow(clippy::match_like_matches_macro)] fn retriable_error(err: &io::Error) -> bool {
131 match err.kind() {
132 io::ErrorKind::WouldBlock | io::ErrorKind::NotConnected => true,
133 _ => false,
134 }
135}
136
137unsafe extern "C" fn bputs<S: Write>(bio: *mut BIO, s: *const c_char) -> c_int {
138 bwrite::<S>(bio, s, strlen(s) as c_int)
139}
140
141unsafe extern "C" fn ctrl<S: Write>(
142 bio: *mut BIO,
143 cmd: c_int,
144 _num: c_long,
145 _ptr: *mut c_void,
146) -> c_long {
147 let state = state::<S>(bio);
148
149 if cmd == BIO_CTRL_FLUSH {
150 match catch_unwind(AssertUnwindSafe(|| state.stream.flush())) {
151 Ok(Ok(())) => 1,
152 Ok(Err(err)) => {
153 state.error = Some(err);
154 0
155 }
156 Err(err) => {
157 state.panic = Some(err);
158 0
159 }
160 }
161 } else if cmd == BIO_CTRL_DGRAM_QUERY_MTU {
162 state.dtls_mtu_size
163 } else {
164 0
165 }
166}
167
168unsafe extern "C" fn create(bio: *mut BIO) -> c_int {
169 BIO_set_init(bio, 0);
170 BIO_set_data(bio, ptr::null_mut());
171 BIO_set_flags(bio, 0);
172 1
173}
174
175unsafe extern "C" fn destroy<S>(bio: *mut BIO) -> c_int {
176 if bio.is_null() {
177 return 0;
178 }
179
180 let data = BIO_get_data(bio);
181 assert!(!data.is_null());
182 let _ = Box::<StreamState<S>>::from_raw(data as *mut _);
183 BIO_set_data(bio, ptr::null_mut());
184 BIO_set_init(bio, 0);
185 1
186}
187
188use crate::cvt;
189use ffi::{BIO_get_data, BIO_set_data, BIO_set_flags, BIO_set_init};
190
191impl BioMethod {
192 fn new<S: Read + Write>() -> Result<BioMethod, ErrorStack> {
193 #[cfg(any(boringssl, awslc))]
194 use ffi::{
195 BIO_meth_set_create, BIO_meth_set_ctrl, BIO_meth_set_destroy, BIO_meth_set_puts,
196 BIO_meth_set_read, BIO_meth_set_write,
197 };
198 #[cfg(not(any(boringssl, awslc)))]
199 use ffi::{
200 BIO_meth_set_create__fixed_rust as BIO_meth_set_create,
201 BIO_meth_set_ctrl__fixed_rust as BIO_meth_set_ctrl,
202 BIO_meth_set_destroy__fixed_rust as BIO_meth_set_destroy,
203 BIO_meth_set_puts__fixed_rust as BIO_meth_set_puts,
204 BIO_meth_set_read__fixed_rust as BIO_meth_set_read,
205 BIO_meth_set_write__fixed_rust as BIO_meth_set_write,
206 };
207
208 unsafe {
209 let ptr = cvt_p(ffi::BIO_meth_new(
210 ffi::BIO_TYPE_NONE,
211 b"rust\0".as_ptr() as *const _,
212 ))?;
213 let method = BioMethod::from_ptr(ptr);
214 cvt(BIO_meth_set_write(method.as_ptr(), Some(bwrite::<S>)))?;
215 cvt(BIO_meth_set_read(method.as_ptr(), Some(bread::<S>)))?;
216 cvt(BIO_meth_set_puts(method.as_ptr(), Some(bputs::<S>)))?;
217 cvt(BIO_meth_set_ctrl(method.as_ptr(), Some(ctrl::<S>)))?;
218 cvt(BIO_meth_set_create(method.as_ptr(), Some(create)))?;
219 cvt(BIO_meth_set_destroy(method.as_ptr(), Some(destroy::<S>)))?;
220 Ok(method)
221 }
222 }
223}