├── .github ├── dependabot.yml └── workflows │ ├── ci.yml │ └── release.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── LICENSE-THIRD-PARTY ├── README.md ├── examples ├── client │ ├── Cargo.toml │ └── src │ │ └── main.rs └── server │ ├── Cargo.toml │ └── src │ └── main.rs ├── src ├── client.rs ├── common │ ├── handshake.rs │ ├── mod.rs │ └── test_stream.rs ├── lib.rs └── server.rs └── tests ├── badssl.rs ├── early-data.rs ├── end.cert ├── end.chain ├── end.rsa ├── test.rs └── utils.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: / 5 | schedule: 6 | interval: weekly 7 | commit-message: 8 | prefix: '' 9 | labels: [] 10 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | permissions: 4 | contents: read 5 | 6 | on: 7 | pull_request: 8 | push: 9 | branches: 10 | - master 11 | schedule: 12 | - cron: '0 2 * * 0' 13 | 14 | env: 15 | CARGO_INCREMENTAL: 0 16 | CARGO_NET_GIT_FETCH_WITH_CLI: true 17 | CARGO_NET_RETRY: 10 18 | CARGO_TERM_COLOR: always 19 | RUST_BACKTRACE: 1 20 | RUSTFLAGS: -D warnings -A deprecated 21 | RUSTDOCFLAGS: -D warnings 22 | RUSTUP_MAX_RETRIES: 10 23 | 24 | defaults: 25 | run: 26 | shell: bash 27 | 28 | jobs: 29 | test: 30 | runs-on: ${{ matrix.os }} 31 | strategy: 32 | fail-fast: false 33 | matrix: 34 | os: [ubuntu-latest] 35 | rust: [nightly, beta, stable] 36 | steps: 37 | - uses: actions/checkout@v4 38 | - name: Install Rust 39 | run: rustup update ${{ matrix.rust }} && rustup default ${{ matrix.rust }} 40 | - run: cargo build --all --all-features --all-targets 41 | - name: Run cargo check (without dev-dependencies to catch missing feature flags) 42 | if: startsWith(matrix.rust, 'nightly') 43 | run: cargo check -Z features=dev_dep 44 | - run: cargo test 45 | 46 | msrv: 47 | runs-on: ubuntu-latest 48 | steps: 49 | - uses: actions/checkout@v4 50 | - uses: taiki-e/install-action@cargo-hack 51 | - run: cargo hack build --workspace --no-private --no-dev-deps --rust-version 52 | 53 | clippy: 54 | runs-on: ubuntu-latest 55 | steps: 56 | - uses: actions/checkout@v4 57 | - name: Install Rust 58 | run: rustup update stable 59 | - run: cargo clippy --all-features 60 | 61 | fmt: 62 | runs-on: ubuntu-latest 63 | steps: 64 | - uses: actions/checkout@v4 65 | - name: Install Rust 66 | run: rustup update stable 67 | - run: cargo fmt --all --check 68 | 69 | security_audit: 70 | permissions: 71 | checks: write 72 | contents: read 73 | issues: write 74 | runs-on: ubuntu-latest 75 | steps: 76 | - uses: actions/checkout@v4 77 | # https://github.com/rustsec/audit-check/issues/2 78 | - uses: rustsec/audit-check@master 79 | with: 80 | token: ${{ secrets.GITHUB_TOKEN }} 81 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | permissions: 4 | contents: write 5 | 6 | on: 7 | push: 8 | tags: 9 | - v[0-9]+.* 10 | 11 | jobs: 12 | create-release: 13 | if: github.repository_owner == 'smol-rs' 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v4 17 | - uses: taiki-e/create-gh-release-action@v1 18 | with: 19 | changelog: CHANGELOG.md 20 | branch: master 21 | env: 22 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Version 0.4.2 2 | 3 | - This crate is now deprecated in favor of [futures-rustls](https://crates.io/crates/futures-rustls). 4 | 5 | # Version 0.4.1 6 | 7 | - Add `smol-rs` logo to docs. (#23) 8 | 9 | # Version 0.4.0 10 | 11 | - **Breaking:** Update rustls to 0.21. (#14) 12 | - **Breaking::** Remove webpki from the public API. (#15, #17) 13 | 14 | # Version 0.3.0 15 | 16 | - Update rustls to 0.20. (#9) 17 | 18 | # Version 0.2.0 19 | 20 | - Update rustls to 0.19. 21 | 22 | # Version 0.1.2 23 | 24 | - Expose feature flags from rustls. 25 | 26 | # Version 0.1.1 27 | 28 | - Add more info to Cargo.toml 29 | 30 | # Version 0.1.0 31 | 32 | - Initial version 33 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "async-rustls" 3 | version = "0.4.2" 4 | authors = [ 5 | "Alex Crichton ", 6 | "quininer kel ", 7 | "Stjepan Glavina ", 8 | "John Nunley ", 9 | ] 10 | license = "Apache-2.0 OR MIT" 11 | repository = "https://github.com/smol-rs/async-rustls" 12 | homepage = "https://github.com/smol-rs/async-rustls" 13 | documentation = "https://docs.rs/async-rustls" 14 | readme = "README.md" 15 | description = "Asynchronous TLS/SSL streams using Rustls." 16 | categories = ["asynchronous", "cryptography", "network-programming"] 17 | edition = "2021" 18 | rust-version = "1.61" 19 | 20 | [workspace] 21 | resolver = "2" 22 | members = ["examples/client", "examples/server"] 23 | 24 | [dependencies] 25 | futures-io = "0.3.24" 26 | rustls = { version = "0.21", default-features = false } 27 | 28 | [features] 29 | default = ["logging", "tls12"] 30 | dangerous_configuration = ["rustls/dangerous_configuration"] 31 | early-data = [] 32 | logging = ["rustls/logging"] 33 | tls12 = ["rustls/tls12"] 34 | quic = ["rustls/quic"] 35 | 36 | [dev-dependencies] 37 | futures-util = "0.3.1" 38 | lazy_static = "1" 39 | once_cell = "1.14" 40 | rustls-pemfile = "1" 41 | rustls-webpki = "0.101" 42 | smol = "2.0" 43 | webpki-roots = "0.25" 44 | -------------------------------------------------------------------------------- /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 [yyyy] [name of copyright owner] 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 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /LICENSE-THIRD-PARTY: -------------------------------------------------------------------------------- 1 | =============================================================================== 2 | 3 | Copyright (c) 2016 Alex Crichton 4 | Copyright (c) 2017 quininer kel 5 | Copyright (c) 2019 Tokio Contributors 6 | 7 | Licensed under the Apache License, Version 2.0 (the "License"); 8 | you may not use this file except in compliance with the License. 9 | You may obtain a copy of the License at 10 | 11 | http://www.apache.org/licenses/LICENSE-2.0 12 | 13 | Unless required by applicable law or agreed to in writing, software 14 | distributed under the License is distributed on an "AS IS" BASIS, 15 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | See the License for the specific language governing permissions and 17 | limitations under the License. 18 | 19 | =============================================================================== 20 | 21 | Copyright (c) 2016 Alex Crichton 22 | Copyright (c) 2017 quininer kel 23 | Copyright (c) 2019 Tokio Contributors 24 | 25 | Permission is hereby granted, free of charge, to any 26 | person obtaining a copy of this software and associated 27 | documentation files (the "Software"), to deal in the 28 | Software without restriction, including without 29 | limitation the rights to use, copy, modify, merge, 30 | publish, distribute, sublicense, and/or sell copies of 31 | the Software, and to permit persons to whom the Software 32 | is furnished to do so, subject to the following 33 | conditions: 34 | 35 | The above copyright notice and this permission notice 36 | shall be included in all copies or substantial portions 37 | of the Software. 38 | 39 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 40 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 41 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 42 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 43 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 44 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 45 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 46 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 47 | DEALINGS IN THE SOFTWARE. 48 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # async-rustls (deprecated) 2 | 3 | [![Build](https://github.com/smol-rs/async-rustls/workflows/Build%20and%20test/badge.svg)]( 4 | https://github.com/smol-rs/async-rustls/actions) 5 | [![License](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)]( 6 | https://github.com/smol-rs/async-rustls) 7 | [![Cargo](https://img.shields.io/crates/v/async-rustls.svg)]( 8 | https://crates.io/crates/async-rustls) 9 | [![Documentation](https://docs.rs/async-rustls/badge.svg)]( 10 | https://docs.rs/async-rustls) 11 | 12 | **This crate is now deprecated in favor of [futures-rustls](https://crates.io/crates/futures-rustls).** 13 | 14 | Asynchronous TLS/SSL streams using [`rustls`]. 15 | 16 | [`rustls`]: https://docs.rs/rustls 17 | 18 | ## License 19 | 20 | Licensed under either of 21 | 22 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 23 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 24 | 25 | at your option. 26 | 27 | This crate started as a fork of [`tokio-rustls`], which started as a fork of [`tokio-tls`]. 28 | 29 | [`tokio-rustls`]: https://github.com/tokio-rs/tls/tree/master/tokio-rustls 30 | [`tokio-tls`]: https://github.com/alexcrichton/tokio-tls 31 | 32 | #### Contribution 33 | 34 | Unless you explicitly state otherwise, any contribution intentionally submitted 35 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 36 | dual licensed as above, without any additional terms or conditions. 37 | -------------------------------------------------------------------------------- /examples/client/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "client" 3 | version = "0.1.0" 4 | authors = ["quininer ", "John Nunley "] 5 | edition = "2021" 6 | publish = false 7 | 8 | [dependencies] 9 | argh = "0.1" 10 | async-rustls = { path = "../.." } 11 | rustls-pemfile = "1" 12 | rustls-webpki = "0.101" 13 | smol = "2" 14 | webpki-roots = "0.25" 15 | -------------------------------------------------------------------------------- /examples/client/src/main.rs: -------------------------------------------------------------------------------- 1 | use argh::FromArgs; 2 | use async_rustls::rustls::{self, OwnedTrustAnchor}; 3 | use async_rustls::TlsConnector; 4 | use smol::io::{copy, split, AsyncWriteExt}; 5 | use smol::net::TcpStream; 6 | use smol::prelude::*; 7 | use smol::Unblock; 8 | use std::fs::File; 9 | use std::io; 10 | use std::io::BufReader; 11 | use std::net::ToSocketAddrs; 12 | use std::path::PathBuf; 13 | use std::sync::Arc; 14 | 15 | /// Tokio Rustls client example 16 | #[derive(FromArgs)] 17 | struct Options { 18 | /// host 19 | #[argh(positional)] 20 | host: String, 21 | 22 | /// port 23 | #[argh(option, short = 'p', default = "443")] 24 | port: u16, 25 | 26 | /// domain 27 | #[argh(option, short = 'd')] 28 | domain: Option, 29 | 30 | /// cafile 31 | #[argh(option, short = 'c')] 32 | cafile: Option, 33 | } 34 | 35 | fn main() -> io::Result<()> { 36 | smol::block_on(async { 37 | let options: Options = argh::from_env(); 38 | 39 | let addr = (options.host.as_str(), options.port) 40 | .to_socket_addrs()? 41 | .next() 42 | .ok_or_else(|| io::Error::from(io::ErrorKind::NotFound))?; 43 | let domain = options.domain.unwrap_or(options.host); 44 | let content = format!("GET / HTTP/1.0\r\nHost: {}\r\n\r\n", domain); 45 | 46 | let mut root_cert_store = rustls::RootCertStore::empty(); 47 | if let Some(cafile) = &options.cafile { 48 | let mut pem = BufReader::new(File::open(cafile)?); 49 | let certs = rustls_pemfile::certs(&mut pem)?; 50 | let trust_anchors = certs.iter().map(|cert| { 51 | let ta = webpki::TrustAnchor::try_from_cert_der(&cert[..]).unwrap(); 52 | OwnedTrustAnchor::from_subject_spki_name_constraints( 53 | ta.subject, 54 | ta.spki, 55 | ta.name_constraints, 56 | ) 57 | }); 58 | root_cert_store.add_trust_anchors(trust_anchors); 59 | } else { 60 | root_cert_store.add_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.iter().map(|ta| { 61 | OwnedTrustAnchor::from_subject_spki_name_constraints( 62 | ta.subject, 63 | ta.spki, 64 | ta.name_constraints, 65 | ) 66 | })); 67 | } 68 | 69 | let config = rustls::ClientConfig::builder() 70 | .with_safe_defaults() 71 | .with_root_certificates(root_cert_store) 72 | .with_no_client_auth(); // i guess this was previously the default? 73 | let connector = TlsConnector::from(Arc::new(config)); 74 | 75 | let stream = TcpStream::connect(&addr).await?; 76 | 77 | let (stdin_obj, stdout_obj) = (std::io::stdin(), std::io::stdout()); 78 | let (mut stdin, mut stdout) = (Unblock::new(stdin_obj), Unblock::new(stdout_obj)); 79 | 80 | let domain = rustls::ServerName::try_from(domain.as_str()) 81 | .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid dnsname"))?; 82 | 83 | let mut stream = connector.connect(domain, stream).await?; 84 | stream.write_all(content.as_bytes()).await?; 85 | 86 | let (mut reader, mut writer) = split(stream); 87 | 88 | copy(&mut reader, &mut stdout) 89 | .or(async move { 90 | copy(&mut stdin, &mut writer).await?; 91 | writer.close().await?; 92 | Ok(0) 93 | }) 94 | .await?; 95 | 96 | Ok(()) 97 | }) 98 | } 99 | -------------------------------------------------------------------------------- /examples/server/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "server" 3 | version = "0.1.0" 4 | authors = ["quininer ", "John Nunley "] 5 | edition = "2021" 6 | publish = false 7 | 8 | [dependencies] 9 | argh = "0.1" 10 | async-rustls = { path = "../.." } 11 | rustls-pemfile = "1" 12 | smol = "2" 13 | -------------------------------------------------------------------------------- /examples/server/src/main.rs: -------------------------------------------------------------------------------- 1 | use argh::FromArgs; 2 | use async_rustls::rustls::{self, Certificate, PrivateKey}; 3 | use async_rustls::TlsAcceptor; 4 | use rustls_pemfile::{certs, rsa_private_keys}; 5 | use smol::io::{copy, sink, split, AsyncWriteExt}; 6 | use smol::net::TcpListener; 7 | use std::fs::File; 8 | use std::io::{self, BufReader}; 9 | use std::net::ToSocketAddrs; 10 | use std::path::{Path, PathBuf}; 11 | use std::sync::Arc; 12 | 13 | /// Tokio Rustls server example 14 | #[derive(FromArgs)] 15 | struct Options { 16 | /// bind addr 17 | #[argh(positional)] 18 | addr: String, 19 | 20 | /// cert file 21 | #[argh(option, short = 'c')] 22 | cert: PathBuf, 23 | 24 | /// key file 25 | #[argh(option, short = 'k')] 26 | key: PathBuf, 27 | 28 | /// echo mode 29 | #[argh(switch, short = 'e')] 30 | echo_mode: bool, 31 | } 32 | 33 | fn load_certs(path: &Path) -> io::Result> { 34 | certs(&mut BufReader::new(File::open(path)?)) 35 | .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid cert")) 36 | .map(|mut certs| certs.drain(..).map(Certificate).collect()) 37 | } 38 | 39 | fn load_keys(path: &Path) -> io::Result> { 40 | rsa_private_keys(&mut BufReader::new(File::open(path)?)) 41 | .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid key")) 42 | .map(|mut keys| keys.drain(..).map(PrivateKey).collect()) 43 | } 44 | 45 | fn main() -> io::Result<()> { 46 | smol::block_on(async { 47 | let options: Options = argh::from_env(); 48 | 49 | let addr = options 50 | .addr 51 | .to_socket_addrs()? 52 | .next() 53 | .ok_or_else(|| io::Error::from(io::ErrorKind::AddrNotAvailable))?; 54 | let certs = load_certs(&options.cert)?; 55 | let mut keys = load_keys(&options.key)?; 56 | let flag_echo = options.echo_mode; 57 | 58 | let config = rustls::ServerConfig::builder() 59 | .with_safe_defaults() 60 | .with_no_client_auth() 61 | .with_single_cert(certs, keys.remove(0)) 62 | .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?; 63 | let acceptor = TlsAcceptor::from(Arc::new(config)); 64 | 65 | let listener = TcpListener::bind(&addr).await?; 66 | 67 | loop { 68 | let (stream, peer_addr) = listener.accept().await?; 69 | let acceptor = acceptor.clone(); 70 | 71 | let fut = async move { 72 | let mut stream = acceptor.accept(stream).await?; 73 | 74 | if flag_echo { 75 | let (mut reader, mut writer) = split(stream); 76 | let n = copy(&mut reader, &mut writer).await?; 77 | writer.flush().await?; 78 | println!("Echo: {} - {}", peer_addr, n); 79 | } else { 80 | let mut output = sink(); 81 | stream 82 | .write_all( 83 | &b"HTTP/1.0 200 ok\r\n\ 84 | Connection: close\r\n\ 85 | Content-length: 12\r\n\ 86 | \r\n\ 87 | Hello world!"[..], 88 | ) 89 | .await?; 90 | stream.close().await?; 91 | copy(&mut stream, &mut output).await?; 92 | println!("Hello: {}", peer_addr); 93 | } 94 | 95 | Ok(()) as io::Result<()> 96 | }; 97 | 98 | smol::spawn(async move { 99 | if let Err(err) = fut.await { 100 | eprintln!("{:?}", err); 101 | } 102 | }) 103 | .detach(); 104 | } 105 | }) 106 | } 107 | -------------------------------------------------------------------------------- /src/client.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | use crate::common::IoSession; 3 | #[cfg(unix)] 4 | use std::os::unix::io::{AsRawFd, RawFd}; 5 | #[cfg(windows)] 6 | use std::os::windows::io::{AsRawSocket, RawSocket}; 7 | 8 | /// A wrapper around an underlying raw stream which implements the TLS or SSL 9 | /// protocol. 10 | #[derive(Debug)] 11 | pub struct TlsStream { 12 | pub(crate) io: IO, 13 | pub(crate) session: ClientConnection, 14 | pub(crate) state: TlsState, 15 | 16 | #[cfg(feature = "early-data")] 17 | pub(crate) early_waker: Option, 18 | } 19 | 20 | impl TlsStream { 21 | #[inline] 22 | pub fn get_ref(&self) -> (&IO, &ClientConnection) { 23 | (&self.io, &self.session) 24 | } 25 | 26 | #[inline] 27 | pub fn get_mut(&mut self) -> (&mut IO, &mut ClientConnection) { 28 | (&mut self.io, &mut self.session) 29 | } 30 | 31 | #[inline] 32 | pub fn into_inner(self) -> (IO, ClientConnection) { 33 | (self.io, self.session) 34 | } 35 | } 36 | 37 | #[cfg(unix)] 38 | impl AsRawFd for TlsStream 39 | where 40 | S: AsRawFd, 41 | { 42 | #[inline] 43 | fn as_raw_fd(&self) -> RawFd { 44 | self.get_ref().0.as_raw_fd() 45 | } 46 | } 47 | 48 | #[cfg(windows)] 49 | impl AsRawSocket for TlsStream 50 | where 51 | S: AsRawSocket, 52 | { 53 | #[inline] 54 | fn as_raw_socket(&self) -> RawSocket { 55 | self.get_ref().0.as_raw_socket() 56 | } 57 | } 58 | 59 | impl IoSession for TlsStream { 60 | type Io = IO; 61 | type Session = ClientConnection; 62 | 63 | #[inline] 64 | fn skip_handshake(&self) -> bool { 65 | self.state.is_early_data() 66 | } 67 | 68 | #[inline] 69 | fn get_mut(&mut self) -> (&mut TlsState, &mut Self::Io, &mut Self::Session) { 70 | (&mut self.state, &mut self.io, &mut self.session) 71 | } 72 | 73 | #[inline] 74 | fn into_io(self) -> Self::Io { 75 | self.io 76 | } 77 | } 78 | 79 | impl AsyncRead for TlsStream 80 | where 81 | IO: AsyncRead + AsyncWrite + Unpin, 82 | { 83 | fn poll_read( 84 | self: Pin<&mut Self>, 85 | cx: &mut Context<'_>, 86 | buf: &mut [u8], 87 | ) -> Poll> { 88 | match self.state { 89 | #[cfg(feature = "early-data")] 90 | TlsState::EarlyData(..) => { 91 | let this = self.get_mut(); 92 | 93 | // In the EarlyData state, we have not really established a Tls connection. 94 | // Before writing data through `AsyncWrite` and completing the tls handshake, 95 | // we ignore read readiness and return to pending. 96 | // 97 | // In order to avoid event loss, 98 | // we need to register a waker and wake it up after tls is connected. 99 | if this 100 | .early_waker 101 | .as_ref() 102 | .filter(|waker| cx.waker().will_wake(waker)) 103 | .is_none() 104 | { 105 | this.early_waker = Some(cx.waker().clone()); 106 | } 107 | 108 | Poll::Pending 109 | } 110 | TlsState::Stream | TlsState::WriteShutdown => { 111 | let this = self.get_mut(); 112 | let mut stream = 113 | Stream::new(&mut this.io, &mut this.session).set_eof(!this.state.readable()); 114 | 115 | match stream.as_mut_pin().poll_read(cx, buf) { 116 | Poll::Ready(Ok(n)) => { 117 | if n == 0 || stream.eof { 118 | this.state.shutdown_read(); 119 | } 120 | 121 | Poll::Ready(Ok(n)) 122 | } 123 | Poll::Ready(Err(err)) if err.kind() == io::ErrorKind::ConnectionAborted => { 124 | this.state.shutdown_read(); 125 | Poll::Ready(Err(err)) 126 | } 127 | output => output, 128 | } 129 | } 130 | TlsState::ReadShutdown | TlsState::FullyShutdown => Poll::Ready(Ok(0)), 131 | } 132 | } 133 | } 134 | 135 | impl AsyncWrite for TlsStream 136 | where 137 | IO: AsyncRead + AsyncWrite + Unpin, 138 | { 139 | /// Note: that it does not guarantee the final data to be sent. 140 | /// To be cautious, you must manually call `flush`. 141 | fn poll_write( 142 | self: Pin<&mut Self>, 143 | cx: &mut Context<'_>, 144 | buf: &[u8], 145 | ) -> Poll> { 146 | let this = self.get_mut(); 147 | let mut stream = 148 | Stream::new(&mut this.io, &mut this.session).set_eof(!this.state.readable()); 149 | 150 | #[allow(clippy::match_single_binding)] 151 | match this.state { 152 | #[cfg(feature = "early-data")] 153 | TlsState::EarlyData(ref mut pos, ref mut data) => { 154 | use std::io::Write; 155 | 156 | // write early data 157 | if let Some(mut early_data) = stream.session.early_data() { 158 | let len = match early_data.write(buf) { 159 | Ok(n) => n, 160 | Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { 161 | return Poll::Pending 162 | } 163 | Err(err) => return Poll::Ready(Err(err)), 164 | }; 165 | if len != 0 { 166 | data.extend_from_slice(&buf[..len]); 167 | return Poll::Ready(Ok(len)); 168 | } 169 | } 170 | 171 | // complete handshake 172 | while stream.session.is_handshaking() { 173 | ready!(stream.handshake(cx))?; 174 | } 175 | 176 | // write early data (fallback) 177 | if !stream.session.is_early_data_accepted() { 178 | while *pos < data.len() { 179 | let len = ready!(stream.as_mut_pin().poll_write(cx, &data[*pos..]))?; 180 | *pos += len; 181 | } 182 | } 183 | 184 | // end 185 | this.state = TlsState::Stream; 186 | 187 | if let Some(waker) = this.early_waker.take() { 188 | waker.wake(); 189 | } 190 | 191 | stream.as_mut_pin().poll_write(cx, buf) 192 | } 193 | _ => stream.as_mut_pin().poll_write(cx, buf), 194 | } 195 | } 196 | 197 | fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 198 | let this = self.get_mut(); 199 | let mut stream = 200 | Stream::new(&mut this.io, &mut this.session).set_eof(!this.state.readable()); 201 | 202 | #[cfg(feature = "early-data")] 203 | { 204 | if let TlsState::EarlyData(ref mut pos, ref mut data) = this.state { 205 | // complete handshake 206 | while stream.session.is_handshaking() { 207 | ready!(stream.handshake(cx))?; 208 | } 209 | 210 | // write early data (fallback) 211 | if !stream.session.is_early_data_accepted() { 212 | while *pos < data.len() { 213 | let len = ready!(stream.as_mut_pin().poll_write(cx, &data[*pos..]))?; 214 | *pos += len; 215 | } 216 | } 217 | 218 | this.state = TlsState::Stream; 219 | 220 | if let Some(waker) = this.early_waker.take() { 221 | waker.wake(); 222 | } 223 | } 224 | } 225 | 226 | stream.as_mut_pin().poll_flush(cx) 227 | } 228 | 229 | fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 230 | // complete handshake 231 | #[cfg(feature = "early-data")] 232 | if matches!(self.state, TlsState::EarlyData(..)) { 233 | ready!(self.as_mut().poll_flush(cx))?; 234 | } 235 | 236 | if self.state.writeable() { 237 | self.session.send_close_notify(); 238 | self.state.shutdown_write(); 239 | } 240 | 241 | let this = self.get_mut(); 242 | let mut stream = 243 | Stream::new(&mut this.io, &mut this.session).set_eof(!this.state.readable()); 244 | stream.as_mut_pin().poll_close(cx) 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /src/common/handshake.rs: -------------------------------------------------------------------------------- 1 | use crate::common::{Stream, TlsState}; 2 | use futures_io::{AsyncRead, AsyncWrite}; 3 | use rustls::{ConnectionCommon, SideData}; 4 | use std::future::Future; 5 | use std::ops::{Deref, DerefMut}; 6 | use std::pin::Pin; 7 | use std::task::{Context, Poll}; 8 | use std::{io, mem}; 9 | 10 | pub(crate) trait IoSession { 11 | type Io; 12 | type Session; 13 | 14 | fn skip_handshake(&self) -> bool; 15 | fn get_mut(&mut self) -> (&mut TlsState, &mut Self::Io, &mut Self::Session); 16 | fn into_io(self) -> Self::Io; 17 | } 18 | 19 | pub(crate) enum MidHandshake { 20 | Handshaking(IS), 21 | End, 22 | Error { io: IS::Io, error: io::Error }, 23 | } 24 | 25 | impl Future for MidHandshake 26 | where 27 | IS: IoSession + Unpin, 28 | IS::Io: AsyncRead + AsyncWrite + Unpin, 29 | IS::Session: DerefMut + Deref> + Unpin, 30 | SD: SideData, 31 | { 32 | type Output = Result; 33 | 34 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 35 | let this = self.get_mut(); 36 | 37 | let mut stream = match mem::replace(this, MidHandshake::End) { 38 | MidHandshake::Handshaking(stream) => stream, 39 | // Starting the handshake returned an error; fail the future immediately. 40 | MidHandshake::Error { io, error } => return Poll::Ready(Err((error, io))), 41 | _ => panic!("unexpected polling after handshake"), 42 | }; 43 | 44 | if !stream.skip_handshake() { 45 | let (state, io, session) = stream.get_mut(); 46 | let mut tls_stream = Stream::new(io, session).set_eof(!state.readable()); 47 | 48 | macro_rules! try_poll { 49 | ( $e:expr ) => { 50 | match $e { 51 | Poll::Ready(Ok(_)) => (), 52 | Poll::Ready(Err(err)) => return Poll::Ready(Err((err, stream.into_io()))), 53 | Poll::Pending => { 54 | *this = MidHandshake::Handshaking(stream); 55 | return Poll::Pending; 56 | } 57 | } 58 | }; 59 | } 60 | 61 | while tls_stream.session.is_handshaking() { 62 | try_poll!(tls_stream.handshake(cx)); 63 | } 64 | 65 | try_poll!(Pin::new(&mut tls_stream).poll_flush(cx)); 66 | } 67 | 68 | Poll::Ready(Ok(stream)) 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/common/mod.rs: -------------------------------------------------------------------------------- 1 | mod handshake; 2 | 3 | use futures_io::{AsyncRead, AsyncWrite}; 4 | pub(crate) use handshake::{IoSession, MidHandshake}; 5 | use rustls::{ConnectionCommon, SideData}; 6 | use std::io::{self, IoSlice, Read, Write}; 7 | use std::ops::{Deref, DerefMut}; 8 | use std::pin::Pin; 9 | use std::task::{Context, Poll}; 10 | 11 | #[derive(Debug)] 12 | pub enum TlsState { 13 | #[cfg(feature = "early-data")] 14 | EarlyData(usize, Vec), 15 | Stream, 16 | ReadShutdown, 17 | WriteShutdown, 18 | FullyShutdown, 19 | } 20 | 21 | impl TlsState { 22 | #[inline] 23 | pub fn shutdown_read(&mut self) { 24 | match *self { 25 | TlsState::WriteShutdown | TlsState::FullyShutdown => *self = TlsState::FullyShutdown, 26 | _ => *self = TlsState::ReadShutdown, 27 | } 28 | } 29 | 30 | #[inline] 31 | pub fn shutdown_write(&mut self) { 32 | match *self { 33 | TlsState::ReadShutdown | TlsState::FullyShutdown => *self = TlsState::FullyShutdown, 34 | _ => *self = TlsState::WriteShutdown, 35 | } 36 | } 37 | 38 | #[inline] 39 | pub fn writeable(&self) -> bool { 40 | !matches!(*self, TlsState::WriteShutdown | TlsState::FullyShutdown) 41 | } 42 | 43 | #[inline] 44 | pub fn readable(&self) -> bool { 45 | !matches!(*self, TlsState::ReadShutdown | TlsState::FullyShutdown) 46 | } 47 | 48 | #[inline] 49 | #[cfg(feature = "early-data")] 50 | pub fn is_early_data(&self) -> bool { 51 | matches!(self, TlsState::EarlyData(..)) 52 | } 53 | 54 | #[inline] 55 | #[cfg(not(feature = "early-data"))] 56 | pub fn is_early_data(&self) -> bool { 57 | false 58 | } 59 | } 60 | 61 | pub struct Stream<'a, IO, S> { 62 | pub io: &'a mut IO, 63 | pub session: &'a mut S, 64 | pub eof: bool, 65 | } 66 | 67 | impl<'a, IO: AsyncRead + AsyncWrite + Unpin, S, SD> Stream<'a, IO, S> 68 | where 69 | S: DerefMut + Deref>, 70 | SD: SideData, 71 | { 72 | pub fn new(io: &'a mut IO, session: &'a mut S) -> Self { 73 | Stream { 74 | io, 75 | session, 76 | // The state so far is only used to detect EOF, so either Stream 77 | // or EarlyData state should both be all right. 78 | eof: false, 79 | } 80 | } 81 | 82 | pub fn set_eof(mut self, eof: bool) -> Self { 83 | self.eof = eof; 84 | self 85 | } 86 | 87 | pub fn as_mut_pin(&mut self) -> Pin<&mut Self> { 88 | Pin::new(self) 89 | } 90 | 91 | pub fn read_io(&mut self, cx: &mut Context) -> Poll> { 92 | let mut reader = SyncReadAdapter { io: self.io, cx }; 93 | 94 | let n = match self.session.read_tls(&mut reader) { 95 | Ok(n) => n, 96 | Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => return Poll::Pending, 97 | Err(err) => return Poll::Ready(Err(err)), 98 | }; 99 | 100 | let stats = self.session.process_new_packets().map_err(|err| { 101 | // In case we have an alert to send describing this error, 102 | // try a last-gasp write -- but don't predate the primary 103 | // error. 104 | let _ = self.write_io(cx); 105 | 106 | io::Error::new(io::ErrorKind::InvalidData, err) 107 | })?; 108 | 109 | if stats.peer_has_closed() && self.session.is_handshaking() { 110 | return Poll::Ready(Err(io::Error::new( 111 | io::ErrorKind::UnexpectedEof, 112 | "tls handshake alert", 113 | ))); 114 | } 115 | 116 | Poll::Ready(Ok(n)) 117 | } 118 | 119 | pub fn write_io(&mut self, cx: &mut Context) -> Poll> { 120 | struct Writer<'a, 'b, T> { 121 | io: &'a mut T, 122 | cx: &'a mut Context<'b>, 123 | } 124 | 125 | impl<'a, 'b, T: Unpin> Writer<'a, 'b, T> { 126 | #[inline] 127 | fn poll_with( 128 | &mut self, 129 | f: impl FnOnce(Pin<&mut T>, &mut Context<'_>) -> Poll>, 130 | ) -> io::Result { 131 | match f(Pin::new(self.io), self.cx) { 132 | Poll::Ready(result) => result, 133 | Poll::Pending => Err(io::ErrorKind::WouldBlock.into()), 134 | } 135 | } 136 | } 137 | 138 | impl<'a, 'b, T: AsyncWrite + Unpin> Write for Writer<'a, 'b, T> { 139 | #[inline] 140 | fn write(&mut self, buf: &[u8]) -> io::Result { 141 | self.poll_with(|io, cx| io.poll_write(cx, buf)) 142 | } 143 | 144 | #[inline] 145 | fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result { 146 | self.poll_with(|io, cx| io.poll_write_vectored(cx, bufs)) 147 | } 148 | 149 | #[inline] 150 | fn flush(&mut self) -> io::Result<()> { 151 | self.poll_with(|io, cx| io.poll_flush(cx)) 152 | } 153 | } 154 | 155 | let mut writer = Writer { io: self.io, cx }; 156 | 157 | match self.session.write_tls(&mut writer) { 158 | Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => Poll::Pending, 159 | result => Poll::Ready(result), 160 | } 161 | } 162 | 163 | pub fn handshake(&mut self, cx: &mut Context) -> Poll> { 164 | let mut wrlen = 0; 165 | let mut rdlen = 0; 166 | 167 | loop { 168 | let mut write_would_block = false; 169 | let mut read_would_block = false; 170 | let mut need_flush = false; 171 | 172 | while self.session.wants_write() { 173 | match self.write_io(cx) { 174 | Poll::Ready(Ok(n)) => { 175 | wrlen += n; 176 | need_flush = true; 177 | } 178 | Poll::Pending => { 179 | write_would_block = true; 180 | break; 181 | } 182 | Poll::Ready(Err(err)) => return Poll::Ready(Err(err)), 183 | } 184 | } 185 | 186 | if need_flush { 187 | match Pin::new(&mut self.io).poll_flush(cx) { 188 | Poll::Ready(Ok(())) => (), 189 | Poll::Ready(Err(err)) => return Poll::Ready(Err(err)), 190 | Poll::Pending => write_would_block = true, 191 | } 192 | } 193 | 194 | while !self.eof && self.session.wants_read() { 195 | match self.read_io(cx) { 196 | Poll::Ready(Ok(0)) => self.eof = true, 197 | Poll::Ready(Ok(n)) => rdlen += n, 198 | Poll::Pending => { 199 | read_would_block = true; 200 | break; 201 | } 202 | Poll::Ready(Err(err)) => return Poll::Ready(Err(err)), 203 | } 204 | } 205 | 206 | return match (self.eof, self.session.is_handshaking()) { 207 | (true, true) => { 208 | let err = io::Error::new(io::ErrorKind::UnexpectedEof, "tls handshake eof"); 209 | Poll::Ready(Err(err)) 210 | } 211 | (_, false) => Poll::Ready(Ok((rdlen, wrlen))), 212 | (_, true) if write_would_block || read_would_block => { 213 | if rdlen != 0 || wrlen != 0 { 214 | Poll::Ready(Ok((rdlen, wrlen))) 215 | } else { 216 | Poll::Pending 217 | } 218 | } 219 | (..) => continue, 220 | }; 221 | } 222 | } 223 | } 224 | 225 | impl<'a, IO: AsyncRead + AsyncWrite + Unpin, S, SD> AsyncRead for Stream<'a, IO, S> 226 | where 227 | S: DerefMut + Deref>, 228 | SD: SideData, 229 | { 230 | fn poll_read( 231 | mut self: Pin<&mut Self>, 232 | cx: &mut Context<'_>, 233 | buf: &mut [u8], 234 | ) -> Poll> { 235 | let mut io_pending = false; 236 | 237 | // read a packet 238 | while !self.eof && self.session.wants_read() { 239 | match self.read_io(cx) { 240 | Poll::Ready(Ok(0)) => { 241 | self.eof = true; 242 | break; 243 | } 244 | Poll::Ready(Ok(_)) => (), 245 | Poll::Pending => { 246 | io_pending = true; 247 | break; 248 | } 249 | Poll::Ready(Err(err)) => return Poll::Ready(Err(err)), 250 | } 251 | } 252 | 253 | match self.session.reader().read(buf) { 254 | // If Rustls returns `Ok(0)` (while `buf` is non-empty), the peer closed the 255 | // connection with a `CloseNotify` message and no more data will be forthcoming. 256 | // 257 | // Rustls yielded more data: advance the buffer, then see if more data is coming. 258 | // 259 | // We don't need to modify `self.eof` here, because it is only a temporary mark. 260 | // rustls will only return 0 if is has received `CloseNotify`, 261 | // in which case no additional processing is required. 262 | Ok(n) => Poll::Ready(Ok(n)), 263 | 264 | // Rustls doesn't have more data to yield, but it believes the connection is open. 265 | Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { 266 | if !io_pending { 267 | // If `wants_read()` is satisfied, rustls will not return `WouldBlock`. 268 | // but if it does, we can try again. 269 | // 270 | // If the rustls state is abnormal, it may cause a cyclic wakeup. 271 | // but tokio's cooperative budget will prevent infinite wakeup. 272 | cx.waker().wake_by_ref(); 273 | } 274 | 275 | Poll::Pending 276 | } 277 | 278 | Err(err) => Poll::Ready(Err(err)), 279 | } 280 | } 281 | } 282 | 283 | impl<'a, IO: AsyncRead + AsyncWrite + Unpin, C, SD> AsyncWrite for Stream<'a, IO, C> 284 | where 285 | C: DerefMut + Deref>, 286 | SD: SideData, 287 | { 288 | fn poll_write( 289 | mut self: Pin<&mut Self>, 290 | cx: &mut Context, 291 | buf: &[u8], 292 | ) -> Poll> { 293 | let mut pos = 0; 294 | 295 | while pos != buf.len() { 296 | let mut would_block = false; 297 | 298 | match self.session.writer().write(&buf[pos..]) { 299 | Ok(n) => pos += n, 300 | Err(err) => return Poll::Ready(Err(err)), 301 | }; 302 | 303 | while self.session.wants_write() { 304 | match self.write_io(cx) { 305 | Poll::Ready(Ok(0)) | Poll::Pending => { 306 | would_block = true; 307 | break; 308 | } 309 | Poll::Ready(Ok(_)) => (), 310 | Poll::Ready(Err(err)) => return Poll::Ready(Err(err)), 311 | } 312 | } 313 | 314 | return match (pos, would_block) { 315 | (0, true) => Poll::Pending, 316 | (n, true) => Poll::Ready(Ok(n)), 317 | (_, false) => continue, 318 | }; 319 | } 320 | 321 | Poll::Ready(Ok(pos)) 322 | } 323 | 324 | fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll> { 325 | self.session.writer().flush()?; 326 | while self.session.wants_write() { 327 | ready!(self.write_io(cx))?; 328 | } 329 | Pin::new(&mut self.io).poll_flush(cx) 330 | } 331 | 332 | fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 333 | while self.session.wants_write() { 334 | ready!(self.write_io(cx))?; 335 | } 336 | Pin::new(&mut self.io).poll_close(cx) 337 | } 338 | } 339 | 340 | /// An adapter that implements a [`Read`] interface for [`AsyncRead`] types and an 341 | /// associated [`Context`]. 342 | /// 343 | /// Turns `Poll::Pending` into `WouldBlock`. 344 | pub struct SyncReadAdapter<'a, 'b, T> { 345 | pub io: &'a mut T, 346 | pub cx: &'a mut Context<'b>, 347 | } 348 | 349 | impl<'a, 'b, T: AsyncRead + Unpin> Read for SyncReadAdapter<'a, 'b, T> { 350 | #[inline] 351 | fn read(&mut self, buf: &mut [u8]) -> io::Result { 352 | match Pin::new(&mut self.io).poll_read(self.cx, buf) { 353 | Poll::Ready(Ok(n)) => Ok(n), 354 | Poll::Ready(Err(err)) => Err(err), 355 | Poll::Pending => Err(io::ErrorKind::WouldBlock.into()), 356 | } 357 | } 358 | } 359 | 360 | #[cfg(test)] 361 | mod test_stream; 362 | -------------------------------------------------------------------------------- /src/common/test_stream.rs: -------------------------------------------------------------------------------- 1 | use super::Stream; 2 | use futures_util::future::poll_fn; 3 | use futures_util::task::noop_waker_ref; 4 | use rustls::{ClientConnection, Connection, ServerConnection}; 5 | use smol::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; 6 | use std::io::{self, Cursor, Read, Write}; 7 | use std::pin::Pin; 8 | use std::task::{Context, Poll}; 9 | 10 | struct Good<'a>(&'a mut Connection); 11 | 12 | impl<'a> AsyncRead for Good<'a> { 13 | fn poll_read( 14 | mut self: Pin<&mut Self>, 15 | _cx: &mut Context<'_>, 16 | mut buf: &mut [u8], 17 | ) -> Poll> { 18 | Poll::Ready(self.0.write_tls(buf.by_ref())) 19 | } 20 | } 21 | 22 | impl<'a> AsyncWrite for Good<'a> { 23 | fn poll_write( 24 | mut self: Pin<&mut Self>, 25 | _cx: &mut Context<'_>, 26 | mut buf: &[u8], 27 | ) -> Poll> { 28 | let len = self.0.read_tls(buf.by_ref())?; 29 | self.0 30 | .process_new_packets() 31 | .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?; 32 | Poll::Ready(Ok(len)) 33 | } 34 | 35 | fn poll_flush(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { 36 | self.0 37 | .process_new_packets() 38 | .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?; 39 | Poll::Ready(Ok(())) 40 | } 41 | 42 | fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 43 | self.0.send_close_notify(); 44 | self.poll_flush(cx) 45 | } 46 | } 47 | 48 | struct Pending; 49 | 50 | impl AsyncRead for Pending { 51 | fn poll_read( 52 | self: Pin<&mut Self>, 53 | _cx: &mut Context<'_>, 54 | _: &mut [u8], 55 | ) -> Poll> { 56 | Poll::Pending 57 | } 58 | } 59 | 60 | impl AsyncWrite for Pending { 61 | fn poll_write( 62 | self: Pin<&mut Self>, 63 | _cx: &mut Context<'_>, 64 | _buf: &[u8], 65 | ) -> Poll> { 66 | Poll::Pending 67 | } 68 | 69 | fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { 70 | Poll::Ready(Ok(())) 71 | } 72 | 73 | fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { 74 | Poll::Ready(Ok(())) 75 | } 76 | } 77 | 78 | struct Expected(Cursor>); 79 | 80 | impl AsyncRead for Expected { 81 | fn poll_read( 82 | self: Pin<&mut Self>, 83 | _cx: &mut Context<'_>, 84 | buf: &mut [u8], 85 | ) -> Poll> { 86 | let this = self.get_mut(); 87 | 88 | Poll::Ready(std::io::Read::read(&mut this.0, buf)) 89 | } 90 | } 91 | 92 | impl AsyncWrite for Expected { 93 | fn poll_write( 94 | self: Pin<&mut Self>, 95 | _cx: &mut Context<'_>, 96 | buf: &[u8], 97 | ) -> Poll> { 98 | Poll::Ready(Ok(buf.len())) 99 | } 100 | 101 | fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { 102 | Poll::Ready(Ok(())) 103 | } 104 | 105 | fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { 106 | Poll::Ready(Ok(())) 107 | } 108 | } 109 | 110 | #[test] 111 | fn stream_good() -> io::Result<()> { 112 | smol::block_on(async { 113 | const FILE: &[u8] = include_bytes!("../../README.md"); 114 | 115 | let (server, mut client) = make_pair(); 116 | let mut server = Connection::from(server); 117 | poll_fn(|cx| do_handshake(&mut client, &mut server, cx)).await?; 118 | 119 | io::copy(&mut Cursor::new(FILE), &mut server.writer())?; 120 | server.send_close_notify(); 121 | 122 | { 123 | let mut good = Good(&mut server); 124 | let mut stream = Stream::new(&mut good, &mut client); 125 | 126 | let mut buf = Vec::new(); 127 | dbg!(stream.read_to_end(&mut buf).await)?; 128 | assert_eq!(buf, FILE); 129 | 130 | dbg!(stream.write_all(b"Hello World!").await)?; 131 | stream.session.send_close_notify(); 132 | 133 | dbg!(stream.close().await)?; 134 | } 135 | 136 | let mut buf = String::new(); 137 | dbg!(server.process_new_packets()).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; 138 | dbg!(server.reader().read_to_string(&mut buf))?; 139 | assert_eq!(buf, "Hello World!"); 140 | 141 | Ok(()) as io::Result<()> 142 | }) 143 | } 144 | 145 | #[test] 146 | fn stream_bad() -> io::Result<()> { 147 | smol::block_on(async { 148 | let (server, mut client) = make_pair(); 149 | let mut server = Connection::from(server); 150 | poll_fn(|cx| do_handshake(&mut client, &mut server, cx)).await?; 151 | client.set_buffer_limit(Some(1024)); 152 | 153 | let mut bad = Pending; 154 | let mut stream = Stream::new(&mut bad, &mut client); 155 | assert_eq!( 156 | poll_fn(|cx| stream.as_mut_pin().poll_write(cx, &[0x42; 8])).await?, 157 | 8 158 | ); 159 | assert_eq!( 160 | poll_fn(|cx| stream.as_mut_pin().poll_write(cx, &[0x42; 8])).await?, 161 | 8 162 | ); 163 | let r = poll_fn(|cx| stream.as_mut_pin().poll_write(cx, &[0x00; 1024])).await?; // fill buffer 164 | assert!(r < 1024); 165 | 166 | let mut cx = Context::from_waker(noop_waker_ref()); 167 | let ret = stream.as_mut_pin().poll_write(&mut cx, &[0x01]); 168 | assert!(ret.is_pending()); 169 | 170 | Ok(()) as io::Result<()> 171 | }) 172 | } 173 | 174 | #[test] 175 | fn stream_handshake() -> io::Result<()> { 176 | smol::block_on(async { 177 | let (server, mut client) = make_pair(); 178 | let mut server = Connection::from(server); 179 | 180 | { 181 | let mut good = Good(&mut server); 182 | let mut stream = Stream::new(&mut good, &mut client); 183 | let (r, w) = poll_fn(|cx| stream.handshake(cx)).await?; 184 | 185 | assert!(r > 0); 186 | assert!(w > 0); 187 | 188 | poll_fn(|cx| stream.handshake(cx)).await?; // finish server handshake 189 | } 190 | 191 | assert!(!server.is_handshaking()); 192 | assert!(!client.is_handshaking()); 193 | 194 | Ok(()) as io::Result<()> 195 | }) 196 | } 197 | 198 | #[test] 199 | fn stream_handshake_eof() -> io::Result<()> { 200 | smol::block_on(async { 201 | let (_, mut client) = make_pair(); 202 | 203 | let mut bad = Expected(Cursor::new(Vec::new())); 204 | let mut stream = Stream::new(&mut bad, &mut client); 205 | 206 | let mut cx = Context::from_waker(noop_waker_ref()); 207 | let r = stream.handshake(&mut cx); 208 | assert_eq!( 209 | r.map_err(|err| err.kind()), 210 | Poll::Ready(Err(io::ErrorKind::UnexpectedEof)) 211 | ); 212 | 213 | Ok(()) as io::Result<()> 214 | }) 215 | } 216 | 217 | // see https://github.com/tokio-rs/tls/issues/77 218 | #[test] 219 | fn stream_handshake_regression_issues_77() -> io::Result<()> { 220 | smol::block_on(async { 221 | let (_, mut client) = make_pair(); 222 | 223 | let mut bad = Expected(Cursor::new(b"\x15\x03\x01\x00\x02\x02\x00".to_vec())); 224 | let mut stream = Stream::new(&mut bad, &mut client); 225 | 226 | let mut cx = Context::from_waker(noop_waker_ref()); 227 | let r = stream.handshake(&mut cx); 228 | assert_eq!( 229 | r.map_err(|err| err.kind()), 230 | Poll::Ready(Err(io::ErrorKind::UnexpectedEof)) 231 | ); 232 | 233 | Ok(()) as io::Result<()> 234 | }) 235 | } 236 | 237 | #[test] 238 | fn stream_eof() -> io::Result<()> { 239 | smol::block_on(async { 240 | let (server, mut client) = make_pair(); 241 | let mut server = Connection::from(server); 242 | poll_fn(|cx| do_handshake(&mut client, &mut server, cx)).await?; 243 | 244 | let mut bad = Expected(Cursor::new(Vec::new())); 245 | let mut stream = Stream::new(&mut bad, &mut client); 246 | 247 | let mut buf = Vec::new(); 248 | let result = stream.read_to_end(&mut buf).await; 249 | assert_eq!( 250 | result.err().map(|e| e.kind()), 251 | Some(io::ErrorKind::UnexpectedEof) 252 | ); 253 | 254 | Ok(()) as io::Result<()> 255 | }) 256 | } 257 | 258 | fn make_pair() -> (ServerConnection, ClientConnection) { 259 | let (sconfig, cconfig) = utils::make_configs(); 260 | let server = ServerConnection::new(sconfig).unwrap(); 261 | 262 | let domain = rustls::ServerName::try_from("foobar.com").unwrap(); 263 | let client = ClientConnection::new(cconfig, domain).unwrap(); 264 | 265 | (server, client) 266 | } 267 | 268 | fn do_handshake( 269 | client: &mut ClientConnection, 270 | server: &mut Connection, 271 | cx: &mut Context<'_>, 272 | ) -> Poll> { 273 | let mut good = Good(server); 274 | let mut stream = Stream::new(&mut good, client); 275 | 276 | while stream.session.is_handshaking() { 277 | ready!(stream.handshake(cx))?; 278 | } 279 | 280 | while stream.session.wants_write() { 281 | ready!(stream.write_io(cx))?; 282 | } 283 | 284 | Poll::Ready(Ok(())) 285 | } 286 | 287 | // Share `utils` module with integration tests 288 | include!("../../tests/utils.rs"); 289 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Asynchronous TLS/SSL streams using [Rustls](https://github.com/ctz/rustls). 2 | 3 | #![doc( 4 | html_favicon_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png" 5 | )] 6 | #![doc( 7 | html_logo_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png" 8 | )] 9 | #![deprecated( 10 | since = "0.4.2", 11 | note = "This crate is now deprecated in favor of [futures-rustls](https://crates.io/crates/futures-rustls)." 12 | )] 13 | 14 | macro_rules! ready { 15 | ( $e:expr ) => { 16 | match $e { 17 | std::task::Poll::Ready(t) => t, 18 | std::task::Poll::Pending => return std::task::Poll::Pending, 19 | } 20 | }; 21 | } 22 | 23 | pub mod client; 24 | mod common; 25 | pub mod server; 26 | 27 | use common::{MidHandshake, Stream, TlsState}; 28 | use futures_io::{AsyncRead, AsyncWrite}; 29 | use rustls::{ClientConfig, ClientConnection, CommonState, ServerConfig, ServerConnection}; 30 | use std::future::Future; 31 | use std::io; 32 | #[cfg(unix)] 33 | use std::os::unix::io::{AsRawFd, RawFd}; 34 | #[cfg(windows)] 35 | use std::os::windows::io::{AsRawSocket, RawSocket}; 36 | use std::pin::Pin; 37 | use std::sync::Arc; 38 | use std::task::{Context, Poll}; 39 | 40 | pub use rustls; 41 | 42 | /// A wrapper around a `rustls::ClientConfig`, providing an async `connect` method. 43 | #[derive(Clone)] 44 | pub struct TlsConnector { 45 | inner: Arc, 46 | #[cfg(feature = "early-data")] 47 | early_data: bool, 48 | } 49 | 50 | /// A wrapper around a `rustls::ServerConfig`, providing an async `accept` method. 51 | #[derive(Clone)] 52 | pub struct TlsAcceptor { 53 | inner: Arc, 54 | } 55 | 56 | impl From> for TlsConnector { 57 | fn from(inner: Arc) -> TlsConnector { 58 | TlsConnector { 59 | inner, 60 | #[cfg(feature = "early-data")] 61 | early_data: false, 62 | } 63 | } 64 | } 65 | 66 | impl From> for TlsAcceptor { 67 | fn from(inner: Arc) -> TlsAcceptor { 68 | TlsAcceptor { inner } 69 | } 70 | } 71 | 72 | impl TlsConnector { 73 | /// Enable 0-RTT. 74 | /// 75 | /// If you want to use 0-RTT, 76 | /// You must also set `ClientConfig.enable_early_data` to `true`. 77 | #[cfg(feature = "early-data")] 78 | pub fn early_data(mut self, flag: bool) -> TlsConnector { 79 | self.early_data = flag; 80 | self 81 | } 82 | 83 | #[inline] 84 | pub fn connect(&self, domain: rustls::ServerName, stream: IO) -> Connect 85 | where 86 | IO: AsyncRead + AsyncWrite + Unpin, 87 | { 88 | self.connect_with(domain, stream, |_| ()) 89 | } 90 | 91 | pub fn connect_with(&self, domain: rustls::ServerName, stream: IO, f: F) -> Connect 92 | where 93 | IO: AsyncRead + AsyncWrite + Unpin, 94 | F: FnOnce(&mut ClientConnection), 95 | { 96 | let mut session = match ClientConnection::new(self.inner.clone(), domain) { 97 | Ok(session) => session, 98 | Err(error) => { 99 | return Connect(MidHandshake::Error { 100 | io: stream, 101 | // TODO(eliza): should this really return an `io::Error`? 102 | // Probably not... 103 | error: io::Error::new(io::ErrorKind::Other, error), 104 | }); 105 | } 106 | }; 107 | f(&mut session); 108 | 109 | Connect(MidHandshake::Handshaking(client::TlsStream { 110 | io: stream, 111 | 112 | #[cfg(not(feature = "early-data"))] 113 | state: TlsState::Stream, 114 | 115 | #[cfg(feature = "early-data")] 116 | state: if self.early_data && session.early_data().is_some() { 117 | TlsState::EarlyData(0, Vec::new()) 118 | } else { 119 | TlsState::Stream 120 | }, 121 | 122 | #[cfg(feature = "early-data")] 123 | early_waker: None, 124 | 125 | session, 126 | })) 127 | } 128 | } 129 | 130 | impl TlsAcceptor { 131 | #[inline] 132 | pub fn accept(&self, stream: IO) -> Accept 133 | where 134 | IO: AsyncRead + AsyncWrite + Unpin, 135 | { 136 | self.accept_with(stream, |_| ()) 137 | } 138 | 139 | pub fn accept_with(&self, stream: IO, f: F) -> Accept 140 | where 141 | IO: AsyncRead + AsyncWrite + Unpin, 142 | F: FnOnce(&mut ServerConnection), 143 | { 144 | let mut session = match ServerConnection::new(self.inner.clone()) { 145 | Ok(session) => session, 146 | Err(error) => { 147 | return Accept(MidHandshake::Error { 148 | io: stream, 149 | // TODO(eliza): should this really return an `io::Error`? 150 | // Probably not... 151 | error: io::Error::new(io::ErrorKind::Other, error), 152 | }); 153 | } 154 | }; 155 | f(&mut session); 156 | 157 | Accept(MidHandshake::Handshaking(server::TlsStream { 158 | session, 159 | io: stream, 160 | state: TlsState::Stream, 161 | })) 162 | } 163 | } 164 | 165 | pub struct LazyConfigAcceptor { 166 | acceptor: rustls::server::Acceptor, 167 | io: Option, 168 | } 169 | 170 | impl LazyConfigAcceptor 171 | where 172 | IO: AsyncRead + AsyncWrite + Unpin, 173 | { 174 | #[inline] 175 | pub fn new(acceptor: rustls::server::Acceptor, io: IO) -> Self { 176 | Self { 177 | acceptor, 178 | io: Some(io), 179 | } 180 | } 181 | } 182 | 183 | impl Future for LazyConfigAcceptor 184 | where 185 | IO: AsyncRead + AsyncWrite + Unpin, 186 | { 187 | type Output = Result, io::Error>; 188 | 189 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 190 | let this = self.get_mut(); 191 | loop { 192 | let io = match this.io.as_mut() { 193 | Some(io) => io, 194 | None => { 195 | panic!("Acceptor cannot be polled after acceptance."); 196 | } 197 | }; 198 | 199 | let mut reader = common::SyncReadAdapter { io, cx }; 200 | match this.acceptor.read_tls(&mut reader) { 201 | Ok(0) => return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())), 202 | Ok(_) => {} 203 | Err(e) if e.kind() == io::ErrorKind::WouldBlock => return Poll::Pending, 204 | Err(e) => return Poll::Ready(Err(e)), 205 | } 206 | 207 | match this.acceptor.accept() { 208 | Ok(Some(accepted)) => { 209 | let io = this.io.take().unwrap(); 210 | return Poll::Ready(Ok(StartHandshake { accepted, io })); 211 | } 212 | Ok(None) => continue, 213 | Err(err) => { 214 | return Poll::Ready(Err(io::Error::new(io::ErrorKind::InvalidInput, err))) 215 | } 216 | } 217 | } 218 | } 219 | } 220 | 221 | pub struct StartHandshake { 222 | accepted: rustls::server::Accepted, 223 | io: IO, 224 | } 225 | 226 | impl StartHandshake 227 | where 228 | IO: AsyncRead + AsyncWrite + Unpin, 229 | { 230 | pub fn client_hello(&self) -> rustls::server::ClientHello<'_> { 231 | self.accepted.client_hello() 232 | } 233 | 234 | pub fn into_stream(self, config: Arc) -> Accept { 235 | self.into_stream_with(config, |_| ()) 236 | } 237 | 238 | pub fn into_stream_with(self, config: Arc, f: F) -> Accept 239 | where 240 | F: FnOnce(&mut ServerConnection), 241 | { 242 | let mut conn = match self.accepted.into_connection(config) { 243 | Ok(conn) => conn, 244 | Err(error) => { 245 | return Accept(MidHandshake::Error { 246 | io: self.io, 247 | // TODO(eliza): should this really return an `io::Error`? 248 | // Probably not... 249 | error: io::Error::new(io::ErrorKind::Other, error), 250 | }); 251 | } 252 | }; 253 | f(&mut conn); 254 | 255 | Accept(MidHandshake::Handshaking(server::TlsStream { 256 | session: conn, 257 | io: self.io, 258 | state: TlsState::Stream, 259 | })) 260 | } 261 | } 262 | 263 | /// Future returned from `TlsConnector::connect` which will resolve 264 | /// once the connection handshake has finished. 265 | pub struct Connect(MidHandshake>); 266 | 267 | /// Future returned from `TlsAcceptor::accept` which will resolve 268 | /// once the accept handshake has finished. 269 | pub struct Accept(MidHandshake>); 270 | 271 | /// Like [Connect], but returns `IO` on failure. 272 | pub struct FallibleConnect(MidHandshake>); 273 | 274 | /// Like [Accept], but returns `IO` on failure. 275 | pub struct FallibleAccept(MidHandshake>); 276 | 277 | impl Connect { 278 | #[inline] 279 | pub fn into_fallible(self) -> FallibleConnect { 280 | FallibleConnect(self.0) 281 | } 282 | 283 | pub fn get_ref(&self) -> Option<&IO> { 284 | match &self.0 { 285 | MidHandshake::Handshaking(sess) => Some(sess.get_ref().0), 286 | MidHandshake::Error { io, .. } => Some(io), 287 | MidHandshake::End => None, 288 | } 289 | } 290 | 291 | pub fn get_mut(&mut self) -> Option<&mut IO> { 292 | match &mut self.0 { 293 | MidHandshake::Handshaking(sess) => Some(sess.get_mut().0), 294 | MidHandshake::Error { io, .. } => Some(io), 295 | MidHandshake::End => None, 296 | } 297 | } 298 | } 299 | 300 | impl Accept { 301 | #[inline] 302 | pub fn into_fallible(self) -> FallibleAccept { 303 | FallibleAccept(self.0) 304 | } 305 | 306 | pub fn get_ref(&self) -> Option<&IO> { 307 | match &self.0 { 308 | MidHandshake::Handshaking(sess) => Some(sess.get_ref().0), 309 | MidHandshake::Error { io, .. } => Some(io), 310 | MidHandshake::End => None, 311 | } 312 | } 313 | 314 | pub fn get_mut(&mut self) -> Option<&mut IO> { 315 | match &mut self.0 { 316 | MidHandshake::Handshaking(sess) => Some(sess.get_mut().0), 317 | MidHandshake::Error { io, .. } => Some(io), 318 | MidHandshake::End => None, 319 | } 320 | } 321 | } 322 | 323 | impl Future for Connect { 324 | type Output = io::Result>; 325 | 326 | #[inline] 327 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 328 | Pin::new(&mut self.0).poll(cx).map_err(|(err, _)| err) 329 | } 330 | } 331 | 332 | impl Future for Accept { 333 | type Output = io::Result>; 334 | 335 | #[inline] 336 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 337 | Pin::new(&mut self.0).poll(cx).map_err(|(err, _)| err) 338 | } 339 | } 340 | 341 | impl Future for FallibleConnect { 342 | type Output = Result, (io::Error, IO)>; 343 | 344 | #[inline] 345 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 346 | Pin::new(&mut self.0).poll(cx) 347 | } 348 | } 349 | 350 | impl Future for FallibleAccept { 351 | type Output = Result, (io::Error, IO)>; 352 | 353 | #[inline] 354 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 355 | Pin::new(&mut self.0).poll(cx) 356 | } 357 | } 358 | 359 | /// Unified TLS stream type 360 | /// 361 | /// This abstracts over the inner `client::TlsStream` and `server::TlsStream`, so you can use 362 | /// a single type to keep both client- and server-initiated TLS-encrypted connections. 363 | #[allow(clippy::large_enum_variant)] // https://github.com/rust-lang/rust-clippy/issues/9798 364 | #[derive(Debug)] 365 | pub enum TlsStream { 366 | Client(client::TlsStream), 367 | Server(server::TlsStream), 368 | } 369 | 370 | impl TlsStream { 371 | pub fn get_ref(&self) -> (&T, &CommonState) { 372 | use TlsStream::*; 373 | match self { 374 | Client(io) => { 375 | let (io, session) = io.get_ref(); 376 | (io, session) 377 | } 378 | Server(io) => { 379 | let (io, session) = io.get_ref(); 380 | (io, session) 381 | } 382 | } 383 | } 384 | 385 | pub fn get_mut(&mut self) -> (&mut T, &mut CommonState) { 386 | use TlsStream::*; 387 | match self { 388 | Client(io) => { 389 | let (io, session) = io.get_mut(); 390 | (io, &mut *session) 391 | } 392 | Server(io) => { 393 | let (io, session) = io.get_mut(); 394 | (io, &mut *session) 395 | } 396 | } 397 | } 398 | } 399 | 400 | impl From> for TlsStream { 401 | fn from(s: client::TlsStream) -> Self { 402 | Self::Client(s) 403 | } 404 | } 405 | 406 | impl From> for TlsStream { 407 | fn from(s: server::TlsStream) -> Self { 408 | Self::Server(s) 409 | } 410 | } 411 | 412 | #[cfg(unix)] 413 | impl AsRawFd for TlsStream 414 | where 415 | S: AsRawFd, 416 | { 417 | #[inline] 418 | fn as_raw_fd(&self) -> RawFd { 419 | self.get_ref().0.as_raw_fd() 420 | } 421 | } 422 | 423 | #[cfg(windows)] 424 | impl AsRawSocket for TlsStream 425 | where 426 | S: AsRawSocket, 427 | { 428 | #[inline] 429 | fn as_raw_socket(&self) -> RawSocket { 430 | self.get_ref().0.as_raw_socket() 431 | } 432 | } 433 | 434 | impl AsyncRead for TlsStream 435 | where 436 | T: AsyncRead + AsyncWrite + Unpin, 437 | { 438 | #[inline] 439 | fn poll_read( 440 | self: Pin<&mut Self>, 441 | cx: &mut Context<'_>, 442 | buf: &mut [u8], 443 | ) -> Poll> { 444 | match self.get_mut() { 445 | TlsStream::Client(x) => Pin::new(x).poll_read(cx, buf), 446 | TlsStream::Server(x) => Pin::new(x).poll_read(cx, buf), 447 | } 448 | } 449 | } 450 | 451 | impl AsyncWrite for TlsStream 452 | where 453 | T: AsyncRead + AsyncWrite + Unpin, 454 | { 455 | #[inline] 456 | fn poll_write( 457 | self: Pin<&mut Self>, 458 | cx: &mut Context<'_>, 459 | buf: &[u8], 460 | ) -> Poll> { 461 | match self.get_mut() { 462 | TlsStream::Client(x) => Pin::new(x).poll_write(cx, buf), 463 | TlsStream::Server(x) => Pin::new(x).poll_write(cx, buf), 464 | } 465 | } 466 | 467 | #[inline] 468 | fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 469 | match self.get_mut() { 470 | TlsStream::Client(x) => Pin::new(x).poll_flush(cx), 471 | TlsStream::Server(x) => Pin::new(x).poll_flush(cx), 472 | } 473 | } 474 | 475 | #[inline] 476 | fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 477 | match self.get_mut() { 478 | TlsStream::Client(x) => Pin::new(x).poll_close(cx), 479 | TlsStream::Server(x) => Pin::new(x).poll_close(cx), 480 | } 481 | } 482 | } 483 | -------------------------------------------------------------------------------- /src/server.rs: -------------------------------------------------------------------------------- 1 | #[cfg(unix)] 2 | use std::os::unix::io::{AsRawFd, RawFd}; 3 | #[cfg(windows)] 4 | use std::os::windows::io::{AsRawSocket, RawSocket}; 5 | 6 | use super::*; 7 | use crate::common::IoSession; 8 | 9 | /// A wrapper around an underlying raw stream which implements the TLS or SSL 10 | /// protocol. 11 | #[derive(Debug)] 12 | pub struct TlsStream { 13 | pub(crate) io: IO, 14 | pub(crate) session: ServerConnection, 15 | pub(crate) state: TlsState, 16 | } 17 | 18 | impl TlsStream { 19 | #[inline] 20 | pub fn get_ref(&self) -> (&IO, &ServerConnection) { 21 | (&self.io, &self.session) 22 | } 23 | 24 | #[inline] 25 | pub fn get_mut(&mut self) -> (&mut IO, &mut ServerConnection) { 26 | (&mut self.io, &mut self.session) 27 | } 28 | 29 | #[inline] 30 | pub fn into_inner(self) -> (IO, ServerConnection) { 31 | (self.io, self.session) 32 | } 33 | } 34 | 35 | impl IoSession for TlsStream { 36 | type Io = IO; 37 | type Session = ServerConnection; 38 | 39 | #[inline] 40 | fn skip_handshake(&self) -> bool { 41 | false 42 | } 43 | 44 | #[inline] 45 | fn get_mut(&mut self) -> (&mut TlsState, &mut Self::Io, &mut Self::Session) { 46 | (&mut self.state, &mut self.io, &mut self.session) 47 | } 48 | 49 | #[inline] 50 | fn into_io(self) -> Self::Io { 51 | self.io 52 | } 53 | } 54 | 55 | impl AsyncRead for TlsStream 56 | where 57 | IO: AsyncRead + AsyncWrite + Unpin, 58 | { 59 | fn poll_read( 60 | self: Pin<&mut Self>, 61 | cx: &mut Context<'_>, 62 | buf: &mut [u8], 63 | ) -> Poll> { 64 | let this = self.get_mut(); 65 | let mut stream = 66 | Stream::new(&mut this.io, &mut this.session).set_eof(!this.state.readable()); 67 | 68 | match &this.state { 69 | TlsState::Stream | TlsState::WriteShutdown => { 70 | match stream.as_mut_pin().poll_read(cx, buf) { 71 | Poll::Ready(Ok(n)) => { 72 | if n == 0 || stream.eof { 73 | this.state.shutdown_read(); 74 | } 75 | 76 | Poll::Ready(Ok(n)) 77 | } 78 | Poll::Ready(Err(err)) if err.kind() == io::ErrorKind::UnexpectedEof => { 79 | this.state.shutdown_read(); 80 | Poll::Ready(Err(err)) 81 | } 82 | output => output, 83 | } 84 | } 85 | TlsState::ReadShutdown | TlsState::FullyShutdown => Poll::Ready(Ok(0)), 86 | #[cfg(feature = "early-data")] 87 | s => unreachable!("server TLS can not hit this state: {:?}", s), 88 | } 89 | } 90 | } 91 | 92 | impl AsyncWrite for TlsStream 93 | where 94 | IO: AsyncRead + AsyncWrite + Unpin, 95 | { 96 | /// Note: that it does not guarantee the final data to be sent. 97 | /// To be cautious, you must manually call `flush`. 98 | fn poll_write( 99 | self: Pin<&mut Self>, 100 | cx: &mut Context<'_>, 101 | buf: &[u8], 102 | ) -> Poll> { 103 | let this = self.get_mut(); 104 | let mut stream = 105 | Stream::new(&mut this.io, &mut this.session).set_eof(!this.state.readable()); 106 | stream.as_mut_pin().poll_write(cx, buf) 107 | } 108 | 109 | fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 110 | let this = self.get_mut(); 111 | let mut stream = 112 | Stream::new(&mut this.io, &mut this.session).set_eof(!this.state.readable()); 113 | stream.as_mut_pin().poll_flush(cx) 114 | } 115 | 116 | fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 117 | if self.state.writeable() { 118 | self.session.send_close_notify(); 119 | self.state.shutdown_write(); 120 | } 121 | 122 | let this = self.get_mut(); 123 | let mut stream = 124 | Stream::new(&mut this.io, &mut this.session).set_eof(!this.state.readable()); 125 | stream.as_mut_pin().poll_close(cx) 126 | } 127 | } 128 | 129 | #[cfg(unix)] 130 | impl AsRawFd for TlsStream 131 | where 132 | IO: AsRawFd, 133 | { 134 | #[inline] 135 | fn as_raw_fd(&self) -> RawFd { 136 | self.get_ref().0.as_raw_fd() 137 | } 138 | } 139 | 140 | #[cfg(windows)] 141 | impl AsRawSocket for TlsStream 142 | where 143 | IO: AsRawSocket, 144 | { 145 | #[inline] 146 | fn as_raw_socket(&self) -> RawSocket { 147 | self.get_ref().0.as_raw_socket() 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /tests/badssl.rs: -------------------------------------------------------------------------------- 1 | use async_rustls::{ 2 | client::TlsStream, 3 | rustls::{self, ClientConfig, OwnedTrustAnchor}, 4 | TlsConnector, 5 | }; 6 | use smol::io::{AsyncReadExt, AsyncWriteExt}; 7 | use smol::net::TcpStream; 8 | use std::io; 9 | use std::net::ToSocketAddrs; 10 | use std::sync::Arc; 11 | 12 | async fn get( 13 | config: Arc, 14 | domain: &str, 15 | port: u16, 16 | ) -> io::Result<(TlsStream, String)> { 17 | let connector = TlsConnector::from(config); 18 | let input = format!("GET / HTTP/1.0\r\nHost: {domain}\r\n\r\n"); 19 | 20 | let addr = (domain, port).to_socket_addrs()?.next().unwrap(); 21 | let domain = rustls::ServerName::try_from(domain).unwrap(); 22 | let mut buf = Vec::new(); 23 | 24 | let stream = TcpStream::connect(&addr).await?; 25 | let mut stream = connector.connect(domain, stream).await?; 26 | stream.write_all(input.as_bytes()).await?; 27 | stream.flush().await?; 28 | stream.read_to_end(&mut buf).await?; 29 | 30 | Ok((stream, String::from_utf8(buf).unwrap())) 31 | } 32 | 33 | #[cfg(feature = "tls12")] 34 | #[test] 35 | fn test_tls12() -> io::Result<()> { 36 | smol::block_on(async { 37 | let mut root_store = rustls::RootCertStore::empty(); 38 | root_store.add_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.iter().map(|ta| { 39 | OwnedTrustAnchor::from_subject_spki_name_constraints( 40 | ta.subject, 41 | ta.spki, 42 | ta.name_constraints, 43 | ) 44 | })); 45 | let config = rustls::ClientConfig::builder() 46 | .with_safe_default_cipher_suites() 47 | .with_safe_default_kx_groups() 48 | .with_protocol_versions(&[&rustls::version::TLS12]) 49 | .unwrap() 50 | .with_root_certificates(root_store) 51 | .with_no_client_auth(); 52 | 53 | let config = Arc::new(config); 54 | let domain = "tls-v1-2.badssl.com"; 55 | 56 | let (_, output) = get(config.clone(), domain, 1012).await?; 57 | assert!( 58 | output.contains("tls-v1-2.badssl.com"), 59 | "failed badssl test, output: {}", 60 | output 61 | ); 62 | 63 | Ok(()) 64 | }) 65 | } 66 | 67 | #[ignore] 68 | #[should_panic] 69 | #[test] 70 | fn test_tls13() { 71 | unimplemented!("todo https://github.com/chromium/badssl.com/pull/373"); 72 | } 73 | 74 | #[test] 75 | fn test_modern() -> io::Result<()> { 76 | smol::block_on(async { 77 | let mut root_store = rustls::RootCertStore::empty(); 78 | root_store.add_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.iter().map(|ta| { 79 | OwnedTrustAnchor::from_subject_spki_name_constraints( 80 | ta.subject, 81 | ta.spki, 82 | ta.name_constraints, 83 | ) 84 | })); 85 | let config = rustls::ClientConfig::builder() 86 | .with_safe_defaults() 87 | .with_root_certificates(root_store) 88 | .with_no_client_auth(); 89 | let config = Arc::new(config); 90 | let domain = "mozilla-modern.badssl.com"; 91 | 92 | let (_, output) = get(config.clone(), domain, 443).await?; 93 | assert!( 94 | output.contains("mozilla-modern.badssl.com"), 95 | "failed badssl test, output: {}", 96 | output 97 | ); 98 | 99 | Ok(()) 100 | }) 101 | } 102 | -------------------------------------------------------------------------------- /tests/early-data.rs: -------------------------------------------------------------------------------- 1 | #![cfg(feature = "early-data")] 2 | 3 | use async_rustls::{client::TlsStream, TlsConnector}; 4 | use rustls::Certificate; 5 | use rustls::ClientConfig; 6 | use rustls::RootCertStore; 7 | use rustls::ServerName; 8 | use smol::net::TcpStream; 9 | use smol::prelude::*; 10 | use smol::Timer; 11 | use smol::{future, future::Future}; 12 | use std::io::{self, BufRead, BufReader, Cursor}; 13 | use std::net::SocketAddr; 14 | use std::pin::Pin; 15 | use std::process::{Child, Command, Stdio}; 16 | use std::sync::Arc; 17 | use std::task::{Context, Poll}; 18 | use std::time::Duration; 19 | 20 | struct Read1(T); 21 | 22 | impl Future for Read1 { 23 | type Output = io::Result<()>; 24 | 25 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 26 | let mut buf = [0]; 27 | smol::ready!(Pin::new(&mut self.0).poll_read(cx, &mut buf))?; 28 | Poll::Pending 29 | } 30 | } 31 | 32 | enum Either { 33 | Left(A), 34 | Right(B), 35 | } 36 | 37 | async fn send( 38 | config: Arc, 39 | addr: SocketAddr, 40 | data: &[u8], 41 | ) -> io::Result> { 42 | let connector = TlsConnector::from(config).early_data(true); 43 | let stream = TcpStream::connect(&addr).await?; 44 | let domain = ServerName::try_from("foobar.com").unwrap(); 45 | 46 | let mut stream = connector.connect(domain, stream).await?; 47 | stream.write_all(data).await?; 48 | stream.flush().await?; 49 | 50 | { 51 | let stream = &mut stream; 52 | 53 | // sleep 1s 54 | // 55 | // see https://www.mail-archive.com/openssl-users@openssl.org/msg84451.html 56 | let sleep1 = Timer::after(Duration::from_secs(1)); 57 | match future::or( 58 | async move { Either::Left(Read1(stream).await) }, 59 | async move { Either::Right(sleep1.await) }, 60 | ) 61 | .await 62 | { 63 | Either::Right(_) => {} 64 | Either::Left(Err(err)) => return Err(err), 65 | Either::Left(Ok(_)) => unreachable!(), 66 | } 67 | } 68 | 69 | stream.close().await?; 70 | Ok(stream) 71 | } 72 | 73 | struct DropKill(Child); 74 | 75 | impl Drop for DropKill { 76 | fn drop(&mut self) { 77 | self.0.kill().unwrap(); 78 | } 79 | } 80 | 81 | #[test] 82 | fn test_0rtt() -> io::Result<()> { 83 | smol::block_on(async { 84 | let mut handle = Command::new("openssl") 85 | .arg("s_server") 86 | .arg("-early_data") 87 | .arg("-tls1_3") 88 | .args(["-cert", "./tests/end.cert"]) 89 | .args(["-key", "./tests/end.rsa"]) 90 | .args(["-port", "12354"]) 91 | .stdin(Stdio::piped()) 92 | .stdout(Stdio::piped()) 93 | .spawn() 94 | .map(DropKill)?; 95 | 96 | // wait openssl server 97 | Timer::after(Duration::from_secs(1)).await; 98 | 99 | let mut root_store = RootCertStore::empty(); 100 | let mut chain = BufReader::new(Cursor::new(include_str!("end.chain"))); 101 | for cert in rustls_pemfile::certs(&mut chain).unwrap() { 102 | root_store.add(&Certificate(cert)).unwrap(); 103 | } 104 | 105 | let mut config = ClientConfig::builder() 106 | .with_safe_default_cipher_suites() 107 | .with_safe_default_kx_groups() 108 | .with_protocol_versions(&[&rustls::version::TLS13]) 109 | .unwrap() 110 | .with_root_certificates(root_store) 111 | .with_no_client_auth(); 112 | 113 | config.enable_early_data = true; 114 | let config = Arc::new(config); 115 | let addr = SocketAddr::from(([127, 0, 0, 1], 12354)); 116 | 117 | let io = send(config.clone(), addr, b"hello").await?; 118 | assert!(!io.get_ref().1.is_early_data_accepted()); 119 | 120 | let io = send(config, addr, b"world!").await?; 121 | assert!(io.get_ref().1.is_early_data_accepted()); 122 | 123 | let stdout = handle.0.stdout.as_mut().unwrap(); 124 | let mut lines = BufReader::new(stdout).lines(); 125 | 126 | let has_msg1 = lines.by_ref().any(|line| line.unwrap().contains("hello")); 127 | let has_msg2 = lines.by_ref().any(|line| line.unwrap().contains("world!")); 128 | 129 | assert!(has_msg1 && has_msg2); 130 | 131 | Ok(()) 132 | }) 133 | } 134 | -------------------------------------------------------------------------------- /tests/end.cert: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIFUDCCAzigAwIBAgIJAJaxEZDuHyedMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV 3 | BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX 4 | aWRnaXRzIFB0eSBMdGQwHhcNMjMwODA0MDkwNTUwWhcNMjQwODAzMDkwNTUwWjBa 5 | MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 6 | ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMRMwEQYDVQQDDApmb29iYXIuY29tMIICIjAN 7 | BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAq7NIGBTw7i/JY43Z53EwugTF6IKP 8 | 6m7zQumtEUXWNQ3nQ7f81GeA+VAz7LZzeMuChjtR1lGcOZmx1PlwEmTr/Drfsip6 9 | Ryd4kjWiphp0mSUAKbKaX5Y9CFXNLQRqE01P8SEWZWhAKrI2iWtfjGetIqX/mt6E 10 | OTGl/PaTKes1a+Nucbq3aUCffsQiRhHbwWlmrq3/Nxi8q5ekjEN9ls2djBzy/+cN 11 | RUrq4e8uUN7LMW1HjQlY2Sod7eO3yZnB+Myq2zzi6odaq4yCi5D6VuPVMYBSrlfz 12 | G2CLcSl0ncztSkqO08Bda6WZQQKqXlX2NhldxHxSo4S9mQliv+LWCCIBcqWsXojr 13 | DYwQChJzTBpjPbQzhWDNdxokR9G9NzUcqYFNLPkxHa1ME+nGJYNX8wXXUL8q62zd 14 | LYNcFEX89luaE/gxcSwWpfVfeMgK0f9dDKCPgn7Db2dv8FPbBLhaUiKCaL8phwJ8 15 | 8K+zXCoiTOUxuni48T4q92DUToGw4uyQKd5s71gjZvaaoIsv+kTgF9J3wVzvmUCc 16 | JE5FY1m6oJ2GIvsfFt+OsN3+KV3riCf5+Ivae/1tuDU9FHhCdgg8UzW2EHe1iPZI 17 | 48gx533NYQzItbgUII0aTIRtAbzOAvG1qiUBxgStR9H8duVKGQDE52MX7805E7az 18 | R+1fIOamrngx1q8CAwEAAaMuMCwwEwYDVR0lBAwwCgYIKwYBBQUHAwEwFQYDVR0R 19 | BA4wDIIKZm9vYmFyLmNvbTANBgkqhkiG9w0BAQsFAAOCAgEALySenJ0pGGjo0W1n 20 | 2pwbzDxkZ6SsjHNDDZsfpA8NadJ6/CCtbNhT2pc87to+zssqocRZg71D46kbLBfC 21 | KtQlg7O1FtS3yLOwnKix96USc562t9kMewAPH2krRr2BLF+mV8DR9plmyVNiqRbo 22 | M6zt7ikUzoxojAcRDaVFNUCqRNKYGwcpvXQBgZ62u33mr0g2rfPq5KHfDtqyZvGm 23 | GhFQiii5qvPgpwbZ/8xuyDx9HM1IqejZ8QtHsDYq2da2pLjEsw6xanN2HpaDqIv8 24 | y6RkBPkpZa9q/maXYmu6iMdT3sKJ4fmCRltpIEFoYB6B3cUDUH8n/0WUV/WH/0Hk 25 | O9m7/zilJIJ6BRkgY48PTfh5rn/CD0BFrkLzGvAd2mJoAGSu//eUMYjt5O/ydZuk 26 | Dc0q50DTKzuN0EycFLK58yJmdmvEt2+Y2bGN4vLqljU4+wdqLvxGXR9iwarq0uWF 27 | 5C7YeI4co2FDp0boOzge81gv/s0MBerQK82jUccJT47YgwbY5cyXK6AYiBdqdiZY 28 | 4ye88mon2gSZkiptT+iqLFvguNLvo0vS7cGcT/fegRc9Kp9E5eOI9fvevfT4pK7O 29 | VVPX/NyOYTVucB3pnv33X50jsoecDDROdDicylj7T3jRykiHJRkCB7rUySmHcYo7 30 | HZCD6YHQc2aYKd2yGp0kXUn9C+E= 31 | -----END CERTIFICATE----- 32 | -------------------------------------------------------------------------------- /tests/end.chain: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIFUDCCAzigAwIBAgIJAJaxEZDuHyedMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV 3 | BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX 4 | aWRnaXRzIFB0eSBMdGQwHhcNMjMwODA0MDkwNTUwWhcNMjQwODAzMDkwNTUwWjBa 5 | MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 6 | ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMRMwEQYDVQQDDApmb29iYXIuY29tMIICIjAN 7 | BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAq7NIGBTw7i/JY43Z53EwugTF6IKP 8 | 6m7zQumtEUXWNQ3nQ7f81GeA+VAz7LZzeMuChjtR1lGcOZmx1PlwEmTr/Drfsip6 9 | Ryd4kjWiphp0mSUAKbKaX5Y9CFXNLQRqE01P8SEWZWhAKrI2iWtfjGetIqX/mt6E 10 | OTGl/PaTKes1a+Nucbq3aUCffsQiRhHbwWlmrq3/Nxi8q5ekjEN9ls2djBzy/+cN 11 | RUrq4e8uUN7LMW1HjQlY2Sod7eO3yZnB+Myq2zzi6odaq4yCi5D6VuPVMYBSrlfz 12 | G2CLcSl0ncztSkqO08Bda6WZQQKqXlX2NhldxHxSo4S9mQliv+LWCCIBcqWsXojr 13 | DYwQChJzTBpjPbQzhWDNdxokR9G9NzUcqYFNLPkxHa1ME+nGJYNX8wXXUL8q62zd 14 | LYNcFEX89luaE/gxcSwWpfVfeMgK0f9dDKCPgn7Db2dv8FPbBLhaUiKCaL8phwJ8 15 | 8K+zXCoiTOUxuni48T4q92DUToGw4uyQKd5s71gjZvaaoIsv+kTgF9J3wVzvmUCc 16 | JE5FY1m6oJ2GIvsfFt+OsN3+KV3riCf5+Ivae/1tuDU9FHhCdgg8UzW2EHe1iPZI 17 | 48gx533NYQzItbgUII0aTIRtAbzOAvG1qiUBxgStR9H8duVKGQDE52MX7805E7az 18 | R+1fIOamrngx1q8CAwEAAaMuMCwwEwYDVR0lBAwwCgYIKwYBBQUHAwEwFQYDVR0R 19 | BA4wDIIKZm9vYmFyLmNvbTANBgkqhkiG9w0BAQsFAAOCAgEALySenJ0pGGjo0W1n 20 | 2pwbzDxkZ6SsjHNDDZsfpA8NadJ6/CCtbNhT2pc87to+zssqocRZg71D46kbLBfC 21 | KtQlg7O1FtS3yLOwnKix96USc562t9kMewAPH2krRr2BLF+mV8DR9plmyVNiqRbo 22 | M6zt7ikUzoxojAcRDaVFNUCqRNKYGwcpvXQBgZ62u33mr0g2rfPq5KHfDtqyZvGm 23 | GhFQiii5qvPgpwbZ/8xuyDx9HM1IqejZ8QtHsDYq2da2pLjEsw6xanN2HpaDqIv8 24 | y6RkBPkpZa9q/maXYmu6iMdT3sKJ4fmCRltpIEFoYB6B3cUDUH8n/0WUV/WH/0Hk 25 | O9m7/zilJIJ6BRkgY48PTfh5rn/CD0BFrkLzGvAd2mJoAGSu//eUMYjt5O/ydZuk 26 | Dc0q50DTKzuN0EycFLK58yJmdmvEt2+Y2bGN4vLqljU4+wdqLvxGXR9iwarq0uWF 27 | 5C7YeI4co2FDp0boOzge81gv/s0MBerQK82jUccJT47YgwbY5cyXK6AYiBdqdiZY 28 | 4ye88mon2gSZkiptT+iqLFvguNLvo0vS7cGcT/fegRc9Kp9E5eOI9fvevfT4pK7O 29 | VVPX/NyOYTVucB3pnv33X50jsoecDDROdDicylj7T3jRykiHJRkCB7rUySmHcYo7 30 | HZCD6YHQc2aYKd2yGp0kXUn9C+E= 31 | -----END CERTIFICATE----- 32 | -----BEGIN CERTIFICATE----- 33 | MIIFajCCA1KgAwIBAgIJAN9o7WeFfW8fMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV 34 | BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX 35 | aWRnaXRzIFB0eSBMdGQwHhcNMjMwODA0MDkwNTQ5WhcNMjQwODAzMDkwNTQ5WjBF 36 | MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 37 | ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC 38 | CgKCAgEAyTfVP7gwXhZyYRxx2j8CGAHkzAWXLfzdmaJ/+1szvR18YxJISVG8XGAY 39 | l4wAJGkd5hTYYhrw9ja6KhS65K55aQ0bpNDUSZALmsKIR1vsfXMRZHdqguVLMY1r 40 | Wqw2uZkSxD2y7Qui86SHsgBCltYqPThxyQsdGyueHcl4HMCK4hJ+xbc+32Z/p5it 41 | j8GsygnYJBo9ZLeV69Ug3rTPJrWJIntuobMjcDg/JksHtagtgh5Ai89H57ELv4fM 42 | a0VBm1oeaXLp7QuLTnybrQIFvMg7Lxk2Fk5/AGIoniskqq3jcDp7b6Atm5VT1tVl 43 | +J4rxWjjHWb/tXIUBBREU4rAak/ezF3DjhLDwK/iUI3SZHv4XRc0FnhLGeIwJAAa 44 | 5ECGtXa9IqIcYbBYnftGUcUhHPFRiYyam6W3ZrlFn/NXE3p4mMVup+cYE7aFOOy+ 45 | q0ZcA+0JKnrWQVusnmnGJth5CiabttLZrmJ9DRluZeEv4O6eJAnTAQoxBGuAhnvO 46 | JKN8qjYXdnA38WnV0W0pOe6DiCQcC9tVISwmu78dfLN6qz+x1M9vkLqT7IOtsL9e 47 | 4vG2gJY3xGxoraBEIMr01mHsuXxAG7Esk78lGz0+RVwXIs3OZaqJSJqGfBelZLwi 48 | 8wPxXYlGaulz9LVH1lVEBivAgBMKvdResmgH7O2QmygpLTi/VG0CAwEAAaNdMFsw 49 | DAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAcYwHQYDVR0OBBYEFB8wxB4pPgS7M557 50 | r2uN7Joao5KxMB8GA1UdIwQYMBaAFB8wxB4pPgS7M557r2uN7Joao5KxMA0GCSqG 51 | SIb3DQEBCwUAA4ICAQByL1ztEnZfIkbkt51z13EZc5o5tw6OXiktzHgRXnOMdiYL 52 | kMQo+NDHqXNW+U4R/AOXzKUXH/nIY9cfC9P7duznpw+muQJfdwGFsATrjplKNLJK 53 | YOgPpVGzC6CwR6nvw3cRtQQWAc7nQ5zUFIIJOM0TRlqZ13OdRK50Tt9jysp0xoMB 54 | lzMzgmYQ/O+RASTKk0UQw9kpP7LMihDc96fdxBFJHE+LTM0RfYZuJ1qj2psnkYvM 55 | kmYRw8xCh8GxRX4b6ErrIeCr7rTc5A5FoL5MsQptsv71TW/FDGENlXZl7G4mXFQM 56 | KqDnIdouakbyc+sX2C+663Mr/lDBCxXFvljVg4IfOreih6WeMorjtRdxCrJlLI++ 57 | UJIl1r0b73jUx9fFCf+PA9b5o7/Y/hMwEBVQztGiIgTFaWSVs2gxZfnsupnz1ura 58 | 66GxYdB+5In6Y5Tsly4NB0RyWrljtWOMSciOrNb5czKfks3JjxPMJ9Mp9KSCEV9l 59 | jcB7wYV5XTs5S2IPde/R7ILb/BHvF79Hw7SDf46g7VX3IZcnH7Mq6RbBJ4MPgScf 60 | afVCX4Q1EqO6wPln5hwRNFELd5Utb1RDTRY+398SY+9QGJd0UUZ2xdK8wEmP8A2p 61 | r4K5vcf8QuqXVvz3Kdi855R8mBlqDEIjm+QbXUwgiR2RAUYNZVDsjH0bx0HN5A== 62 | -----END CERTIFICATE----- 63 | -------------------------------------------------------------------------------- /tests/end.rsa: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIJKgIBAAKCAgEAq7NIGBTw7i/JY43Z53EwugTF6IKP6m7zQumtEUXWNQ3nQ7f8 3 | 1GeA+VAz7LZzeMuChjtR1lGcOZmx1PlwEmTr/Drfsip6Ryd4kjWiphp0mSUAKbKa 4 | X5Y9CFXNLQRqE01P8SEWZWhAKrI2iWtfjGetIqX/mt6EOTGl/PaTKes1a+Nucbq3 5 | aUCffsQiRhHbwWlmrq3/Nxi8q5ekjEN9ls2djBzy/+cNRUrq4e8uUN7LMW1HjQlY 6 | 2Sod7eO3yZnB+Myq2zzi6odaq4yCi5D6VuPVMYBSrlfzG2CLcSl0ncztSkqO08Bd 7 | a6WZQQKqXlX2NhldxHxSo4S9mQliv+LWCCIBcqWsXojrDYwQChJzTBpjPbQzhWDN 8 | dxokR9G9NzUcqYFNLPkxHa1ME+nGJYNX8wXXUL8q62zdLYNcFEX89luaE/gxcSwW 9 | pfVfeMgK0f9dDKCPgn7Db2dv8FPbBLhaUiKCaL8phwJ88K+zXCoiTOUxuni48T4q 10 | 92DUToGw4uyQKd5s71gjZvaaoIsv+kTgF9J3wVzvmUCcJE5FY1m6oJ2GIvsfFt+O 11 | sN3+KV3riCf5+Ivae/1tuDU9FHhCdgg8UzW2EHe1iPZI48gx533NYQzItbgUII0a 12 | TIRtAbzOAvG1qiUBxgStR9H8duVKGQDE52MX7805E7azR+1fIOamrngx1q8CAwEA 13 | AQKCAgEAkiVUvSK9/I9yRKnOCwC+b+d2KTVQmEP+DTtnU2d1L814xpxJuOWs0wkg 14 | WWDnIq9elzDQtLLcXe7jfhse+JksgJIAK9+aGwyOxSygF/A2xM/ItrVOTwRLSNf3 15 | f1TdkTZiUCVQsdotm+n7H7bkKldo+DABQ+oY87G9znZ2xtxsqTt5m5ZJXW5jE/yQ 16 | C8JRoew8OXzi2hvVI908cyNTN9QmQMe3UnhxRETDbrIuYylwHM8ecv68wIPn27/T 17 | hOa6QzK6T0ghAW1akOBVkcRCQUlGAw9t0PYNeIURy610lIiEhZK2xahcHC9lJf/F 18 | 0ewrWNr4hDEqCgMHesaRZjEG6v8+6Nj8Jx+uFQMrIPPJHOK6pzj+VZl4FlcqQGJN 19 | NSlXP2gt8t+6WzLEGy0sPiQNghwEqLO1cIt8lbWeFChDgRuiuipQFgD3bgBeEcSJ 20 | rQG520EtQbwysTPtD3MAa1BwYFNMbWQHi0++tPK2wosaYPfGI/L33c8EjTxgDJgw 21 | Z6GRx9P2PWSzcgKs0EQsSyh/9QI1cAmG7kr4D0BWj4Jn6tJITQOj6Ajy5irnQ2Yr 22 | qOtwV9cFznzy0M75WF5Jh4uli/Wpwh+62Auc9srK20oAdWS5lboV+KXD8Ftc6PzK 23 | X1EEY6EqMoLCx6mmtJip6Ufpd0EzgUh0bI8xyTwhVtHB7IDnm8ECggEBANYwPLmV 24 | N8PakybVPEiduK0SQBllA6fmpEF5oKoPdrV84m5ckejPXpXV0jlpVNCMPGV5jR6f 25 | G6PcnxpirngcZUh1pLWmAYwYpTWAm2CnQ/lGgrDWlVIqB3w8UmjPYJuRkghKaOF4 26 | g0bJEfk1p8V9ndpuDYvyXlAPMrPKUsi8y1r9wU7xcMnI39IQ8YIfkUiW75g0f/VK 27 | coANPABlsvwutpXIhWc0h0XiG6yY4qr1s+KH94uih7JRvwC2L/oMhRRH2uuB1iHT 28 | oEMwA/dAQpbJSFSUltziXA7QtnilPryDDUEk9oNf6BGlLwM45CQjgaKgcE+T1W9L 29 | zOvUO1uNF3gZr+ECggEBAM03wvFGslop2nAVsLacMaqb4Lwbx6XgORYxXxD2fyr4 30 | JMZKp32KhtVTOK8MPZkn1L8tkwD/Cmol6yqj9lxTXby3Hu44lczUgjGYaO39Rk5Q 31 | /CBYcbGtQu7LyLmehH0quVBSQmtMVk91ziU1X+Bj6qVaAeAX23jDyE/KAoH/vY6i 32 | 4ViLGpJR2znT45IbGuXaZw5CZOk+/Of6vdfXMSVToHTFpHYAuQkVtuK/lbEbjEnE 33 | c42AgXrWQ2HxQWRYHAW2hIx34H2PsO/JQxnl8io+Zfze/ElpsxYk/u9tTkpydaeF 34 | EPrEpnlEIP4N8sqxQJ8986AmBWW7lJYwaCSIQerLmI8CggEBAJSzOoVxNhzwE3dD 35 | VS3o6fymDgBTY/1eH60hPsyyHa0UPbN26wmhZj5KC0A2g16h7ZBZmgKnXa4ejgro 36 | dc4HkL2Eh0xhKvPTbGc/mR+6IHPgYv1YjKRVb4rt6hy/1IdMwgClgDkAzMsI70R/ 37 | 3rE6a6vo+dit9JJKat3tWhnpEJlkUJ94+d/taI5TmwfG2Lt3pnGaCTgHboS+K2jv 38 | MhroZ3SHmS40hrGar7HdFoiwOinMUa0Msn63SA67bYWAyadx12fnZP1pCft7S1WN 39 | tG0w4tltq2tAb78NYZFSz8JajYormkVNATW243OuPJ1mVSrNjguBTA2Pp34Wgvsl 40 | ciS8WKECggEAVxd0Fvs+077xYiICZe0xsssGfC558y6Oa5m2U7eYzn6S9MhX/pJc 41 | mIoCA1/5gFcEFcJcoc6a9+Nxwx3kftgubtl0Ofsvr8b8HdolpeKYBMKfzYZbceEr 42 | B7baT9QzO/92t9zBLVIvSvee7fGR5+PfgB8LrrPRQ5YrG5mKqOsE4lTDt9UJCNHO 43 | bOM8sBPqvWOL2uRYeRhvMnAaQ1CjHck4znXWTvINlQpvHBnciFY9mkzSEVpZGO13 44 | mUhOzSwLcG0+IXL6ha8Gkyzh2krZFA55L/DeNrWx+BLpUmkcEcIzpk11oEb2s34z 45 | Vj5LLLQ+zZX4H54jKkKKU5bli6N7/g47hwKCAQEAhTwxs7xWQ7GEzR6svN1FpiwN 46 | hP2SlY3i5ed8PIsRSASWJ6rJpJJKgEccXdcnAO3MscleL/cO4s6FSHsGyHFyZ4/D 47 | EsXY/eo5q3Bjv5/hvQt7nnCp1LwNQ0durj2bKdpj7P6Kjli38OF1CDU1E31pVOWJ 48 | kKi/YUIFgJq/rN9Uyx2Y8Km6ubohjuVRVWmva2xOe1mX1ZEOGu8aFliW/1h/m8Ct 49 | B+ywtn4mUDDJqNJ6W5k54SyJXWceMrW8i5t8qOCN5Yd3NYHNFMMBg/XhpIsc+bDL 50 | 0ekvo9w0gfJFnNH1V4uNinGaNBJp7xZSC0TK0I0hvMyRoQQ+M5iGpMBEVYZnAw== 51 | -----END RSA PRIVATE KEY----- 52 | -------------------------------------------------------------------------------- /tests/test.rs: -------------------------------------------------------------------------------- 1 | use async_rustls::{LazyConfigAcceptor, TlsAcceptor, TlsConnector}; 2 | use futures_util::future::TryFutureExt; 3 | use once_cell::sync::Lazy; 4 | use rustls::{ClientConfig, OwnedTrustAnchor}; 5 | use rustls_pemfile::{certs, rsa_private_keys}; 6 | use smol::io::{copy, split, AssertAsync, AsyncReadExt, AsyncWriteExt}; 7 | use smol::net::{TcpListener, TcpStream}; 8 | use smol::prelude::*; 9 | use std::io::{BufReader, Cursor, ErrorKind}; 10 | use std::net::SocketAddr; 11 | use std::sync::mpsc::channel; 12 | use std::sync::Arc; 13 | use std::time::Duration; 14 | use std::{io, thread}; 15 | 16 | const CERT: &str = include_str!("end.cert"); 17 | const CHAIN: &[u8] = include_bytes!("end.chain"); 18 | const RSA: &str = include_str!("end.rsa"); 19 | 20 | static TEST_SERVER: Lazy<(SocketAddr, &'static str, &'static [u8])> = Lazy::new(|| { 21 | let cert = certs(&mut BufReader::new(Cursor::new(CERT))) 22 | .unwrap() 23 | .drain(..) 24 | .map(rustls::Certificate) 25 | .collect(); 26 | let mut keys = rsa_private_keys(&mut BufReader::new(Cursor::new(RSA))).unwrap(); 27 | let mut keys = keys.drain(..).map(rustls::PrivateKey); 28 | 29 | let config = rustls::ServerConfig::builder() 30 | .with_safe_defaults() 31 | .with_no_client_auth() 32 | .with_single_cert(cert, keys.next().unwrap()) 33 | .unwrap(); 34 | let acceptor = TlsAcceptor::from(Arc::new(config)); 35 | 36 | let (send, recv) = channel(); 37 | 38 | thread::spawn(move || { 39 | smol::block_on( 40 | async move { 41 | let addr = SocketAddr::from(([127, 0, 0, 1], 0)); 42 | let listener = TcpListener::bind(&addr).await?; 43 | 44 | send.send(listener.local_addr()?).unwrap(); 45 | 46 | loop { 47 | let (stream, _) = listener.accept().await?; 48 | 49 | let acceptor = acceptor.clone(); 50 | let fut = async move { 51 | let stream = acceptor.accept(stream).await?; 52 | 53 | let (mut reader, mut writer) = split(stream); 54 | copy(&mut reader, &mut writer).await?; 55 | 56 | Ok(()) as io::Result<()> 57 | } 58 | .unwrap_or_else(|err| eprintln!("server: {err:?}")); 59 | 60 | smol::spawn(fut).detach(); 61 | } 62 | } 63 | .unwrap_or_else(|err: io::Error| eprintln!("server: {err:?}")), 64 | ); 65 | }); 66 | 67 | let addr = recv.recv().unwrap(); 68 | (addr, "foobar.com", CHAIN) 69 | }); 70 | 71 | fn start_server() -> &'static (SocketAddr, &'static str, &'static [u8]) { 72 | &TEST_SERVER 73 | } 74 | 75 | async fn start_client(addr: SocketAddr, domain: &str, config: Arc) -> io::Result<()> { 76 | const FILE: &[u8] = include_bytes!("../README.md"); 77 | 78 | let domain = rustls::ServerName::try_from(domain).unwrap(); 79 | let config = TlsConnector::from(config); 80 | let mut buf = vec![0; FILE.len()]; 81 | 82 | let stream = TcpStream::connect(&addr).await?; 83 | let mut stream = config.connect(domain, stream).await?; 84 | stream.write_all(FILE).await?; 85 | stream.flush().await?; 86 | stream.read_exact(&mut buf).await?; 87 | 88 | assert_eq!(buf, FILE); 89 | 90 | Ok(()) 91 | } 92 | 93 | #[test] 94 | fn pass() -> io::Result<()> { 95 | smol::block_on(async { 96 | let (addr, domain, chain) = start_server(); 97 | 98 | // TODO: not sure how to resolve this right now but since 99 | // TcpStream::bind now returns a future it creates a race 100 | // condition until its ready sometimes. 101 | use std::time::*; 102 | smol::Timer::after(Duration::from_secs(1)).await; 103 | 104 | let chain = certs(&mut std::io::Cursor::new(*chain)).unwrap(); 105 | let trust_anchors = chain.iter().map(|cert| { 106 | let ta = webpki::TrustAnchor::try_from_cert_der(&cert[..]).unwrap(); 107 | OwnedTrustAnchor::from_subject_spki_name_constraints( 108 | ta.subject, 109 | ta.spki, 110 | ta.name_constraints, 111 | ) 112 | }); 113 | let mut root_store = rustls::RootCertStore::empty(); 114 | root_store.add_trust_anchors(trust_anchors.into_iter()); 115 | let config = rustls::ClientConfig::builder() 116 | .with_safe_defaults() 117 | .with_root_certificates(root_store) 118 | .with_no_client_auth(); 119 | let config = Arc::new(config); 120 | 121 | start_client(*addr, domain, config).await?; 122 | 123 | Ok(()) 124 | }) 125 | } 126 | 127 | #[test] 128 | fn fail() -> io::Result<()> { 129 | smol::block_on(async { 130 | let (addr, domain, chain) = start_server(); 131 | 132 | let chain = certs(&mut std::io::Cursor::new(*chain)).unwrap(); 133 | let trust_anchors = chain.iter().map(|cert| { 134 | let ta = webpki::TrustAnchor::try_from_cert_der(&cert[..]).unwrap(); 135 | OwnedTrustAnchor::from_subject_spki_name_constraints( 136 | ta.subject, 137 | ta.spki, 138 | ta.name_constraints, 139 | ) 140 | }); 141 | let mut root_store = rustls::RootCertStore::empty(); 142 | root_store.add_trust_anchors(trust_anchors.into_iter()); 143 | let config = rustls::ClientConfig::builder() 144 | .with_safe_defaults() 145 | .with_root_certificates(root_store) 146 | .with_no_client_auth(); 147 | let config = Arc::new(config); 148 | 149 | assert_ne!(domain, &"google.com"); 150 | let ret = start_client(*addr, "google.com", config).await; 151 | assert!(ret.is_err()); 152 | 153 | Ok(()) 154 | }) 155 | } 156 | 157 | // This test is a follow-up from https://github.com/tokio-rs/tls/issues/85 158 | #[test] 159 | fn lazy_config_acceptor_eof() { 160 | smol::block_on(async { 161 | let buf = Cursor::new(Vec::new()); 162 | let acceptor = 163 | LazyConfigAcceptor::new(rustls::server::Acceptor::default(), AssertAsync::new(buf)); 164 | let acceptor = async move { Ok(acceptor.await) }; 165 | let timeout = async { 166 | smol::Timer::after(Duration::from_secs(3)).await; 167 | Err(()) 168 | }; 169 | 170 | let accept_result = acceptor.or(timeout).await.expect("timeout"); 171 | 172 | match accept_result { 173 | Ok(_) => panic!("accepted a connection from zero bytes of data"), 174 | Err(e) if e.kind() == ErrorKind::UnexpectedEof => {} 175 | Err(e) => panic!("unexpected error: {:?}", e), 176 | } 177 | }); 178 | } 179 | 180 | // Include `utils` module 181 | include!("utils.rs"); 182 | -------------------------------------------------------------------------------- /tests/utils.rs: -------------------------------------------------------------------------------- 1 | mod utils { 2 | use std::io::{BufReader, Cursor}; 3 | use std::sync::Arc; 4 | 5 | use rustls::{ClientConfig, OwnedTrustAnchor, PrivateKey, RootCertStore, ServerConfig}; 6 | use rustls_pemfile::{certs, rsa_private_keys}; 7 | 8 | #[allow(dead_code)] 9 | pub fn make_configs() -> (Arc, Arc) { 10 | const CERT: &str = include_str!("end.cert"); 11 | const CHAIN: &str = include_str!("end.chain"); 12 | const RSA: &str = include_str!("end.rsa"); 13 | 14 | let cert = certs(&mut BufReader::new(Cursor::new(CERT))) 15 | .unwrap() 16 | .drain(..) 17 | .map(rustls::Certificate) 18 | .collect(); 19 | let mut keys = rsa_private_keys(&mut BufReader::new(Cursor::new(RSA))).unwrap(); 20 | let mut keys = keys.drain(..).map(PrivateKey); 21 | let sconfig = ServerConfig::builder() 22 | .with_safe_defaults() 23 | .with_no_client_auth() 24 | .with_single_cert(cert, keys.next().unwrap()) 25 | .unwrap(); 26 | 27 | let mut client_root_cert_store = RootCertStore::empty(); 28 | let mut chain = BufReader::new(Cursor::new(CHAIN)); 29 | let certs = certs(&mut chain).unwrap(); 30 | let trust_anchors = certs.iter().map(|cert| { 31 | let ta = webpki::TrustAnchor::try_from_cert_der(&cert[..]).unwrap(); 32 | OwnedTrustAnchor::from_subject_spki_name_constraints( 33 | ta.subject, 34 | ta.spki, 35 | ta.name_constraints, 36 | ) 37 | }); 38 | client_root_cert_store.add_trust_anchors(trust_anchors.into_iter()); 39 | let cconfig = ClientConfig::builder() 40 | .with_safe_defaults() 41 | .with_root_certificates(client_root_cert_store) 42 | .with_no_client_auth(); 43 | 44 | (Arc::new(sconfig), Arc::new(cconfig)) 45 | } 46 | } 47 | --------------------------------------------------------------------------------