diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4fffb2f --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +/Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..0ce62b6 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,6 @@ +[workspace] + +members = [ + "monoio-rustls", + "example", +] diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..493bd6c --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,202 @@ +Copyright (c) 2022 ihciah and other Monoio Contributors + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..dd55236 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2022 ihciah and other Monoio Contributors + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/LICENSE-THIRD-PARTY b/LICENSE-THIRD-PARTY new file mode 100644 index 0000000..407debd --- /dev/null +++ b/LICENSE-THIRD-PARTY @@ -0,0 +1,239 @@ +Third party project code used by this project: tokio-rustls. + +=============================================================================== + +tokio-rustls +https://github.com/tokio-rs/tls/blob/master/tokio-rustls/LICENSE-MIT + +Copyright (c) 2017 quininer kel + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + +=============================================================================== + +tokio-rustls +https://github.com/tokio-rs/tls/blob/master/tokio-rustls/LICENSE-APACHE + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2017 quininer kel + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..086ff5d --- /dev/null +++ b/README.md @@ -0,0 +1,15 @@ +# Monoio TLS +TLS Stream Wrapper for Monoio. + +## TLS with rustls +`monoio-rustls` provides a TLS stream wrapper. It implements the `monoio::io::AsyncReadRent` and `monoio::io::AsyncWriteRent` trait. + +Read `example/src/client.rs` and `example/src/server.rs` for more details. + +## TLS with native tls +Maybe todo. + +## Licenses +Monoio-tls is licensed under the MIT license or Apache license. + +During developing we referenced a lot from tokio-rustls. We would like to thank the authors of the project. \ No newline at end of file diff --git a/example/Cargo.toml b/example/Cargo.toml new file mode 100644 index 0000000..14c4d5a --- /dev/null +++ b/example/Cargo.toml @@ -0,0 +1,20 @@ +[package] +edition = "2021" +name = "monoio-tls-example" +version = "0.1.0" + +[dependencies] +monoio = {version = "0.0.5"} +rustls = {version = "0.20", features = ["tls12"]} +rustls-pemfile = "1" +webpki-roots = "0.22" + +monoio-rustls = {version = "0.0.1", path = "../monoio-rustls", features = ["tls12"]} + +[[bin]] +name = "server" +path = "src/server.rs" + +[[bin]] +name = "client" +path = "src/client.rs" diff --git a/example/README.md b/example/README.md new file mode 100644 index 0000000..9271a39 --- /dev/null +++ b/example/README.md @@ -0,0 +1,3 @@ +# TLS Demo + +Use curl to verify tls handshake: `curl --resolve monoio.rs:50443:127.0.0.1 --cacert rootCA.crt -vvv https://monoio.rs:50443` \ No newline at end of file diff --git a/example/certs/README.md b/example/certs/README.md new file mode 100644 index 0000000..22f7836 --- /dev/null +++ b/example/certs/README.md @@ -0,0 +1,36 @@ +# Certs +Note: The certificates here are only for demo. + +## Self Signed Cert Generation +If you want to generate CA and server certificates by yourself, please make sure the certificates are in x509 v3 format(since webpki only support v3, and there's no way to convert v1 to v3). By default openssl generate server certificate in x509 v1. + +```bash +openssl genrsa -out rootCA.key 4096 +openssl req -x509 -new -nodes -sha512 -days 3650 \ +-subj "/C=CN/ST=Shanghai/L=Shanghai/O=Monoio/OU=TLSDemo/CN=monoio-ca" \ +-key rootCA.key \ +-out rootCA.crt + +openssl genrsa -out server.key 4096 +openssl req -sha512 -new \ +-subj "/C=CN/ST=Shanghai/L=Shanghai/O=Monoio/OU=TLSDemoServer/CN=monoio.rs" \ +-key server.key \ +-out server.csr + +cat > v3.ext <<-EOF +authorityKeyIdentifier=keyid,issuer +basicConstraints=CA:FALSE +keyUsage=digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment +extendedKeyUsage=serverAuth +subjectAltName=@alt_names + +[alt_names] +DNS.1=monoio.rs +EOF + +openssl x509 -req -sha512 -days 3650 \ +-extfile v3.ext \ +-CA rootCA.crt -CAkey rootCA.key -CAcreateserial \ +-in server.csr \ +-out server.crt +``` \ No newline at end of file diff --git a/example/certs/rootCA.crt b/example/certs/rootCA.crt new file mode 100644 index 0000000..4b32a30 --- /dev/null +++ b/example/certs/rootCA.crt @@ -0,0 +1,33 @@ +-----BEGIN CERTIFICATE----- +MIIFtTCCA52gAwIBAgIUPKQnHXsU6Uwd0vQFjy+Rkh0FTKAwDQYJKoZIhvcNAQEN +BQAwajELMAkGA1UEBhMCQ04xETAPBgNVBAgMCFNoYW5naGFpMREwDwYDVQQHDAhT +aGFuZ2hhaTEPMA0GA1UECgwGTW9ub2lvMRAwDgYDVQQLDAdUTFNEZW1vMRIwEAYD +VQQDDAltb25vaW8tY2EwHhcNMjIwNTMwMTA0NDQ5WhcNMzIwNTI3MTA0NDQ5WjBq +MQswCQYDVQQGEwJDTjERMA8GA1UECAwIU2hhbmdoYWkxETAPBgNVBAcMCFNoYW5n +aGFpMQ8wDQYDVQQK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Yt2lKQRLgtV/1rnFnF1uxp/JyjEzkMDg +ongVN62Xu9K9FU/ZK/cTG/YGfg6vQuHOlpO9e2EbmCN4VkITHsid/ZkTN2cgzh6K +SBXmpJ4XQsFqYYcLqHSnL0BFUjZiP19ggSN6FG/Ds8nN1dC5yjOd8blRiMKMHeU5 +ZLvaSk6495ckAym2qP0nFhiMiBS6fkapHd2xG518Stzken87WnlBbj1HOzG1VBIc +3OkmHplGR4JIeJo8ZH/3K7E5G1zbowIoCJYzmIOrhk3tpwCxAzZbMOYU+OWSuWNN +SSr959vsLtFnLKo5o8q8tA+2zVb0xOaJNBbQox+Okz2TnuubBZS2LMKa2RwnrnFW +6xTSnHWHvKidCd5cAZOIyi/J9/5ylEDIzyg3+iqxqv2ltv2NAsANCjcUogAHQBGN +Kto/boQ+zpLc2t982pEGjp9ODn6+FS2WiBMSh/ceVT3XWWBclRDtf2MsQrLYH159 +tSCECBhSxknfIIny90CoLFXQUtwde07rzbPAXKRn6a8qKvyn1uJh75gAapj2vNef +5FEh+FRqhfQ2V6UZ8Z/ny5c37yFi+Xe20A== +-----END CERTIFICATE----- diff --git a/example/certs/rootCA.key b/example/certs/rootCA.key new file mode 100644 index 0000000..1793c09 --- /dev/null +++ b/example/certs/rootCA.key @@ -0,0 +1,51 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIJKQIBAAKCAgEAu3WqvaK31pwVsGR1nwIxdUk35Qn+yofM20Q6X5iR2SuA+anb +YFUk88/DecgP+9ibaNo5yKJVIV4u2EijPeEm5CJMvn/JYchnn0aETbUb2OJA6wE6 +kvFt3K/fNgDQls2H0GX0/MwF1S1SEj92rhyN8Yc1+WG9CJKozbuEewfprcYG+XAz +RREDo/LwkST/4dudGCFCrLYBIh2602XMuNHY6BjwUcDHMrUoTRBQFAnNmU8crFMm +P2TXxLuOXraWfHINoGQQSdk0f/ZmzIAydnBIPm7+T93gWQ/02TJK5OlFrzs1X1Vc +iaODHgXpW76ExerRwQQHCbCCVPBllzZFu0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IshmSrcqQujkkrlMx5skMJ6OQ +oQHTTZv4mj69i78ym+rZrikGRzn5s0mQWPbTNjd6Luxul4loLpxkCMn+x+X/A3NA +Pun4EsZJ2i0AOlxnKqlLIVrN3rQ6cLKJSpfRUrOeMPLrCUd5r9SCd4Yq24AmLgjG +Htfi2G96fHonuYZzsiPY3RvwwPrNoPL+S70LsI67LirjaM9llhtUC4ixdIdSyuuu +blZ5pgK1l9LhnuQ18ycvZpServq54b79AEz05wTNGNjtWlUHLYNCRYowYSc4ptbd +FJ2QaT3xFwVUqumCZS0za2KJfV7VCNMBAoIBAQC2LFqB11PhTg0DIvfWCwGwLkXC +GwW2YBvUNGthQIcPawfdC9ynpHanROkNJputnKNR2pZMWtkwImeHSPCfZSkyKWnh +l/ytx5UOT8iH1LSbI2cWaDar/HYpxlUUn6CcQIQT/ACbGwwDUluVC8KGEdE8QIOd +BaEkHbLYL3uTv61eUs7hGJTEsWfHtcJxAd+XF2k1kANaJbuQheayd2o1QuGYhu3e +lChvRfmRenpqkUUBi1dHFEoxGNSdDWr6HyRDhHXEblvCHdXW3t02GUkY7hnUmw4d +YQDcDxb0XSVJKwFg3caLszS6W0lxVGqqyZc3WHiZ2k0IKBrl3SmnJtOGlaL/ +-----END RSA PRIVATE KEY----- diff --git a/example/certs/rootCA.srl b/example/certs/rootCA.srl new file mode 100644 index 0000000..b68ad68 --- /dev/null +++ b/example/certs/rootCA.srl @@ -0,0 +1 @@ +6890BF801227B6406D46B41DB48334CC8EE5E7BB diff --git a/example/certs/server.crt b/example/certs/server.crt new file mode 100644 index 0000000..c06734f --- /dev/null +++ b/example/certs/server.crt @@ -0,0 +1,34 @@ +-----BEGIN CERTIFICATE----- +MIIFzjCCA7agAwIBAgIUaJC/gBIntkBtRrQdtIM0zI7l57swDQYJKoZIhvcNAQEN +BQAwajELMAkGA1UEBhMCQ04xETAPBgNVBAgMCFNoYW5naGFpMREwDwYDVQQHDAhT +aGFuZ2hhaTEPMA0GA1UECgwGTW9ub2lv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QMMAoGCCsGAQUFBwMBMBQGA1UdEQQNMAuCCW1vbm9pby5yczAN +BgkqhkiG9w0BAQ0FAAOCAgEAhCJrBDCxfreqGqdFr/iGJscAxH/PxlaHUyH71JQy +1aIsoLFGRYgS0be+KIuiR0TzTRIOgZGohcJPWFVE48MeHsnbTjs2GaDyinUj8zxi +VY9zH9fQY/r3Jgz+2SKeKBFuFM4hCIpU4FceVPnVtqxLJ2EqCdz5q/Imif5wtqzd +FdqPLVndKXEwItQSqCrToLbLAIM69j6HJAZU4uXTAH/kBzqV1IpcFZQQDo34xh+6 +ixohlV0Gw7woi8qxymxOgiE2Enw/Z+IKVOi3E4X240oHDCO/TMJPCVyARed7Djsc +L7NUIFAFhyJouUuhUJC3Dvc4KSkkayEx//CFT4c+DEnjFmR9LiRElnnmlI0xvvhN +OcsFPFYxrzelOsus1P7e8geQsS+0RLfOLGZPcjUrx/5TH9OHjjxCZHL9wRjswfRD +Hyaf7/zp3AjDqFKGWyaINtiaWgPFZAIj+6EMZeL6RYpBfOIBwP/klpCDNqhYhVUd +sUIqjjDPt1jomMlE8G5SCxbhduDF/AV15LYPEGXFXGT4G3p2Vc0vydYP8KtRTOok +IirRFxvgCeIvmTPqX6U72BHioZWmlkiTVQ+RI0OL3WseWn+zxkhQB0VwJMqaguR4 +1WKyt6eKMse3xiy29PklnkTS+qLZZivI7n2oCm6CW3vRg7SWMNAX3smFxbKmYyrE +Yws= +-----END CERTIFICATE----- diff --git a/example/certs/server.csr b/example/certs/server.csr new file mode 100644 index 0000000..7b7f187 --- /dev/null +++ b/example/certs/server.csr @@ -0,0 +1,28 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIEtTCCAp0CAQAwcDELMAkGA1UEBhMCQ04xETAPBgNVBAgMCFNoYW5naGFpMREw +DwYDVQQHDAhTaGFuZ2hhaTEPMA0GA1UECgwGTW9ub2lvMRYwFAYDVQQLDA1UTFNE +ZW1vU2VydmVyMRIwEAYDVQQDDAltb25vaW8ucnMwggIiMA0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FeHWZCRKD3aHeDQBVgO5PqpRC28zlObN6 +Itf7xPJosu+H8VSDvfsBI/8oJBMkTCpjxdWkiTM8gF+OijA/gdk/1aJFpWFGWrWQ +u6AZFoBbg4PBIOL11CXYzctql4RPfl1XS3A+XdmWM0kmOfkA+MzflCmStTxylE5F +P96RTfoHeT7HZ+TSTSetA3BI0hkynhD8hnpv3gstsvmtV4ALg1UXytwwqmKmAZ1j +nTkVHm7tdq+wbJjCur845Jvzh8Dcdz7oXy1ezKGk1n8VLoDqULYVbXXX8EEXl9nx +1VSUQM9H8oqazgy5QsSO5cGOSQt7HYKEF5C1sm4DwK1vVKpduBKRom8YIemwZoXR +LKZ7Qdn1RxHH +-----END CERTIFICATE REQUEST----- diff --git a/example/certs/server.key b/example/certs/server.key new file mode 100644 index 0000000..c4f853d --- /dev/null +++ b/example/certs/server.key @@ -0,0 +1,51 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIJKQIBAAKCAgEA0IOTSxrjtE0ltdAvhZMpMZjvfYsQjaW4vPcOUd+59pqHvYCx +rwrRd5WTWwT4sfKpHZxGsV4ZAwIuEctsXQNdYEwyO5qFqzR3GsT5PZyrXP9HawV5 +07RBUawmxrTAjW0h64nv1qHzse+7FW3tzZyjCh/Sqp4WsX7rXThWgzT4F7hd7nIN +wYsu2zckA3f+56v4DxIoFKJhOmIvzBYd6J4U5VemPPWkJd8i008eEMRkiuvTVIz8 +vVw0uKtCpfLWGxRu13gbdZcSz1Wc2gh8GbfsKp6E0Z07foXkgkR+erCLbmf8lsnn +onnHm2vfnbyi65Of6HyLB6ObKJbV/mEBC93SSZNjdZjmi38tmdKSMbb5mgcsskLF +HHdI3x53/DFH7B4RaDm2t4jf1btz1dzjXorZXJVd6AKXoA8m2jUpuFLpGEqkiGrs +99VeO0nU3VOS8wUJn/GZ/voq36KeF34wYkMmRf/pu7CFWJGjdVfsgBGnNmEnO7g8 +kWdgNOZkXMQqTI1dGUrQUKAwU30pHObOUZk2jiLwxOuM2AWKC2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MJVLriN2rwAM +4Kmfog/U5XO0omwY4eV6r1MEdEVAS5aY5PT9myg4p04MvVcAiGI5M/5mcpW1jEA2 +ezRUR5kLR1bbs1OyUci3UbXHN1ZNMzMDFQKCAQAzHYFCuEfQoGMu8Fp+IE3DRJ5i +a48cuKJett4gPUAa/nbAZb0DHg/0A6uCSAk+4FNf9Svno+V17EnBCiri/f4cGSpP +DjtoRV0iJKrnbvAmaKhSGC6Oz1DZjpbqF4cXTGr5+xfmjmgQ3bgaeXqp3pEXYxRT +hdM3Vfy7XWYHIp23eZazP3ikKk/VfHmi8qQFxzSiwfJhTDVzqseTNCZMTpltcAdr +v7Jc61mqiXpw2IXV0ctNt1rxVTHc1a3CEkRMHsaZDaBqgrIifnyKqf2lEdYG90w+ +35Xhas5ap+msAwSlyVQ79oYNCIM38lhcP+wljJOuIYqQ5+gxyIvqiJY9Gw6O +-----END RSA PRIVATE KEY----- diff --git a/example/certs/v3.ext b/example/certs/v3.ext new file mode 100644 index 0000000..e4d2624 --- /dev/null +++ b/example/certs/v3.ext @@ -0,0 +1,8 @@ +authorityKeyIdentifier=keyid,issuer +basicConstraints=CA:FALSE +keyUsage=digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment +extendedKeyUsage=serverAuth +subjectAltName=@alt_names + +[alt_names] +DNS.1=monoio.rs diff --git a/example/src/client.rs b/example/src/client.rs new file mode 100644 index 0000000..43c62fe --- /dev/null +++ b/example/src/client.rs @@ -0,0 +1,46 @@ +use std::io::Cursor; + +use monoio::{net::TcpStream, io::{AsyncWriteRentExt, AsyncReadRentExt, AsyncWriteRent}}; +use monoio_rustls::TlsConnector; +use rustls::{RootCertStore, OwnedTrustAnchor, Certificate}; +use rustls_pemfile::certs; + +#[monoio::main] +async fn main() { + let mut root_store = RootCertStore::empty(); + root_store.add_server_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.0.iter().map(|ta| { + OwnedTrustAnchor::from_subject_spki_name_constraints( + ta.subject, + ta.spki, + ta.name_constraints, + ) + })); + root_store.add(&read_ca_certs()).expect("unable to trust self-signed CA"); + let config = rustls::ClientConfig::builder() + .with_safe_defaults() + .with_root_certificates(root_store) + .with_no_client_auth(); + + let connector = TlsConnector::from(config); + let stream = TcpStream::connect("127.0.0.1:50443").await.unwrap(); + println!("127.0.0.1:50443 connected"); + + let domain = rustls::ServerName::try_from("monoio.rs").unwrap(); + let mut stream = connector.connect(domain, stream).await.unwrap(); + println!("handshake success"); + + let data = "hello world"; + stream.write_all(data).await.0.expect("unable to send data"); + println!("send data: {data}"); + let buf = vec![0; data.len()]; + let (res, buf) = stream.read_exact(buf).await; + assert!(res.is_ok(), "unable to recv data"); + println!("recv data: {}", String::from_utf8(buf).expect("invalid data")); + let _ = stream.shutdown().await; +} + +fn read_ca_certs() -> Certificate { + let mut ca_cursor = Cursor::new(include_bytes!("../certs/rootCA.crt")); + let ca_data = certs(&mut ca_cursor).unwrap().pop().unwrap(); + Certificate(ca_data) +} \ No newline at end of file diff --git a/example/src/server.rs b/example/src/server.rs new file mode 100644 index 0000000..0e154a8 --- /dev/null +++ b/example/src/server.rs @@ -0,0 +1,81 @@ +// An echo server with tls. + +use std::io::{Cursor, self}; + +use monoio::{net::{TcpListener, TcpStream}, io::{AsyncReadRent, AsyncWriteRentExt}}; +use monoio_rustls::TlsAcceptor; +use rustls::{Certificate, PrivateKey, ServerConfig}; +use rustls_pemfile::{certs, rsa_private_keys}; + +#[monoio::main] +async fn main() { + let (chain, key) = read_server_certs(); + let config = ServerConfig::builder() + .with_safe_defaults() + .with_no_client_auth() + .with_single_cert(chain, key) + .expect("invalid cert chain or key"); + let tls_acceptor = TlsAcceptor::from(config); + + let listener = TcpListener::bind("127.0.0.1:50443").expect("unable to listen 127.0.0.1:50443"); + while let Ok((stream, addr)) = listener.accept().await { + println!("Accepted from {addr}, will accept tls handshake"); + let tls_acceptor = tls_acceptor.clone(); + monoio::spawn(async move { + let e = process_raw_stream(stream, tls_acceptor).await; + println!("Relay finished {e:?}"); + }); + } + println!("Server exit"); +} + +async fn process_raw_stream(stream: TcpStream, tls_acceptor: TlsAcceptor) -> io::Result<()> { + let mut tls_stream = match tls_acceptor.accept(stream).await { + Ok(s) => { + println!("Handshake finished, will relay data"); + s + }, + Err(e) => { + println!("Unable to do handshake: {e}"); + return Err(e.into()); + }, + }; + + let mut n = 0; + let mut buf = Vec::with_capacity(8 * 1024); + loop { + // read + let (res, _buf) = tls_stream.read(buf).await; + buf = _buf; + let res: usize = res?; + if res == 0 { + // eof + break; + } + + // write all + let (res, _buf) = tls_stream.write_all(buf).await; + buf = _buf; + n += res?; + } + + println!("Relay finished normally, {n} bytes processed"); + Ok(()) +} + +fn read_server_certs() -> (Vec, PrivateKey) { + let mut ca_cursor = Cursor::new(include_bytes!("../certs/rootCA.crt")); + let ca_data = certs(&mut ca_cursor).unwrap().pop().unwrap(); + let ca = Certificate(ca_data); + + let mut crt_cursor = Cursor::new(include_bytes!("../certs/server.crt")); + let crt_data = certs(&mut crt_cursor).unwrap().pop().unwrap(); + let crt = Certificate(crt_data); + + let mut key_cursor = Cursor::new(include_bytes!("../certs/server.key")); + let key_data = rsa_private_keys(&mut key_cursor).unwrap().pop().unwrap(); + let key = PrivateKey(key_data); + + let chain = vec![crt, ca]; + (chain, key) +} diff --git a/monoio-rustls/Cargo.toml b/monoio-rustls/Cargo.toml new file mode 100644 index 0000000..b60ad37 --- /dev/null +++ b/monoio-rustls/Cargo.toml @@ -0,0 +1,26 @@ +[package] +authors = ["ChiHai "] +categories = ["asynchronous", "cryptography", "network-programming"] +description = "Asynchronous TLS streams wrapper for Monoio based on Rustls." +edition = "2021" +homepage = "https://github.com/monoio-rs/monoio-tls" +license = "MIT/Apache-2.0" +name = "monoio-rustls" +readme = "README.md" +repository = "https://github.com/monoio-rs/monoio-tls" +version = "0.0.1" + +[dependencies] +monoio = {version = "0.0.5", default-features = false} +rustls = {version = "0.20", default-features = false} +thiserror = "1" + +[features] +dangerous_configuration = ["rustls/dangerous_configuration"] +default = ["logging", "tls12"] +logging = ["rustls/logging"] +tls12 = ["rustls/tls12"] + +[dev-dependencies] +monoio = {version = "0.0.5"} +webpki-roots = "0.22" diff --git a/monoio-rustls/README.md b/monoio-rustls/README.md new file mode 100644 index 0000000..fc045d0 --- /dev/null +++ b/monoio-rustls/README.md @@ -0,0 +1 @@ +# Monoio-rustls diff --git a/monoio-rustls/examples/connect.rs b/monoio-rustls/examples/connect.rs new file mode 100644 index 0000000..0f2dc8d --- /dev/null +++ b/monoio-rustls/examples/connect.rs @@ -0,0 +1,40 @@ +use std::sync::Arc; + +use monoio::{net::TcpStream, io::{AsyncWriteRentExt, AsyncReadRent}}; +use monoio_rustls::TlsConnector; +use rustls::{RootCertStore, OwnedTrustAnchor}; + +#[monoio::main] +async fn main() { + let mut root_store = RootCertStore::empty(); + root_store.add_server_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.0.iter().map(|ta| { + OwnedTrustAnchor::from_subject_spki_name_constraints( + ta.subject, + ta.spki, + ta.name_constraints, + ) + })); + let config = rustls::ClientConfig::builder() + .with_safe_defaults() + .with_root_certificates(root_store) + .with_no_client_auth(); + + let connector = TlsConnector::from(Arc::new(config)); + let stream = TcpStream::connect("rsproxy.cn:443").await.unwrap(); + println!("rsproxy.cn:443 connected"); + + let domain = rustls::ServerName::try_from("rsproxy.cn").unwrap(); + let mut stream = connector.connect(domain, stream).await.unwrap(); + println!("handshake success"); + + let content = b"GET / HTTP/1.0\r\nHost: rsproxy.cn\r\n\r\n"; + let (r, _) = stream.write_all(content).await; + r.expect("unable to write http request"); + println!("http request sent"); + + let buf = vec![0_u8; 64]; + let (r, buf) = stream.read(buf).await; + r.expect("unable to read http response"); + let resp = String::from_utf8(buf).unwrap(); + println!("http response recv: \n\n{}", resp); +} \ No newline at end of file diff --git a/monoio-rustls/src/client.rs b/monoio-rustls/src/client.rs new file mode 100644 index 0000000..3b18c6b --- /dev/null +++ b/monoio-rustls/src/client.rs @@ -0,0 +1,99 @@ +use std::{future::Future, sync::Arc}; + +use monoio::{ + io::{AsyncReadRent, AsyncWriteRent}, + BufResult, +}; +use rustls::{ClientConfig, ClientConnection}; + +use crate::{stream::Stream, TlsError}; + +/// A wrapper around an underlying raw stream which implements the TLS protocol. +#[derive(Debug)] +pub struct TlsStream(pub(crate) Stream); + +impl AsyncReadRent for TlsStream +where + IO: AsyncReadRent + AsyncWriteRent, +{ + type ReadFuture<'a, T> = impl Future> + where + T: 'a, IO: 'a; + + type ReadvFuture<'a, T> = impl Future> + where + T: 'a, IO: 'a; + + fn read(&mut self, buf: T) -> Self::ReadFuture<'_, T> { + self.0.read(buf) + } + + fn readv(&mut self, buf: T) -> Self::ReadvFuture<'_, T> { + self.0.readv(buf) + } +} + +impl AsyncWriteRent for TlsStream +where + IO: AsyncReadRent + AsyncWriteRent, +{ + type WriteFuture<'a, T> = impl Future> + where + T: 'a, IO: 'a; + + type WritevFuture<'a, T> = impl Future> + where + T: 'a, IO: 'a; + + type ShutdownFuture<'a> = impl Future> + where + IO: 'a; + + fn write(&mut self, buf: T) -> Self::WriteFuture<'_, T> { + self.0.write(buf) + } + + fn writev(&mut self, buf_vec: T) -> Self::WritevFuture<'_, T> { + self.0.writev(buf_vec) + } + + fn shutdown(&mut self) -> Self::ShutdownFuture<'_> { + self.0.shutdown() + } +} + +/// A wrapper around a `rustls::ClientConfig`, providing an async `connect` method. +#[derive(Clone)] +pub struct TlsConnector { + inner: Arc, +} + +impl From> for TlsConnector { + fn from(inner: Arc) -> TlsConnector { + TlsConnector { inner } + } +} + +impl From for TlsConnector { + fn from(inner: ClientConfig) -> TlsConnector { + TlsConnector { + inner: Arc::new(inner), + } + } +} + +impl TlsConnector { + pub async fn connect( + &self, + domain: rustls::ServerName, + stream: IO, + ) -> Result, TlsError> + where + IO: AsyncReadRent + AsyncWriteRent, + { + let session = ClientConnection::new(self.inner.clone(), domain)?; + let mut stream = Stream::new(stream, session); + stream.handshake().await?; + Ok(TlsStream(stream)) + } +} diff --git a/monoio-rustls/src/error.rs b/monoio-rustls/src/error.rs new file mode 100644 index 0000000..0c4f8a6 --- /dev/null +++ b/monoio-rustls/src/error.rs @@ -0,0 +1,20 @@ +use std::io; + +use thiserror::Error; + +#[derive(Error, Debug)] +pub enum TlsError { + #[error("io error")] + Io(#[from] std::io::Error), + #[error("rustls error")] + Rustls(#[from] rustls::Error), +} + +impl From for io::Error { + fn from(e: TlsError) -> Self { + match e { + TlsError::Io(e) => e, + TlsError::Rustls(e) => io::Error::new(io::ErrorKind::Other, e), + } + } +} diff --git a/monoio-rustls/src/lib.rs b/monoio-rustls/src/lib.rs new file mode 100644 index 0000000..70f7d44 --- /dev/null +++ b/monoio-rustls/src/lib.rs @@ -0,0 +1,12 @@ +#![feature(generic_associated_types)] +#![feature(type_alias_impl_trait)] + +mod client; +mod error; +mod server; +mod stream; +mod unsafe_io; + +pub use client::{TlsConnector, TlsStream as ClientTlsStream}; +pub use error::TlsError; +pub use server::{TlsAcceptor, TlsStream as ServerTlsStream}; diff --git a/monoio-rustls/src/server.rs b/monoio-rustls/src/server.rs new file mode 100644 index 0000000..3fc711a --- /dev/null +++ b/monoio-rustls/src/server.rs @@ -0,0 +1,95 @@ +use std::{future::Future, sync::Arc}; + +use monoio::{ + io::{AsyncReadRent, AsyncWriteRent}, + BufResult, +}; +use rustls::{ServerConfig, ServerConnection}; + +use crate::{stream::Stream, TlsError}; + +/// A wrapper around an underlying raw stream which implements the TLS protocol. +#[derive(Debug)] +pub struct TlsStream(pub(crate) Stream); + +impl AsyncReadRent for TlsStream +where + IO: AsyncReadRent + AsyncWriteRent, +{ + type ReadFuture<'a, T> = impl Future> + where + T: 'a, IO: 'a; + + type ReadvFuture<'a, T> = impl Future> + where + T: 'a, IO: 'a; + + fn read(&mut self, buf: T) -> Self::ReadFuture<'_, T> { + self.0.read(buf) + } + + fn readv(&mut self, buf: T) -> Self::ReadvFuture<'_, T> { + self.0.readv(buf) + } +} + +impl AsyncWriteRent for TlsStream +where + IO: AsyncReadRent + AsyncWriteRent, +{ + type WriteFuture<'a, T> = impl Future> + where + T: 'a, IO: 'a; + + type WritevFuture<'a, T> = impl Future> + where + T: 'a, IO: 'a; + + type ShutdownFuture<'a> = impl Future> + where + IO: 'a; + + fn write(&mut self, buf: T) -> Self::WriteFuture<'_, T> { + self.0.write(buf) + } + + fn writev(&mut self, buf_vec: T) -> Self::WritevFuture<'_, T> { + self.0.writev(buf_vec) + } + + fn shutdown(&mut self) -> Self::ShutdownFuture<'_> { + self.0.shutdown() + } +} + +/// A wrapper around a `rustls::ServerConfig`, providing an async `accept` method. +#[derive(Clone)] +pub struct TlsAcceptor { + inner: Arc, +} + +impl From> for TlsAcceptor { + fn from(inner: Arc) -> TlsAcceptor { + TlsAcceptor { inner } + } +} + +impl From for TlsAcceptor { + fn from(inner: ServerConfig) -> TlsAcceptor { + TlsAcceptor { + inner: Arc::new(inner), + } + } +} + +impl TlsAcceptor { + pub async fn accept(&self, stream: IO) -> Result, TlsError> + where + IO: AsyncReadRent + AsyncWriteRent, + { + let session = ServerConnection::new(self.inner.clone())?; + let mut stream = Stream::new(stream, session); + stream.handshake().await?; + Ok(TlsStream(stream)) + } +} diff --git a/monoio-rustls/src/stream.rs b/monoio-rustls/src/stream.rs new file mode 100644 index 0000000..de2fc33 --- /dev/null +++ b/monoio-rustls/src/stream.rs @@ -0,0 +1,239 @@ +use std::{ + future::Future, + io::{self, Read, Write}, + ops::{Deref, DerefMut}, +}; + +use monoio::{ + io::{AsyncReadRent, AsyncWriteRent}, + BufResult, +}; +use rustls::{ConnectionCommon, SideData}; + +use crate::unsafe_io::{UnsafeRead, UnsafeWrite}; + +#[derive(Debug)] +pub(crate) struct Stream { + pub(crate) io: IO, + pub(crate) session: C, +} + +impl Stream { + pub fn new(io: IO, session: C) -> Self { + Self { io, session } + } +} + +impl Stream +where + C: DerefMut + Deref>, +{ + pub(crate) async fn read_io(&mut self) -> io::Result { + let mut unsafe_read = UnsafeRead::default(); + + let n = loop { + match self.session.read_tls(&mut unsafe_read) { + Ok(n) => { + break n; + } + Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { + unsafe { unsafe_read.do_io(&mut self.io).await? }; + continue; + } + Err(err) => return Err(err), + } + }; + + let state = match self.session.process_new_packets() { + Ok(state) => state, + Err(err) => { + // TODO(ihciah): when to write_io? If we do this in read call, the UnsafeWrite may crash + // when we impl split in an UnsafeCell way. + let _ = self.write_io().await; + return Err(io::Error::new(io::ErrorKind::InvalidData, err)); + } + }; + + if state.peer_has_closed() && self.session.is_handshaking() { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "tls handshake alert", + )); + } + + Ok(n) + } + + pub(crate) async fn write_io(&mut self) -> io::Result { + let mut unsafe_write = UnsafeWrite::default(); + + let n = loop { + match self.session.write_tls(&mut unsafe_write) { + Ok(n) => { + break n; + } + Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { + unsafe { unsafe_write.do_io(&mut self.io).await? }; + continue; + } + Err(err) => return Err(err), + } + }; + + Ok(n) + } + + pub(crate) async fn handshake(&mut self) -> io::Result<(usize, usize)> { + let mut wrlen = 0; + let mut rdlen = 0; + let mut eof = false; + + loop { + while self.session.wants_write() && self.session.is_handshaking() { + wrlen += self.write_io().await?; + } + while !eof && self.session.wants_read() && self.session.is_handshaking() { + let n = self.read_io().await?; + rdlen += n; + if n == 0 { + eof = true; + } + } + + match (eof, self.session.is_handshaking()) { + (true, true) => { + let err = io::Error::new(io::ErrorKind::UnexpectedEof, "tls handshake eof"); + return Err(err); + } + (false, true) => (), + (_, false) => { + break; + } + }; + } + + // flush buffer + while self.session.wants_write() { + wrlen += self.write_io().await?; + } + + Ok((rdlen, wrlen)) + } +} + +impl AsyncReadRent for Stream +where + C: DerefMut + Deref>, +{ + type ReadFuture<'a, T> = impl Future> + where + T: 'a, Self: 'a; + + type ReadvFuture<'a, T> = impl Future> + where + T: 'a, Self: 'a; + + fn read(&mut self, mut buf: T) -> Self::ReadFuture<'_, T> { + let slice = unsafe { std::slice::from_raw_parts_mut(buf.write_ptr(), buf.bytes_total()) }; + async move { + loop { + // read from rustls to buffer + match self.session.reader().read(slice) { + Ok(n) => { + unsafe { buf.set_init(n) }; + return (Ok(n), buf); + } + // we need more data, read something. + Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => (), + Err(e) => { + return (Err(e), buf); + } + } + + // now we need data, read something into rustls + match self.read_io().await { + Ok(0) => { + return ( + Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "tls raw stream eof", + )), + buf, + ); + } + Ok(_) => (), + Err(e) => { + return (Err(e), buf); + } + }; + } + } + } + + fn readv(&mut self, buf: T) -> Self::ReadvFuture<'_, T> { + // TODO + async move { + let _ = buf; + todo!() + } + } +} + +impl AsyncWriteRent for Stream +where + C: DerefMut + Deref>, +{ + type WriteFuture<'a, T> = impl Future> + where + T: 'a, Self: 'a; + + type WritevFuture<'a, T> = impl Future> + where + T: 'a, Self: 'a; + + type ShutdownFuture<'a> = impl Future> + where + Self: 'a; + + fn write(&mut self, buf: T) -> Self::WriteFuture<'_, T> { + async move { + // construct slice + let slice = unsafe { std::slice::from_raw_parts(buf.read_ptr(), buf.bytes_init()) }; + + // write slice to rustls + let n = match self.session.writer().write(slice) { + Ok(n) => n, + Err(e) => return (Err(e), buf), + }; + + // write from rustls to connection + while self.session.wants_write() { + match self.write_io().await { + Ok(0) => { + break; + } + Ok(_) => (), + Err(e) => return (Err(e), buf), + } + } + (Ok(n), buf) + } + } + + fn writev(&mut self, buf_vec: T) -> Self::WritevFuture<'_, T> { + async move { + let _ = buf_vec; + todo!() + } + } + + fn shutdown(&mut self) -> Self::ShutdownFuture<'_> { + self.session.send_close_notify(); + async move { + while self.session.wants_write() { + self.write_io().await?; + } + self.io.shutdown().await + } + } +} diff --git a/monoio-rustls/src/unsafe_io.rs b/monoio-rustls/src/unsafe_io.rs new file mode 100644 index 0000000..dd958d6 --- /dev/null +++ b/monoio-rustls/src/unsafe_io.rs @@ -0,0 +1,143 @@ +use std::io; + +use monoio::{buf::{IoBufMut, IoBuf}, io::{AsyncReadRent, AsyncWriteRent}}; + +/// Used by both UnsafeRead and UnsafeWrite. +enum Status { + /// We haven't do real io, and maybe the dest is recorded. + WaitFill(Option<(*const u8, usize)>), + /// We have already do real io. The length maybe zero or non-zero. + Filled(usize), +} + +impl Default for Status { + fn default() -> Self { + Status::WaitFill(None) + } +} + +/// UnsafeRead is a wrapper of some meta data. +/// It implements std::io::Read trait. But it do real io in an async way. +/// On the first read, it may returns WouldBlock error, which means the +/// `fullfill` should be called to do real io. +/// The data is read directly into the dest that last std read passes. +/// Note that this action is an unsafe hack to avoid data copy. +/// You can only use this wrapper when you make sure the read dest is always +/// a valid buffer. +#[derive(Default)] +pub(crate) struct UnsafeRead { + status: Status, +} + +impl UnsafeRead { + /// `do_io` must be called after calling to io::Read::read. + pub(crate) async unsafe fn do_io(&mut self, mut io: IO) -> io::Result { + match self.status { + Status::WaitFill(Some((ptr, len))) => { + let buf = RawBuf { ptr, len }; + let n = io.read(buf).await.0?; + self.status = Status::Filled(n); + Ok(n) + } + Status::Filled(len) => Ok(len), + Status::WaitFill(None) => Err(io::ErrorKind::WouldBlock.into()), + } + } +} + +impl io::Read for UnsafeRead { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match self.status { + Status::WaitFill(_) => { + let ptr = buf.as_ptr(); + let len = buf.len(); + self.status = Status::WaitFill(Some((ptr, len))); + Err(io::ErrorKind::WouldBlock.into()) + } + Status::Filled(len) => { + if len != 0 { + // reset only when not eof + self.status = Status::WaitFill(None); + } + Ok(len) + } + } + } +} + +/// UnsafeWrite behaves like `UnsafeRead`. +#[derive(Default)] +pub(crate) struct UnsafeWrite { + status: Status, +} + +impl UnsafeWrite { + /// `do_io` must be called after calling to io::Write::write. + pub(crate) async unsafe fn do_io(&mut self, mut io: IO) -> io::Result { + match self.status { + Status::WaitFill(Some((ptr, len))) => { + let buf = RawBuf { ptr, len }; + let n = io.write(buf).await.0?; + self.status = Status::Filled(n); + Ok(n) + } + Status::Filled(len) => Ok(len), + Status::WaitFill(None) => Err(io::ErrorKind::WouldBlock.into()), + } + } +} + +impl io::Write for UnsafeWrite { + fn write(&mut self, buf: &[u8]) -> io::Result { + match self.status { + Status::WaitFill(_) => { + let ptr = buf.as_ptr(); + let len = buf.len(); + self.status = Status::WaitFill(Some((ptr, len))); + Err(io::ErrorKind::WouldBlock.into()) + } + Status::Filled(len) => { + if len != 0 { + // reset only when not eof + self.status = Status::WaitFill(None); + } + Ok(len) + } + } + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +/// RawBuf is a wrapper of buffer ptr and len. +/// It seems that it hold the ownership of the buffer, which infact not. +/// Use this wrapper only when you can make sure the buffer ptr lives +/// longer than the wrapper. +struct RawBuf { + ptr: *const u8, + len: usize, +} + +unsafe impl IoBuf for RawBuf { + fn read_ptr(&self) -> *const u8 { + self.ptr + } + + fn bytes_init(&self) -> usize { + self.len + } +} + +unsafe impl IoBufMut for RawBuf { + fn write_ptr(&mut self) -> *mut u8 { + self.ptr as *mut u8 + } + + fn bytes_total(&self) -> usize { + self.len + } + + unsafe fn set_init(&mut self, _pos: usize) {} +} \ No newline at end of file diff --git a/rust-toolchain b/rust-toolchain new file mode 100644 index 0000000..07ade69 --- /dev/null +++ b/rust-toolchain @@ -0,0 +1 @@ +nightly \ No newline at end of file