1 // Copyright (c) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 use core::pin::Pin;
15 use core::task::{Context, Poll};
16 use core::{future, ptr, slice};
17 use std::io::{self, Read, Write};
18
19 use crate::async_impl::ssl_stream::{check_io_to_poll, Wrapper};
20 use crate::util::c_openssl::error::ErrorStack;
21 use crate::util::c_openssl::ssl::{self, ShutdownResult, Ssl, SslErrorCode};
22 use crate::{AsyncRead, AsyncWrite, ReadBuf};
23
24 /// An asynchronous version of [`openssl::ssl::SslStream`].
25 #[derive(Debug)]
26 pub struct AsyncSslStream<S>(ssl::SslStream<Wrapper<S>>);
27
28 impl<S> AsyncSslStream<S> {
with_context<F, R>(self: Pin<&mut Self>, ctx: &mut Context<'_>, f: F) -> R where F: FnOnce(&mut ssl::SslStream<Wrapper<S>>) -> R,29 fn with_context<F, R>(self: Pin<&mut Self>, ctx: &mut Context<'_>, f: F) -> R
30 where
31 F: FnOnce(&mut ssl::SslStream<Wrapper<S>>) -> R,
32 {
33 // SAFETY: must guarantee that you will never move the data out of the
34 // mutable reference you receive.
35 let this = unsafe { self.get_unchecked_mut() };
36
37 // sets context, SslStream to R, reset 0.
38 this.0.get_mut().context = ctx as *mut _ as *mut ();
39 let r = f(&mut this.0);
40 this.0.get_mut().context = ptr::null_mut();
41 r
42 }
43
44 /// Returns a pinned mutable reference to the underlying stream.
get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut S>45 fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut S> {
46 // SAFETY:
47 unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0.get_mut().stream) }
48 }
49 }
50
51 impl<S> AsyncSslStream<S>
52 where
53 S: AsyncRead + AsyncWrite,
54 {
55 /// Like [`SslStream::new`](ssl::SslStream::new).
new(ssl: Ssl, stream: S) -> Result<Self, ErrorStack>56 pub(crate) fn new(ssl: Ssl, stream: S) -> Result<Self, ErrorStack> {
57 // This corresponds to `SSL_set_bio`.
58 ssl::SslStream::new_base(
59 ssl,
60 Wrapper {
61 stream,
62 context: ptr::null_mut(),
63 },
64 )
65 .map(AsyncSslStream)
66 }
67
68 /// Like [`SslStream::connect`](ssl::SslStream::connect).
poll_connect(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), ssl::SslError>>69 fn poll_connect(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), ssl::SslError>> {
70 self.with_context(cx, |s| check_result_to_poll(s.connect()))
71 }
72
73 /// A convenience method wrapping [`poll_connect`](Self::poll_connect).
connect(mut self: Pin<&mut Self>) -> Result<(), ssl::SslError>74 pub(crate) async fn connect(mut self: Pin<&mut Self>) -> Result<(), ssl::SslError> {
75 future::poll_fn(|cx| self.as_mut().poll_connect(cx)).await
76 }
77 }
78
79 impl<S> AsyncRead for AsyncSslStream<S>
80 where
81 S: AsyncRead + AsyncWrite,
82 {
83 // wrap read.
poll_read( self: Pin<&mut Self>, ctx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>>84 fn poll_read(
85 self: Pin<&mut Self>,
86 ctx: &mut Context<'_>,
87 buf: &mut ReadBuf<'_>,
88 ) -> Poll<io::Result<()>> {
89 // set async func
90 self.with_context(ctx, |s| {
91 let slice = unsafe {
92 let buf = buf.unfilled_mut();
93 slice::from_raw_parts_mut(buf.as_mut_ptr().cast::<u8>(), buf.len())
94 };
95 match check_io_to_poll(s.read(slice))? {
96 Poll::Ready(len) => {
97 #[cfg(feature = "tokio_base")]
98 unsafe {
99 buf.assume_init(len);
100 }
101 #[cfg(feature = "ylong_base")]
102 buf.assume_init(len);
103
104 buf.advance(len);
105 Poll::Ready(Ok(()))
106 }
107 Poll::Pending => Poll::Pending,
108 }
109 })
110 }
111 }
112
113 impl<S> AsyncWrite for AsyncSslStream<S>
114 where
115 S: AsyncRead + AsyncWrite,
116 {
poll_write(self: Pin<&mut Self>, ctx: &mut Context, buf: &[u8]) -> Poll<io::Result<usize>>117 fn poll_write(self: Pin<&mut Self>, ctx: &mut Context, buf: &[u8]) -> Poll<io::Result<usize>> {
118 self.with_context(ctx, |s| check_io_to_poll(s.write(buf)))
119 }
120
poll_flush(self: Pin<&mut Self>, ctx: &mut Context) -> Poll<io::Result<()>>121 fn poll_flush(self: Pin<&mut Self>, ctx: &mut Context) -> Poll<io::Result<()>> {
122 self.with_context(ctx, |s| check_io_to_poll(s.flush()))
123 }
124
poll_shutdown(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll<io::Result<()>>125 fn poll_shutdown(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll<io::Result<()>> {
126 // Shuts down the session.
127 match self.as_mut().with_context(ctx, |s| s.shutdown()) {
128 // Sends a close notify message to the peer, after which `ShutdownResult::Sent` is
129 // returned. Awaits the receipt of a close notify message from the peer,
130 // after which `ShutdownResult::Received` is returned.
131 Ok(ShutdownResult::Sent) | Ok(ShutdownResult::Received) => {}
132 // The SSL session has been closed.
133 Err(ref e) if e.code() == SslErrorCode::ZERO_RETURN => {}
134 // When the underlying BIO could not satisfy the needs of SSL_shutdown() to continue the
135 // handshake
136 Err(ref e)
137 if e.code() == SslErrorCode::WANT_READ || e.code() == SslErrorCode::WANT_WRITE =>
138 {
139 return Poll::Pending;
140 }
141 // Really error.
142 Err(e) => {
143 return Poll::Ready(Err(e
144 .into_io_error()
145 .unwrap_or_else(|e| io::Error::new(io::ErrorKind::Other, e))));
146 }
147 }
148 // Returns success when the I/O connection has completely shut down.
149 self.get_pin_mut().poll_shutdown(ctx)
150 }
151 }
152
153 /// Checks `ssl::Error`.
check_result_to_poll<T>(r: Result<T, ssl::SslError>) -> Poll<Result<T, ssl::SslError>>154 fn check_result_to_poll<T>(r: Result<T, ssl::SslError>) -> Poll<Result<T, ssl::SslError>> {
155 match r {
156 Ok(t) => Poll::Ready(Ok(t)),
157 Err(e) => match e.code() {
158 SslErrorCode::WANT_READ | SslErrorCode::WANT_WRITE => Poll::Pending,
159 _ => Poll::Ready(Err(e)),
160 },
161 }
162 }
163