├── .github ├── dependabot.yml └── workflows │ ├── ci.yml │ └── rustfmt.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── build.rs ├── src ├── lib.rs └── test.rs └── tests ├── cert.pem └── key.pem /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "13:00" 8 | open-pull-requests-limit: 10 9 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - master 7 | push: 8 | branches: 9 | - master 10 | 11 | env: 12 | RUSTFLAGS: -D warnings 13 | RUST_BACKTRACE: 1 14 | 15 | jobs: 16 | test: 17 | name: test 18 | runs-on: ubuntu-latest 19 | steps: 20 | - uses: actions/checkout@v4 21 | - name: Install Rust 22 | run: | 23 | rustup update --no-self-update stable 24 | rustup default stable 25 | - name: Get Rust version 26 | id: rust-version 27 | run: echo "::set-output name=version:$(rustc --version)" 28 | - name: Index cache 29 | uses: actions/cache@v3 30 | with: 31 | path: ~/.cargo/registry/index 32 | key: index-${{ github.run_id }} 33 | restore-keys: | 34 | index- 35 | - name: Create lockfile 36 | run: cargo generate-lockfile 37 | - name: Registry cache 38 | uses: actions/cache@v3 39 | with: 40 | path: ~/.cargo/registry/cache 41 | key: registry-${{ hashFiles('Cargo.lock') }} 42 | - name: Fetch dependencies 43 | run: cargo fetch 44 | - name: Target cache 45 | uses: actions/cache@v3 46 | with: 47 | path: target 48 | key: target-${{ steps.rust-version.outputs.version }}-${{ hashFiles('Cargo.lock') }} 49 | - name: Test 50 | run: cargo test 51 | -------------------------------------------------------------------------------- /.github/workflows/rustfmt.yml: -------------------------------------------------------------------------------- 1 | name: Enforce Rust formatting 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | rustfmt: 11 | name: rustfmt 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | - uses: sfackler/actions/rustup@master 16 | - uses: sfackler/actions/rustfmt@master 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | .idea/ 4 | *.iml 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tokio-openssl" 3 | version = "0.6.5" 4 | authors = ["Alex Crichton "] 5 | license = "MIT/Apache-2.0" 6 | edition = "2018" 7 | repository = "https://github.com/tokio-rs/tokio-openssl" 8 | description = """ 9 | An implementation of SSL streams for Tokio backed by OpenSSL 10 | """ 11 | 12 | [dependencies] 13 | openssl = "0.10.61" 14 | openssl-sys = "0.9" 15 | tokio = "1.0" 16 | 17 | [dev-dependencies] 18 | futures-util = { version = "0.3", default-features = false } 19 | tokio = { version = "1.0", features = ["full"] } 20 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2016 Tokio contributors 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 Tokio contributors 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tokio-openssl 2 | 3 | An implementation of SSL streams for Tokio built on top of the [`openssl` crate] 4 | 5 | [Documentation](https://docs.rs/tokio-openssl) 6 | 7 | [`openssl` crate]: https://github.com/sfackler/rust-openssl 8 | 9 | # License 10 | 11 | This project is licensed under either of 12 | 13 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or 14 | http://www.apache.org/licenses/LICENSE-2.0) 15 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or 16 | http://opensource.org/licenses/MIT) 17 | 18 | at your option. 19 | 20 | ### Contribution 21 | 22 | Unless you explicitly state otherwise, any contribution intentionally submitted 23 | for inclusion in tokio-openssl by you, as defined in the Apache-2.0 license, 24 | shall be dual licensed as above, without any additional terms or conditions. 25 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::unusual_byte_groupings)] 2 | use std::env; 3 | 4 | fn main() { 5 | println!("cargo:rustc-check-cfg=cfg(ossl111)"); 6 | 7 | if let Ok(version) = env::var("DEP_OPENSSL_VERSION_NUMBER") { 8 | let version = u64::from_str_radix(&version, 16).unwrap(); 9 | 10 | if version >= 0x1_01_01_00_0 { 11 | println!("cargo:rustc-cfg=ossl111"); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Async TLS streams backed by OpenSSL. 2 | //! 3 | //! This crate provides a wrapper around the [`openssl`] crate's [`SslStream`](ssl::SslStream) type 4 | //! that works with with [`tokio`]'s [`AsyncRead`] and [`AsyncWrite`] traits rather than std's 5 | //! blocking [`Read`] and [`Write`] traits. 6 | #![warn(missing_docs)] 7 | 8 | use openssl::error::ErrorStack; 9 | use openssl::ssl::{self, ErrorCode, ShutdownResult, Ssl, SslRef}; 10 | use std::fmt; 11 | use std::future; 12 | use std::io::{self, Read, Write}; 13 | use std::pin::Pin; 14 | use std::task::{Context, Poll}; 15 | use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; 16 | 17 | #[cfg(test)] 18 | mod test; 19 | 20 | struct StreamWrapper { 21 | stream: S, 22 | context: usize, 23 | } 24 | 25 | impl fmt::Debug for StreamWrapper 26 | where 27 | S: fmt::Debug, 28 | { 29 | fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { 30 | fmt::Debug::fmt(&self.stream, fmt) 31 | } 32 | } 33 | 34 | impl StreamWrapper { 35 | /// # Safety 36 | /// 37 | /// Must be called with `context` set to a valid pointer to a live `Context` object, and the 38 | /// wrapper must be pinned in memory. 39 | unsafe fn parts(&mut self) -> (Pin<&mut S>, &mut Context<'_>) { 40 | debug_assert_ne!(self.context, 0); 41 | let stream = Pin::new_unchecked(&mut self.stream); 42 | let context = &mut *(self.context as *mut _); 43 | (stream, context) 44 | } 45 | } 46 | 47 | impl Read for StreamWrapper 48 | where 49 | S: AsyncRead, 50 | { 51 | fn read(&mut self, buf: &mut [u8]) -> io::Result { 52 | let (stream, cx) = unsafe { self.parts() }; 53 | let mut buf = ReadBuf::new(buf); 54 | match stream.poll_read(cx, &mut buf)? { 55 | Poll::Ready(()) => Ok(buf.filled().len()), 56 | Poll::Pending => Err(io::Error::from(io::ErrorKind::WouldBlock)), 57 | } 58 | } 59 | } 60 | 61 | impl Write for StreamWrapper 62 | where 63 | S: AsyncWrite, 64 | { 65 | fn write(&mut self, buf: &[u8]) -> io::Result { 66 | let (stream, cx) = unsafe { self.parts() }; 67 | match stream.poll_write(cx, buf) { 68 | Poll::Ready(r) => r, 69 | Poll::Pending => Err(io::Error::from(io::ErrorKind::WouldBlock)), 70 | } 71 | } 72 | 73 | fn flush(&mut self) -> io::Result<()> { 74 | let (stream, cx) = unsafe { self.parts() }; 75 | match stream.poll_flush(cx) { 76 | Poll::Ready(r) => r, 77 | Poll::Pending => Err(io::Error::from(io::ErrorKind::WouldBlock)), 78 | } 79 | } 80 | } 81 | 82 | fn cvt(r: io::Result) -> Poll> { 83 | match r { 84 | Ok(v) => Poll::Ready(Ok(v)), 85 | Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => Poll::Pending, 86 | Err(e) => Poll::Ready(Err(e)), 87 | } 88 | } 89 | 90 | fn cvt_ossl(r: Result) -> Poll> { 91 | match r { 92 | Ok(v) => Poll::Ready(Ok(v)), 93 | Err(e) => match e.code() { 94 | ErrorCode::WANT_READ | ErrorCode::WANT_WRITE => Poll::Pending, 95 | _ => Poll::Ready(Err(e)), 96 | }, 97 | } 98 | } 99 | 100 | /// An asynchronous version of [`openssl::ssl::SslStream`]. 101 | #[derive(Debug)] 102 | pub struct SslStream(ssl::SslStream>); 103 | 104 | impl SslStream 105 | where 106 | S: AsyncRead + AsyncWrite, 107 | { 108 | /// Like [`SslStream::new`](ssl::SslStream::new). 109 | pub fn new(ssl: Ssl, stream: S) -> Result { 110 | ssl::SslStream::new(ssl, StreamWrapper { stream, context: 0 }).map(SslStream) 111 | } 112 | 113 | /// Like [`SslStream::connect`](ssl::SslStream::connect). 114 | pub fn poll_connect( 115 | self: Pin<&mut Self>, 116 | cx: &mut Context<'_>, 117 | ) -> Poll> { 118 | self.with_context(cx, |s| cvt_ossl(s.connect())) 119 | } 120 | 121 | /// A convenience method wrapping [`poll_connect`](Self::poll_connect). 122 | pub async fn connect(mut self: Pin<&mut Self>) -> Result<(), ssl::Error> { 123 | future::poll_fn(|cx| self.as_mut().poll_connect(cx)).await 124 | } 125 | 126 | /// Like [`SslStream::accept`](ssl::SslStream::accept). 127 | pub fn poll_accept(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 128 | self.with_context(cx, |s| cvt_ossl(s.accept())) 129 | } 130 | 131 | /// A convenience method wrapping [`poll_accept`](Self::poll_accept). 132 | pub async fn accept(mut self: Pin<&mut Self>) -> Result<(), ssl::Error> { 133 | future::poll_fn(|cx| self.as_mut().poll_accept(cx)).await 134 | } 135 | 136 | /// Like [`SslStream::do_handshake`](ssl::SslStream::do_handshake). 137 | pub fn poll_do_handshake( 138 | self: Pin<&mut Self>, 139 | cx: &mut Context<'_>, 140 | ) -> Poll> { 141 | self.with_context(cx, |s| cvt_ossl(s.do_handshake())) 142 | } 143 | 144 | /// A convenience method wrapping [`poll_do_handshake`](Self::poll_do_handshake). 145 | pub async fn do_handshake(mut self: Pin<&mut Self>) -> Result<(), ssl::Error> { 146 | future::poll_fn(|cx| self.as_mut().poll_do_handshake(cx)).await 147 | } 148 | 149 | /// Like [`SslStream::ssl_peek`](ssl::SslStream::ssl_peek). 150 | pub fn poll_peek( 151 | self: Pin<&mut Self>, 152 | cx: &mut Context<'_>, 153 | buf: &mut [u8], 154 | ) -> Poll> { 155 | self.with_context(cx, |s| cvt_ossl(s.ssl_peek(buf))) 156 | } 157 | 158 | /// A convenience method wrapping [`poll_peek`](Self::poll_peek). 159 | pub async fn peek(mut self: Pin<&mut Self>, buf: &mut [u8]) -> Result { 160 | future::poll_fn(|cx| self.as_mut().poll_peek(cx, buf)).await 161 | } 162 | 163 | /// Like [`SslStream::read_early_data`](ssl::SslStream::read_early_data). 164 | #[cfg(ossl111)] 165 | pub fn poll_read_early_data( 166 | self: Pin<&mut Self>, 167 | cx: &mut Context<'_>, 168 | buf: &mut [u8], 169 | ) -> Poll> { 170 | self.with_context(cx, |s| cvt_ossl(s.read_early_data(buf))) 171 | } 172 | 173 | /// A convenience method wrapping [`poll_read_early_data`](Self::poll_read_early_data). 174 | #[cfg(ossl111)] 175 | pub async fn read_early_data( 176 | mut self: Pin<&mut Self>, 177 | buf: &mut [u8], 178 | ) -> Result { 179 | future::poll_fn(|cx| self.as_mut().poll_read_early_data(cx, buf)).await 180 | } 181 | 182 | /// Like [`SslStream::write_early_data`](ssl::SslStream::write_early_data). 183 | #[cfg(ossl111)] 184 | pub fn poll_write_early_data( 185 | self: Pin<&mut Self>, 186 | cx: &mut Context<'_>, 187 | buf: &[u8], 188 | ) -> Poll> { 189 | self.with_context(cx, |s| cvt_ossl(s.write_early_data(buf))) 190 | } 191 | 192 | /// A convenience method wrapping [`poll_write_early_data`](Self::poll_write_early_data). 193 | #[cfg(ossl111)] 194 | pub async fn write_early_data( 195 | mut self: Pin<&mut Self>, 196 | buf: &[u8], 197 | ) -> Result { 198 | future::poll_fn(|cx| self.as_mut().poll_write_early_data(cx, buf)).await 199 | } 200 | } 201 | 202 | impl SslStream { 203 | /// Returns a shared reference to the `Ssl` object associated with this stream. 204 | pub fn ssl(&self) -> &SslRef { 205 | self.0.ssl() 206 | } 207 | 208 | /// Returns a shared reference to the underlying stream. 209 | pub fn get_ref(&self) -> &S { 210 | &self.0.get_ref().stream 211 | } 212 | 213 | /// Returns a mutable reference to the underlying stream. 214 | pub fn get_mut(&mut self) -> &mut S { 215 | &mut self.0.get_mut().stream 216 | } 217 | 218 | /// Returns a pinned mutable reference to the underlying stream. 219 | pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut S> { 220 | unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0.get_mut().stream) } 221 | } 222 | 223 | fn with_context(self: Pin<&mut Self>, ctx: &mut Context<'_>, f: F) -> R 224 | where 225 | F: FnOnce(&mut ssl::SslStream>) -> R, 226 | { 227 | let this = unsafe { self.get_unchecked_mut() }; 228 | this.0.get_mut().context = ctx as *mut _ as usize; 229 | let r = f(&mut this.0); 230 | this.0.get_mut().context = 0; 231 | r 232 | } 233 | } 234 | 235 | impl AsyncRead for SslStream 236 | where 237 | S: AsyncRead + AsyncWrite, 238 | { 239 | fn poll_read( 240 | self: Pin<&mut Self>, 241 | ctx: &mut Context<'_>, 242 | buf: &mut ReadBuf<'_>, 243 | ) -> Poll> { 244 | self.with_context(ctx, |s| { 245 | // SAFETY: read_uninit does not de-initialize the buffer. 246 | match cvt(s.read_uninit(unsafe { buf.unfilled_mut() }))? { 247 | Poll::Ready(nread) => { 248 | // SAFETY: read_uninit guarantees that nread bytes have been initialized. 249 | unsafe { buf.assume_init(nread) }; 250 | buf.advance(nread); 251 | Poll::Ready(Ok(())) 252 | } 253 | Poll::Pending => Poll::Pending, 254 | } 255 | }) 256 | } 257 | } 258 | 259 | impl AsyncWrite for SslStream 260 | where 261 | S: AsyncRead + AsyncWrite, 262 | { 263 | fn poll_write(self: Pin<&mut Self>, ctx: &mut Context, buf: &[u8]) -> Poll> { 264 | self.with_context(ctx, |s| cvt(s.write(buf))) 265 | } 266 | 267 | fn poll_flush(self: Pin<&mut Self>, ctx: &mut Context) -> Poll> { 268 | self.with_context(ctx, |s| cvt(s.flush())) 269 | } 270 | 271 | fn poll_shutdown(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll> { 272 | match self.as_mut().with_context(ctx, |s| s.shutdown()) { 273 | Ok(ShutdownResult::Sent) | Ok(ShutdownResult::Received) => {} 274 | Err(ref e) if e.code() == ErrorCode::ZERO_RETURN => {} 275 | Err(ref e) if e.code() == ErrorCode::WANT_READ || e.code() == ErrorCode::WANT_WRITE => { 276 | return Poll::Pending; 277 | } 278 | Err(e) => { 279 | return Poll::Ready(Err(e 280 | .into_io_error() 281 | .unwrap_or_else(|e| io::Error::new(io::ErrorKind::Other, e)))); 282 | } 283 | } 284 | 285 | self.get_pin_mut().poll_shutdown(ctx) 286 | } 287 | } 288 | -------------------------------------------------------------------------------- /src/test.rs: -------------------------------------------------------------------------------- 1 | use crate::SslStream; 2 | use futures_util::future; 3 | use openssl::ssl::{Ssl, SslAcceptor, SslConnector, SslFiletype, SslMethod}; 4 | use std::net::ToSocketAddrs; 5 | use std::pin::Pin; 6 | use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt}; 7 | use tokio::net::{TcpListener, TcpStream}; 8 | 9 | #[tokio::test] 10 | async fn google() { 11 | let addr = "google.com:443".to_socket_addrs().unwrap().next().unwrap(); 12 | let stream = TcpStream::connect(&addr).await.unwrap(); 13 | 14 | let ssl = SslConnector::builder(SslMethod::tls()) 15 | .unwrap() 16 | .build() 17 | .configure() 18 | .unwrap() 19 | .into_ssl("google.com") 20 | .unwrap(); 21 | let mut stream = SslStream::new(ssl, stream).unwrap(); 22 | 23 | Pin::new(&mut stream).connect().await.unwrap(); 24 | 25 | stream.write_all(b"GET / HTTP/1.0\r\n\r\n").await.unwrap(); 26 | 27 | let mut buf = vec![]; 28 | stream.read_to_end(&mut buf).await.unwrap(); 29 | let response = String::from_utf8_lossy(&buf); 30 | let response = response.trim_end(); 31 | 32 | // any response code is fine 33 | assert!(response.starts_with("HTTP/1.0 ")); 34 | assert!(response.ends_with("") || response.ends_with("")); 35 | } 36 | 37 | #[tokio::test] 38 | async fn server() { 39 | let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); 40 | let addr = listener.local_addr().unwrap(); 41 | 42 | let server = async move { 43 | let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); 44 | acceptor 45 | .set_private_key_file("tests/key.pem", SslFiletype::PEM) 46 | .unwrap(); 47 | acceptor 48 | .set_certificate_chain_file("tests/cert.pem") 49 | .unwrap(); 50 | let acceptor = acceptor.build(); 51 | 52 | let ssl = Ssl::new(acceptor.context()).unwrap(); 53 | let stream = listener.accept().await.unwrap().0; 54 | let mut stream = SslStream::new(ssl, stream).unwrap(); 55 | 56 | Pin::new(&mut stream).accept().await.unwrap(); 57 | 58 | let mut buf = [0; 4]; 59 | stream.read_exact(&mut buf).await.unwrap(); 60 | assert_eq!(&buf, b"asdf"); 61 | 62 | stream.write_all(b"jkl;").await.unwrap(); 63 | 64 | future::poll_fn(|ctx| Pin::new(&mut stream).poll_shutdown(ctx)) 65 | .await 66 | .unwrap() 67 | }; 68 | 69 | let client = async { 70 | let mut connector = SslConnector::builder(SslMethod::tls()).unwrap(); 71 | connector.set_ca_file("tests/cert.pem").unwrap(); 72 | let ssl = connector 73 | .build() 74 | .configure() 75 | .unwrap() 76 | .into_ssl("localhost") 77 | .unwrap(); 78 | 79 | let stream = TcpStream::connect(&addr).await.unwrap(); 80 | let mut stream = SslStream::new(ssl, stream).unwrap(); 81 | 82 | Pin::new(&mut stream).connect().await.unwrap(); 83 | 84 | stream.write_all(b"asdf").await.unwrap(); 85 | 86 | let mut buf = vec![]; 87 | stream.read_to_end(&mut buf).await.unwrap(); 88 | assert_eq!(buf, b"jkl;"); 89 | }; 90 | 91 | future::join(server, client).await; 92 | } 93 | -------------------------------------------------------------------------------- /tests/cert.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDhTCCAm2gAwIBAgIJALClJS+cq+ykMA0GCSqGSIb3DQEBCwUAMFkxCzAJBgNV 3 | BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX 4 | aWRnaXRzIFB0eSBMdGQxEjAQBgNVBAMMCWxvY2FsaG9zdDAeFw0xNjExMjgwNTU5 5 | MjNaFw0yNjExMjYwNTU5MjNaMFkxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21l 6 | LVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQxEjAQBgNV 7 | BAMMCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL4k 8 | A0mghV17MPi033tKh1IK4pM6zpzHFrgi2smU97O/kxvSbNnDoZHEdqq3AtRcjELg 9 | HeKTd02jyAHxGoRTAVORIp0p4LCCvlR7EnHH78e3vIq3lkLe5uqyujnx2NJJIrIX 10 | r5Y+Z3QuMUSAix6GreAb19KcTZG82igvh4dOQP/pmlqQsyrPpioLy50O2NuBqU5Q 11 | xyevFRHsWfe3M7ayzJBVwMpDJxg3saOETXgzMzfKtrj2Pw0mfcHQMtsPv7z85ug0 12 | yyd9iXwwLYx2RqZ6epChsWuY2zj7Zfcis3DzbsrW8/J758KNkjZVWS9aJmDGsT3R 13 | xRlVDnIeow/SWi5qtqECAwEAAaNQME4wHQYDVR0OBBYEFNU1F6I+C06y6rN1yjn0 14 | i/ARufw1MB8GA1UdIwQYMBaAFNU1F6I+C06y6rN1yjn0i/ARufw1MAwGA1UdEwQF 15 | MAMBAf8wDQYJKoZIhvcNAQELBQADggEBACvFmTY+QSrc9EIAtuGk20L4OHrkOoRv 16 | veMIu3PAGbrzjE0rRC1qeLqkqudlWCk+xE6nNe90tB0qyY8AOgj68K2OplrJIhqt 17 | rxJ/Ohtbepwi53Q5npRoib6f9aL+FuT0hnVtVon2ngWRizSdH/CY7vCWuJjTtlon 18 | 3J8TGPA1cnj8FtEEfF3ISd0/XCE2oar875FOscf7S0eLnORbuunCVU/RaNn25h/r 19 | 9EhvoaPZ6cSZpt7UliMkSt6b07/A2SwU5C19BS1XoqGH02P9OV0pmuJn7N/fOGer 20 | aVbDiPpb+UAUHFUSyu32iK6T2/6OuJS7MQ1cI2biB2SWgWNBTmhRF1s= 21 | -----END CERTIFICATE----- 22 | -------------------------------------------------------------------------------- /tests/key.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC+JANJoIVdezD4 3 | tN97SodSCuKTOs6cxxa4ItrJlPezv5Mb0mzZw6GRxHaqtwLUXIxC4B3ik3dNo8gB 4 | 8RqEUwFTkSKdKeCwgr5UexJxx+/Ht7yKt5ZC3ubqsro58djSSSKyF6+WPmd0LjFE 5 | gIsehq3gG9fSnE2RvNooL4eHTkD/6ZpakLMqz6YqC8udDtjbgalOUMcnrxUR7Fn3 6 | tzO2ssyQVcDKQycYN7GjhE14MzM3yra49j8NJn3B0DLbD7+8/OboNMsnfYl8MC2M 7 | dkamenqQobFrmNs4+2X3IrNw827K1vPye+fCjZI2VVkvWiZgxrE90cUZVQ5yHqMP 8 | 0louarahAgMBAAECggEAd08brQCHjs/1O6orLS7n2IgyAhZ9fQzD6ckdJi5Oe8Cz 9 | K1sPqFlEMbZoi9iIcv6bmH8O4ZSM4O/rWaSTcgKvq2M/qASWE8wGZ/ZN7Y16nQRi 10 | z1xBcjZyCUUa668g0VrI5Z1NNWZ0/gbaLVTHduEli6GM/H/NgKxS67JfRXzJ9onl 11 | d6vrK+xmeHyA7QSOieEDettaNCvm+HjU8mmOb4F1pCNZktDrch5rI8EzQlmFQuq4 12 | y50YLRZGSlK1QLjzMnT//oaP7mHjN/inzZTHBvTzhU2OjcjzEW7l4ry224Sdu/eH 13 | lhEnNk2eq+mH/yESkn3sJcmH4uYIXh8Dyvcy/uVkPQKBgQDzSC89qxT4sls9n0sL 14 | 0DfVhq1D7kEXggD/4wNA714N24N/NWi5BYUDZVh9Kxqy9SuWlFYg1L1ZNZHB02aV 15 | GJdEiFMFgRea2E5NHnhWop+qYPq5N9jD72MHmz/6swX9VGi1p5DqjzK2hWMgoih9 16 | 4ky1zxMw+P+aDaQ6xwZF1nr+mwKBgQDIFKTvaJYjqQ/lzRMIPLA3sg6RQ+Mqwt/C 17 | BZ9Oc3DGtuglV8F73i7ML2Ptg0GtVZo3NJgGzMerpNvEoc1pDCuZkzSYitcYysQQ 18 | wsailMQFCv9jJ9g28lSGKlEPYhcLejH8ZRi8jH0fObHIvgr7komNvvPIDFnw/uR8 19 | WsgrloD1cwKBgAdlAkqVkKWehjdxSA6r3YaX+Vw/OatFQFKGy+qFXA5/xZdwQCaf 20 | jFN2GSJ01PLrkM+a4qNM1BSKFEwX6N5PSQnEOwHH0rfaK0cczfuUJdY/7F8E24nZ 21 | FOF+TouINX5lumkLFtSKVbhGhaTQSPrKjhpYmPS8HMjJ8Vv4ALDOvB5RAoGBAJAS 22 | RX3bCpmdCESKOdUplh5UyaaSgsZs0qCsWb0s5R1B4cHaAgnGwF3pFgSWCjndNRHh 23 | fkMPPAv9xv49IGMvD0ojtLDO8Pn6L9p91niFtOyIscNdkpRmRLTjTcFM+ZkbIVlE 24 | Ft7WLtbIPZt2NQRXzVLTGEmJk040zKQ63n58flm/AoGBAKt97WLeHB9S/q0dpEGX 25 | Qk+1BXRAH0/4wK9lNrSeaw+npFr8rNN9K3sIBC/XnOwhT+wbKBpOoBT3PNHbNxVr 26 | EPPQ/pPmZ1TcHc7bszJnZon2S2PFJRDN4601X1/eFoTvakBnLlt1096paaolSmCG 27 | nYED9qXuh2VzUU1GgcqPXgf/ 28 | -----END PRIVATE KEY----- 29 | --------------------------------------------------------------------------------