├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples ├── certificates.rs ├── document.rs ├── routing.rs ├── serve_dir.rs └── twinstar_logo.txt ├── public └── README.gemini └── src ├── lib.rs ├── routing.rs ├── types.rs ├── types ├── body.rs ├── document.rs ├── meta.rs ├── request.rs ├── response.rs ├── response_header.rs └── status.rs └── util.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | /cert/ 4 | /public/ 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - stable 4 | - beta 5 | - nightly 6 | jobs: 7 | allow_failures: 8 | - rust: nightly 9 | fast_finish: true 10 | script: 11 | - cargo test --verbose --workspace -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | ## [Unreleased] 8 | 9 | ## [0.4.0] - 2020-12-05 10 | ### Added 11 | - `document` API for creating Gemini documents 12 | - preliminary timeout API, incl a special case for complex MIMEs by [@Alch-Emi] 13 | - `Response::success_*` variants by [@Alch-Emi] 14 | - `redirect_temporary_lossy` for `Response` and `ResponseHeader` 15 | - `bad_request_lossy` for `Response` and `ResponseHeader` 16 | - support for a lot more mime-types in `guess_mime_from_path`, backed by the `mime_guess` crate 17 | - customizable TLS cert & key paths by [@Alch-Emi] 18 | - `server_dir` default feature for serve_dir utils [@Alch-Emi] 19 | - Docments can be converted into responses with std::convert::Into [@Alch-Emi] 20 | ### Improved 21 | - build time and size by [@Alch-Emi](https://github.com/Alch-Emi) 22 | ### Changed 23 | - Added route API [@Alch-Emi](https://github.com/Alch-Emi) 24 | - Improved error handling in serve_dir [@Alch-Emi] 25 | 26 | ## [0.3.0] - 2020-11-14 27 | ### Added 28 | - `GEMINI_MIME_STR`, the `&str` representation of the Gemini MIME 29 | - `Meta::new_lossy`, constructor that never fails 30 | - `Meta::MAX_LEN`, which is `1024` 31 | - "lossy" constructors for `Response` and `Status` (see `Meta::new_lossy`) 32 | 33 | ### Changed 34 | - `Meta::new` now rejects strings exceeding `Meta::MAX_LEN` (`1024`) 35 | - Some `Response` and `Status` constructors are now infallible 36 | - Improve error messages 37 | 38 | ### Deprecated 39 | - Instead of `gemini_mime()` use `GEMINI_MIME` 40 | 41 | ## [0.2.0] - 2020-11-14 42 | ### Added 43 | - Access to client certificates by [@Alch-Emi] 44 | 45 | [@Alch-Emi]: https://github.com/Alch-Emi 46 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "twinstar" 3 | version = "0.4.0" 4 | authors = ["panicbit "] 5 | edition = "2018" 6 | license = "MIT OR Apache-2.0" 7 | description = 'Gemini server implementation (previously called "northstar")' 8 | repository = "https://github.com/panicbit/twinstar" 9 | documentation = "https://docs.rs/twinstar" 10 | 11 | [features] 12 | default = ["serve_dir"] 13 | serve_dir = ["mime_guess", "tokio/fs"] 14 | 15 | [dependencies] 16 | anyhow = "1.0.33" 17 | rustls = { version = "0.18.1", features = ["dangerous_configuration"] } 18 | tokio-rustls = "0.20.0" 19 | tokio = { version = "0.3.1", features = ["io-util","net","time", "rt"] } 20 | mime = "0.3.16" 21 | uriparse = "0.6.3" 22 | percent-encoding = "2.1.0" 23 | futures-core = "0.3.7" 24 | log = "0.4.11" 25 | webpki = "0.21.0" 26 | lazy_static = "1.4.0" 27 | mime_guess = { version = "2.0.3", optional = true } 28 | 29 | [dev-dependencies] 30 | env_logger = "0.8.1" 31 | futures-util = "0.3.7" 32 | tokio = { version = "0.3.1", features = ["macros", "rt-multi-thread", "sync"] } 33 | 34 | [[example]] 35 | name = "serve_dir" 36 | required-features = ["serve_dir"] 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT OR Apache-2.0 2 | -------------------------------------------------------------------------------- /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 2021 panicbit 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2021 panicbit 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ``` 2 | __ _ __ 3 | / /__ __(_)___ _____/ /_____ ______ 4 | / __/ | /| / / / __ \/ ___/ __/ __ `/ ___/ 5 | / /_ | |/ |/ / / / / (__ ) /_/ /_/ / / 6 | \__/ |__/|__/_/_/ /_/____/\__/\__,_/_/ 7 | ``` 8 | 9 | - [Documentation](https://docs.rs/twinstar) 10 | - [GitHub](https://github.com/panicbit/twinstar) 11 | 12 | # Usage 13 | 14 | Add the latest version of twinstar to your `Cargo.toml`. 15 | 16 | ## Manually 17 | 18 | ```toml 19 | twinstar = "0.4.0" # check crates.io for the latest version 20 | ``` 21 | 22 | ## Automatically 23 | 24 | ```sh 25 | cargo add twinstar 26 | ``` 27 | 28 | # Generating a key & certificate 29 | 30 | Run 31 | ```sh 32 | mkdir cert && cd cert 33 | openssl req -x509 -nodes -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 34 | ``` 35 | and enter your domain name (e.g. "localhost" for testing) as Common Name (CN). 36 | 37 | Alternatively, if you want to include multiple domains add something like `-addext "subjectAltName = DNS:localhost, DNS:example.org"`. 38 | -------------------------------------------------------------------------------- /examples/certificates.rs: -------------------------------------------------------------------------------- 1 | use anyhow::*; 2 | use futures_core::future::BoxFuture; 3 | use futures_util::FutureExt; 4 | use log::LevelFilter; 5 | use tokio::sync::RwLock; 6 | use twinstar::{Certificate, GEMINI_PORT, Request, Response, Server}; 7 | use std::collections::HashMap; 8 | use std::sync::Arc; 9 | 10 | // Workaround for Certificates not being hashable 11 | type CertBytes = Vec; 12 | 13 | #[tokio::main] 14 | async fn main() -> Result<()> { 15 | env_logger::builder() 16 | .filter_module("twinstar", LevelFilter::Debug) 17 | .init(); 18 | 19 | let users = Arc::>>::default(); 20 | 21 | Server::bind(("0.0.0.0", GEMINI_PORT)) 22 | .add_route("/", move|req| handle_request(users.clone(), req)) 23 | .serve() 24 | .await 25 | } 26 | 27 | /// An ultra-simple demonstration of simple authentication. 28 | /// 29 | /// If the user attempts to connect, they will be prompted to create a client certificate. 30 | /// Once they've made one, they'll be given the opportunity to create an account by 31 | /// selecting a username. They'll then get a message confirming their account creation. 32 | /// Any time this user visits the site in the future, they'll get a personalized welcome 33 | /// message. 34 | fn handle_request(users: Arc>>, request: Request) -> BoxFuture<'static, Result> { 35 | async move { 36 | if let Some(Certificate(cert_bytes)) = request.certificate() { 37 | // The user provided a certificate 38 | let users_read = users.read().await; 39 | if let Some(user) = users_read.get(cert_bytes) { 40 | // The user has already registered 41 | Ok( 42 | Response::success_gemini( 43 | format!("Welcome {}!", user) 44 | ) 45 | ) 46 | } else { 47 | // The user still needs to register 48 | drop(users_read); 49 | if let Some(query_part) = request.uri().query() { 50 | // The user provided some input (a username request) 51 | let username = query_part.as_str(); 52 | let mut users_write = users.write().await; 53 | users_write.insert(cert_bytes.clone(), username.to_owned()); 54 | Ok( 55 | Response::success_gemini( 56 | format!( 57 | "Your account has been created {}! Welcome!", 58 | username 59 | ) 60 | ) 61 | ) 62 | } else { 63 | // The user didn't provide input, and should be prompted 64 | Response::input("What username would you like?") 65 | } 66 | } 67 | } else { 68 | // The user didn't provide a certificate 69 | Ok(Response::client_certificate_required()) 70 | } 71 | }.boxed() 72 | } 73 | -------------------------------------------------------------------------------- /examples/document.rs: -------------------------------------------------------------------------------- 1 | use anyhow::*; 2 | use futures_core::future::BoxFuture; 3 | use futures_util::FutureExt; 4 | use log::LevelFilter; 5 | use twinstar::{Server, Request, Response, GEMINI_PORT, Document}; 6 | use twinstar::document::HeadingLevel::*; 7 | 8 | #[tokio::main] 9 | async fn main() -> Result<()> { 10 | env_logger::builder() 11 | .filter_module("twinstar", LevelFilter::Debug) 12 | .init(); 13 | 14 | Server::bind(("localhost", GEMINI_PORT)) 15 | .add_route("/",handle_request) 16 | .serve() 17 | .await 18 | } 19 | 20 | fn handle_request(_request: Request) -> BoxFuture<'static, Result> { 21 | async move { 22 | let response = Document::new() 23 | .add_preformatted(include_str!("twinstar_logo.txt")) 24 | .add_blank_line() 25 | .add_link("https://docs.rs/twinstar", "Documentation") 26 | .add_link("https://github.com/panicbit/twinstar", "GitHub") 27 | .add_blank_line() 28 | .add_heading(H1, "Usage") 29 | .add_blank_line() 30 | .add_text("Add the latest version of twinstar to your `Cargo.toml`.") 31 | .add_blank_line() 32 | .add_heading(H2, "Manually") 33 | .add_blank_line() 34 | .add_preformatted_with_alt("toml", r#"twinstar = "0.3.0" # check crates.io for the latest version"#) 35 | .add_blank_line() 36 | .add_heading(H2, "Automatically") 37 | .add_blank_line() 38 | .add_preformatted_with_alt("sh", "cargo add twinstar") 39 | .add_blank_line() 40 | .add_heading(H1, "Generating a key & certificate") 41 | .add_blank_line() 42 | .add_preformatted_with_alt("sh", concat!( 43 | "mkdir cert && cd cert\n", 44 | "openssl req -x509 -nodes -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365", 45 | )) 46 | .into(); 47 | Ok(response) 48 | } 49 | .boxed() 50 | } 51 | -------------------------------------------------------------------------------- /examples/routing.rs: -------------------------------------------------------------------------------- 1 | use anyhow::*; 2 | use futures_core::future::BoxFuture; 3 | use futures_util::FutureExt; 4 | use log::LevelFilter; 5 | use twinstar::{Document, document::HeadingLevel, Request, Response, GEMINI_PORT}; 6 | 7 | #[tokio::main] 8 | async fn main() -> Result<()> { 9 | env_logger::builder() 10 | .filter_module("twinstar", LevelFilter::Debug) 11 | .init(); 12 | 13 | twinstar::Server::bind(("localhost", GEMINI_PORT)) 14 | .add_route("/", handle_base) 15 | .add_route("/route", handle_short) 16 | .add_route("/route/long", handle_long) 17 | .serve() 18 | .await 19 | } 20 | 21 | fn handle_base(req: Request) -> BoxFuture<'static, Result> { 22 | let doc = generate_doc("base", &req); 23 | async move { 24 | Ok(Response::document(doc)) 25 | }.boxed() 26 | } 27 | 28 | fn handle_short(req: Request) -> BoxFuture<'static, Result> { 29 | let doc = generate_doc("short", &req); 30 | async move { 31 | Ok(Response::document(doc)) 32 | }.boxed() 33 | } 34 | 35 | fn handle_long(req: Request) -> BoxFuture<'static, Result> { 36 | let doc = generate_doc("long", &req); 37 | async move { 38 | Ok(Response::document(doc)) 39 | }.boxed() 40 | } 41 | 42 | fn generate_doc(route_name: &str, req: &Request) -> Document { 43 | let trailing = req.trailing_segments().join("/"); 44 | let mut doc = Document::new(); 45 | doc.add_heading(HeadingLevel::H1, "Routing Demo") 46 | .add_text(&format!("You're currently on the {} route", route_name)) 47 | .add_text(&format!("Trailing segments: /{}", trailing)) 48 | .add_blank_line() 49 | .add_text("Here's some links to try:") 50 | .add_link_without_label("/") 51 | .add_link_without_label("/route") 52 | .add_link_without_label("/route/long") 53 | .add_link_without_label("/route/not_real") 54 | .add_link_without_label("/rowte"); 55 | doc 56 | } 57 | -------------------------------------------------------------------------------- /examples/serve_dir.rs: -------------------------------------------------------------------------------- 1 | use anyhow::*; 2 | use futures_core::future::BoxFuture; 3 | use futures_util::FutureExt; 4 | use log::LevelFilter; 5 | use twinstar::{Server, Request, Response, GEMINI_PORT}; 6 | 7 | #[tokio::main] 8 | async fn main() -> Result<()> { 9 | env_logger::builder() 10 | .filter_module("twinstar", LevelFilter::Debug) 11 | .init(); 12 | 13 | Server::bind(("localhost", GEMINI_PORT)) 14 | .add_route("/", handle_request) 15 | .serve() 16 | .await 17 | } 18 | 19 | fn handle_request(request: Request) -> BoxFuture<'static, Result> { 20 | async move { 21 | let path = request.path_segments(); 22 | let response = twinstar::util::serve_dir("public", &path).await?; 23 | 24 | Ok(response) 25 | } 26 | .boxed() 27 | } 28 | -------------------------------------------------------------------------------- /examples/twinstar_logo.txt: -------------------------------------------------------------------------------- 1 | __ _ __ 2 | / /__ __(_)___ _____/ /_____ ______ 3 | / __/ | /| / / / __ \/ ___/ __/ __ `/ ___/ 4 | / /_ | |/ |/ / / / / (__ ) /_/ /_/ / / 5 | \__/ |__/|__/_/_/ /_/____/\__/\__,_/_/ 6 | -------------------------------------------------------------------------------- /public/README.gemini: -------------------------------------------------------------------------------- 1 | ``` 2 | __ _ __ 3 | / /__ __(_)___ _____/ /_____ ______ 4 | / __/ | /| / / / __ \/ ___/ __/ __ `/ ___/ 5 | / /_ | |/ |/ / / / / (__ ) /_/ /_/ / / 6 | \__/ |__/|__/_/_/ /_/____/\__/\__,_/_/ 7 | ``` 8 | 9 | => https://docs.rs/twinstar Documentation 10 | => https://github.com/panicbit/twinstar GitHub 11 | 12 | # Usage 13 | 14 | Add the latest version of twinstar to your `Cargo.toml`. 15 | 16 | ## Manually 17 | 18 | ```toml 19 | twinstar = "0.4.0" # check crates.io for the latest version 20 | ``` 21 | 22 | ## Automatically 23 | 24 | ```sh 25 | cargo add twinstar 26 | ``` 27 | 28 | # Generating a key & certificate 29 | 30 | ```sh 31 | mkdir cert && cd cert 32 | openssl req -x509 -nodes -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 33 | ``` 34 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] extern crate log; 2 | 3 | use std::{ 4 | panic::AssertUnwindSafe, 5 | convert::TryFrom, 6 | io::BufReader, 7 | sync::Arc, 8 | path::PathBuf, 9 | time::Duration, 10 | }; 11 | use futures_core::future::BoxFuture; 12 | use tokio::{ 13 | prelude::*, 14 | io::{self, BufStream}, 15 | net::{TcpStream, ToSocketAddrs}, 16 | time::timeout, 17 | }; 18 | use tokio::net::TcpListener; 19 | use rustls::ClientCertVerifier; 20 | use rustls::internal::msgs::handshake::DigitallySignedStruct; 21 | use tokio_rustls::{rustls, TlsAcceptor}; 22 | use rustls::*; 23 | use anyhow::{Result, Context, anyhow, bail, ensure}; 24 | use lazy_static::lazy_static; 25 | use crate::util::opt_timeout; 26 | use routing::RoutingNode; 27 | 28 | pub mod types; 29 | pub mod util; 30 | pub mod routing; 31 | 32 | pub use mime; 33 | pub use uriparse as uri; 34 | pub use types::*; 35 | 36 | pub const REQUEST_URI_MAX_LEN: usize = 1024; 37 | pub const GEMINI_PORT: u16 = 1965; 38 | 39 | type Handler = Arc HandlerResponse + Send + Sync>; 40 | pub (crate) type HandlerResponse = BoxFuture<'static, Result>; 41 | 42 | #[derive(Clone)] 43 | pub struct Server { 44 | tls_acceptor: TlsAcceptor, 45 | listener: Arc, 46 | routes: Arc>, 47 | timeout: Duration, 48 | complex_timeout: Option, 49 | } 50 | 51 | impl Server { 52 | pub fn bind(addr: A) -> Builder { 53 | Builder::bind(addr) 54 | } 55 | 56 | async fn serve(self) -> Result<()> { 57 | loop { 58 | let (stream, _addr) = self.listener.accept().await 59 | .context("Failed to accept client")?; 60 | let this = self.clone(); 61 | 62 | tokio::spawn(async move { 63 | if let Err(err) = this.serve_client(stream).await { 64 | error!("{:?}", err); 65 | } 66 | }); 67 | } 68 | } 69 | 70 | async fn serve_client(self, stream: TcpStream) -> Result<()> { 71 | let fut_accept_request = async { 72 | let stream = self.tls_acceptor.accept(stream).await 73 | .context("Failed to establish TLS session")?; 74 | let mut stream = BufStream::new(stream); 75 | 76 | let request = receive_request(&mut stream).await 77 | .context("Failed to receive request")?; 78 | 79 | Result::<_, anyhow::Error>::Ok((request, stream)) 80 | }; 81 | 82 | // Use a timeout for interacting with the client 83 | let fut_accept_request = timeout(self.timeout, fut_accept_request); 84 | let (mut request, mut stream) = fut_accept_request.await 85 | .context("Client timed out while waiting for response")??; 86 | 87 | debug!("Client requested: {}", request.uri()); 88 | 89 | // Identify the client certificate from the tls stream. This is the first 90 | // certificate in the certificate chain. 91 | let client_cert = stream.get_ref() 92 | .get_ref() 93 | .1 94 | .get_peer_certificates() 95 | .and_then(|mut v| if v.is_empty() {None} else {Some(v.remove(0))}); 96 | 97 | request.set_cert(client_cert); 98 | 99 | let response = if let Some((trailing, handler)) = self.routes.match_request(&request) { 100 | 101 | request.set_trailing(trailing); 102 | 103 | let handler = (handler)(request); 104 | let handler = AssertUnwindSafe(handler); 105 | 106 | util::HandlerCatchUnwind::new(handler).await 107 | .unwrap_or_else(|_| Response::server_error("")) 108 | .or_else(|err| { 109 | error!("Handler failed: {:?}", err); 110 | Response::server_error("") 111 | }) 112 | .context("Request handler failed")? 113 | } else { 114 | Response::not_found() 115 | }; 116 | 117 | self.send_response(response, &mut stream).await 118 | .context("Failed to send response")?; 119 | 120 | Ok(()) 121 | } 122 | 123 | async fn send_response(&self, mut response: Response, stream: &mut (impl AsyncWrite + Unpin)) -> Result<()> { 124 | let maybe_body = response.take_body(); 125 | let header = response.header(); 126 | 127 | let use_complex_timeout = 128 | header.status.is_success() && 129 | maybe_body.is_some() && 130 | header.meta.as_str() != "text/plain" && 131 | header.meta.as_str() != "text/gemini" && 132 | self.complex_timeout.is_some(); 133 | 134 | let send_general_timeout; 135 | let send_header_timeout; 136 | let send_body_timeout; 137 | 138 | if use_complex_timeout { 139 | send_general_timeout = None; 140 | send_header_timeout = Some(self.timeout); 141 | send_body_timeout = self.complex_timeout; 142 | } else { 143 | send_general_timeout = Some(self.timeout); 144 | send_header_timeout = None; 145 | send_body_timeout = None; 146 | } 147 | 148 | opt_timeout(send_general_timeout, async { 149 | // Send the header 150 | opt_timeout(send_header_timeout, send_response_header(response.header(), stream)) 151 | .await 152 | .context("Timed out while sending response header")? 153 | .context("Failed to write response header")?; 154 | 155 | // Send the body 156 | opt_timeout(send_body_timeout, maybe_send_response_body(maybe_body, stream)) 157 | .await 158 | .context("Timed out while sending response body")? 159 | .context("Failed to write response body")?; 160 | 161 | Ok::<_,anyhow::Error>(()) 162 | }) 163 | .await 164 | .context("Timed out while sending response data")??; 165 | 166 | Ok(()) 167 | } 168 | } 169 | 170 | pub struct Builder { 171 | addr: A, 172 | cert_path: PathBuf, 173 | key_path: PathBuf, 174 | timeout: Duration, 175 | complex_body_timeout_override: Option, 176 | routes: RoutingNode, 177 | } 178 | 179 | impl Builder { 180 | fn bind(addr: A) -> Self { 181 | Self { 182 | addr, 183 | timeout: Duration::from_secs(1), 184 | complex_body_timeout_override: Some(Duration::from_secs(30)), 185 | cert_path: PathBuf::from("cert/cert.pem"), 186 | key_path: PathBuf::from("cert/key.pem"), 187 | routes: RoutingNode::default(), 188 | } 189 | } 190 | 191 | /// Sets the directory that twinstar should look for TLS certs and keys into 192 | /// 193 | /// Northstar will look for files called `cert.pem` and `key.pem` in the provided 194 | /// directory. 195 | /// 196 | /// This does not need to be set if both [`set_cert()`](Self::set_cert()) and 197 | /// [`set_key()`](Self::set_key()) have been called. 198 | /// 199 | /// If not set, the default is `cert/` 200 | pub fn set_tls_dir(self, dir: impl Into) -> Self { 201 | let dir = dir.into(); 202 | self.set_cert(dir.join("cert.pem")) 203 | .set_key(dir.join("key.pem")) 204 | } 205 | 206 | /// Set the path to the TLS certificate twinstar will use 207 | /// 208 | /// This defaults to `cert/cert.pem`. 209 | /// 210 | /// This does not need to be called it [`set_tls_dir()`](Self::set_tls_dir()) has been 211 | /// called. 212 | pub fn set_cert(mut self, cert_path: impl Into) -> Self { 213 | self.cert_path = cert_path.into(); 214 | self 215 | } 216 | 217 | /// Set the path to the ertificate key twinstar will use 218 | /// 219 | /// This defaults to `cert/key.pem`. 220 | /// 221 | /// This does not need to be called it [`set_tls_dir()`](Self::set_tls_dir()) has been 222 | /// called. 223 | /// 224 | /// This should of course correspond to the key set in 225 | /// [`set_cert()`](Self::set_cert()) 226 | pub fn set_key(mut self, key_path: impl Into) -> Self { 227 | self.key_path = key_path.into(); 228 | self 229 | } 230 | 231 | /// Set the timeout on incoming requests 232 | /// 233 | /// Note that this timeout is applied twice, once for the delivery of the request, and 234 | /// once for sending the client's response. This means that for a 1 second timeout, 235 | /// the client will have 1 second to complete the TLS handshake and deliver a request 236 | /// header, then your API will have as much time as it needs to handle the request, 237 | /// before the client has another second to receive the response. 238 | /// 239 | /// If you would like a timeout for your code itself, please use 240 | /// [`tokio::time::Timeout`] to implement it internally. 241 | /// 242 | /// **The default timeout is 1 second.** As somewhat of a workaround for 243 | /// shortcomings of the specification, this timeout, and any timeout set using this 244 | /// method, is overridden in special cases, specifically for MIME types outside of 245 | /// `text/plain` and `text/gemini`, to be 30 seconds. If you would like to change or 246 | /// prevent this, please see 247 | /// [`override_complex_body_timeout`](Self::override_complex_body_timeout()). 248 | pub fn set_timeout(mut self, timeout: Duration) -> Self { 249 | self.timeout = timeout; 250 | self 251 | } 252 | 253 | /// Override the timeout for complex body types 254 | /// 255 | /// Many clients choose to handle body types which cannot be displayed by prompting 256 | /// the user if they would like to download or open the request body. However, since 257 | /// this prompt occurs in the middle of receiving a request, often the connection 258 | /// times out before the end user is able to respond to the prompt. 259 | /// 260 | /// As a workaround, it is possible to set an override on the request timeout in 261 | /// specific conditions: 262 | /// 263 | /// 1. **Only override the timeout for receiving the body of the request.** This will 264 | /// not override the timeout on sending the request header, nor on receiving the 265 | /// response header. 266 | /// 2. **Only override the timeout for successful responses.** The only bodies which 267 | /// have bodies are successful ones. In all other cases, there's no body to 268 | /// timeout for 269 | /// 3. **Only override the timeout for complex body types.** Almost all clients are 270 | /// able to display `text/plain` and `text/gemini` responses, and will not prompt 271 | /// the user for these response types. This means that there is no reason to 272 | /// expect a client to have a human-length response time for these MIME types. 273 | /// Because of this, responses of this type will not be overridden. 274 | /// 275 | /// This method is used to override the timeout for responses meeting these specific 276 | /// criteria. All other stages of the connection will use the timeout specified in 277 | /// [`set_timeout()`](Self::set_timeout()). 278 | /// 279 | /// If this is set to [`None`], then the client will have the default amount of time 280 | /// to both receive the header and the body. If this is set to [`Some`], the client 281 | /// will have the default amount of time to recieve the header, and an *additional* 282 | /// alotment of time to recieve the body. 283 | /// 284 | /// The default timeout for this is 30 seconds. 285 | pub fn override_complex_body_timeout(mut self, timeout: Option) -> Self { 286 | self.complex_body_timeout_override = timeout; 287 | self 288 | } 289 | 290 | /// Add a handler for a route 291 | /// 292 | /// A route must be an absolute path, for example "/endpoint" or "/", but not 293 | /// "endpoint". Entering a relative or malformed path will result in a panic. 294 | /// 295 | /// For more information about routing mechanics, see the docs for [`RoutingNode`]. 296 | pub fn add_route(mut self, path: &'static str, handler: H) -> Self 297 | where 298 | H: Fn(Request) -> HandlerResponse + Send + Sync + 'static, 299 | { 300 | self.routes.add_route(path, Arc::new(handler)); 301 | self 302 | } 303 | 304 | pub async fn serve(mut self) -> Result<()> { 305 | let config = tls_config(&self.cert_path, &self.key_path) 306 | .context("Failed to create TLS config")?; 307 | 308 | let listener = TcpListener::bind(self.addr).await 309 | .context("Failed to create socket")?; 310 | 311 | self.routes.shrink(); 312 | 313 | let server = Server { 314 | tls_acceptor: TlsAcceptor::from(config), 315 | listener: Arc::new(listener), 316 | routes: Arc::new(self.routes), 317 | timeout: self.timeout, 318 | complex_timeout: self.complex_body_timeout_override, 319 | }; 320 | 321 | server.serve().await 322 | } 323 | } 324 | 325 | async fn receive_request(stream: &mut (impl AsyncBufRead + Unpin)) -> Result { 326 | let limit = REQUEST_URI_MAX_LEN + "\r\n".len(); 327 | let mut stream = stream.take(limit as u64); 328 | let mut uri = Vec::new(); 329 | 330 | stream.read_until(b'\n', &mut uri).await?; 331 | 332 | if !uri.ends_with(b"\r\n") { 333 | if uri.len() < REQUEST_URI_MAX_LEN { 334 | bail!("Request header not terminated with CRLF") 335 | } else { 336 | bail!("Request URI too long") 337 | } 338 | } 339 | 340 | // Strip CRLF 341 | uri.pop(); 342 | uri.pop(); 343 | 344 | let uri = URIReference::try_from(&*uri) 345 | .context("Request URI is invalid")? 346 | .into_owned(); 347 | let request = Request::from_uri(uri) 348 | .context("Failed to create request from URI")?; 349 | 350 | Ok(request) 351 | } 352 | 353 | async fn send_response_header(header: &ResponseHeader, stream: &mut (impl AsyncWrite + Unpin)) -> Result<()> { 354 | let header = format!( 355 | "{status} {meta}\r\n", 356 | status = header.status.code(), 357 | meta = header.meta.as_str(), 358 | ); 359 | 360 | stream.write_all(header.as_bytes()).await?; 361 | stream.flush().await?; 362 | 363 | Ok(()) 364 | } 365 | 366 | async fn maybe_send_response_body(maybe_body: Option, stream: &mut (impl AsyncWrite + Unpin)) -> Result<()> { 367 | if let Some(body) = maybe_body { 368 | send_response_body(body, stream).await?; 369 | } 370 | 371 | Ok(()) 372 | } 373 | 374 | async fn send_response_body(body: Body, stream: &mut (impl AsyncWrite + Unpin)) -> Result<()> { 375 | match body { 376 | Body::Bytes(bytes) => stream.write_all(&bytes).await?, 377 | Body::Reader(mut reader) => { io::copy(&mut reader, stream).await?; }, 378 | } 379 | 380 | stream.flush().await?; 381 | 382 | Ok(()) 383 | } 384 | 385 | fn tls_config(cert_path: &PathBuf, key_path: &PathBuf) -> Result> { 386 | let mut config = ServerConfig::new(AllowAnonOrSelfsignedClient::new()); 387 | 388 | let cert_chain = load_cert_chain(cert_path) 389 | .context("Failed to load TLS certificate")?; 390 | let key = load_key(key_path) 391 | .context("Failed to load TLS key")?; 392 | config.set_single_cert(cert_chain, key) 393 | .context("Failed to use loaded TLS certificate")?; 394 | 395 | Ok(config.into()) 396 | } 397 | 398 | fn load_cert_chain(cert_path: &PathBuf) -> Result> { 399 | let certs = std::fs::File::open(cert_path) 400 | .with_context(|| format!("Failed to open `{:?}`", cert_path))?; 401 | let mut certs = BufReader::new(certs); 402 | let certs = rustls::internal::pemfile::certs(&mut certs) 403 | .map_err(|_| anyhow!("failed to load certs `{:?}`", cert_path))?; 404 | 405 | Ok(certs) 406 | } 407 | 408 | fn load_key(key_path: &PathBuf) -> Result { 409 | let keys = std::fs::File::open(key_path) 410 | .with_context(|| format!("Failed to open `{:?}`", key_path))?; 411 | let mut keys = BufReader::new(keys); 412 | let mut keys = rustls::internal::pemfile::pkcs8_private_keys(&mut keys) 413 | .map_err(|_| anyhow!("failed to load key `{:?}`", key_path))?; 414 | 415 | ensure!(!keys.is_empty(), "no key found"); 416 | 417 | let key = keys.swap_remove(0); 418 | 419 | Ok(key) 420 | } 421 | 422 | /// Mime for Gemini documents 423 | pub const GEMINI_MIME_STR: &str = "text/gemini"; 424 | 425 | lazy_static! { 426 | /// Mime for Gemini documents ("text/gemini") 427 | pub static ref GEMINI_MIME: Mime = GEMINI_MIME_STR.parse().expect("twinstar BUG"); 428 | } 429 | 430 | #[deprecated(note = "Use `GEMINI_MIME` instead", since = "0.3.0")] 431 | pub fn gemini_mime() -> Result { 432 | Ok(GEMINI_MIME.clone()) 433 | } 434 | 435 | /// A client cert verifier that accepts all connections 436 | /// 437 | /// Unfortunately, rustls doesn't provide a ClientCertVerifier that accepts self-signed 438 | /// certificates, so we need to implement this ourselves. 439 | struct AllowAnonOrSelfsignedClient { } 440 | impl AllowAnonOrSelfsignedClient { 441 | 442 | /// Create a new verifier 443 | fn new() -> Arc { 444 | Arc::new(Self {}) 445 | } 446 | 447 | } 448 | 449 | impl ClientCertVerifier for AllowAnonOrSelfsignedClient { 450 | 451 | fn client_auth_root_subjects( 452 | &self, 453 | _: Option<&webpki::DNSName> 454 | ) -> Option { 455 | Some(Vec::new()) 456 | } 457 | 458 | fn client_auth_mandatory(&self, _sni: Option<&webpki::DNSName>) -> Option { 459 | Some(false) 460 | } 461 | 462 | // the below methods are a hack until webpki doesn't break with certain certs 463 | 464 | fn verify_client_cert( 465 | &self, 466 | _: &[Certificate], 467 | _: Option<&webpki::DNSName> 468 | ) -> Result { 469 | Ok(ClientCertVerified::assertion()) 470 | } 471 | 472 | fn verify_tls12_signature( 473 | &self, 474 | _message: &[u8], 475 | _cert: &Certificate, 476 | _dss: &DigitallySignedStruct, 477 | ) -> Result { 478 | Ok(HandshakeSignatureValid::assertion()) 479 | } 480 | 481 | fn verify_tls13_signature( 482 | &self, 483 | _message: &[u8], 484 | _cert: &Certificate, 485 | _dss: &DigitallySignedStruct, 486 | ) -> Result { 487 | Ok(HandshakeSignatureValid::assertion()) 488 | } 489 | } 490 | 491 | #[cfg(test)] 492 | mod tests { 493 | use super::*; 494 | 495 | #[test] 496 | fn gemini_mime_parses() { 497 | let _: &Mime = &GEMINI_MIME; 498 | } 499 | } 500 | -------------------------------------------------------------------------------- /src/routing.rs: -------------------------------------------------------------------------------- 1 | //! Utilities for routing requests 2 | //! 3 | //! See [`RoutingNode`] for details on how routes are matched. 4 | 5 | use uriparse::path::{Path, Segment}; 6 | 7 | use std::collections::HashMap; 8 | use std::convert::TryInto; 9 | 10 | use crate::types::Request; 11 | 12 | /// A node for linking values to routes 13 | /// 14 | /// Routing is processed by a tree, with each child being a single path segment. For 15 | /// example, if an entry existed at "/trans/rights", then the root-level node would have 16 | /// a child "trans", which would have a child "rights". "rights" would have no children, 17 | /// but would have an attached entry. 18 | /// 19 | /// If one route is shorter than another, say "/trans/rights" and 20 | /// "/trans/rights/r/human", then the longer route always matches first, so a request for 21 | /// "/trans/rights/r/human/rights" would be routed to "/trans/rights/r/human", and 22 | /// "/trans/rights/now" would route to "/trans/rights" 23 | /// 24 | /// Routing is only performed on normalized paths, so "/endpoint" and "/endpoint/" are 25 | /// considered to be the same route. 26 | /// 27 | /// ``` 28 | /// # use twinstar::routing::RoutingNode; 29 | /// let mut routes = RoutingNode::<&'static str>::default(); 30 | /// routes.add_route("/", "base"); 31 | /// routes.add_route("/trans/rights/", "short route"); 32 | /// routes.add_route("/trans/rights/r/human", "long route"); 33 | /// 34 | /// assert_eq!( 35 | /// routes.match_path(&["any", "other", "request"]), 36 | /// Some((vec![&"any", &"other", &"request"], &"base")) 37 | /// ); 38 | /// assert_eq!( 39 | /// routes.match_path(&["trans", "rights"]), 40 | /// Some((vec![], &"short route")) 41 | /// ); 42 | /// assert_eq!( 43 | /// routes.match_path(&["trans", "rights", "now"]), 44 | /// Some((vec![&"now"], &"short route")) 45 | /// ); 46 | /// assert_eq!( 47 | /// routes.match_path(&["trans", "rights", "r", "human", "rights"]), 48 | /// Some((vec![&"rights"], &"long route")) 49 | /// ); 50 | /// ``` 51 | pub struct RoutingNode(Option, HashMap); 52 | 53 | impl RoutingNode { 54 | /// Attempt to find and entry based on path segments 55 | /// 56 | /// This searches the network of routing nodes attempting to match a specific request, 57 | /// represented as a sequence of path segments. For example, "/dir/image.png?text" 58 | /// should be represented as `&["dir", "image.png"]`. 59 | /// 60 | /// If a match is found, it is returned, along with the segments of the path trailing 61 | /// the subpath matching the route. For example, a route `/foo` receiving a request to 62 | /// `/foo/bar` would produce `vec!["bar"]` 63 | /// 64 | /// See [`RoutingNode`] for details on how routes are matched. 65 | pub fn match_path(&self, path: I) -> Option<(Vec, &T)> 66 | where 67 | I: IntoIterator, 68 | S: AsRef, 69 | { 70 | let mut node = self; 71 | let mut path = path.into_iter().filter(|seg| !seg.as_ref().is_empty()); 72 | let mut last_seen_handler = None; 73 | let mut since_last_handler = Vec::new(); 74 | loop { 75 | let Self(maybe_handler, map) = node; 76 | 77 | if maybe_handler.is_some() { 78 | last_seen_handler = maybe_handler.as_ref(); 79 | since_last_handler.clear(); 80 | } 81 | 82 | if let Some(segment) = path.next() { 83 | let maybe_route = map.get(segment.as_ref()); 84 | since_last_handler.push(segment); 85 | 86 | if let Some(route) = maybe_route { 87 | node = route; 88 | } else { 89 | break; 90 | } 91 | } else { 92 | break; 93 | } 94 | }; 95 | 96 | if let Some(handler) = last_seen_handler { 97 | since_last_handler.extend(path); 98 | Some((since_last_handler, handler)) 99 | } else { 100 | None 101 | } 102 | } 103 | 104 | /// Attempt to identify a route for a given [`Request`] 105 | /// 106 | /// See [`RoutingNode::match_path()`] for more information 107 | pub fn match_request(&self, req: &Request) -> Option<(Vec, &T)> { 108 | let mut path = req.path().to_borrowed(); 109 | path.normalize(false); 110 | self.match_path(path.segments()) 111 | .map(|(segs, h)| ( 112 | segs.into_iter() 113 | .map(Segment::as_str) 114 | .map(str::to_owned) 115 | .collect(), 116 | h, 117 | )) 118 | } 119 | 120 | /// Add a route to the network 121 | /// 122 | /// This method wraps [`add_route_by_path()`](Self::add_route_by_path()) while 123 | /// unwrapping any errors that might occur. For this reason, this method only takes 124 | /// static strings. If you would like to add a string dynamically, please use 125 | /// [`RoutingNode::add_route_by_path()`] in order to appropriately deal with any 126 | /// errors that might arise. 127 | pub fn add_route(&mut self, path: &'static str, data: T) { 128 | let path: Path = path.try_into().expect("Malformed path route received"); 129 | self.add_route_by_path(path, data).unwrap(); 130 | } 131 | 132 | /// Add a route to the network 133 | /// 134 | /// The path provided MUST be absolute. Callers should verify this before calling 135 | /// this method. 136 | /// 137 | /// For information about how routes work, see [`RoutingNode::match_path()`] 138 | pub fn add_route_by_path(&mut self, mut path: Path, data: T) -> Result<(), ConflictingRouteError>{ 139 | debug_assert!(path.is_absolute()); 140 | path.normalize(false); 141 | 142 | let mut node = self; 143 | for segment in path.segments() { 144 | if segment != "" { 145 | node = node.1.entry(segment.to_string()).or_default(); 146 | } 147 | } 148 | 149 | if node.0.is_some() { 150 | Err(ConflictingRouteError()) 151 | } else { 152 | node.0 = Some(data); 153 | Ok(()) 154 | } 155 | } 156 | 157 | /// Recursively shrink maps to fit 158 | pub fn shrink(&mut self) { 159 | let mut to_shrink = vec![&mut self.1]; 160 | while let Some(shrink) = to_shrink.pop() { 161 | shrink.shrink_to_fit(); 162 | to_shrink.extend(shrink.values_mut().map(|n| &mut n.1)); 163 | } 164 | } 165 | 166 | /// Iterate over the items in this map 167 | /// 168 | /// This includes not just the direct children of this node, but also all children of 169 | /// those children. No guarantees are made as to the order values are visited in. 170 | /// 171 | /// ## Example 172 | /// ``` 173 | /// # use std::collections::HashSet; 174 | /// # use twinstar::routing::RoutingNode; 175 | /// let mut map = RoutingNode::::default(); 176 | /// map.add_route("/", 0); 177 | /// map.add_route("/hello/world", 1312); 178 | /// map.add_route("/example", 621); 179 | /// 180 | /// let values: HashSet<&usize> = map.iter().collect(); 181 | /// assert!(values.contains(&0)); 182 | /// assert!(values.contains(&1312)); 183 | /// assert!(values.contains(&621)); 184 | /// assert!(!values.contains(&1)); 185 | /// ``` 186 | pub fn iter(&self) -> Iter<'_, T> { 187 | Iter { 188 | unexplored: vec![self], 189 | } 190 | } 191 | } 192 | 193 | impl<'a, T> IntoIterator for &'a RoutingNode { 194 | type Item = &'a T; 195 | type IntoIter = Iter<'a, T>; 196 | 197 | fn into_iter(self) -> Iter<'a, T> { 198 | self.iter() 199 | } 200 | } 201 | 202 | impl Default for RoutingNode { 203 | fn default() -> Self { 204 | Self(None, HashMap::default()) 205 | } 206 | } 207 | 208 | #[derive(Debug, Clone, Copy)] 209 | pub struct ConflictingRouteError(); 210 | 211 | impl std::error::Error for ConflictingRouteError { } 212 | 213 | impl std::fmt::Display for ConflictingRouteError { 214 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 215 | write!(f, "Attempted to create a route with the same matcher as an existing route") 216 | } 217 | } 218 | 219 | #[derive(Clone)] 220 | /// An iterator over the values in a [`RoutingNode`] map 221 | pub struct Iter<'a, T> { 222 | unexplored: Vec<&'a RoutingNode>, 223 | } 224 | 225 | impl<'a, T> Iterator for Iter<'a, T> { 226 | type Item = &'a T; 227 | 228 | fn next(&mut self) -> Option { 229 | while let Some(node) = self.unexplored.pop() { 230 | self.unexplored.extend(node.1.values()); 231 | if node.0.is_some() { 232 | return node.0.as_ref(); 233 | } 234 | } 235 | None 236 | } 237 | } 238 | 239 | impl std::iter::FusedIterator for Iter<'_, T> { } 240 | -------------------------------------------------------------------------------- /src/types.rs: -------------------------------------------------------------------------------- 1 | pub use ::mime::Mime; 2 | pub use rustls::Certificate; 3 | pub use uriparse::URIReference; 4 | 5 | mod meta; 6 | pub use self::meta::Meta; 7 | 8 | mod request; 9 | pub use request::Request; 10 | 11 | mod response_header; 12 | pub use response_header::ResponseHeader; 13 | 14 | mod status; 15 | pub use status::{Status, StatusCategory}; 16 | 17 | mod response; 18 | pub use response::Response; 19 | 20 | mod body; 21 | pub use body::Body; 22 | 23 | pub mod document; 24 | pub use document::Document; 25 | -------------------------------------------------------------------------------- /src/types/body.rs: -------------------------------------------------------------------------------- 1 | use tokio::io::AsyncRead; 2 | #[cfg(feature="serve_dir")] 3 | use tokio::fs::File; 4 | 5 | use std::borrow::Borrow; 6 | 7 | use crate::types::Document; 8 | 9 | pub enum Body { 10 | Bytes(Vec), 11 | Reader(Box), 12 | } 13 | 14 | impl> From for Body { 15 | fn from(document: D) -> Self { 16 | Self::from(document.borrow().to_string()) 17 | } 18 | } 19 | 20 | impl From> for Body { 21 | fn from(bytes: Vec) -> Self { 22 | Self::Bytes(bytes) 23 | } 24 | } 25 | 26 | impl<'a> From<&'a [u8]> for Body { 27 | fn from(bytes: &[u8]) -> Self { 28 | Self::Bytes(bytes.to_owned()) 29 | } 30 | } 31 | 32 | impl From for Body { 33 | fn from(text: String) -> Self { 34 | Self::Bytes(text.into_bytes()) 35 | } 36 | } 37 | 38 | impl<'a> From<&'a str> for Body { 39 | fn from(text: &str) -> Self { 40 | Self::Bytes(text.to_owned().into_bytes()) 41 | } 42 | } 43 | 44 | #[cfg(feature="serve_dir")] 45 | impl From for Body { 46 | fn from(file: File) -> Self { 47 | Self::Reader(Box::new(file)) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/types/document.rs: -------------------------------------------------------------------------------- 1 | //! Provides types for creating Gemini Documents. 2 | //! 3 | //! The module is centered around the `Document` type, 4 | //! which provides all the necessary methods for programatically 5 | //! creation of Gemini documents. 6 | //! 7 | //! # Examples 8 | //! 9 | //! ``` 10 | //! use twinstar::document::HeadingLevel::*; 11 | //! 12 | //! let mut document = twinstar::Document::new(); 13 | //! 14 | //! document.add_heading(H1, "Heading 1"); 15 | //! document.add_heading(H2, "Heading 2"); 16 | //! document.add_heading(H3, "Heading 3"); 17 | //! document.add_blank_line(); 18 | //! document.add_text("text"); 19 | //! document.add_link("gemini://gemini.circumlunar.space", "Project Gemini"); 20 | //! document.add_unordered_list_item("list item"); 21 | //! document.add_quote("quote"); 22 | //! document.add_preformatted("preformatted"); 23 | //! 24 | //! assert_eq!(document.to_string(), "\ 25 | //! ## Heading 1\n\ 26 | //! ### Heading 2\n\ 27 | //! #### Heading 3\n\ 28 | //! \n\ 29 | //! text\n\ 30 | //! => gemini://gemini.circumlunar.space/ Project Gemini\n\ 31 | //! * list item\n\ 32 | //! > quote\n\ 33 | //! ```\n\ 34 | //! preformatted\n\ 35 | //! ```\n\ 36 | //! "); 37 | //! ``` 38 | #![warn(missing_docs)] 39 | use std::convert::TryInto; 40 | use std::fmt; 41 | 42 | use crate::types::URIReference; 43 | use crate::util::Cowy; 44 | 45 | #[derive(Default)] 46 | /// Represents a Gemini document. 47 | /// 48 | /// Provides convenient methods for programatically 49 | /// creation of Gemini documents. 50 | pub struct Document { 51 | items: Vec, 52 | } 53 | 54 | impl Document { 55 | /// Creates an empty Gemini `Document`. 56 | /// 57 | /// # Examples 58 | /// 59 | /// ``` 60 | /// let document = twinstar::Document::new(); 61 | /// 62 | /// assert_eq!(document.to_string(), ""); 63 | /// ``` 64 | pub fn new() -> Self { 65 | Self::default() 66 | } 67 | 68 | /// Adds an `item` to the document. 69 | /// 70 | /// An `item` usually corresponds to a single line, 71 | /// except in the case of preformatted text. 72 | /// 73 | /// # Examples 74 | /// 75 | /// ```compile_fail 76 | /// use twinstar::document::{Document, Item, Text}; 77 | /// 78 | /// let mut document = Document::new(); 79 | /// let text = Text::new_lossy("foo"); 80 | /// let item = Item::Text(text); 81 | /// 82 | /// document.add_item(item); 83 | /// 84 | /// assert_eq!(document.to_string(), "foo\n"); 85 | /// ``` 86 | fn add_item(&mut self, item: Item) -> &mut Self { 87 | self.items.push(item); 88 | self 89 | } 90 | 91 | /// Adds multiple `items` to the document. 92 | /// 93 | /// This is a convenience wrapper around `add_item`. 94 | /// 95 | /// # Examples 96 | /// 97 | /// ```compile_fail 98 | /// use twinstar::document::{Document, Item, Text}; 99 | /// 100 | /// let mut document = Document::new(); 101 | /// let items = vec!["foo", "bar", "baz"] 102 | /// .into_iter() 103 | /// .map(Text::new_lossy) 104 | /// .map(Item::Text); 105 | /// 106 | /// document.add_items(items); 107 | /// 108 | /// assert_eq!(document.to_string(), "foo\nbar\nbaz\n"); 109 | /// ``` 110 | fn add_items(&mut self, items: I) -> &mut Self 111 | where 112 | I: IntoIterator, 113 | { 114 | self.items.extend(items); 115 | self 116 | } 117 | 118 | /// Adds a blank line to the document. 119 | /// 120 | /// # Examples 121 | /// 122 | /// ``` 123 | /// let mut document = twinstar::Document::new(); 124 | /// 125 | /// document.add_blank_line(); 126 | /// 127 | /// assert_eq!(document.to_string(), "\n"); 128 | /// ``` 129 | pub fn add_blank_line(&mut self) -> &mut Self { 130 | self.add_item(Item::Text(Text::blank())) 131 | } 132 | 133 | /// Adds plain text to the document. 134 | /// 135 | /// This function allows adding multiple lines at once. 136 | /// 137 | /// It inserts a whitespace at the beginning of a line 138 | /// if it starts with a character sequence that 139 | /// would make it a non-plain text line (e.g. link, heading etc). 140 | /// 141 | /// # Examples 142 | /// 143 | /// ``` 144 | /// let mut document = twinstar::Document::new(); 145 | /// 146 | /// document.add_text("hello\n* world!"); 147 | /// 148 | /// assert_eq!(document.to_string(), "hello\n * world!\n"); 149 | /// ``` 150 | pub fn add_text(&mut self, text: impl AsRef) -> &mut Self { 151 | let text = text 152 | .as_ref() 153 | .lines() 154 | .map(Text::new_lossy) 155 | .map(Item::Text); 156 | 157 | self.add_items(text); 158 | 159 | self 160 | } 161 | 162 | /// Adds a link to the document. 163 | /// 164 | /// `uri`s that fail to parse are substituted with `.`. 165 | /// 166 | /// Consecutive newlines in `label` will be replaced 167 | /// with a single whitespace. 168 | /// 169 | /// # Examples 170 | /// 171 | /// ``` 172 | /// let mut document = twinstar::Document::new(); 173 | /// 174 | /// document.add_link("https://wikipedia.org", "Wiki\n\nWiki"); 175 | /// 176 | /// assert_eq!(document.to_string(), "=> https://wikipedia.org/ Wiki Wiki\n"); 177 | /// ``` 178 | pub fn add_link<'a, U>(&mut self, uri: U, label: impl Cowy) -> &mut Self 179 | where 180 | U: TryInto>, 181 | { 182 | let uri = uri 183 | .try_into() 184 | .map(URIReference::into_owned) 185 | .or_else(|_| ".".try_into()).expect("Northstar BUG"); 186 | let label = LinkLabel::from_lossy(label); 187 | let link = Link { uri: Box::new(uri), label: Some(label) }; 188 | let link = Item::Link(link); 189 | 190 | self.add_item(link); 191 | 192 | self 193 | } 194 | 195 | /// Adds a link to the document, but without a label. 196 | /// 197 | /// See `add_link` for details. 198 | /// 199 | /// # Examples 200 | /// 201 | /// ``` 202 | /// let mut document = twinstar::Document::new(); 203 | /// 204 | /// document.add_link_without_label("https://wikipedia.org"); 205 | /// 206 | /// assert_eq!(document.to_string(), "=> https://wikipedia.org/\n"); 207 | /// ``` 208 | pub fn add_link_without_label<'a, U>(&mut self, uri: U) -> &mut Self 209 | where 210 | U: TryInto>, 211 | { 212 | let uri = uri 213 | .try_into() 214 | .map(URIReference::into_owned) 215 | .or_else(|_| ".".try_into()).expect("Northstar BUG"); 216 | let link = Link { 217 | uri: Box::new(uri), 218 | label: None, 219 | }; 220 | let link = Item::Link(link); 221 | 222 | self.add_item(link); 223 | 224 | self 225 | } 226 | 227 | /// Adds a block of preformatted text. 228 | /// 229 | /// Lines that start with ` ``` ` will be prependend with a whitespace. 230 | /// 231 | /// # Examples 232 | /// 233 | /// ``` 234 | /// let mut document = twinstar::Document::new(); 235 | /// 236 | /// document.add_preformatted("a\n b\n c"); 237 | /// 238 | /// assert_eq!(document.to_string(), "```\na\n b\n c\n```\n"); 239 | /// ``` 240 | pub fn add_preformatted(&mut self, preformatted_text: impl AsRef) -> &mut Self { 241 | self.add_preformatted_with_alt("", preformatted_text.as_ref()) 242 | } 243 | 244 | /// Adds a block of preformatted text with an alt text. 245 | /// 246 | /// Consecutive newlines in `alt` will be replaced 247 | /// with a single whitespace. 248 | /// 249 | /// `preformatted_text` lines that start with ` ``` ` 250 | /// will be prependend with a whitespace. 251 | /// 252 | /// # Examples 253 | /// 254 | /// ``` 255 | /// let mut document = twinstar::Document::new(); 256 | /// 257 | /// document.add_preformatted_with_alt("rust", "fn main() {\n}\n"); 258 | /// 259 | /// assert_eq!(document.to_string(), "```rust\nfn main() {\n}\n```\n"); 260 | /// ``` 261 | pub fn add_preformatted_with_alt(&mut self, alt: impl AsRef, preformatted_text: impl AsRef) -> &mut Self { 262 | let alt = AltText::new_lossy(alt.as_ref()); 263 | let lines = preformatted_text 264 | .as_ref() 265 | .lines() 266 | .map(PreformattedText::new_lossy) 267 | .collect(); 268 | let preformatted = Preformatted { 269 | alt, 270 | lines, 271 | }; 272 | let preformatted = Item::Preformatted(preformatted); 273 | 274 | self.add_item(preformatted); 275 | 276 | self 277 | } 278 | 279 | /// Adds a heading. 280 | /// 281 | /// Consecutive newlines in `text` will be replaced 282 | /// with a single whitespace. 283 | /// 284 | /// # Examples 285 | /// 286 | /// ``` 287 | /// use twinstar::document::HeadingLevel::H1; 288 | /// 289 | /// let mut document = twinstar::Document::new(); 290 | /// 291 | /// document.add_heading(H1, "Welcome!"); 292 | /// 293 | /// assert_eq!(document.to_string(), "# Welcome!\n"); 294 | /// ``` 295 | pub fn add_heading(&mut self, level: HeadingLevel, text: impl Cowy) -> &mut Self { 296 | let text = HeadingText::new_lossy(text); 297 | let heading = Heading { 298 | level, 299 | text, 300 | }; 301 | let heading = Item::Heading(heading); 302 | 303 | self.add_item(heading); 304 | 305 | self 306 | } 307 | 308 | /// Adds an unordered list item. 309 | /// 310 | /// Consecutive newlines in `text` will be replaced 311 | /// with a single whitespace. 312 | /// 313 | /// # Examples 314 | /// 315 | /// ``` 316 | /// let mut document = twinstar::Document::new(); 317 | /// 318 | /// document.add_unordered_list_item("milk"); 319 | /// document.add_unordered_list_item("eggs"); 320 | /// 321 | /// assert_eq!(document.to_string(), "* milk\n* eggs\n"); 322 | /// ``` 323 | pub fn add_unordered_list_item(&mut self, text: impl AsRef) -> &mut Self { 324 | let item = UnorderedListItem::new_lossy(text.as_ref()); 325 | let item = Item::UnorderedListItem(item); 326 | 327 | self.add_item(item); 328 | 329 | self 330 | } 331 | 332 | /// Adds a quote. 333 | /// 334 | /// This function allows adding multiple quote lines at once. 335 | /// 336 | /// # Examples 337 | /// 338 | /// ``` 339 | /// let mut document = twinstar::Document::new(); 340 | /// 341 | /// document.add_quote("I think,\ntherefore I am"); 342 | /// 343 | /// assert_eq!(document.to_string(), "> I think,\n> therefore I am\n"); 344 | /// ``` 345 | pub fn add_quote(&mut self, text: impl AsRef) -> &mut Self { 346 | let quote = text 347 | .as_ref() 348 | .lines() 349 | .map(Quote::new_lossy) 350 | .map(Item::Quote); 351 | 352 | self.add_items(quote); 353 | 354 | self 355 | } 356 | } 357 | 358 | impl fmt::Display for Document { 359 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 360 | for item in &self.items { 361 | match item { 362 | Item::Text(text) => writeln!(f, "{}", text.0)?, 363 | Item::Link(link) => { 364 | let separator = if link.label.is_some() {" "} else {""}; 365 | let label = link.label.as_ref().map(|label| label.0.as_str()) 366 | .unwrap_or(""); 367 | 368 | writeln!(f, "=> {}{}{}", link.uri, separator, label)?; 369 | } 370 | Item::Preformatted(preformatted) => { 371 | writeln!(f, "```{}", preformatted.alt.0)?; 372 | 373 | for line in &preformatted.lines { 374 | writeln!(f, "{}", line.0)?; 375 | } 376 | 377 | writeln!(f, "```")? 378 | } 379 | Item::Heading(heading) => { 380 | let level = match heading.level { 381 | HeadingLevel::H1 => "#", 382 | HeadingLevel::H2 => "##", 383 | HeadingLevel::H3 => "###", 384 | }; 385 | 386 | writeln!(f, "{} {}", level, heading.text.0)?; 387 | } 388 | Item::UnorderedListItem(item) => writeln!(f, "* {}", item.0)?, 389 | Item::Quote(quote) => writeln!(f, "> {}", quote.0)?, 390 | } 391 | } 392 | 393 | Ok(()) 394 | } 395 | } 396 | 397 | #[allow(clippy::enum_variant_names)] 398 | enum Item { 399 | Text(Text), 400 | Link(Link), 401 | Preformatted(Preformatted), 402 | Heading(Heading), 403 | UnorderedListItem(UnorderedListItem), 404 | Quote(Quote), 405 | } 406 | 407 | #[derive(Default)] 408 | struct Text(String); 409 | 410 | impl Text { 411 | fn blank() -> Self { 412 | Self::default() 413 | } 414 | 415 | fn new_lossy(line: impl Cowy) -> Self { 416 | Self(lossy_escaped_line(line, SPECIAL_STARTS)) 417 | } 418 | } 419 | 420 | struct Link { 421 | uri: Box>, 422 | label: Option, 423 | } 424 | 425 | struct LinkLabel(String); 426 | 427 | impl LinkLabel { 428 | fn from_lossy(line: impl Cowy) -> Self { 429 | let line = strip_newlines(line); 430 | 431 | Self(line) 432 | } 433 | } 434 | 435 | struct Preformatted { 436 | alt: AltText, 437 | lines: Vec, 438 | } 439 | 440 | struct PreformattedText(String); 441 | 442 | impl PreformattedText { 443 | fn new_lossy(line: impl Cowy) -> Self { 444 | Self(lossy_escaped_line(line, &[PREFORMATTED_TOGGLE_START])) 445 | } 446 | } 447 | 448 | struct AltText(String); 449 | 450 | impl AltText { 451 | fn new_lossy(alt: &str) -> Self { 452 | let alt = strip_newlines(alt); 453 | 454 | Self(alt) 455 | } 456 | } 457 | 458 | struct Heading { 459 | level: HeadingLevel, 460 | text: HeadingText, 461 | } 462 | 463 | /// The level of a heading. 464 | pub enum HeadingLevel { 465 | /// Heading level 1 (`#`) 466 | H1, 467 | /// Heading level 2 (`##`) 468 | H2, 469 | /// Heading level 3 (`###`) 470 | H3, 471 | } 472 | 473 | struct HeadingText(String); 474 | 475 | impl HeadingText { 476 | fn new_lossy(line: impl Cowy) -> Self { 477 | let line = strip_newlines(line); 478 | 479 | Self(line) 480 | } 481 | } 482 | 483 | struct UnorderedListItem(String); 484 | 485 | impl UnorderedListItem { 486 | fn new_lossy(text: &str) -> Self { 487 | let text = strip_newlines(text); 488 | 489 | Self(text) 490 | } 491 | } 492 | 493 | struct Quote(String); 494 | 495 | impl Quote { 496 | fn new_lossy(text: &str) -> Self { 497 | Self(lossy_escaped_line(text, &[QUOTE_START])) 498 | } 499 | } 500 | 501 | 502 | const LINK_START: &str = "=>"; 503 | const PREFORMATTED_TOGGLE_START: &str = "```"; 504 | const HEADING_START: &str = "#"; 505 | const UNORDERED_LIST_ITEM_START: &str = "*"; 506 | const QUOTE_START: &str = ">"; 507 | 508 | const SPECIAL_STARTS: &[&str] = &[ 509 | LINK_START, 510 | PREFORMATTED_TOGGLE_START, 511 | HEADING_START, 512 | UNORDERED_LIST_ITEM_START, 513 | QUOTE_START, 514 | ]; 515 | 516 | fn starts_with_any(s: &str, starts: &[&str]) -> bool { 517 | for start in starts { 518 | if s.starts_with(start) { 519 | return true; 520 | } 521 | } 522 | 523 | false 524 | } 525 | 526 | fn lossy_escaped_line(line: impl Cowy, escape_starts: &[&str]) -> String { 527 | let line_ref = line.as_ref(); 528 | let contains_newline = line_ref.contains('\n'); 529 | let has_special_start = starts_with_any(line_ref, escape_starts); 530 | 531 | if !contains_newline && !has_special_start { 532 | return line.into(); 533 | } 534 | 535 | let mut line = String::new(); 536 | 537 | if has_special_start { 538 | line.push(' '); 539 | } 540 | 541 | if let Some(line_ref) = line_ref.split('\n').next() { 542 | line.push_str(line_ref); 543 | } 544 | 545 | line 546 | } 547 | 548 | fn strip_newlines(text: impl Cowy) -> String { 549 | if !text.as_ref().contains(&['\r', '\n'][..]) { 550 | return text.into(); 551 | } 552 | 553 | text.as_ref() 554 | .lines() 555 | .filter(|part| !part.is_empty()) 556 | .collect::>() 557 | .join(" ") 558 | } 559 | -------------------------------------------------------------------------------- /src/types/meta.rs: -------------------------------------------------------------------------------- 1 | use anyhow::*; 2 | use crate::Mime; 3 | use crate::util::Cowy; 4 | 5 | 6 | #[derive(Debug,Clone,PartialEq,Eq,Default)] 7 | pub struct Meta(String); 8 | 9 | impl Meta { 10 | pub const MAX_LEN: usize = 1024; 11 | 12 | /// Creates a new "Meta" string. 13 | /// Fails if `meta` contains `\n`. 14 | pub fn new(meta: impl Cowy) -> Result { 15 | ensure!(!meta.as_ref().contains('\n'), "Meta must not contain newlines"); 16 | ensure!(meta.as_ref().len() <= Self::MAX_LEN, "Meta must not exceed {} bytes", Self::MAX_LEN); 17 | 18 | Ok(Self(meta.into())) 19 | } 20 | 21 | /// Creates a new "Meta" string. 22 | /// Truncates `meta` to before: 23 | /// - the first occurrence of `\n` 24 | /// - the character that makes `meta` exceed `Meta::MAX_LEN` 25 | pub fn new_lossy(meta: impl Cowy) -> Self { 26 | let meta = meta.as_ref(); 27 | let truncate_pos = meta.char_indices().position(|(i, ch)| { 28 | let is_newline = ch == '\n'; 29 | let exceeds_limit = (i + ch.len_utf8()) > Self::MAX_LEN; 30 | 31 | is_newline || exceeds_limit 32 | }); 33 | 34 | let meta: String = match truncate_pos { 35 | None => meta.into(), 36 | Some(truncate_pos) => meta.get(..truncate_pos).expect("twinstar BUG").into(), 37 | }; 38 | 39 | Self(meta) 40 | } 41 | 42 | pub fn empty() -> Self { 43 | Self::default() 44 | } 45 | 46 | pub fn as_str(&self) -> &str { 47 | &self.0 48 | } 49 | 50 | pub fn to_mime(&self) -> Result { 51 | let mime = self.as_str().parse::() 52 | .context("Meta is not a valid MIME")?; 53 | Ok(mime) 54 | } 55 | } 56 | 57 | #[cfg(test)] 58 | mod tests { 59 | use super::*; 60 | use std::iter::repeat; 61 | 62 | #[test] 63 | fn new_rejects_newlines() { 64 | let meta = "foo\nbar"; 65 | let meta = Meta::new(meta); 66 | 67 | assert!(meta.is_err()); 68 | } 69 | 70 | #[test] 71 | fn new_accepts_max_len() { 72 | let meta: String = repeat('x').take(Meta::MAX_LEN).collect(); 73 | let meta = Meta::new(meta); 74 | 75 | assert!(meta.is_ok()); 76 | } 77 | 78 | #[test] 79 | fn new_rejects_exceeding_max_len() { 80 | let meta: String = repeat('x').take(Meta::MAX_LEN + 1).collect(); 81 | let meta = Meta::new(meta); 82 | 83 | assert!(meta.is_err()); 84 | } 85 | 86 | #[test] 87 | fn new_lossy_truncates() { 88 | let meta = "foo\r\nbar\nquux"; 89 | let meta = Meta::new_lossy(meta); 90 | 91 | assert_eq!(meta.as_str(), "foo\r"); 92 | } 93 | 94 | #[test] 95 | fn new_lossy_no_truncate() { 96 | let meta = "foo bar\r"; 97 | let meta = Meta::new_lossy(meta); 98 | 99 | assert_eq!(meta.as_str(), "foo bar\r"); 100 | } 101 | 102 | #[test] 103 | fn new_lossy_empty() { 104 | let meta = ""; 105 | let meta = Meta::new_lossy(meta); 106 | 107 | assert_eq!(meta.as_str(), ""); 108 | } 109 | 110 | #[test] 111 | fn new_lossy_truncates_to_empty() { 112 | let meta = "\n\n\n"; 113 | let meta = Meta::new_lossy(meta); 114 | 115 | assert_eq!(meta.as_str(), ""); 116 | } 117 | 118 | #[test] 119 | fn new_lossy_truncates_to_max_len() { 120 | let meta: String = repeat('x').take(Meta::MAX_LEN + 1).collect(); 121 | let meta = Meta::new_lossy(meta); 122 | 123 | assert_eq!(meta.as_str().len(), Meta::MAX_LEN); 124 | } 125 | 126 | #[test] 127 | fn new_lossy_truncates_multi_byte_sequences() { 128 | let mut meta: String = repeat('x').take(Meta::MAX_LEN - 1).collect(); 129 | meta.push('🦀'); 130 | 131 | assert_eq!(meta.len(), Meta::MAX_LEN + 3); 132 | 133 | let meta = Meta::new_lossy(meta); 134 | 135 | assert_eq!(meta.as_str().len(), Meta::MAX_LEN - 1); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /src/types/request.rs: -------------------------------------------------------------------------------- 1 | use std::ops; 2 | use anyhow::*; 3 | use percent_encoding::percent_decode_str; 4 | use uriparse::URIReference; 5 | use rustls::Certificate; 6 | 7 | pub struct Request { 8 | uri: URIReference<'static>, 9 | input: Option, 10 | certificate: Option, 11 | trailing_segments: Option>, 12 | } 13 | 14 | impl Request { 15 | pub fn from_uri(uri: URIReference<'static>) -> Result { 16 | Self::with_certificate(uri, None) 17 | } 18 | 19 | pub fn with_certificate( 20 | mut uri: URIReference<'static>, 21 | certificate: Option 22 | ) -> Result { 23 | uri.normalize(); 24 | 25 | let input = match uri.query() { 26 | None => None, 27 | Some(query) => { 28 | let input = percent_decode_str(query.as_str()) 29 | .decode_utf8() 30 | .context("Request URI query contains invalid UTF-8")? 31 | .into_owned(); 32 | Some(input) 33 | } 34 | }; 35 | 36 | Ok(Self { 37 | uri, 38 | input, 39 | certificate, 40 | trailing_segments: None, 41 | }) 42 | } 43 | 44 | pub const fn uri(&self) -> &URIReference { 45 | &self.uri 46 | } 47 | 48 | #[allow(clippy::missing_const_for_fn)] 49 | /// All of the path segments following the route to which this request was bound. 50 | /// 51 | /// For example, if this handler was bound to the `/api` route, and a request was 52 | /// received to `/api/v1/endpoint`, then this value would be `["v1", "endpoint"]`. 53 | /// This should not be confused with [`path_segments()`](Self::path_segments()), which 54 | /// contains *all* of the segments, not just those trailing the route. 55 | /// 56 | /// If the trailing segments have not been set, this method will panic, but this 57 | /// should only be possible if you are constructing the Request yourself. Requests 58 | /// to handlers registered through [`add_route`](crate::Builder::add_route()) will 59 | /// always have trailing segments set. 60 | pub fn trailing_segments(&self) -> &Vec { 61 | self.trailing_segments.as_ref().unwrap() 62 | } 63 | 64 | /// All of the segments in this path, percent decoded 65 | /// 66 | /// For example, for a request to `/api/v1/endpoint`, this would return `["api", "v1", 67 | /// "endpoint"]`, no matter what route the handler that received this request was 68 | /// bound to. This is not to be confused with 69 | /// [`trailing_segments()`](Self::trailing_segments), which contains only the segments 70 | /// following the bound route. 71 | /// 72 | /// Additionally, unlike `trailing_segments()`, this method percent decodes the path. 73 | pub fn path_segments(&self) -> Vec { 74 | self.uri() 75 | .path() 76 | .segments() 77 | .iter() 78 | .map(|segment| percent_decode_str(segment.as_str()).decode_utf8_lossy().into_owned()) 79 | .collect::>() 80 | } 81 | 82 | pub fn input(&self) -> Option<&str> { 83 | self.input.as_deref() 84 | } 85 | 86 | pub fn set_cert(&mut self, cert: Option) { 87 | self.certificate = cert; 88 | } 89 | 90 | pub fn set_trailing(&mut self, segments: Vec) { 91 | self.trailing_segments = Some(segments); 92 | } 93 | 94 | #[allow(clippy::missing_const_for_fn)] 95 | pub fn certificate(&self) -> Option<&Certificate> { 96 | self.certificate.as_ref() 97 | } 98 | } 99 | 100 | impl ops::Deref for Request { 101 | type Target = URIReference<'static>; 102 | 103 | fn deref(&self) -> &Self::Target { 104 | &self.uri 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/types/response.rs: -------------------------------------------------------------------------------- 1 | use std::convert::TryInto; 2 | use std::borrow::Borrow; 3 | 4 | use anyhow::*; 5 | use uriparse::URIReference; 6 | use crate::types::{ResponseHeader, Body, Mime, Document}; 7 | use crate::util::Cowy; 8 | use crate::GEMINI_MIME; 9 | 10 | pub struct Response { 11 | header: ResponseHeader, 12 | body: Option, 13 | } 14 | 15 | impl Response { 16 | pub const fn new(header: ResponseHeader) -> Self { 17 | Self { 18 | header, 19 | body: None, 20 | } 21 | } 22 | 23 | #[deprecated( 24 | since = "0.4.0", 25 | note = "Deprecated in favor of Response::success_gemini() or Document::into()" 26 | )] 27 | pub fn document(document: impl Borrow) -> Self { 28 | Self::success_gemini(document) 29 | } 30 | 31 | pub fn input(prompt: impl Cowy) -> Result { 32 | let header = ResponseHeader::input(prompt)?; 33 | Ok(Self::new(header)) 34 | } 35 | 36 | pub fn input_lossy(prompt: impl Cowy) -> Self { 37 | let header = ResponseHeader::input_lossy(prompt); 38 | Self::new(header) 39 | } 40 | 41 | pub fn redirect_temporary_lossy<'a>(location: impl TryInto>) -> Self { 42 | let header = ResponseHeader::redirect_temporary_lossy(location); 43 | Self::new(header) 44 | } 45 | 46 | /// Create a successful response with a given body and MIME 47 | pub fn success(mime: &Mime, body: impl Into) -> Self { 48 | Self { 49 | header: ResponseHeader::success(mime), 50 | body: Some(body.into()), 51 | } 52 | } 53 | 54 | /// Create a successful response with a `text/gemini` MIME 55 | pub fn success_gemini(body: impl Into) -> Self { 56 | Self::success(&GEMINI_MIME, body) 57 | } 58 | 59 | /// Create a successful response with a `text/plain` MIME 60 | pub fn success_plain(body: impl Into) -> Self { 61 | Self::success(&mime::TEXT_PLAIN, body) 62 | } 63 | 64 | pub fn server_error(reason: impl Cowy) -> Result { 65 | let header = ResponseHeader::server_error(reason)?; 66 | Ok(Self::new(header)) 67 | } 68 | 69 | pub fn not_found() -> Self { 70 | let header = ResponseHeader::not_found(); 71 | Self::new(header) 72 | } 73 | 74 | pub fn bad_request_lossy(reason: impl Cowy) -> Self { 75 | let header = ResponseHeader::bad_request_lossy(reason); 76 | Self::new(header) 77 | } 78 | 79 | pub fn client_certificate_required() -> Self { 80 | let header = ResponseHeader::client_certificate_required(); 81 | Self::new(header) 82 | } 83 | 84 | pub fn certificate_not_authorized() -> Self { 85 | let header = ResponseHeader::certificate_not_authorized(); 86 | Self::new(header) 87 | } 88 | 89 | pub fn with_body(mut self, body: impl Into) -> Self { 90 | self.body = Some(body.into()); 91 | self 92 | } 93 | 94 | pub const fn header(&self) -> &ResponseHeader { 95 | &self.header 96 | } 97 | 98 | pub fn take_body(&mut self) -> Option { 99 | self.body.take() 100 | } 101 | } 102 | 103 | impl> From for Response { 104 | fn from(doc: D) -> Self { 105 | Self::success_gemini(doc) 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/types/response_header.rs: -------------------------------------------------------------------------------- 1 | use std::convert::TryInto; 2 | 3 | use anyhow::{Result, Context}; 4 | use uriparse::URIReference; 5 | use crate::Mime; 6 | use crate::util::Cowy; 7 | use crate::types::{Status, Meta}; 8 | 9 | #[derive(Debug,Clone)] 10 | pub struct ResponseHeader { 11 | pub status: Status, 12 | pub meta: Meta, 13 | } 14 | 15 | impl ResponseHeader { 16 | pub fn input(prompt: impl Cowy) -> Result { 17 | Ok(Self { 18 | status: Status::INPUT, 19 | meta: Meta::new(prompt).context("Invalid input prompt")?, 20 | }) 21 | } 22 | 23 | pub fn input_lossy(prompt: impl Cowy) -> Self { 24 | Self { 25 | status: Status::INPUT, 26 | meta: Meta::new_lossy(prompt), 27 | } 28 | } 29 | 30 | pub fn success(mime: &Mime) -> Self { 31 | Self { 32 | status: Status::SUCCESS, 33 | meta: Meta::new_lossy(mime.to_string()), 34 | } 35 | } 36 | 37 | pub fn redirect_temporary_lossy<'a>(location: impl TryInto>) -> Self { 38 | let location = match location.try_into() { 39 | Ok(location) => location, 40 | Err(_) => return Self::bad_request_lossy("Invalid redirect location"), 41 | }; 42 | 43 | Self { 44 | status: Status::REDIRECT_TEMPORARY, 45 | meta: Meta::new_lossy(location.to_string()), 46 | } 47 | } 48 | 49 | pub fn server_error(reason: impl Cowy) -> Result { 50 | Ok(Self { 51 | status: Status::PERMANENT_FAILURE, 52 | meta: Meta::new(reason).context("Invalid server error reason")?, 53 | }) 54 | } 55 | 56 | pub fn server_error_lossy(reason: impl Cowy) -> Self { 57 | Self { 58 | status: Status::PERMANENT_FAILURE, 59 | meta: Meta::new_lossy(reason), 60 | } 61 | } 62 | 63 | pub fn not_found() -> Self { 64 | Self { 65 | status: Status::NOT_FOUND, 66 | meta: Meta::new_lossy("Not found"), 67 | } 68 | } 69 | 70 | pub fn bad_request_lossy(reason: impl Cowy) -> Self { 71 | Self { 72 | status: Status::BAD_REQUEST, 73 | meta: Meta::new_lossy(reason), 74 | } 75 | } 76 | 77 | pub fn client_certificate_required() -> Self { 78 | Self { 79 | status: Status::CLIENT_CERTIFICATE_REQUIRED, 80 | meta: Meta::new_lossy("No certificate provided"), 81 | } 82 | } 83 | 84 | pub fn certificate_not_authorized() -> Self { 85 | Self { 86 | status: Status::CERTIFICATE_NOT_AUTHORIZED, 87 | meta: Meta::new_lossy("Your certificate is not authorized to view this content"), 88 | } 89 | } 90 | 91 | pub const fn status(&self) -> &Status { 92 | &self.status 93 | } 94 | 95 | pub const fn meta(&self) -> &Meta { 96 | &self.meta 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/types/status.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug,Copy,Clone,PartialEq,Eq)] 2 | pub struct Status(u8); 3 | 4 | impl Status { 5 | pub const INPUT: Self = Self(10); 6 | pub const SENSITIVE_INPUT: Self = Self(11); 7 | pub const SUCCESS: Self = Self(20); 8 | pub const REDIRECT_TEMPORARY: Self = Self(30); 9 | pub const REDIRECT_PERMANENT: Self = Self(31); 10 | pub const TEMPORARY_FAILURE: Self = Self(40); 11 | pub const SERVER_UNAVAILABLE: Self = Self(41); 12 | pub const CGI_ERROR: Self = Self(42); 13 | pub const PROXY_ERROR: Self = Self(43); 14 | pub const SLOW_DOWN: Self = Self(44); 15 | pub const PERMANENT_FAILURE: Self = Self(50); 16 | pub const NOT_FOUND: Self = Self(51); 17 | pub const GONE: Self = Self(52); 18 | pub const PROXY_REQUEST_REFUSED: Self = Self(53); 19 | pub const BAD_REQUEST: Self = Self(59); 20 | pub const CLIENT_CERTIFICATE_REQUIRED: Self = Self(60); 21 | pub const CERTIFICATE_NOT_AUTHORIZED: Self = Self(61); 22 | pub const CERTIFICATE_NOT_VALID: Self = Self(62); 23 | 24 | pub const fn code(&self) -> u8 { 25 | self.0 26 | } 27 | 28 | pub fn is_success(&self) -> bool { 29 | self.category().is_success() 30 | } 31 | 32 | #[allow(clippy::missing_const_for_fn)] 33 | pub fn category(&self) -> StatusCategory { 34 | let class = self.0 / 10; 35 | 36 | match class { 37 | 1 => StatusCategory::Input, 38 | 2 => StatusCategory::Success, 39 | 3 => StatusCategory::Redirect, 40 | 4 => StatusCategory::TemporaryFailure, 41 | 5 => StatusCategory::PermanentFailure, 42 | 6 => StatusCategory::ClientCertificateRequired, 43 | _ => StatusCategory::PermanentFailure, 44 | } 45 | } 46 | } 47 | 48 | #[derive(Copy,Clone,PartialEq,Eq)] 49 | pub enum StatusCategory { 50 | Input, 51 | Success, 52 | Redirect, 53 | TemporaryFailure, 54 | PermanentFailure, 55 | ClientCertificateRequired, 56 | } 57 | 58 | impl StatusCategory { 59 | pub fn is_input(&self) -> bool { 60 | *self == Self::Input 61 | } 62 | 63 | pub fn is_success(&self) -> bool { 64 | *self == Self::Success 65 | } 66 | 67 | pub fn redirect(&self) -> bool { 68 | *self == Self::Redirect 69 | } 70 | 71 | pub fn is_temporary_failure(&self) -> bool { 72 | *self == Self::TemporaryFailure 73 | } 74 | 75 | pub fn is_permanent_failure(&self) -> bool { 76 | *self == Self::PermanentFailure 77 | } 78 | 79 | pub fn is_client_certificate_required(&self) -> bool { 80 | *self == Self::ClientCertificateRequired 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/util.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature="serve_dir")] 2 | use std::path::{Path, PathBuf}; 3 | #[cfg(feature="serve_dir")] 4 | use mime::Mime; 5 | use anyhow::{Result, Context}; 6 | #[cfg(feature="serve_dir")] 7 | use tokio::{ 8 | fs::{self, File}, 9 | io, 10 | }; 11 | #[cfg(feature="serve_dir")] 12 | use crate::types::{Document, document::HeadingLevel::*}; 13 | use crate::types::Response; 14 | use std::panic::{catch_unwind, AssertUnwindSafe}; 15 | use std::task::Poll; 16 | use futures_core::future::Future; 17 | use tokio::time; 18 | 19 | #[cfg(feature="serve_dir")] 20 | pub async fn serve_file>(path: P, mime: &Mime) -> Result { 21 | let path = path.as_ref(); 22 | 23 | let file = match File::open(path).await { 24 | Ok(file) => file, 25 | Err(err) => match err.kind() { 26 | std::io::ErrorKind::PermissionDenied => { 27 | warn!("Asked to serve {}, but permission denied by OS", path.display()); 28 | return Ok(Response::not_found()); 29 | }, 30 | _ => return warn_unexpected(err, path, line!()), 31 | } 32 | }; 33 | 34 | Ok(Response::success(mime, file)) 35 | } 36 | 37 | #[cfg(feature="serve_dir")] 38 | pub async fn serve_dir, P: AsRef>(dir: D, virtual_path: &[P]) -> Result { 39 | debug!("Dir: {}", dir.as_ref().display()); 40 | let dir = dir.as_ref(); 41 | let dir = match dir.canonicalize() { 42 | Ok(dir) => dir, 43 | Err(e) => { 44 | match e.kind() { 45 | std::io::ErrorKind::NotFound => { 46 | warn!("Path {} not found. Check your configuration.", dir.display()); 47 | return Response::server_error("Server incorrectly configured") 48 | }, 49 | std::io::ErrorKind::PermissionDenied => { 50 | warn!("Permission denied for {}. Check that the server has access.", dir.display()); 51 | return Response::server_error("Server incorrectly configured") 52 | }, 53 | _ => return warn_unexpected(e, dir, line!()), 54 | } 55 | }, 56 | }; 57 | let mut path = dir.to_path_buf(); 58 | 59 | for segment in virtual_path { 60 | path.push(segment); 61 | } 62 | 63 | let path = match path.canonicalize() { 64 | Ok(dir) => dir, 65 | Err(e) => { 66 | match e.kind() { 67 | std::io::ErrorKind::NotFound => return Ok(Response::not_found()), 68 | std::io::ErrorKind::PermissionDenied => { 69 | // Runs when asked to serve a file in a restricted dir 70 | // i.e. not /noaccess, but /noaccess/file 71 | warn!("Asked to serve {}, but permission denied by OS", path.display()); 72 | return Ok(Response::not_found()); 73 | }, 74 | _ => return warn_unexpected(e, path.as_ref(), line!()), 75 | } 76 | }, 77 | }; 78 | 79 | if !path.starts_with(&dir) { 80 | return Ok(Response::not_found()); 81 | } 82 | 83 | if !path.is_dir() { 84 | let mime = guess_mime_from_path(&path); 85 | return serve_file(path, &mime).await; 86 | } 87 | 88 | serve_dir_listing(path, virtual_path).await 89 | } 90 | 91 | #[cfg(feature="serve_dir")] 92 | async fn serve_dir_listing, B: AsRef>(path: P, virtual_path: &[B]) -> Result { 93 | let mut dir = match fs::read_dir(path.as_ref()).await { 94 | Ok(dir) => dir, 95 | Err(err) => match err.kind() { 96 | io::ErrorKind::NotFound => return Ok(Response::not_found()), 97 | std::io::ErrorKind::PermissionDenied => { 98 | warn!("Asked to serve {}, but permission denied by OS", path.as_ref().display()); 99 | return Ok(Response::not_found()); 100 | }, 101 | _ => return warn_unexpected(err, path.as_ref(), line!()), 102 | } 103 | }; 104 | 105 | let breadcrumbs: PathBuf = virtual_path.iter().collect(); 106 | let mut document = Document::new(); 107 | 108 | document.add_heading(H1, format!("Index of /{}", breadcrumbs.display())); 109 | document.add_blank_line(); 110 | 111 | if virtual_path.get(0).map(<_>::as_ref) != Some(Path::new("")) { 112 | document.add_link("..", "📁 ../"); 113 | } 114 | 115 | while let Some(entry) = dir.next_entry().await.context("Failed to list directory")? { 116 | let file_name = entry.file_name(); 117 | let file_name = file_name.to_string_lossy(); 118 | let is_dir = entry.file_type().await 119 | .with_context(|| format!("Failed to get file type of `{}`", entry.path().display()))? 120 | .is_dir(); 121 | let trailing_slash = if is_dir { "/" } else { "" }; 122 | let uri = format!("./{}{}", file_name, trailing_slash); 123 | 124 | document.add_link(uri.as_str(), format!("{icon} {name}{trailing_slash}", 125 | icon = if is_dir { '📁' } else { '📄' }, 126 | name = file_name, 127 | trailing_slash = trailing_slash 128 | )); 129 | } 130 | 131 | Ok(document.into()) 132 | } 133 | 134 | #[cfg(feature="serve_dir")] 135 | pub fn guess_mime_from_path>(path: P) -> Mime { 136 | let path = path.as_ref(); 137 | let extension = path.extension().and_then(|s| s.to_str()); 138 | let extension = match extension { 139 | Some(extension) => extension, 140 | None => return mime::APPLICATION_OCTET_STREAM, 141 | }; 142 | 143 | if let "gemini" | "gmi" = extension { 144 | return crate::GEMINI_MIME.clone(); 145 | } 146 | 147 | mime_guess::from_ext(extension).first_or_octet_stream() 148 | } 149 | 150 | #[cfg(feature="serve_dir")] 151 | /// Print a warning to the log asking to file an issue and respond with "Unexpected Error" 152 | pub (crate) fn warn_unexpected(err: impl std::fmt::Debug, path: &Path, line: u32) -> Result { 153 | warn!( 154 | concat!( 155 | "Unexpected error serving path {} at util.rs:{}, please report to ", 156 | env!("CARGO_PKG_REPOSITORY"), 157 | "/issues: {:?}", 158 | ), 159 | path.display(), 160 | line, 161 | err 162 | ); 163 | Response::server_error("Unexpected error") 164 | } 165 | 166 | /// A convenience trait alias for `AsRef + Into`, 167 | /// most commonly used to accept `&str` or `String`: 168 | /// 169 | /// `Cowy` ⇔ `AsRef + Into` 170 | pub trait Cowy 171 | where 172 | Self: AsRef + Into, 173 | T: ToOwned + ?Sized, 174 | {} 175 | 176 | impl Cowy for C 177 | where 178 | C: AsRef + Into, 179 | T: ToOwned + ?Sized, 180 | {} 181 | 182 | /// A utility for catching unwinds on Futures. 183 | /// 184 | /// This is adapted from the futures-rs CatchUnwind, in an effort to reduce the large 185 | /// amount of dependencies tied into the feature that provides this simple struct. 186 | #[must_use = "futures do nothing unless polled"] 187 | pub (crate) struct HandlerCatchUnwind { 188 | future: AssertUnwindSafe, 189 | } 190 | 191 | impl HandlerCatchUnwind { 192 | pub(super) fn new(future: AssertUnwindSafe) -> Self { 193 | Self { future } 194 | } 195 | } 196 | 197 | impl Future for HandlerCatchUnwind { 198 | type Output = Result, Box>; 199 | 200 | fn poll( 201 | mut self: std::pin::Pin<&mut Self>, 202 | cx: &mut std::task::Context 203 | ) -> Poll { 204 | match catch_unwind(AssertUnwindSafe(|| self.future.as_mut().poll(cx))) { 205 | Ok(res) => res.map(Ok), 206 | Err(e) => Poll::Ready(Err(e)) 207 | } 208 | } 209 | } 210 | 211 | pub(crate) async fn opt_timeout(duration: Option, future: impl Future) -> Result { 212 | match duration { 213 | Some(duration) => time::timeout(duration, future).await, 214 | None => Ok(future.await), 215 | } 216 | } 217 | --------------------------------------------------------------------------------