1#![warn(missing_docs)]
14
15use boring::ssl::{
16 self, ConnectConfiguration, ErrorCode, MidHandshakeSslStream, ShutdownResult, SslAcceptor,
17 SslRef,
18};
19use boring_sys as ffi;
20use std::error::Error;
21use std::fmt;
22use std::future::Future;
23use std::io::{self, Write};
24use std::pin::Pin;
25use std::task::{Context, Poll};
26use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
27
28mod async_callbacks;
29mod bridge;
30
31use self::bridge::AsyncStreamBridge;
32
33pub use crate::async_callbacks::SslContextBuilderExt;
34pub use boring::ssl::{
35 AsyncPrivateKeyMethod, AsyncPrivateKeyMethodError, AsyncSelectCertError, BoxGetSessionFinish,
36 BoxGetSessionFuture, BoxPrivateKeyMethodFinish, BoxPrivateKeyMethodFuture, BoxSelectCertFinish,
37 BoxSelectCertFuture, ExDataFuture,
38};
39
40pub async fn connect<S>(
45 config: ConnectConfiguration,
46 domain: &str,
47 stream: S,
48) -> Result<SslStream<S>, HandshakeError<S>>
49where
50 S: AsyncRead + AsyncWrite + Unpin,
51{
52 let mid_handshake = config
53 .setup_connect(domain, AsyncStreamBridge::new(stream))
54 .map_err(|err| HandshakeError(ssl::HandshakeError::SetupFailure(err)))?;
55
56 HandshakeFuture(Some(mid_handshake)).await
57}
58
59pub async fn accept<S>(acceptor: &SslAcceptor, stream: S) -> Result<SslStream<S>, HandshakeError<S>>
64where
65 S: AsyncRead + AsyncWrite + Unpin,
66{
67 let mid_handshake = acceptor
68 .setup_accept(AsyncStreamBridge::new(stream))
69 .map_err(|err| HandshakeError(ssl::HandshakeError::SetupFailure(err)))?;
70
71 HandshakeFuture(Some(mid_handshake)).await
72}
73
74fn cvt<T>(r: io::Result<T>) -> Poll<io::Result<T>> {
75 match r {
76 Ok(v) => Poll::Ready(Ok(v)),
77 Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => Poll::Pending,
78 Err(e) => Poll::Ready(Err(e)),
79 }
80}
81
82pub struct SslStreamBuilder<S> {
84 inner: ssl::SslStreamBuilder<AsyncStreamBridge<S>>,
85}
86
87impl<S> SslStreamBuilder<S>
88where
89 S: AsyncRead + AsyncWrite + Unpin,
90{
91 pub fn new(ssl: ssl::Ssl, stream: S) -> Self {
93 Self {
94 inner: ssl::SslStreamBuilder::new(ssl, AsyncStreamBridge::new(stream)),
95 }
96 }
97
98 pub async fn accept(self) -> Result<SslStream<S>, HandshakeError<S>> {
100 let mid_handshake = self.inner.setup_accept();
101
102 HandshakeFuture(Some(mid_handshake)).await
103 }
104
105 pub async fn connect(self) -> Result<SslStream<S>, HandshakeError<S>> {
107 let mid_handshake = self.inner.setup_connect();
108
109 HandshakeFuture(Some(mid_handshake)).await
110 }
111}
112
113impl<S> SslStreamBuilder<S> {
114 #[must_use]
116 pub fn ssl(&self) -> &SslRef {
117 self.inner.ssl()
118 }
119
120 pub fn ssl_mut(&mut self) -> &mut SslRef {
122 self.inner.ssl_mut()
123 }
124}
125
126#[derive(Debug)]
134pub struct SslStream<S>(ssl::SslStream<AsyncStreamBridge<S>>);
135
136impl<S> SslStream<S> {
137 #[must_use]
139 pub fn ssl(&self) -> &SslRef {
140 self.0.ssl()
141 }
142
143 pub fn ssl_mut(&mut self) -> &mut SslRef {
145 self.0.ssl_mut()
146 }
147
148 #[must_use]
150 pub fn get_ref(&self) -> &S {
151 &self.0.get_ref().stream
152 }
153
154 pub fn get_mut(&mut self) -> &mut S {
156 &mut self.0.get_mut().stream
157 }
158
159 fn run_in_context<F, R>(&mut self, ctx: &mut Context<'_>, f: F) -> R
160 where
161 F: FnOnce(&mut ssl::SslStream<AsyncStreamBridge<S>>) -> R,
162 {
163 self.0.get_mut().set_waker(Some(ctx));
164
165 let result = f(&mut self.0);
166
167 self.0.get_mut().set_waker(None);
172
173 result
174 }
175}
176
177impl<S> SslStream<S>
178where
179 S: AsyncRead + AsyncWrite + Unpin,
180{
181 pub unsafe fn from_raw_parts(ssl: *mut ffi::SSL, stream: S) -> Self {
189 unsafe {
190 Self(ssl::SslStream::from_raw_parts(
191 ssl,
192 AsyncStreamBridge::new(stream),
193 ))
194 }
195 }
196}
197
198impl<S> AsyncRead for SslStream<S>
199where
200 S: AsyncRead + AsyncWrite + Unpin,
201{
202 fn poll_read(
203 mut self: Pin<&mut Self>,
204 ctx: &mut Context<'_>,
205 buf: &mut ReadBuf,
206 ) -> Poll<io::Result<()>> {
207 self.run_in_context(ctx, |s| {
208 match cvt(s.read_uninit(unsafe { buf.unfilled_mut() }))? {
210 Poll::Ready(nread) => {
211 unsafe {
212 buf.assume_init(nread);
213 }
214 buf.advance(nread);
215 Poll::Ready(Ok(()))
216 }
217 Poll::Pending => Poll::Pending,
218 }
219 })
220 }
221}
222
223impl<S> AsyncWrite for SslStream<S>
224where
225 S: AsyncRead + AsyncWrite + Unpin,
226{
227 fn poll_write(
228 mut self: Pin<&mut Self>,
229 ctx: &mut Context,
230 buf: &[u8],
231 ) -> Poll<io::Result<usize>> {
232 self.run_in_context(ctx, |s| cvt(s.write(buf)))
233 }
234
235 fn poll_flush(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll<io::Result<()>> {
236 self.run_in_context(ctx, |s| cvt(s.flush()))
237 }
238
239 fn poll_shutdown(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll<io::Result<()>> {
240 match self.run_in_context(ctx, |s| s.shutdown()) {
241 Ok(ShutdownResult::Sent | ShutdownResult::Received) => {}
242 Err(ref e) if e.code() == ErrorCode::ZERO_RETURN => {}
243 Err(ref e) if e.code() == ErrorCode::WANT_READ || e.code() == ErrorCode::WANT_WRITE => {
244 return Poll::Pending;
245 }
246 Err(e) => {
247 return Poll::Ready(Err(e.into_io_error().unwrap_or_else(io::Error::other)));
248 }
249 }
250
251 Pin::new(&mut self.0.get_mut().stream).poll_shutdown(ctx)
252 }
253}
254
255pub struct HandshakeError<S>(ssl::HandshakeError<AsyncStreamBridge<S>>);
257
258impl<S> HandshakeError<S> {
259 #[must_use]
261 pub fn ssl(&self) -> Option<&SslRef> {
262 match &self.0 {
263 ssl::HandshakeError::Failure(s) => Some(s.ssl()),
264 _ => None,
265 }
266 }
267
268 #[must_use]
270 pub fn into_source_stream(self) -> Option<S> {
271 match self.0 {
272 ssl::HandshakeError::Failure(s) => Some(s.into_source_stream().stream),
273 _ => None,
274 }
275 }
276
277 #[must_use]
279 pub fn as_source_stream(&self) -> Option<&S> {
280 match &self.0 {
281 ssl::HandshakeError::Failure(s) => Some(&s.get_ref().stream),
282 _ => None,
283 }
284 }
285
286 #[must_use]
288 pub fn code(&self) -> Option<ErrorCode> {
289 match &self.0 {
290 ssl::HandshakeError::Failure(s) => Some(s.error().code()),
291 _ => None,
292 }
293 }
294
295 #[must_use]
297 pub fn as_io_error(&self) -> Option<&io::Error> {
298 match &self.0 {
299 ssl::HandshakeError::Failure(s) => s.error().io_error(),
300 _ => None,
301 }
302 }
303}
304
305impl<S> fmt::Debug for HandshakeError<S>
306where
307 S: fmt::Debug,
308{
309 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
310 fmt::Debug::fmt(&self.0, fmt)
311 }
312}
313
314impl<S> fmt::Display for HandshakeError<S> {
315 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
316 fmt::Display::fmt(&self.0, fmt)
317 }
318}
319
320impl<S> Error for HandshakeError<S>
321where
322 S: fmt::Debug,
323{
324 fn source(&self) -> Option<&(dyn Error + 'static)> {
325 self.0.source()
326 }
327}
328
329pub struct HandshakeFuture<S>(Option<MidHandshakeSslStream<AsyncStreamBridge<S>>>);
333
334impl<S> Future for HandshakeFuture<S>
335where
336 S: AsyncRead + AsyncWrite + Unpin,
337{
338 type Output = Result<SslStream<S>, HandshakeError<S>>;
339
340 fn poll(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
341 let mut mid_handshake = self.0.take().expect("future polled after completion");
342
343 mid_handshake.get_mut().set_waker(Some(ctx));
344 mid_handshake
345 .ssl_mut()
346 .set_task_waker(Some(ctx.waker().clone()));
347
348 match mid_handshake.handshake() {
349 Ok(mut stream) => {
350 stream.get_mut().set_waker(None);
351 stream.ssl_mut().set_task_waker(None);
352
353 Poll::Ready(Ok(SslStream(stream)))
354 }
355 Err(ssl::HandshakeError::WouldBlock(mut mid_handshake)) => {
356 mid_handshake.get_mut().set_waker(None);
357 mid_handshake.ssl_mut().set_task_waker(None);
358
359 self.0 = Some(mid_handshake);
360
361 Poll::Pending
362 }
363 Err(ssl::HandshakeError::Failure(mut mid_handshake)) => {
364 mid_handshake.get_mut().set_waker(None);
365
366 Poll::Ready(Err(HandshakeError(ssl::HandshakeError::Failure(
367 mid_handshake,
368 ))))
369 }
370 Err(err @ ssl::HandshakeError::SetupFailure(_)) => {
371 Poll::Ready(Err(HandshakeError(err)))
372 }
373 }
374 }
375}