Skip to main content

leyline_bssl_tokio/
lib.rs

1use leyline_bssl::ssl::{
2    self, ConnectConfiguration, ErrorCode, MidHandshakeSslStream, ShutdownResult, SslAcceptor,
3    SslRef,
4};
5use leyline_bssl_sys as ffi;
6use std::error::Error;
7use std::fmt;
8use std::future::Future;
9use std::io::{self, Write};
10use std::pin::Pin;
11use std::task::{Context, Poll};
12use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
13
14mod async_callbacks;
15mod bridge;
16mod records;
17
18use self::bridge::AsyncStreamBridge;
19
20pub use crate::async_callbacks::SslContextBuilderExt;
21pub use crate::records::RecordStream;
22pub use leyline_bssl::ssl::{
23    AsyncPrivateKeyMethod, AsyncPrivateKeyMethodError, AsyncSelectCertError, BoxGetSessionFinish,
24    BoxGetSessionFuture, BoxPrivateKeyMethodFinish, BoxPrivateKeyMethodFuture, BoxSelectCertFinish,
25    BoxSelectCertFuture, ExDataFuture,
26};
27
28pub async fn connect<S>(
29    config: ConnectConfiguration,
30    domain: &str,
31    stream: S,
32) -> Result<SslStream<S>, HandshakeError<S>>
33where
34    S: AsyncRead + AsyncWrite + Unpin,
35{
36    let mid_handshake = config
37        .setup_connect(domain, AsyncStreamBridge::new(stream))
38        .map_err(|err| HandshakeError(ssl::HandshakeError::SetupFailure(err)))?;
39
40    HandshakeFuture(Some(mid_handshake)).await
41}
42
43pub async fn accept<S>(acceptor: &SslAcceptor, stream: S) -> Result<SslStream<S>, HandshakeError<S>>
44where
45    S: AsyncRead + AsyncWrite + Unpin,
46{
47    let mid_handshake = acceptor
48        .setup_accept(AsyncStreamBridge::new(stream))
49        .map_err(|err| HandshakeError(ssl::HandshakeError::SetupFailure(err)))?;
50
51    HandshakeFuture(Some(mid_handshake)).await
52}
53
54fn cvt<T>(r: io::Result<T>) -> Poll<io::Result<T>> {
55    match r {
56        Ok(v) => Poll::Ready(Ok(v)),
57        Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => Poll::Pending,
58        Err(e) => Poll::Ready(Err(e)),
59    }
60}
61
62pub struct SslStreamBuilder<S> {
63    inner: ssl::SslStreamBuilder<AsyncStreamBridge<S>>,
64}
65
66impl<S> SslStreamBuilder<S>
67where
68    S: AsyncRead + AsyncWrite + Unpin,
69{
70    pub fn new(ssl: ssl::Ssl, stream: S) -> Self {
71        Self {
72            inner: ssl::SslStreamBuilder::new(ssl, AsyncStreamBridge::new(stream)),
73        }
74    }
75
76    pub async fn accept(self) -> Result<SslStream<S>, HandshakeError<S>> {
77        let mid_handshake = self.inner.setup_accept();
78
79        HandshakeFuture(Some(mid_handshake)).await
80    }
81
82    pub async fn connect(self) -> Result<SslStream<S>, HandshakeError<S>> {
83        let mid_handshake = self.inner.setup_connect();
84
85        HandshakeFuture(Some(mid_handshake)).await
86    }
87}
88
89impl<S> SslStreamBuilder<S> {
90    #[must_use]
91    pub fn ssl(&self) -> &SslRef {
92        self.inner.ssl()
93    }
94
95    pub fn ssl_mut(&mut self) -> &mut SslRef {
96        self.inner.ssl_mut()
97    }
98}
99
100#[derive(Debug)]
101pub struct SslStream<S>(ssl::SslStream<AsyncStreamBridge<S>>);
102
103impl<S> SslStream<S> {
104    #[must_use]
105    pub fn ssl(&self) -> &SslRef {
106        self.0.ssl()
107    }
108
109    pub fn ssl_mut(&mut self) -> &mut SslRef {
110        self.0.ssl_mut()
111    }
112
113    #[must_use]
114    pub fn get_ref(&self) -> &S {
115        &self.0.get_ref().stream
116    }
117
118    pub fn get_mut(&mut self) -> &mut S {
119        &mut self.0.get_mut().stream
120    }
121
122    fn run_in_context<F, R>(&mut self, ctx: &mut Context<'_>, f: F) -> R
123    where
124        F: FnOnce(&mut ssl::SslStream<AsyncStreamBridge<S>>) -> R,
125    {
126        self.0.get_mut().set_waker(Some(ctx));
127
128        let result = f(&mut self.0);
129
130        self.0.get_mut().set_waker(None);
131
132        result
133    }
134}
135
136impl<S> SslStream<S>
137where
138    S: AsyncRead + AsyncWrite + Unpin,
139{
140    /// Moves a finished TLS 1.3 connection onto a [`RecordStream`], or returns it unchanged.
141    pub fn into_records(self) -> Result<RecordStream<S>, Self> {
142        let Some(records) = leyline_bssl::records::Records::new(self.ssl()) else {
143            return Err(self);
144        };
145        let (bridge, ssl) = self.0.detach();
146        let (stream, inbound, unread) = bridge.into_parts();
147        Ok(RecordStream::new(stream, ssl, records, &inbound[unread]))
148    }
149
150    pub unsafe fn from_raw_parts(ssl: *mut ffi::SSL, stream: S) -> Self {
151        unsafe {
152            Self(ssl::SslStream::from_raw_parts(
153                ssl,
154                AsyncStreamBridge::new(stream),
155            ))
156        }
157    }
158}
159
160impl<S> AsyncRead for SslStream<S>
161where
162    S: AsyncRead + AsyncWrite + Unpin,
163{
164    fn poll_read(
165        mut self: Pin<&mut Self>,
166        ctx: &mut Context<'_>,
167        buf: &mut ReadBuf,
168    ) -> Poll<io::Result<()>> {
169        self.run_in_context(ctx, |s| {
170            // SAFETY: read_uninit does not de-initialize the buffer.
171            match cvt(s.read_uninit(unsafe { buf.unfilled_mut() }))? {
172                Poll::Ready(nread) => {
173                    unsafe {
174                        buf.assume_init(nread);
175                    }
176                    buf.advance(nread);
177                    Poll::Ready(Ok(()))
178                }
179                Poll::Pending => Poll::Pending,
180            }
181        })
182    }
183}
184
185impl<S> AsyncWrite for SslStream<S>
186where
187    S: AsyncRead + AsyncWrite + Unpin,
188{
189    fn poll_write(
190        mut self: Pin<&mut Self>,
191        ctx: &mut Context,
192        buf: &[u8],
193    ) -> Poll<io::Result<usize>> {
194        self.run_in_context(ctx, |s| cvt(s.write(buf)))
195    }
196
197    fn poll_flush(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll<io::Result<()>> {
198        self.run_in_context(ctx, |s| cvt(s.flush()))
199    }
200
201    fn poll_shutdown(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll<io::Result<()>> {
202        match self.run_in_context(ctx, |s| s.shutdown()) {
203            Ok(ShutdownResult::Sent | ShutdownResult::Received) => {}
204            Err(ref e) if e.code() == ErrorCode::ZERO_RETURN => {}
205            Err(ref e) if e.code() == ErrorCode::WANT_READ || e.code() == ErrorCode::WANT_WRITE => {
206                return Poll::Pending;
207            }
208            Err(e) => {
209                return Poll::Ready(Err(e.into_io_error().unwrap_or_else(io::Error::other)));
210            }
211        }
212
213        Pin::new(&mut self.0.get_mut().stream).poll_shutdown(ctx)
214    }
215}
216
217pub struct HandshakeError<S>(ssl::HandshakeError<AsyncStreamBridge<S>>);
218
219impl<S> HandshakeError<S> {
220    #[must_use]
221    pub fn ssl(&self) -> Option<&SslRef> {
222        match &self.0 {
223            ssl::HandshakeError::Failure(s) => Some(s.ssl()),
224            _ => None,
225        }
226    }
227
228    #[must_use]
229    pub fn code(&self) -> Option<ErrorCode> {
230        match &self.0 {
231            ssl::HandshakeError::Failure(s) => Some(s.error().code()),
232            _ => None,
233        }
234    }
235
236    #[must_use]
237    pub fn as_io_error(&self) -> Option<&io::Error> {
238        match &self.0 {
239            ssl::HandshakeError::Failure(s) => s.error().io_error(),
240            _ => None,
241        }
242    }
243}
244
245impl<S> fmt::Debug for HandshakeError<S>
246where
247    S: fmt::Debug,
248{
249    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
250        fmt::Debug::fmt(&self.0, fmt)
251    }
252}
253
254impl<S> fmt::Display for HandshakeError<S> {
255    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
256        fmt::Display::fmt(&self.0, fmt)
257    }
258}
259
260impl<S> Error for HandshakeError<S>
261where
262    S: fmt::Debug,
263{
264    fn source(&self) -> Option<&(dyn Error + 'static)> {
265        self.0.source()
266    }
267}
268
269pub struct HandshakeFuture<S>(Option<MidHandshakeSslStream<AsyncStreamBridge<S>>>);
270
271impl<S> Future for HandshakeFuture<S>
272where
273    S: AsyncRead + AsyncWrite + Unpin,
274{
275    type Output = Result<SslStream<S>, HandshakeError<S>>;
276
277    fn poll(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
278        let mut mid_handshake = self.0.take().expect("future polled after completion");
279
280        mid_handshake.get_mut().set_waker(Some(ctx));
281        mid_handshake
282            .ssl_mut()
283            .set_task_waker(Some(ctx.waker().clone()));
284
285        match mid_handshake.handshake() {
286            Ok(mut stream) => {
287                stream.get_mut().set_waker(None);
288                stream.ssl_mut().set_task_waker(None);
289
290                Poll::Ready(Ok(SslStream(stream)))
291            }
292            Err(ssl::HandshakeError::WouldBlock(mut mid_handshake)) => {
293                mid_handshake.get_mut().set_waker(None);
294                mid_handshake.ssl_mut().set_task_waker(None);
295
296                self.0 = Some(mid_handshake);
297
298                Poll::Pending
299            }
300            Err(ssl::HandshakeError::Failure(mut mid_handshake)) => {
301                mid_handshake.get_mut().set_waker(None);
302
303                Poll::Ready(Err(HandshakeError(ssl::HandshakeError::Failure(
304                    mid_handshake,
305                ))))
306            }
307            Err(err @ ssl::HandshakeError::SetupFailure(_)) => {
308                Poll::Ready(Err(HandshakeError(err)))
309            }
310        }
311    }
312}