├── rust-toolchain.toml ├── .gitignore ├── src ├── router_option.rs ├── handler │ ├── hooks.rs │ ├── response.rs │ ├── hooks │ │ ├── pre_route.rs │ │ └── post_route.rs │ ├── partial.rs │ └── response │ │ ├── error.rs │ │ └── route.rs ├── prelude.rs ├── module.rs ├── context.rs ├── handler.rs ├── module │ ├── sync.rs │ └── asynchronous.rs ├── context │ ├── error.rs │ ├── route.rs │ └── hook.rs ├── utilities.rs ├── lib.rs ├── response.rs ├── response │ └── macros.rs └── router.rs ├── rossweisse ├── Cargo.toml ├── src │ ├── implementations.rs │ ├── implementations │ │ ├── router.rs │ │ ├── router │ │ │ ├── parser.rs │ │ │ ├── parser │ │ │ │ ├── field_initializers.rs │ │ │ │ └── field_initializer.rs │ │ │ ├── methods.rs │ │ │ └── fields.rs │ │ └── route.rs │ └── lib.rs └── README.md ├── .github └── workflows │ └── check.yaml ├── rustfmt.toml ├── examples ├── empty.rs ├── simple_tokio.rs ├── simple_async_std.rs ├── mime.rs ├── stateless_module.rs ├── query.rs ├── partial.rs ├── default_logger.rs ├── fix_path.rs ├── error_handler.rs ├── struct_router.rs ├── binary.rs ├── input.rs ├── parameters.rs ├── responses.rs ├── callbacks.rs ├── async.rs ├── certificate.rs ├── stateful_module.rs ├── async_stateful_module.rs └── README.md ├── justfile ├── Cargo.toml ├── README.md └── LICENSE /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "stable" 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Cargo 2 | target 3 | Cargo.lock 4 | 5 | # CLion 6 | .idea 7 | 8 | # Privacy-Enhanced Mail 9 | *.pem 10 | 11 | # Visual Studio Code 12 | .vscode 13 | 14 | # macOS 15 | .DS_Store 16 | 17 | # Fuwn/justfiles 18 | *.just 19 | -------------------------------------------------------------------------------- /src/router_option.rs: -------------------------------------------------------------------------------- 1 | /// Options that can be set for the `Router` 2 | #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)] 3 | pub enum RouterOption { 4 | /// If enabled, removes a trailing slash from the request URL path if a route 5 | /// exists for the path without the slash (e.g., `/foo/` becomes `/foo`). 6 | RemoveExtraTrailingSlash, 7 | /// If enabled, adds a trailing slash to the request URL path if a route 8 | /// exists for the path with the slash (e.g., `/foo` becomes `/foo/`). 9 | AddMissingTrailingSlash, 10 | /// If enabled, the router will perform case-insensitive matching for 11 | /// incoming request URL paths (e.g., `/foo` will match `/Foo` or `/FOO`). 12 | AllowCaseInsensitiveLookup, 13 | } 14 | -------------------------------------------------------------------------------- /rossweisse/Cargo.toml: -------------------------------------------------------------------------------- 1 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 2 | 3 | [package] 4 | name = "rossweisse" 5 | version = "0.0.3" 6 | authors = ["Fuwn "] 7 | edition = "2021" 8 | description = "`struct`-based Router Framework for Windmark" 9 | documentation = "https://docs.rs/rossweisse" 10 | readme = "README.md" 11 | repository = "https://github.com/gemrest/windmark" 12 | license = "GPL-3.0-only" 13 | keywords = ["gemini", "windmark"] 14 | categories = ["network-programming"] 15 | 16 | [lib] 17 | proc-macro = true 18 | 19 | [dependencies] 20 | quote = "1.0.26" # Quasi-quoting 21 | syn = { version = "2.0.15", features = ["full"] } # Source Code Parsing 22 | proc-macro2 = "1.0.56" # `proc-macro` Wrapper 23 | -------------------------------------------------------------------------------- /.github/workflows/check.yaml: -------------------------------------------------------------------------------- 1 | name: Check ✅ 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | paths: 7 | - "*" 8 | pull_request: 9 | paths: 10 | - "*" 11 | 12 | env: 13 | CARGO_TERM_COLOR: always 14 | 15 | jobs: 16 | check: 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: Checkout 🛒 20 | uses: actions/checkout@v3 21 | 22 | - name: Toolchain 🧰 23 | uses: actions-rs/toolchain@v1 24 | with: 25 | profile: minimal 26 | toolchain: stable 27 | components: rustfmt, clippy 28 | override: true 29 | 30 | - name: Check ✅ 31 | uses: actions-rs/cargo@v1 32 | continue-on-error: false 33 | with: 34 | command: check 35 | args: --verbose 36 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | condense_wildcard_suffixes = true 2 | edition = "2021" 3 | enum_discrim_align_threshold = 20 4 | # error_on_line_overflow = true 5 | # error_on_unformatted = true 6 | fn_single_line = true 7 | force_multiline_blocks = true 8 | format_code_in_doc_comments = true 9 | format_macro_matchers = true 10 | format_strings = true 11 | imports_layout = "HorizontalVertical" 12 | max_width = 80 13 | match_arm_blocks = false 14 | imports_granularity = "Crate" 15 | newline_style = "Unix" 16 | normalize_comments = true 17 | normalize_doc_attributes = true 18 | reorder_impl_items = true 19 | group_imports = "StdExternalCrate" 20 | reorder_modules = true 21 | struct_field_align_threshold = 20 22 | struct_lit_single_line = false 23 | tab_spaces = 2 24 | use_field_init_shorthand = true 25 | use_try_shorthand = true 26 | where_single_line = true 27 | wrap_comments = true 28 | -------------------------------------------------------------------------------- /rossweisse/src/implementations.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | mod route; 19 | mod router; 20 | 21 | pub use route::route; 22 | pub use router::{fields, methods}; 23 | -------------------------------------------------------------------------------- /src/handler/hooks.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | mod post_route; 19 | mod pre_route; 20 | 21 | pub use post_route::PostRouteHook; 22 | pub use pre_route::PreRouteHook; 23 | -------------------------------------------------------------------------------- /src/prelude.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | pub use crate::{ 19 | context, 20 | module::{AsyncModule, Module}, 21 | response::Response, 22 | router::Router, 23 | }; 24 | -------------------------------------------------------------------------------- /rossweisse/src/implementations/router.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | mod fields; 19 | mod methods; 20 | mod parser; 21 | 22 | pub use fields::fields; 23 | pub use methods::methods; 24 | -------------------------------------------------------------------------------- /rossweisse/src/implementations/router/parser.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | mod field_initializer; 19 | mod field_initializers; 20 | 21 | pub use field_initializers::FieldInitializers; 22 | -------------------------------------------------------------------------------- /src/module.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | mod asynchronous; 19 | mod sync; 20 | 21 | #[allow(clippy::module_name_repetitions)] 22 | pub use asynchronous::AsyncModule; 23 | pub use sync::Module; 24 | -------------------------------------------------------------------------------- /src/handler/response.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | #![allow(clippy::module_name_repetitions)] 19 | 20 | mod error; 21 | mod route; 22 | 23 | pub use error::ErrorResponse; 24 | pub use route::RouteResponse; 25 | -------------------------------------------------------------------------------- /rossweisse/src/implementations/route.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | use proc_macro::TokenStream; 19 | 20 | pub fn route(_arguments: TokenStream, item: syn::ItemFn) -> TokenStream { 21 | quote::quote! { #item }.into() 22 | } 23 | -------------------------------------------------------------------------------- /src/context.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | #![allow(clippy::module_name_repetitions)] 19 | 20 | mod error; 21 | mod hook; 22 | mod route; 23 | 24 | pub use error::ErrorContext; 25 | pub use hook::HookContext; 26 | pub use route::RouteContext; 27 | -------------------------------------------------------------------------------- /src/handler.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | mod hooks; 19 | mod partial; 20 | mod response; 21 | 22 | pub use self::{ 23 | hooks::{PostRouteHook, PreRouteHook}, 24 | partial::Partial, 25 | response::{ErrorResponse, RouteResponse}, 26 | }; 27 | -------------------------------------------------------------------------------- /examples/empty.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example empty` 19 | 20 | #[windmark::main] 21 | async fn main() -> Result<(), Box> { 22 | windmark::router::Router::new() 23 | .set_private_key_file("windmark_private.pem") 24 | .set_certificate_file("windmark_public.pem") 25 | .run() 26 | .await 27 | } 28 | -------------------------------------------------------------------------------- /rossweisse/README.md: -------------------------------------------------------------------------------- 1 | # Rossweisse 2 | 3 | `struct`-based Router Framework for [Windmark](https://github.com/gemrest/windmark) 4 | 5 | ## Usage 6 | 7 | Rossweisse is in it's infancy, and a much comprehensive interface is planned. 8 | 9 | For now, a simple Rosswiesse router can be implemented like this: 10 | 11 | ```rust 12 | use rossweisse::route; 13 | use windmark::response::Response; 14 | 15 | #[rossweisse::router] 16 | struct Router; 17 | 18 | #[rossweisse::router] 19 | impl Router { 20 | #[route(index)] 21 | pub fn index( 22 | _context: windmark::context::RouteContext, 23 | ) -> Response { 24 | Response::success("Hello, World!") 25 | } 26 | } 27 | 28 | #[windmark::main] 29 | async fn main() -> Result<(), Box> { 30 | { 31 | let mut router = Router::new(); 32 | 33 | router.router().set_private_key_file("windmark_private.pem"); 34 | router.router().set_certificate_file("windmark_public.pem"); 35 | 36 | router 37 | } 38 | .run() 39 | .await 40 | } 41 | ``` 42 | 43 | ## License 44 | 45 | This project is licensed with the 46 | [GNU General Public License v3.0](https://github.com/gemrest/windmark/blob/main/LICENSE). 47 | -------------------------------------------------------------------------------- /src/handler/hooks/pre_route.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | use crate::context::HookContext; 19 | 20 | #[allow(clippy::module_name_repetitions)] 21 | pub trait PreRouteHook: Send + Sync { 22 | fn call(&mut self, context: HookContext); 23 | } 24 | 25 | impl PreRouteHook for T 26 | where T: FnMut(HookContext) + Send + Sync 27 | { 28 | fn call(&mut self, context: HookContext) { (*self)(context) } 29 | } 30 | -------------------------------------------------------------------------------- /src/handler/partial.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | use crate::context::RouteContext; 19 | 20 | #[allow(clippy::module_name_repetitions)] 21 | pub trait Partial: Send + Sync { 22 | fn call(&mut self, context: RouteContext) -> String; 23 | } 24 | 25 | impl Partial for T 26 | where T: FnMut(RouteContext) -> String + Send + Sync 27 | { 28 | fn call(&mut self, context: RouteContext) -> String { (*self)(context) } 29 | } 30 | -------------------------------------------------------------------------------- /src/module/sync.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | use crate::context::HookContext; 19 | 20 | pub trait Module { 21 | /// Called right after the module is attached. 22 | fn on_attach(&mut self, _: &mut crate::router::Router) {} 23 | 24 | /// Called before a route is mounted. 25 | fn on_pre_route(&mut self, _: HookContext) {} 26 | 27 | /// Called after a route is mounted. 28 | fn on_post_route(&mut self, _: HookContext) {} 29 | } 30 | -------------------------------------------------------------------------------- /examples/simple_tokio.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example simple_tokio --features tokio` 19 | 20 | #[windmark::main] 21 | async fn main() -> Result<(), Box> { 22 | windmark::router::Router::new() 23 | .set_private_key_file("windmark_private.pem") 24 | .set_certificate_file("windmark_public.pem") 25 | .mount("/", |_| { 26 | windmark::response::Response::success("Hello, Tokio!") 27 | }) 28 | .run() 29 | .await 30 | } 31 | -------------------------------------------------------------------------------- /examples/simple_async_std.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example simple_async_std --features async-std` 19 | 20 | #[windmark::main] 21 | async fn main() -> Result<(), Box> { 22 | windmark::router::Router::new() 23 | .set_private_key_file("windmark_private.pem") 24 | .set_certificate_file("windmark_public.pem") 25 | .mount("/", |_| { 26 | windmark::response::Response::success("Hello, async-std!") 27 | }) 28 | .run() 29 | .await 30 | } 31 | -------------------------------------------------------------------------------- /src/module/asynchronous.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | use crate::context::HookContext; 19 | 20 | #[async_trait::async_trait] 21 | pub trait AsyncModule: Send + Sync { 22 | /// Called right after the module is attached. 23 | async fn on_attach(&mut self, _: &mut crate::router::Router) {} 24 | 25 | /// Called before a route is mounted. 26 | async fn on_pre_route(&mut self, _: HookContext) {} 27 | 28 | /// Called after a route is mounted. 29 | async fn on_post_route(&mut self, _: HookContext) {} 30 | } 31 | -------------------------------------------------------------------------------- /examples/mime.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example mime` 19 | 20 | #[windmark::main] 21 | async fn main() -> Result<(), Box> { 22 | windmark::router::Router::new() 23 | .set_private_key_file("windmark_private.pem") 24 | .set_certificate_file("windmark_public.pem") 25 | .mount("/mime", |_| { 26 | windmark::response::Response::success("Hello!".to_string()) 27 | .with_mime("text/plain") 28 | .clone() 29 | }) 30 | .run() 31 | .await 32 | } 33 | -------------------------------------------------------------------------------- /src/handler/hooks/post_route.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | use crate::{context::HookContext, response::Response}; 19 | 20 | #[allow(clippy::module_name_repetitions)] 21 | pub trait PostRouteHook: Send + Sync { 22 | fn call(&mut self, context: HookContext, response: &mut Response); 23 | } 24 | 25 | impl PostRouteHook for T 26 | where T: FnMut(HookContext, &mut Response) + Send + Sync 27 | { 28 | fn call(&mut self, context: HookContext, response: &mut Response) { 29 | (*self)(context, response); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /rossweisse/src/implementations/router/parser/field_initializers.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | use syn::parse::{self, Parse}; 19 | 20 | use super::field_initializer::FieldInitializer; 21 | 22 | pub struct FieldInitializers(pub Vec>); 23 | 24 | impl Parse for FieldInitializers { 25 | fn parse(input: parse::ParseStream<'_>) -> syn::Result { 26 | Ok(Self(syn::punctuated::Punctuated::, syn::Token![,]>::parse_terminated(input)?.into_iter().collect())) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /justfile: -------------------------------------------------------------------------------- 1 | import? 'cargo.just' 2 | 3 | set allow-duplicate-recipes := true 4 | 5 | default-features := "--features=logger,auto-deduce-mime,response-macros," 6 | 7 | default: 8 | @just --list 9 | 10 | fetch: 11 | curl https://raw.githubusercontent.com/Fuwn/justfiles/refs/heads/main/cargo.just > cargo.just 12 | 13 | fmt: 14 | cargo +nightly fmt 15 | 16 | [private] 17 | generic-task task async-feature: 18 | cargo +nightly {{ task }} --no-default-features \ 19 | {{ default-features }}{{ async-feature }} 20 | 21 | check async-feature: 22 | @just generic-task check {{ async-feature }} 23 | 24 | clippy async-feature: 25 | @just generic-task clippy {{ async-feature }} 26 | 27 | test async-feature: 28 | @just generic-task test {{ async-feature }} 29 | 30 | checkf: 31 | @just fmt 32 | @just check tokio 33 | @just check async-std 34 | 35 | checkfc: 36 | @just checkf 37 | @just clippy tokio 38 | @just clippy async-std 39 | 40 | docs: 41 | cargo +nightly doc --open --no-deps 42 | 43 | example example async-feature="tokio": 44 | cargo run --example {{ example }} --no-default-features \ 45 | {{ default-features }}{{ async-feature }} 46 | 47 | gen-key: 48 | openssl req -new -subj /CN=localhost -x509 -newkey ec -pkeyopt \ 49 | ec_paramgen_curve:prime256v1 -days 365 -nodes -out windmark_public.pem \ 50 | -keyout windmark_private.pem -inform pem 51 | -------------------------------------------------------------------------------- /rossweisse/src/implementations/router/parser/field_initializer.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | use syn::parse::{self, Parse}; 19 | 20 | pub struct FieldInitializer { 21 | pub ident: syn::Ident, 22 | #[allow(unused)] 23 | eq_token: syn::Token![=], 24 | pub expr: T, 25 | } 26 | 27 | impl Parse for FieldInitializer { 28 | fn parse(input: parse::ParseStream<'_>) -> syn::Result { 29 | let ident = input.parse()?; 30 | let eq_token = input.parse()?; 31 | let expr = input.parse()?; 32 | 33 | Ok(Self { 34 | ident, 35 | eq_token, 36 | expr, 37 | }) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /examples/stateless_module.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example stateless_module` 19 | 20 | use windmark::{response::Response, router::Router}; 21 | 22 | fn smiley(_context: windmark::context::RouteContext) -> Response { 23 | Response::success("😀") 24 | } 25 | 26 | fn emojis(router: &mut Router) { router.mount("/smiley", smiley); } 27 | 28 | #[windmark::main] 29 | async fn main() -> Result<(), Box> { 30 | Router::new() 31 | .set_private_key_file("windmark_private.pem") 32 | .set_certificate_file("windmark_public.pem") 33 | .attach_stateless(emojis) 34 | .run() 35 | .await 36 | } 37 | -------------------------------------------------------------------------------- /src/handler/response/error.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | use async_trait::async_trait; 19 | 20 | use crate::{context::ErrorContext, response::Response}; 21 | 22 | #[allow(clippy::module_name_repetitions)] 23 | #[async_trait] 24 | pub trait ErrorResponse: Send + Sync { 25 | async fn call(&mut self, context: ErrorContext) -> Response; 26 | } 27 | 28 | #[async_trait] 29 | impl ErrorResponse for T 30 | where 31 | T: FnMut(ErrorContext) -> F + Send + Sync, 32 | F: std::future::Future + Send + 'static, 33 | { 34 | async fn call(&mut self, context: ErrorContext) -> Response { 35 | (*self)(context).await 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/handler/response/route.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | use async_trait::async_trait; 19 | 20 | use crate::{context::RouteContext, response::Response}; 21 | 22 | #[allow(clippy::module_name_repetitions)] 23 | #[async_trait] 24 | pub trait RouteResponse: Send + Sync { 25 | async fn call(&mut self, context: RouteContext) -> Response; 26 | } 27 | 28 | #[async_trait] 29 | impl RouteResponse for T 30 | where 31 | T: FnMut(RouteContext) -> F + Send + Sync, 32 | F: std::future::Future + Send + 'static, 33 | { 34 | async fn call(&mut self, context: RouteContext) -> Response { 35 | (*self)(context).await 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/context/error.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | use openssl::x509::X509; 19 | use url::Url; 20 | 21 | #[allow(clippy::module_name_repetitions)] 22 | #[derive(Clone)] 23 | pub struct ErrorContext { 24 | pub peer_address: Option, 25 | pub url: Url, 26 | pub certificate: Option, 27 | } 28 | 29 | impl ErrorContext { 30 | #[must_use] 31 | pub fn new( 32 | peer_address: std::io::Result, 33 | url: Url, 34 | certificate: Option, 35 | ) -> Self { 36 | Self { 37 | peer_address: peer_address.ok(), 38 | url, 39 | certificate, 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /examples/query.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example input --features response-macros` 19 | 20 | #[windmark::main] 21 | async fn main() -> Result<(), Box> { 22 | windmark::router::Router::new() 23 | .set_private_key_file("windmark_private.pem") 24 | .set_certificate_file("windmark_public.pem") 25 | .mount( 26 | "/query", 27 | windmark::success!( 28 | context, 29 | format!( 30 | "You provided the following queries: '{:?}'", 31 | windmark::utilities::queries_from_url(&context.url) 32 | ) 33 | ), 34 | ) 35 | .run() 36 | .await 37 | } 38 | -------------------------------------------------------------------------------- /examples/partial.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example partial` 19 | 20 | #[windmark::main] 21 | async fn main() -> Result<(), Box> { 22 | windmark::router::Router::new() 23 | .set_private_key_file("windmark_private.pem") 24 | .set_certificate_file("windmark_public.pem") 25 | .add_header(|_| "This is fancy art.\n".to_string()) 26 | .add_footer(|context: windmark::context::RouteContext| { 27 | format!("\nYou came from '{}'.", context.url.path()) 28 | }) 29 | .add_footer(|_| "\nCopyright (C) 2022".to_string()) 30 | .mount("/", windmark::success!("Hello!")) 31 | .run() 32 | .await 33 | } 34 | -------------------------------------------------------------------------------- /examples/default_logger.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example default_logger --features logger,response-macros` 19 | 20 | #[windmark::main] 21 | async fn main() -> Result<(), Box> { 22 | let mut router = windmark::router::Router::new(); 23 | 24 | router.set_private_key_file("windmark_private.pem"); 25 | router.set_certificate_file("windmark_public.pem"); 26 | #[cfg(feature = "logger")] 27 | { 28 | router.enable_default_logger(true); 29 | } 30 | router.mount( 31 | "/", 32 | windmark::success!({ 33 | log::info!("Hello!"); 34 | 35 | "Hello!" 36 | }), 37 | ); 38 | 39 | router.run().await 40 | } 41 | -------------------------------------------------------------------------------- /src/utilities.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! Utilities to make cumbersome tasks simpler 19 | 20 | use std::collections::HashMap; 21 | 22 | /// Extract the queries from a URL into a `HashMap`. 23 | #[must_use] 24 | pub fn queries_from_url(url: &url::Url) -> HashMap { 25 | let mut queries = HashMap::new(); 26 | 27 | for (key, value) in url.query_pairs() { 28 | queries.insert(key.to_string(), value.to_string()); 29 | } 30 | 31 | queries 32 | } 33 | 34 | #[must_use] 35 | pub fn params_to_hashmap( 36 | params: &matchit::Params<'_, '_>, 37 | ) -> HashMap { 38 | params 39 | .iter() 40 | .map(|(k, v)| (k.to_string(), v.to_string())) 41 | .collect() 42 | } 43 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | #![deny( 19 | clippy::all, 20 | clippy::nursery, 21 | clippy::pedantic, 22 | future_incompatible, 23 | nonstandard_style, 24 | rust_2018_idioms, 25 | unsafe_code, 26 | unused, 27 | warnings 28 | )] 29 | #![doc = include_str!("../README.md")] 30 | #![recursion_limit = "128"] 31 | 32 | pub mod context; 33 | pub mod handler; 34 | pub mod module; 35 | #[cfg(feature = "prelude")] 36 | pub mod prelude; 37 | pub mod response; 38 | pub mod router; 39 | pub mod router_option; 40 | pub mod utilities; 41 | 42 | #[macro_use] 43 | extern crate log; 44 | 45 | #[cfg(feature = "async-std")] 46 | pub use async_std::main; 47 | #[cfg(feature = "tokio")] 48 | pub use tokio::main; 49 | -------------------------------------------------------------------------------- /examples/fix_path.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example fix_path --features response-macros` 19 | 20 | use windmark::router_option::RouterOption; 21 | 22 | #[windmark::main] 23 | async fn main() -> Result<(), Box> { 24 | windmark::router::Router::new() 25 | .set_private_key_file("windmark_private.pem") 26 | .set_certificate_file("windmark_public.pem") 27 | .add_options(&[ 28 | RouterOption::RemoveExtraTrailingSlash, 29 | RouterOption::AddMissingTrailingSlash, 30 | RouterOption::AllowCaseInsensitiveLookup, 31 | ]) 32 | .mount( 33 | "/close", 34 | windmark::success!("Visit '/close/'; you should be close enough!"), 35 | ) 36 | .run() 37 | .await 38 | } 39 | -------------------------------------------------------------------------------- /examples/error_handler.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example error_handler` 19 | 20 | use windmark::response::Response; 21 | 22 | #[windmark::main] 23 | async fn main() -> Result<(), Box> { 24 | let mut error_count = 0; 25 | 26 | windmark::router::Router::new() 27 | .set_private_key_file("windmark_private.pem") 28 | .set_certificate_file("windmark_public.pem") 29 | .set_error_handler(move |_| { 30 | error_count += 1; 31 | 32 | println!("{} errors so far", error_count); 33 | 34 | Response::permanent_failure("e") 35 | }) 36 | .mount("/error", |_| { 37 | let nothing = None::; 38 | 39 | Response::success(nothing.unwrap()) 40 | }) 41 | .run() 42 | .await 43 | } 44 | -------------------------------------------------------------------------------- /examples/struct_router.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example struct_router` 19 | 20 | use rossweisse::route; 21 | use windmark::response::Response; 22 | 23 | #[rossweisse::router] 24 | struct Router; 25 | 26 | #[rossweisse::router] 27 | impl Router { 28 | #[route(index)] 29 | pub fn index(_context: windmark::context::RouteContext) -> Response { 30 | Response::success("Hello, World!") 31 | } 32 | } 33 | 34 | #[windmark::main] 35 | async fn main() -> Result<(), Box> { 36 | { 37 | let mut router = Router::new(); 38 | 39 | router.router().set_private_key_file("windmark_private.pem"); 40 | router.router().set_certificate_file("windmark_public.pem"); 41 | 42 | router 43 | } 44 | .run() 45 | .await 46 | } 47 | -------------------------------------------------------------------------------- /src/context/route.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | use std::collections::HashMap; 19 | 20 | use matchit::Params; 21 | use openssl::x509::X509; 22 | use url::Url; 23 | 24 | #[allow(clippy::module_name_repetitions)] 25 | #[derive(Clone)] 26 | pub struct RouteContext { 27 | pub peer_address: Option, 28 | pub url: Url, 29 | pub parameters: HashMap, 30 | pub certificate: Option, 31 | } 32 | 33 | impl RouteContext { 34 | #[must_use] 35 | pub fn new( 36 | peer_address: std::io::Result, 37 | url: Url, 38 | parameters: &Params<'_, '_>, 39 | certificate: Option, 40 | ) -> Self { 41 | Self { 42 | peer_address: peer_address.ok(), 43 | url, 44 | parameters: crate::utilities::params_to_hashmap(parameters), 45 | certificate, 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/context/hook.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | use std::collections::HashMap; 19 | 20 | use matchit::Params; 21 | use openssl::x509::X509; 22 | use url::Url; 23 | 24 | #[allow(clippy::module_name_repetitions)] 25 | #[derive(Clone)] 26 | pub struct HookContext { 27 | pub peer_address: Option, 28 | pub url: Url, 29 | pub parameters: Option>, 30 | pub certificate: Option, 31 | } 32 | 33 | impl HookContext { 34 | #[must_use] 35 | pub fn new( 36 | peer_address: std::io::Result, 37 | url: Url, 38 | parameters: Option>, 39 | certificate: Option, 40 | ) -> Self { 41 | Self { 42 | peer_address: peer_address.ok(), 43 | url, 44 | parameters: parameters.map(|p| crate::utilities::params_to_hashmap(&p)), 45 | certificate, 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /examples/binary.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example binary --features response-macros` 19 | //! 20 | //! Optionally, you can run this example with the `auto-deduce-mime` feature 21 | //! enabled. 22 | 23 | #[windmark::main] 24 | async fn main() -> Result<(), Box> { 25 | let mut router = windmark::router::Router::new(); 26 | 27 | router.set_private_key_file("windmark_private.pem"); 28 | router.set_certificate_file("windmark_public.pem"); 29 | #[cfg(feature = "auto-deduce-mime")] 30 | router.mount("/automatic", { 31 | windmark::binary_success!(include_bytes!("../LICENSE")) 32 | }); 33 | router.mount("/specific", { 34 | windmark::binary_success!(include_bytes!("../LICENSE"), "text/plain") 35 | }); 36 | router.mount("/direct", { 37 | windmark::binary_success!("This is a string.", "text/plain") 38 | }); 39 | 40 | router.run().await 41 | } 42 | -------------------------------------------------------------------------------- /examples/input.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example input` 19 | 20 | use windmark::{context::RouteContext, response::Response}; 21 | 22 | #[windmark::main] 23 | async fn main() -> Result<(), Box> { 24 | windmark::router::Router::new() 25 | .set_private_key_file("windmark_private.pem") 26 | .set_certificate_file("windmark_public.pem") 27 | .mount("/input", |context: RouteContext| { 28 | if let Some(name) = context.url.query() { 29 | Response::success(format!("Your name is {}!", name)) 30 | } else { 31 | Response::input("What is your name?") 32 | } 33 | }) 34 | .mount("/sensitive", |context: RouteContext| { 35 | if let Some(password) = context.url.query() { 36 | Response::success(format!("Your password is {}!", password)) 37 | } else { 38 | Response::sensitive_input("What is your password?") 39 | } 40 | }) 41 | .run() 42 | .await 43 | } 44 | -------------------------------------------------------------------------------- /examples/parameters.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example parameters --features response-macros` 19 | 20 | use windmark::success; 21 | 22 | #[windmark::main] 23 | async fn main() -> Result<(), Box> { 24 | windmark::router::Router::new() 25 | .set_private_key_file("windmark_private.pem") 26 | .set_certificate_file("windmark_public.pem") 27 | .mount( 28 | "/language/:language", 29 | success!( 30 | context, 31 | format!( 32 | "Your language of choice is {}.", 33 | context.parameters.get("language").unwrap() 34 | ) 35 | ), 36 | ) 37 | .mount( 38 | "/name/:first/:last", 39 | success!( 40 | context, 41 | format!( 42 | "Your name is {} {}.", 43 | context.parameters.get("first").unwrap(), 44 | context.parameters.get("last").unwrap() 45 | ) 46 | ), 47 | ) 48 | .run() 49 | .await 50 | } 51 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 2 | 3 | [workspace] 4 | members = ["rossweisse"] 5 | 6 | [package] 7 | name = "windmark" 8 | version = "0.4.0" 9 | authors = ["Fuwn "] 10 | edition = "2021" 11 | description = "An elegant and highly performant async Gemini server framework" 12 | documentation = "https://docs.rs/windmark" 13 | readme = "README.md" 14 | homepage = "https://github.com/gemrest/windmark" 15 | repository = "https://github.com/gemrest/windmark" 16 | license = "GPL-3.0-only" 17 | keywords = ["gemini"] 18 | categories = ["web-programming"] 19 | 20 | [features] 21 | default = ["tokio"] 22 | logger = ["pretty_env_logger"] 23 | auto-deduce-mime = ["tree_magic"] 24 | response-macros = [] 25 | tokio = ["dep:tokio", "tokio-openssl"] 26 | async-std = ["dep:async-std", "async-std-openssl"] 27 | prelude = [] 28 | 29 | [dependencies] 30 | # SSL 31 | openssl = "0.10.38" 32 | tokio-openssl = { version = "0.6.3", optional = true } 33 | async-std-openssl = { version = "0.6.3", optional = true } 34 | 35 | # Non-blocking I/O 36 | tokio = { version = "1.26.0", default-features = false, features = [ 37 | "rt-multi-thread", 38 | "sync", 39 | "net", 40 | "io-util", 41 | "macros", 42 | ], optional = true } 43 | async-trait = "0.1.68" 44 | async-std = { version = "1.12.0", features = ["attributes"], optional = true } 45 | 46 | # Logging 47 | pretty_env_logger = { version = "0.5.0", optional = true } 48 | log = "0.4.16" 49 | 50 | # URL 51 | url = "2.2.2" 52 | matchit = "0.6.0" 53 | 54 | tree_magic = { version = "0.2.3", optional = true } # MIME 55 | 56 | paste = "1.0.12" # Token Pasting 57 | 58 | [dev-dependencies] 59 | rossweisse = { version = "0.0.3", path = "./rossweisse" } 60 | -------------------------------------------------------------------------------- /examples/responses.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example responses --features response-macros` 19 | 20 | use windmark::success; 21 | 22 | #[windmark::main] 23 | async fn main() -> Result<(), Box> { 24 | windmark::router::Router::new() 25 | .set_private_key_file("windmark_private.pem") 26 | .set_certificate_file("windmark_public.pem") 27 | .mount( 28 | "/", 29 | success!( 30 | "# Index\n\nWelcome!\n\n=> /test Test Page\n=> /time Unix Epoch" 31 | ), 32 | ) 33 | .mount("/test", success!("This is a test page.\n=> / back")) 34 | .mount( 35 | "/failure", 36 | windmark::temporary_failure!("Woops ... temporarily."), 37 | ) 38 | .mount( 39 | "/time", 40 | success!(std::time::UNIX_EPOCH.elapsed().unwrap().as_nanos()), 41 | ) 42 | .mount( 43 | "/redirect", 44 | windmark::permanent_redirect!("gemini://localhost/test"), 45 | ) 46 | .run() 47 | .await 48 | } 49 | -------------------------------------------------------------------------------- /examples/callbacks.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example callbacks` 19 | 20 | use windmark::context::HookContext; 21 | 22 | #[windmark::main] 23 | async fn main() -> Result<(), Box> { 24 | windmark::router::Router::new() 25 | .set_private_key_file("windmark_private.pem") 26 | .set_certificate_file("windmark_public.pem") 27 | .mount("/", windmark::success!("Hello!")) 28 | .set_pre_route_callback(|context: HookContext| { 29 | println!( 30 | "accepted connection from {} to {}", 31 | context.peer_address.unwrap().ip(), 32 | context.url.to_string() 33 | ) 34 | }) 35 | .set_post_route_callback( 36 | |context: HookContext, content: &mut windmark::response::Response| { 37 | content.content = content.content.replace("Hello", "Hi"); 38 | 39 | println!( 40 | "closed connection from {}", 41 | context.peer_address.unwrap().ip() 42 | ) 43 | }, 44 | ) 45 | .run() 46 | .await 47 | } 48 | -------------------------------------------------------------------------------- /examples/async.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example async --features response-macros` 19 | 20 | #[windmark::main] 21 | async fn main() -> Result<(), Box> { 22 | let mut router = windmark::router::Router::new(); 23 | #[cfg(feature = "tokio")] 24 | let async_clicks = std::sync::Arc::new(tokio::sync::Mutex::new(0)); 25 | #[cfg(feature = "async-std")] 26 | let async_clicks = std::sync::Arc::new(async_std::sync::Mutex::new(0)); 27 | 28 | router.set_private_key_file("windmark_private.pem"); 29 | router.set_certificate_file("windmark_public.pem"); 30 | router.mount("/clicks", move |_| { 31 | let async_clicks = async_clicks.clone(); 32 | 33 | async move { 34 | let mut clicks = async_clicks.lock().await; 35 | 36 | *clicks += 1; 37 | 38 | windmark::response::Response::success(*clicks) 39 | } 40 | }); 41 | router.mount( 42 | "/macro", 43 | windmark::success_async!( 44 | async { "This response was sent using an asynchronous macro." }.await 45 | ), 46 | ); 47 | 48 | router.run().await 49 | } 50 | -------------------------------------------------------------------------------- /examples/certificate.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example certificate --features response-macros` 19 | 20 | use windmark::response::Response; 21 | 22 | #[windmark::main] 23 | async fn main() -> Result<(), Box> { 24 | windmark::router::Router::new() 25 | .set_private_key_file("windmark_private.pem") 26 | .set_certificate_file("windmark_public.pem") 27 | .mount("/secret", |context: windmark::context::RouteContext| { 28 | if let Some(certificate) = context.certificate { 29 | Response::success(format!("Your public key is '{}'.", { 30 | (|| -> Result { 31 | Ok(format!( 32 | "{:?}", 33 | certificate.public_key()?.rsa()?.public_key_to_pem()? 34 | )) 35 | })() 36 | .unwrap_or_else(|_| { 37 | "An error occurred while reading your public key.".to_string() 38 | }) 39 | })) 40 | } else { 41 | Response::client_certificate_required( 42 | "This is a secret route ... Identify yourself!", 43 | ) 44 | } 45 | }) 46 | .mount( 47 | "/invalid", 48 | windmark::certificate_not_valid!("Your certificate is invalid."), 49 | ) 50 | .run() 51 | .await 52 | } 53 | -------------------------------------------------------------------------------- /examples/stateful_module.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example stateful_module --features response-macros` 19 | 20 | use windmark::{context::HookContext, router::Router}; 21 | 22 | #[derive(Default)] 23 | struct Clicker { 24 | clicks: usize, 25 | } 26 | 27 | impl windmark::module::Module for Clicker { 28 | fn on_attach(&mut self, _router: &mut Router) { 29 | println!("module 'clicker' has been attached!"); 30 | } 31 | 32 | fn on_pre_route(&mut self, context: HookContext) { 33 | self.clicks += 1; 34 | 35 | println!( 36 | "module 'clicker' has been called before the route '{}' with {} clicks!", 37 | context.url.path(), 38 | self.clicks, 39 | ); 40 | } 41 | 42 | fn on_post_route(&mut self, context: HookContext) { 43 | println!( 44 | "module 'clicker' clicker has been called after the route '{}' with {} \ 45 | clicks!", 46 | context.url.path(), 47 | self.clicks, 48 | ); 49 | } 50 | } 51 | 52 | #[windmark::main] 53 | async fn main() -> Result<(), Box> { 54 | let mut router = Router::new(); 55 | 56 | router.set_private_key_file("windmark_private.pem"); 57 | router.set_certificate_file("windmark_public.pem"); 58 | #[cfg(feature = "logger")] 59 | { 60 | router.enable_default_logger(true); 61 | } 62 | router.attach(Clicker::default()); 63 | router.mount("/", windmark::success!("Hello!")); 64 | 65 | router.run().await 66 | } 67 | -------------------------------------------------------------------------------- /examples/async_stateful_module.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! `cargo run --example async_stateful_module --features response-macros` 19 | 20 | use windmark::{context::HookContext, router::Router}; 21 | 22 | #[derive(Default)] 23 | struct Clicker { 24 | clicks: std::sync::Arc>, 25 | } 26 | 27 | #[async_trait::async_trait] 28 | impl windmark::module::AsyncModule for Clicker { 29 | async fn on_attach(&mut self, _router: &mut Router) { 30 | println!("module 'clicker' has been attached!"); 31 | } 32 | 33 | async fn on_pre_route(&mut self, context: HookContext) { 34 | *self.clicks.lock().unwrap() += 1; 35 | 36 | println!( 37 | "module 'clicker' has been called before the route '{}' with {} clicks!", 38 | context.url.path(), 39 | self.clicks.lock().unwrap() 40 | ); 41 | } 42 | 43 | async fn on_post_route(&mut self, context: HookContext) { 44 | println!( 45 | "module 'clicker' clicker has been called after the route '{}' with {} \ 46 | clicks!", 47 | context.url.path(), 48 | self.clicks.lock().unwrap() 49 | ); 50 | } 51 | } 52 | 53 | #[windmark::main] 54 | async fn main() -> Result<(), Box> { 55 | let mut router = Router::new(); 56 | 57 | router.set_private_key_file("windmark_private.pem"); 58 | router.set_certificate_file("windmark_public.pem"); 59 | #[cfg(feature = "logger")] 60 | { 61 | router.enable_default_logger(true); 62 | } 63 | router.attach_async(Clicker::default()); 64 | router.mount("/", windmark::success!("Hello!")); 65 | 66 | router.run().await 67 | } 68 | -------------------------------------------------------------------------------- /rossweisse/src/implementations/router/methods.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | use proc_macro::TokenStream; 19 | 20 | pub fn methods( 21 | _arguments: TokenStream, 22 | mut item: syn::ItemImpl, 23 | ) -> TokenStream { 24 | let routes = item 25 | .items 26 | .iter_mut() 27 | .filter_map(|item| { 28 | if let syn::ImplItem::Fn(method) = item { 29 | for attribute in method.attrs.iter() { 30 | if attribute.path().is_ident("route") { 31 | let arguments = quote::ToTokens::into_token_stream(attribute) 32 | .to_string() 33 | .trim_end_matches(")]") 34 | .trim_start_matches("#[route(") 35 | .to_string(); 36 | 37 | if arguments == "index" { 38 | method.sig.ident = 39 | syn::Ident::new("__router_index", method.sig.ident.span()); 40 | } 41 | 42 | return Some(method.sig.ident.clone()); 43 | } else { 44 | return None; 45 | } 46 | } 47 | 48 | None 49 | } else { 50 | None 51 | } 52 | }) 53 | .collect::>(); 54 | let (implementation_generics, type_generics, where_clause) = 55 | item.generics.split_for_impl(); 56 | let name = &item.self_ty; 57 | let route_paths = routes 58 | .iter() 59 | .map(|route| { 60 | format!( 61 | "/{}", 62 | if route == "__router_index" { 63 | "".to_string() 64 | } else { 65 | route.to_string() 66 | } 67 | ) 68 | }) 69 | .collect::>(); 70 | 71 | quote::quote! { 72 | #item 73 | 74 | impl #implementation_generics #name #type_generics #where_clause { 75 | pub fn new() -> Self { 76 | let mut router = Self::_new(); 77 | 78 | #( 79 | router.router.mount(#route_paths, |context| { 80 | Self::#routes(context) 81 | }); 82 | )* 83 | 84 | router 85 | } 86 | } 87 | } 88 | .into() 89 | } 90 | -------------------------------------------------------------------------------- /rossweisse/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | #![deny( 19 | clippy::all, 20 | clippy::nursery, 21 | clippy::pedantic, 22 | future_incompatible, 23 | nonstandard_style, 24 | rust_2018_idioms, 25 | unsafe_code, 26 | unused, 27 | warnings 28 | )] 29 | #![recursion_limit = "128"] 30 | 31 | mod implementations; 32 | 33 | use proc_macro::TokenStream; 34 | use syn::Item; 35 | 36 | /// Marks a `struct` as a router or marks an `impl` block as a router 37 | /// implementation 38 | /// 39 | /// # Examples 40 | /// 41 | /// ```rust 42 | /// use rossweisse::route; 43 | /// use windmark::response::Response; 44 | /// 45 | /// #[rossweisse::router] 46 | /// struct Router { 47 | /// _phantom: (), 48 | /// } 49 | /// 50 | /// #[rossweisse::router] 51 | /// impl Router { 52 | /// #[route] 53 | /// pub fn index(_context: windmark::context::RouteContext) -> Response { 54 | /// Response::success("Hello, World!") 55 | /// } 56 | /// } 57 | /// ``` 58 | #[proc_macro_attribute] 59 | pub fn router(arguments: TokenStream, item: TokenStream) -> TokenStream { 60 | let output = match syn::parse::(item.clone()) { 61 | Ok(Item::Struct(item)) => implementations::fields(arguments, item), 62 | Ok(Item::Impl(item)) => implementations::methods(arguments, item), 63 | _ => panic!("`#[rossweisse::router]` can only be used on `struct`s"), 64 | }; 65 | 66 | output.into() 67 | } 68 | 69 | /// Marks a method of a router implementation as a route to mount 70 | /// 71 | /// # Examples 72 | /// 73 | /// ```rust 74 | /// use rossweisse::route; 75 | /// use windmark::response::Response; 76 | /// 77 | /// #[rossweisse::router] 78 | /// impl Router { 79 | /// #[route] 80 | /// pub fn index(_context: windmark::context::RouteContext) -> Response { 81 | /// Response::success("Hello, World!") 82 | /// } 83 | /// } 84 | /// ``` 85 | #[proc_macro_attribute] 86 | pub fn route(arguments: TokenStream, item: TokenStream) -> TokenStream { 87 | let output = match syn::parse::(item.clone()) { 88 | Ok(Item::Fn(item)) => implementations::route(arguments, item), 89 | _ => panic!("`#[rossweisse::route]` can only be used on `fn`s"), 90 | }; 91 | 92 | output.into() 93 | } 94 | -------------------------------------------------------------------------------- /rossweisse/src/implementations/router/fields.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | use proc_macro::TokenStream; 19 | use quote::quote; 20 | 21 | pub fn fields(arguments: TokenStream, item: syn::ItemStruct) -> TokenStream { 22 | let field_initializers = syn::parse_macro_input!( 23 | arguments as super::parser::FieldInitializers 24 | ); 25 | let router_identifier = item.ident; 26 | let (named_fields, has_fields) = match item.fields { 27 | syn::Fields::Named(fields) => (fields, true), 28 | syn::Fields::Unit => 29 | ( 30 | syn::FieldsNamed { 31 | brace_token: syn::token::Brace::default(), 32 | named: Default::default(), 33 | }, 34 | false, 35 | ), 36 | _ => 37 | panic!( 38 | "`#[rossweisse::router]` can only be used on `struct`s with named \ 39 | fields or unit structs" 40 | ), 41 | }; 42 | let mut default_expressions = vec![]; 43 | let new_method_fields = named_fields.named.iter().map(|field| { 44 | let name = &field.ident; 45 | let initialiser = field_initializers 46 | .0 47 | .iter() 48 | .find(|initialiser| initialiser.ident == name.clone().unwrap()) 49 | .map(|initialiser| &initialiser.expr) 50 | .unwrap_or_else(|| { 51 | default_expressions.push({ 52 | let default_expression: syn::Expr = 53 | syn::parse_quote! { ::std::default::Default::default() }; 54 | 55 | default_expression 56 | }); 57 | 58 | default_expressions.last().unwrap() 59 | }); 60 | 61 | quote! { 62 | #name: #initialiser, 63 | } 64 | }); 65 | let new_methods = if has_fields { 66 | quote! { 67 | fn _new() -> Self { 68 | Self { 69 | #(#new_method_fields)* 70 | router: ::windmark::router::Router::new(), 71 | } 72 | } 73 | } 74 | } else { 75 | quote! { 76 | fn _new() -> Self { 77 | Self { 78 | router: ::windmark::router::Router::new(), 79 | } 80 | } 81 | } 82 | }; 83 | let output_fields = named_fields.named; 84 | let output = quote! { 85 | struct #router_identifier { 86 | #output_fields 87 | router: ::windmark::router::Router, 88 | } 89 | 90 | impl #router_identifier { 91 | #new_methods 92 | 93 | pub async fn run(&mut self) -> Result<(), Box> { 94 | self.router.run().await 95 | } 96 | 97 | pub fn router(&mut self) -> &mut ::windmark::router::Router { 98 | &mut self.router 99 | } 100 | } 101 | }; 102 | 103 | output.into() 104 | } 105 | -------------------------------------------------------------------------------- /src/response.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | //! Content and response handlers 19 | 20 | #[cfg(feature = "response-macros")] 21 | mod macros; 22 | 23 | macro_rules! response { 24 | ($name:ident, $status:expr) => { 25 | pub fn $name(content: S) -> Self 26 | where S: Into + AsRef { 27 | Self::new($status, content.into()) 28 | } 29 | }; 30 | } 31 | 32 | /// The content and response type a handler should reply with. 33 | #[derive(Clone)] 34 | pub struct Response { 35 | pub status: i32, 36 | pub mime: Option, 37 | pub content: String, 38 | pub character_set: Option, 39 | pub languages: Option>, 40 | } 41 | 42 | impl Response { 43 | response!(input, 10); 44 | 45 | response!(sensitive_input, 11); 46 | 47 | response!(temporary_redirect, 30); 48 | 49 | response!(permanent_redirect, 31); 50 | 51 | response!(temporary_failure, 40); 52 | 53 | response!(server_unavailable, 41); 54 | 55 | response!(cgi_error, 42); 56 | 57 | response!(proxy_error, 43); 58 | 59 | response!(slow_down, 44); 60 | 61 | response!(permanent_failure, 50); 62 | 63 | response!(not_found, 51); 64 | 65 | response!(gone, 52); 66 | 67 | response!(proxy_refused, 53); 68 | 69 | response!(bad_request, 59); 70 | 71 | response!(client_certificate_required, 60); 72 | 73 | response!(certificate_not_authorised, 61); 74 | 75 | response!(certificate_not_valid, 62); 76 | 77 | #[allow(clippy::needless_pass_by_value)] 78 | pub fn success(content: impl ToString) -> Self { 79 | Self::new(20, content.to_string()) 80 | .with_mime("text/gemini") 81 | .with_languages(["en"]) 82 | .with_character_set("utf-8") 83 | .clone() 84 | } 85 | 86 | #[must_use] 87 | pub fn binary_success( 88 | content: impl AsRef<[u8]>, 89 | mime: impl Into + AsRef, 90 | ) -> Self { 91 | Self::new(21, String::from_utf8_lossy(content.as_ref())) 92 | .with_mime(mime) 93 | .clone() 94 | } 95 | 96 | #[cfg(feature = "auto-deduce-mime")] 97 | #[must_use] 98 | pub fn binary_success_auto(content: &[u8]) -> Self { 99 | Self::new(22, String::from_utf8_lossy(content)) 100 | .with_mime(tree_magic::from_u8(content)) 101 | .clone() 102 | } 103 | 104 | #[must_use] 105 | pub fn new(status: i32, content: impl Into + AsRef) -> Self { 106 | Self { 107 | status, 108 | mime: None, 109 | content: content.into(), 110 | character_set: None, 111 | languages: None, 112 | } 113 | } 114 | 115 | pub fn with_mime( 116 | &mut self, 117 | mime: impl Into + AsRef, 118 | ) -> &mut Self { 119 | self.mime = Some(mime.into()); 120 | 121 | self 122 | } 123 | 124 | pub fn with_character_set( 125 | &mut self, 126 | character_set: impl Into + AsRef, 127 | ) -> &mut Self { 128 | self.character_set = Some(character_set.into()); 129 | 130 | self 131 | } 132 | 133 | pub fn with_languages(&mut self, languages: impl AsRef<[S]>) -> &mut Self 134 | where S: Into + AsRef { 135 | self.languages = Some( 136 | languages 137 | .as_ref() 138 | .iter() 139 | .map(|s| s.as_ref().to_string()) 140 | .collect::>(), 141 | ); 142 | 143 | self 144 | } 145 | } 146 | 147 | impl std::future::IntoFuture for Response { 148 | type IntoFuture = std::future::Ready; 149 | type Output = Self; 150 | 151 | fn into_future(self) -> Self::IntoFuture { std::future::ready(self) } 152 | } 153 | -------------------------------------------------------------------------------- /src/response/macros.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | macro_rules! sync_response { 19 | ($($name:ident),*) => { 20 | $( 21 | /// Trailing commas are not supported at the moment! 22 | #[macro_export] 23 | macro_rules! $name { 24 | ($body:expr /* $(,)? */) => { 25 | |_: $crate::context::RouteContext| $crate::response::Response::$name($body) 26 | }; 27 | ($context:ident, $body:expr /* $(,)? */) => { 28 | |$context: $crate::context::RouteContext| $crate::response::Response::$name($body) 29 | }; 30 | } 31 | )* 32 | }; 33 | } 34 | 35 | macro_rules! async_response { 36 | ($($name:ident),*) => { 37 | $(::paste::paste! { 38 | /// Trailing commas are not supported at the moment! 39 | #[macro_export] 40 | macro_rules! [< $name _async >] { 41 | ($body:expr /* $(,)? */) => { 42 | |_: $crate::context::RouteContext| async { $crate::response::Response::$name($body) } 43 | }; 44 | ($context:ident, $body:expr /* $(,)? */) => { 45 | |$context: $crate::context::RouteContext| async { $crate::response::Response::$name($body) } 46 | }; 47 | } 48 | })* 49 | }; 50 | } 51 | 52 | macro_rules! response { 53 | ($($name:ident),* $(,)?) => { 54 | $( 55 | sync_response!($name); 56 | async_response!($name); 57 | )* 58 | }; 59 | } 60 | 61 | response!( 62 | input, 63 | sensitive_input, 64 | success, 65 | temporary_redirect, 66 | permanent_redirect, 67 | temporary_failure, 68 | server_unavailable, 69 | cgi_error, 70 | proxy_error, 71 | slow_down, 72 | permanent_failure, 73 | not_found, 74 | gone, 75 | proxy_refused, 76 | bad_request, 77 | client_certificate_required, 78 | certificate_not_valid, 79 | ); 80 | 81 | #[cfg(feature = "auto-deduce-mime")] 82 | response!(binary_success_auto); 83 | 84 | /// Trailing commas are not supported at the moment! 85 | #[macro_export] 86 | macro_rules! binary_success { 87 | ($body:expr, $mime:expr) => { 88 | |_: $crate::context::RouteContext| { 89 | $crate::response::Response::binary_success($body, $mime) 90 | } 91 | }; 92 | ($body:expr) => {{ 93 | #[cfg(not(feature = "auto-deduce-mime"))] 94 | compile_error!( 95 | "`binary_success` without a MIME type requires the `auto-deduce-mime` \ 96 | feature to be enabled" 97 | ); 98 | 99 | |_: $crate::context::RouteContext| { 100 | #[cfg(feature = "auto-deduce-mime")] 101 | return $crate::response::Response::binary_success_auto($body); 102 | 103 | // Suppress item not found warning 104 | #[cfg(not(feature = "auto-deduce-mime"))] 105 | $crate::response::Response::binary_success( 106 | $body, 107 | "application/octet-stream", 108 | ) 109 | } 110 | }}; 111 | ($context:ident, $body:expr, $mime:expr) => { 112 | |$context: $crate::context::RouteContext| { 113 | $crate::response::Response::binary_success($body, $mime) 114 | } 115 | }; 116 | ($context:ident, $body:expr) => {{ 117 | #[cfg(not(feature = "auto-deduce-mime"))] 118 | compile_error!( 119 | "`binary_success` without a MIME type requires the `auto-deduce-mime` \ 120 | feature to be enabled" 121 | ); 122 | 123 | |$context: $crate::context::RouteContext| { 124 | #[cfg(feature = "auto-deduce-mime")] 125 | return $crate::response::Response::binary_success_auto($body); 126 | 127 | // Suppress item not found warning 128 | #[cfg(not(feature = "auto-deduce-mime"))] 129 | $crate::response::Response::binary_success( 130 | $body, 131 | "application/octet-stream", 132 | ) 133 | } 134 | }}; 135 | } 136 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Windmark 2 | 3 | [![crates.io](https://img.shields.io/crates/v/windmark.svg)](https://crates.io/crates/windmark) 4 | [![docs.rs](https://docs.rs/windmark/badge.svg)](https://docs.rs/windmark) 5 | [![github.com](https://github.com/gemrest/windmark/actions/workflows/check.yaml/badge.svg?branch=main)](https://github.com/gemrest/windmark/actions/workflows/check.yaml) 6 | 7 | Windmark is an elegant and highly performant async Gemini server framework for 8 | the modern age! 9 | 10 | Now supporting both [Tokio](https://tokio.rs/) and [`async-std`](https://async.rs/)! 11 | 12 | ## Usage 13 | 14 | > [!NOTE] 15 | > A macro-based "`struct`-router" is in active development as a simplified 16 | > alternative to the standard server creation approach. Check out 17 | > [Rossweisse](./rossweisse/) for more information! 18 | 19 | ### Features 20 | 21 | | Feature | Description | 22 | | ------------------ | ------------------------------------------------------------------------------------------------------- | 23 | | `default` | Base Windmark framework using [Tokio](https://tokio.rs/) | 24 | | `logger` | Enables the default [`pretty_env_logger`](https://github.com/seanmonstar/pretty-env-logger) integration | 25 | | `auto-deduce-mime` | Exposes `Response`s and macros that automatically fill MIMEs for non-Gemini responses | 26 | | `response-macros` | Simple macros for all `Response`s | 27 | | `tokio` | Marks [Tokio](https://tokio.rs/) as the asynchronous runtime | 28 | | `async-std` | Marks [`async-std`](https://async.rs/) as the asynchronous runtime | 29 | | `prelude` | Exposes the `prelude` module containing the most used Windmark features | 30 | 31 | ### Add Windmark and Tokio as Dependencies 32 | 33 | ```toml 34 | # Cargo.toml 35 | 36 | [dependencies] 37 | windmark = "0.4.0" 38 | tokio = { version = "1.26.0", features = ["full"] } 39 | 40 | # If you would like to use the built-in logger (recommended) 41 | # windmark = { version = "0.4.0", features = ["logger"] } 42 | 43 | # If you would like to use the built-in MIME deduction when `Success`-ing a file 44 | # (recommended) 45 | # windmark = { version = "0.4.0", features = ["auto-deduce-mime"] } 46 | 47 | # If you would like to use macro-based responses (as seen below) 48 | # windmark = { version = "0.4.0", features = ["response-macros"] } 49 | ``` 50 | 51 | ### Implementing a Windmark Server 52 | 53 | ```rust 54 | // src/main.rs 55 | 56 | use windmark::response::Response; 57 | 58 | #[windmark::main] 59 | async fn main() -> Result<(), Box> { 60 | windmark::router::Router::new() 61 | .set_private_key_file("windmark_private.pem") 62 | .set_certificate_file("windmark_public.pem") 63 | .mount("/", |_| Response::success("Hello, World!")) 64 | .set_error_handler(|_| 65 | Response::permanent_failure("This route does not exist!") 66 | ) 67 | .run() 68 | .await 69 | } 70 | ``` 71 | 72 | ### Implementing a Windmark Server Using Rossweisse 73 | 74 | ```rust 75 | // src/main.rs 76 | 77 | use windmark::response::Response; 78 | 79 | #[rossweisse::router] 80 | struct Router; 81 | 82 | #[rossweisse::router] 83 | impl Router { 84 | #[rossweisse::route(index)] 85 | pub fn index( 86 | _context: windmark::context::RouteContext, 87 | ) -> Response { 88 | Response::success("Hello, World!") 89 | } 90 | } 91 | 92 | // ... 93 | ``` 94 | 95 | ## Examples 96 | 97 | Examples can be found within the 98 | [`examples/`](https://github.com/gemrest/windmark/tree/main/examples) directory 99 | along with a rundown of each of their purposes and useful facts. 100 | 101 | Run an example by cloning this repository and running `cargo run --example example_name`. 102 | 103 | ## Modules 104 | 105 | Modules are composable extensions which can be procedurally mounted onto Windmark 106 | routers. 107 | 108 | ### Examples 109 | 110 | - [Simple Stateless Module](https://github.com/gemrest/windmark/blob/main/examples/stateless_module.rs) 111 | \- Mounts the `/smiley` route, returning an 😀 emoji 112 | - [Simple Stateful Module](https://github.com/gemrest/windmark/blob/main/examples/stateful_module.rs) 113 | \- Adds a click tracker (route hit tracker) that additionally notifies before and after route visits 114 | - [Windmark Comments](https://github.com/gemrest/windmark-comments) - A fully featured comment engine 115 | for your capsule 116 | 117 | ## License 118 | 119 | This project is licensed with the 120 | [GNU General Public License v3.0](https://github.com/gemrest/windmark/blob/main/LICENSE). 121 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Examples 2 | 3 | ## [Async Stateful Module](./async_stateful_module.rs) 4 | 5 | `cargo run --example async_stateful_module --features response-macros` 6 | 7 | Demonstrates use of the `AsyncModule` trait by implementing the module 8 | `Clicker` which tracks the global number of visits to the capsule. 9 | 10 | This can easily be adapted to contain a hashmap of routes which are individually 11 | tracked for clicks. 12 | 13 | ## [Async](./async.rs) 14 | 15 | `cargo run --example async --features response-macros` 16 | 17 | Demonstrates use of async routes through an async response macro and 18 | implementing a click tracker using a shared variable through an thread-safe, 19 | async mutex. 20 | 21 | ## [Binary](./binary.rs) 22 | 23 | `cargo run --example binary --features response-macros` 24 | 25 | Demonstrates the binary response functionality by using both manual 26 | and automatic mime resolution (`--features auto-deduce-mime`). 27 | 28 | ## [Callbacks](./callbacks.rs) 29 | 30 | `cargo run --example callbacks` 31 | 32 | Demonstrates use of the pre and post-route callback handlers. 33 | 34 | ## [Certificate](./certificate.rs) 35 | 36 | `cargo run --example certificate --features response-macros` 37 | 38 | Demonstrate the various certificate related responses as well as 39 | reading the client certificate to give conditional access. 40 | 41 | ## [Default Logger](./default_logger.rs) 42 | 43 | `cargo run --example default_logger --features logger,response-macros` 44 | 45 | A simple example showing the use of the default default logger implementation. 46 | 47 | ## [Empty](./empty.rs) 48 | 49 | `cargo run --example empty` 50 | 51 | An empty example which starts up a server but has no mounted routes. 52 | 53 | ## [Error Handler](./error_handler.rs) 54 | 55 | `cargo run --example error_handler` 56 | 57 | Creates an intentional error within a route, invoking the error handler. 58 | 59 | ## [Fix Path](./fix_path.rs) 60 | 61 | `cargo run --example fix_path --features response-macros` 62 | 63 | A simple example which demonstrates use of the path fixer that attempts to resolve the closest match of a route when an invalid route is visited. 64 | 65 | This feature is limited to simple resolution patches such as resolving 66 | trailing and missing trailing slashes. If your capsule requires a more sophisticated path fixer, please use any of the provided mechanisms to do so before your routes execute. 67 | 68 | ## [Input](./input.rs) 69 | 70 | `cargo run --example input` 71 | 72 | Demonstrates how to accept and inspect both standard and sensitive input. 73 | 74 | ## [MIME](./mime.rs) 75 | 76 | `cargo run --example mime` 77 | 78 | Demonstrate how to modify the MIME of a response before use. 79 | 80 | ## [Parameters](./parameters.rs) 81 | 82 | `cargo run --example parameters --features response-macros` 83 | 84 | Demonstrate the use of route parameters (not URL queries). 85 | 86 | ## [Partial](./partial.rs) 87 | 88 | `cargo run --example partial` 89 | 90 | Demonstrates use of appending headers and footers to routes, globally. 91 | 92 | If you would like to conditionally append headers and footers based on route, please look into using a templating framework. 93 | 94 | ## [Query](./query.rs) 95 | 96 | `cargo run --example input --features response-macros` 97 | 98 | Demonstrates the inspection of URL queries parameters. 99 | 100 | ## [Responses](./responses.rs) 101 | 102 | `cargo run --example responses --features response-macros` 103 | 104 | Demonstrates the use of a wide variety of responses, additionally exposing the flexibility of response bodies types. 105 | 106 | ## [Simple `async-std`](./simple_async_std.rs) 107 | 108 | `cargo run --example simple_async_std --features async-std` 109 | 110 | Demonstrates how to explicitly specify Windmark to use the [`async-std`](https://github.com/async-rs/async-std) runtime. 111 | 112 | If the `async-std` feature is NOT enabled, Windmark will default to using Tokio as the async runtime. 113 | 114 | ## [Simple Tokio](./simple_tokio.rs) 115 | 116 | `cargo run --example simple_async_std --features async-std` 117 | 118 | Demonstrates how to explicitly specify Windmark to use the [Tokio](https://github.com/tokio-rs/tokio) runtime. 119 | 120 | ## [Stateful Module](./stateful_module.rs) 121 | 122 | `cargo run --example stateful_module --features response-macros` 123 | 124 | Demonstrates use of `Module`s by implementing a click tracker 125 | 126 | Identical in functionality to the Async Stateful Module example, just not asynchronous. 127 | 128 | ## [Stateless Module](./stateless_module.rs) 129 | 130 | `cargo run --example stateless_module` 131 | 132 | Demonstrates use of a stateless module. 133 | 134 | Unlike a `Module`, a stateless module is not encapsulated into a `struct`, but is a simple function which is used to perform operations. 135 | 136 | Stateless modules are able to emulate stateful modules employing `static` variables. The earliest Windmark modules (add-ons) were made this way. 137 | 138 | The only requirement of a module is to implement the signature of a stateless module: `FnMut(&mut Router) -> ()`. 139 | -------------------------------------------------------------------------------- /src/router.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Windmark . 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, version 3. 6 | // 7 | // This program is distributed in the hope that it will be useful, but 8 | // WITHOUT ANY WARRANTY; without even the implied warranty of 9 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | // General Public License for more details. 11 | // 12 | // You should have received a copy of the GNU General Public License 13 | // along with this program. If not, see . 14 | // 15 | // Copyright (C) 2022-2023 Fuwn 16 | // SPDX-License-Identifier: GPL-3.0-only 17 | 18 | #![allow(clippy::significant_drop_tightening)] 19 | 20 | use std::{ 21 | collections::HashSet, 22 | error::Error, 23 | fmt::Write, 24 | future::IntoFuture, 25 | sync::{Arc, Mutex}, 26 | time, 27 | }; 28 | 29 | #[cfg(feature = "async-std")] 30 | use async_std::{ 31 | io::{ReadExt, WriteExt}, 32 | sync::Mutex as AsyncMutex, 33 | }; 34 | use openssl::ssl::{self, SslAcceptor, SslMethod}; 35 | #[cfg(feature = "tokio")] 36 | use tokio::{ 37 | io::{AsyncReadExt, AsyncWriteExt}, 38 | sync::Mutex as AsyncMutex, 39 | }; 40 | use url::Url; 41 | 42 | use crate::{ 43 | context::{ErrorContext, HookContext, RouteContext}, 44 | handler::{ 45 | ErrorResponse, 46 | Partial, 47 | PostRouteHook, 48 | PreRouteHook, 49 | RouteResponse, 50 | }, 51 | module::{AsyncModule, Module}, 52 | response::Response, 53 | router_option::RouterOption, 54 | }; 55 | 56 | macro_rules! block { 57 | ($body:expr) => { 58 | #[cfg(feature = "tokio")] 59 | ::tokio::task::block_in_place(|| { 60 | ::tokio::runtime::Handle::current().block_on(async { $body }); 61 | }); 62 | #[cfg(feature = "async-std")] 63 | ::async_std::task::block_on(async { $body }); 64 | }; 65 | } 66 | 67 | macro_rules! or_error { 68 | ($stream:ident, $operation:expr, $error_format:literal) => { 69 | match $operation { 70 | Ok(u) => u, 71 | Err(e) => { 72 | $stream 73 | .write_all(format!($error_format, e).as_bytes()) 74 | .await?; 75 | 76 | // $stream.shutdown().await?; 77 | 78 | return Ok(()); 79 | } 80 | } 81 | }; 82 | } 83 | 84 | #[cfg(feature = "tokio")] 85 | type Stream = tokio_openssl::SslStream; 86 | #[cfg(feature = "async-std")] 87 | type Stream = async_std_openssl::SslStream; 88 | 89 | /// A router which takes care of all tasks a Windmark server should handle: 90 | /// response generation, panics, logging, and more. 91 | #[derive(Clone)] 92 | pub struct Router { 93 | routes: matchit::Router>>>, 94 | error_handler: Arc>>, 95 | private_key_file_name: String, 96 | private_key_content: Option, 97 | certificate_file_name: String, 98 | certificate_content: Option, 99 | headers: Arc>>>, 100 | footers: Arc>>>, 101 | ssl_acceptor: Arc, 102 | #[cfg(feature = "logger")] 103 | default_logger: bool, 104 | pre_route_callback: Arc>>, 105 | post_route_callback: Arc>>, 106 | character_set: String, 107 | languages: Vec, 108 | port: i32, 109 | async_modules: Arc>>>, 110 | modules: Arc>>>, 111 | options: HashSet, 112 | listener_address: String, 113 | } 114 | 115 | impl Router { 116 | /// Create a new `Router` 117 | /// 118 | /// # Examples 119 | /// 120 | /// ```rust 121 | /// windmark::router::Router::new(); 122 | /// ``` 123 | /// 124 | /// # Panics 125 | /// 126 | /// if a default `SslAcceptor` could not be built. 127 | #[must_use] 128 | pub fn new() -> Self { Self::default() } 129 | 130 | /// Set the filename of the private key file. 131 | /// 132 | /// # Examples 133 | /// 134 | /// ```rust 135 | /// windmark::router::Router::new().set_private_key_file("windmark_private.pem"); 136 | /// ``` 137 | pub fn set_private_key_file( 138 | &mut self, 139 | private_key_file_name: impl Into + AsRef, 140 | ) -> &mut Self { 141 | self.private_key_file_name = private_key_file_name.into(); 142 | 143 | self 144 | } 145 | 146 | /// Set the content of the private key 147 | /// 148 | /// # Examples 149 | /// 150 | /// ```rust 151 | /// windmark::router::Router::new().set_private_key("..."); 152 | /// ``` 153 | pub fn set_private_key( 154 | &mut self, 155 | private_key_content: impl Into + AsRef, 156 | ) -> &mut Self { 157 | self.private_key_content = Some(private_key_content.into()); 158 | 159 | self 160 | } 161 | 162 | /// Set the filename of the certificate chain file. 163 | /// 164 | /// # Examples 165 | /// 166 | /// ```rust 167 | /// windmark::router::Router::new().set_certificate_file("windmark_public.pem"); 168 | /// ``` 169 | pub fn set_certificate_file( 170 | &mut self, 171 | certificate_name: impl Into + AsRef, 172 | ) -> &mut Self { 173 | self.certificate_file_name = certificate_name.into(); 174 | 175 | self 176 | } 177 | 178 | /// Set the content of the certificate chain file. 179 | /// 180 | /// # Examples 181 | /// 182 | /// ```rust 183 | /// windmark::router::Router::new().set_certificate("..."); 184 | /// ``` 185 | pub fn set_certificate( 186 | &mut self, 187 | certificate_content: impl Into + AsRef, 188 | ) -> &mut Self { 189 | self.certificate_content = Some(certificate_content.into()); 190 | 191 | self 192 | } 193 | 194 | /// Map routes to URL paths 195 | /// 196 | /// Supports both synchronous and asynchronous handlers 197 | /// 198 | /// # Examples 199 | /// 200 | /// ```rust 201 | /// use windmark::response::Response; 202 | /// 203 | /// windmark::router::Router::new() 204 | /// .mount("/", |_| { 205 | /// async { Response::success("This is the index page!") } 206 | /// }) 207 | /// .mount("/about", |_| async { Response::success("About that...") }); 208 | /// ``` 209 | /// 210 | /// # Panics 211 | /// 212 | /// May panic if the route cannot be mounted. 213 | pub fn mount( 214 | &mut self, 215 | route: impl Into + AsRef, 216 | mut handler: impl FnMut(RouteContext) -> R + Send + Sync + 'static, 217 | ) -> &mut Self 218 | where 219 | R: IntoFuture + Send + 'static, 220 | ::IntoFuture: Send, 221 | { 222 | self 223 | .routes 224 | .insert( 225 | route.into(), 226 | Arc::new(AsyncMutex::new(Box::new(move |context: RouteContext| { 227 | handler(context).into_future() 228 | }))), 229 | ) 230 | .unwrap(); 231 | 232 | self 233 | } 234 | 235 | /// Create an error handler which will be displayed on any error. 236 | /// 237 | /// # Examples 238 | /// 239 | /// ```rust 240 | /// windmark::router::Router::new().set_error_handler(|_| { 241 | /// windmark::response::Response::success("You have encountered an error!") 242 | /// }); 243 | /// ``` 244 | pub fn set_error_handler( 245 | &mut self, 246 | mut handler: impl FnMut(ErrorContext) -> R + Send + Sync + 'static, 247 | ) -> &mut Self 248 | where 249 | R: IntoFuture + Send + 'static, 250 | ::IntoFuture: Send, 251 | { 252 | self.error_handler = Arc::new(AsyncMutex::new(Box::new(move |context| { 253 | handler(context).into_future() 254 | }))); 255 | 256 | self 257 | } 258 | 259 | /// Add a header for the `Router` which should be displayed on every route. 260 | /// 261 | /// # Panics 262 | /// 263 | /// May panic if the header cannot be added. 264 | /// 265 | /// # Examples 266 | /// 267 | /// ```rust 268 | /// windmark::router::Router::new().add_header( 269 | /// |context: windmark::context::RouteContext| { 270 | /// format!("This is displayed at the top of {}!", context.url.path()) 271 | /// }, 272 | /// ); 273 | /// ``` 274 | pub fn add_header(&mut self, handler: impl Partial + 'static) -> &mut Self { 275 | (*self.headers.lock().unwrap()).push(Box::new(handler)); 276 | 277 | self 278 | } 279 | 280 | /// Add a footer for the `Router` which should be displayed on every route. 281 | /// 282 | /// # Panics 283 | /// 284 | /// May panic if the header cannot be added. 285 | /// 286 | /// # Examples 287 | /// 288 | /// ```rust 289 | /// windmark::router::Router::new().add_footer( 290 | /// |context: windmark::context::RouteContext| { 291 | /// format!("This is displayed at the bottom of {}!", context.url.path()) 292 | /// }, 293 | /// ); 294 | /// ``` 295 | pub fn add_footer(&mut self, handler: impl Partial + 'static) -> &mut Self { 296 | (*self.footers.lock().unwrap()).push(Box::new(handler)); 297 | 298 | self 299 | } 300 | 301 | /// Run the `Router` and wait for requests 302 | /// 303 | /// # Examples 304 | /// 305 | /// ```rust 306 | /// windmark::router::Router::new().run(); 307 | /// ``` 308 | /// 309 | /// # Panics 310 | /// 311 | /// if the client could not be accepted. 312 | /// 313 | /// # Errors 314 | /// 315 | /// if the `TcpListener` could not be bound. 316 | pub async fn run(&mut self) -> Result<(), Box> { 317 | self.create_acceptor()?; 318 | 319 | #[cfg(feature = "logger")] 320 | if self.default_logger { 321 | pretty_env_logger::init(); 322 | } 323 | 324 | #[cfg(feature = "tokio")] 325 | let listener = tokio::net::TcpListener::bind(format!( 326 | "{}:{}", 327 | self.listener_address, self.port 328 | )) 329 | .await?; 330 | #[cfg(feature = "async-std")] 331 | let listener = async_std::net::TcpListener::bind(format!( 332 | "{}:{}", 333 | self.listener_address, self.port 334 | )) 335 | .await?; 336 | 337 | #[cfg(feature = "logger")] 338 | info!("windmark is listening for connections"); 339 | 340 | loop { 341 | match listener.accept().await { 342 | Ok((stream, _)) => { 343 | let mut self_clone = self.clone(); 344 | let acceptor = self_clone.ssl_acceptor.clone(); 345 | #[cfg(feature = "tokio")] 346 | let spawner = tokio::spawn; 347 | #[cfg(feature = "async-std")] 348 | let spawner = async_std::task::spawn; 349 | 350 | spawner(async move { 351 | let ssl = match ssl::Ssl::new(acceptor.context()) { 352 | Ok(ssl) => ssl, 353 | Err(e) => { 354 | error!("ssl context error: {e:?}"); 355 | 356 | return; 357 | } 358 | }; 359 | 360 | #[cfg(feature = "tokio")] 361 | let quick_stream = tokio_openssl::SslStream::new(ssl, stream); 362 | #[cfg(feature = "async-std")] 363 | let quick_stream = async_std_openssl::SslStream::new(ssl, stream); 364 | 365 | match quick_stream { 366 | Ok(mut stream) => { 367 | if let Err(e) = std::pin::Pin::new(&mut stream).accept().await { 368 | println!("stream accept error: {e:?}"); 369 | } 370 | 371 | if let Err(e) = self_clone.handle(&mut stream).await { 372 | error!("handle error: {e}"); 373 | } 374 | } 375 | Err(e) => error!("ssl stream error: {e:?}"), 376 | } 377 | }); 378 | } 379 | Err(e) => error!("tcp stream error: {e:?}"), 380 | } 381 | } 382 | 383 | // Ok(()) 384 | } 385 | 386 | #[allow( 387 | clippy::too_many_lines, 388 | clippy::needless_pass_by_ref_mut, 389 | clippy::significant_drop_in_scrutinee, 390 | clippy::cognitive_complexity 391 | )] 392 | async fn handle( 393 | &mut self, 394 | stream: &mut Stream, 395 | ) -> Result<(), Box> { 396 | let mut buffer = [0u8; 1024]; 397 | let mut url = Url::parse("gemini://fuwn.me/")?; 398 | let mut footer = String::new(); 399 | let mut header = String::new(); 400 | 401 | while let Ok(size) = stream.read(&mut buffer).await { 402 | let request = or_error!( 403 | stream, 404 | String::from_utf8(buffer[0..size].to_vec()), 405 | "59 The server (Windmark) received a bad request: {}" 406 | ); 407 | 408 | url = or_error!( 409 | stream, 410 | Url::parse(&request.replace("\r\n", "")), 411 | "59 The server (Windmark) received a bad request: {}" 412 | ); 413 | 414 | if request.contains("\r\n") { 415 | break; 416 | } 417 | } 418 | 419 | if url.path().is_empty() { 420 | url.set_path("/"); 421 | } 422 | 423 | let mut path = url.path().to_string(); 424 | 425 | if self 426 | .options 427 | .contains(&RouterOption::AllowCaseInsensitiveLookup) 428 | { 429 | path = path.to_lowercase(); 430 | } 431 | 432 | let mut route = self.routes.at(&path); 433 | 434 | if route.is_err() { 435 | if self 436 | .options 437 | .contains(&RouterOption::RemoveExtraTrailingSlash) 438 | && path.ends_with('/') 439 | && path != "/" 440 | { 441 | path = path.trim_end_matches('/').to_string(); 442 | route = self.routes.at(&path); 443 | } else if self 444 | .options 445 | .contains(&RouterOption::AddMissingTrailingSlash) 446 | && !path.ends_with('/') 447 | { 448 | let path_with_slash = format!("{path}/"); 449 | 450 | if self.routes.at(&path_with_slash).is_ok() { 451 | path = path_with_slash; 452 | route = self.routes.at(&path); 453 | } 454 | } 455 | } 456 | 457 | let peer_certificate = stream.ssl().peer_certificate(); 458 | let hook_context = HookContext::new( 459 | stream.get_ref().peer_addr(), 460 | url.clone(), 461 | route 462 | .as_ref() 463 | .map_or(None, |route| Some(route.params.clone())), 464 | peer_certificate.clone(), 465 | ); 466 | 467 | for module in &mut *self.async_modules.lock().await { 468 | module.on_pre_route(hook_context.clone()).await; 469 | } 470 | 471 | if let Ok(mut modules) = self.modules.lock() { 472 | for module in &mut *modules { 473 | module.on_pre_route(hook_context.clone()); 474 | } 475 | } 476 | 477 | if let Ok(mut callback) = self.pre_route_callback.lock() { 478 | callback.call(hook_context.clone()); 479 | } 480 | 481 | let mut content = if let Ok(ref route) = route { 482 | let footers_length = (*self.footers.lock().unwrap()).len(); 483 | let route_context = RouteContext::new( 484 | stream.get_ref().peer_addr(), 485 | url.clone(), 486 | &route.params, 487 | peer_certificate, 488 | ); 489 | 490 | if let Ok(mut headers) = self.headers.lock() { 491 | for partial_header in &mut *headers { 492 | writeln!( 493 | &mut header, 494 | "{}", 495 | partial_header.call(route_context.clone()), 496 | ) 497 | .unwrap(); 498 | } 499 | } 500 | 501 | for (i, partial_footer) in { 502 | #[allow(clippy::needless_borrow, clippy::explicit_auto_deref)] 503 | (&mut *self.footers.lock().unwrap()).iter_mut().enumerate() 504 | } { 505 | let _ = write!( 506 | &mut footer, 507 | "{}{}", 508 | partial_footer.call(route_context.clone()), 509 | if footers_length > 1 && i != footers_length - 1 { 510 | "\n" 511 | } else { 512 | "" 513 | }, 514 | ); 515 | } 516 | 517 | let mut lock = (*route.value).lock().await; 518 | let handler = lock.call(route_context); 519 | 520 | handler.await 521 | } else { 522 | (*self.error_handler) 523 | .lock() 524 | .await 525 | .call(ErrorContext::new( 526 | stream.get_ref().peer_addr(), 527 | url.clone(), 528 | peer_certificate, 529 | )) 530 | .await 531 | }; 532 | 533 | for module in &mut *self.async_modules.lock().await { 534 | module.on_post_route(hook_context.clone()).await; 535 | } 536 | 537 | if let Ok(mut modules) = self.modules.lock() { 538 | for module in &mut *modules { 539 | module.on_post_route(hook_context.clone()); 540 | } 541 | } 542 | 543 | if let Ok(mut callback) = self.post_route_callback.lock() { 544 | callback.call(hook_context.clone(), &mut content); 545 | } 546 | 547 | stream 548 | .write_all( 549 | format!( 550 | "{}{}\r\n{}", 551 | if content.status == 21 552 | || content.status == 22 553 | || content.status == 23 554 | { 555 | 20 556 | } else { 557 | content.status 558 | }, 559 | match content.status { 560 | 20 => 561 | format!( 562 | " {}; charset={}; lang={}", 563 | content.mime.unwrap_or_else(|| "text/gemini".to_string()), 564 | content 565 | .character_set 566 | .unwrap_or_else(|| self.character_set.clone()), 567 | content 568 | .languages 569 | .unwrap_or_else(|| self.languages.clone()) 570 | .join(","), 571 | ), 572 | 21 => content.mime.unwrap_or_default(), 573 | #[cfg(feature = "auto-deduce-mime")] 574 | 22 => format!(" {}", content.mime.unwrap_or_default()), 575 | _ => format!(" {}", content.content), 576 | }, 577 | match content.status { 578 | 20 => format!("{header}{}\n{footer}", content.content), 579 | 21 | 22 => content.content, 580 | _ => String::new(), 581 | } 582 | ) 583 | .as_bytes(), 584 | ) 585 | .await?; 586 | 587 | #[cfg(feature = "tokio")] 588 | stream.shutdown().await?; 589 | #[cfg(feature = "async-std")] 590 | stream.get_mut().shutdown(std::net::Shutdown::Both)?; 591 | 592 | Ok(()) 593 | } 594 | 595 | fn create_acceptor(&mut self) -> Result<(), Box> { 596 | let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls())?; 597 | 598 | if self.certificate_content.is_some() { 599 | builder.set_certificate( 600 | openssl::x509::X509::from_pem( 601 | self.certificate_content.clone().unwrap().as_bytes(), 602 | )? 603 | .as_ref(), 604 | )?; 605 | } else { 606 | builder.set_certificate_file( 607 | &self.certificate_file_name, 608 | ssl::SslFiletype::PEM, 609 | )?; 610 | } 611 | 612 | if self.private_key_content.is_some() { 613 | builder.set_private_key( 614 | openssl::pkey::PKey::private_key_from_pem( 615 | self.private_key_content.clone().unwrap().as_bytes(), 616 | )? 617 | .as_ref(), 618 | )?; 619 | } else { 620 | builder.set_private_key_file( 621 | &self.private_key_file_name, 622 | ssl::SslFiletype::PEM, 623 | )?; 624 | } 625 | 626 | builder.check_private_key()?; 627 | builder.set_verify_callback(ssl::SslVerifyMode::PEER, |_, _| true); 628 | builder.set_session_id_context( 629 | time::SystemTime::now() 630 | .duration_since(time::UNIX_EPOCH)? 631 | .as_secs() 632 | .to_string() 633 | .as_bytes(), 634 | )?; 635 | 636 | self.ssl_acceptor = Arc::new(builder.build()); 637 | 638 | Ok(()) 639 | } 640 | 641 | /// Use a self-made `SslAcceptor` 642 | /// 643 | /// # Examples 644 | /// 645 | /// ```rust 646 | /// use openssl::ssl; 647 | /// 648 | /// windmark::router::Router::new().set_ssl_acceptor({ 649 | /// let mut builder = 650 | /// ssl::SslAcceptor::mozilla_intermediate(ssl::SslMethod::tls()).unwrap(); 651 | /// 652 | /// builder 653 | /// .set_private_key_file("windmark_private.pem", ssl::SslFiletype::PEM) 654 | /// .unwrap(); 655 | /// builder 656 | /// .set_certificate_file("windmark_public.pem", ssl::SslFiletype::PEM) 657 | /// .unwrap(); 658 | /// builder.check_private_key().unwrap(); 659 | /// 660 | /// builder.build() 661 | /// }); 662 | /// ``` 663 | pub fn set_ssl_acceptor(&mut self, ssl_acceptor: SslAcceptor) -> &mut Self { 664 | self.ssl_acceptor = Arc::new(ssl_acceptor); 665 | 666 | self 667 | } 668 | 669 | /// Enabled the default logger (the 670 | /// [`pretty_env_logger`](https://crates.io/crates/pretty_env_logger) and 671 | /// [`log`](https://crates.io/crates/log) crates). 672 | #[cfg(feature = "logger")] 673 | pub fn enable_default_logger(&mut self, enable: bool) -> &mut Self { 674 | self.default_logger = enable; 675 | 676 | std::env::set_var("RUST_LOG", "windmark=trace"); 677 | 678 | self 679 | } 680 | 681 | /// Set the default logger's log level. 682 | /// 683 | /// If you enable Windmark's default logger with `enable_default_logger`, 684 | /// Windmark will only log, logs from itself. By setting a log level with 685 | /// this method, you are overriding the default log level, so you must choose 686 | /// to enable logs from Windmark with the `log_windmark` parameter. 687 | /// 688 | /// Log level "language" is detailed 689 | /// [here](https://docs.rs/env_logger/0.9.0/env_logger/#enabling-logging). 690 | /// 691 | /// # Examples 692 | /// 693 | /// ```rust 694 | /// windmark::router::Router::new() 695 | /// .enable_default_logger(true) 696 | /// .set_log_level("your_crate_name=trace", true); 697 | /// // If you would only like to log, logs from your crate: 698 | /// // .set_log_level("your_crate_name=trace", false); 699 | /// ``` 700 | #[cfg(feature = "logger")] 701 | pub fn set_log_level( 702 | &mut self, 703 | log_level: impl Into + AsRef, 704 | log_windmark: bool, 705 | ) -> &mut Self { 706 | std::env::set_var( 707 | "RUST_LOG", 708 | format!( 709 | "{}{}", 710 | if log_windmark { "windmark," } else { "" }, 711 | log_level.into() 712 | ), 713 | ); 714 | 715 | self 716 | } 717 | 718 | /// Set a callback to run before a client response is delivered 719 | /// 720 | /// # Examples 721 | /// 722 | /// ```rust 723 | /// use log::info; 724 | /// 725 | /// windmark::router::Router::new().set_pre_route_callback( 726 | /// |context: windmark::context::HookContext| { 727 | /// info!( 728 | /// "accepted connection from {}", 729 | /// context.peer_address.unwrap().ip(), 730 | /// ) 731 | /// }, 732 | /// ); 733 | /// ``` 734 | pub fn set_pre_route_callback( 735 | &mut self, 736 | callback: impl PreRouteHook + 'static, 737 | ) -> &mut Self { 738 | self.pre_route_callback = Arc::new(Mutex::new(Box::new(callback))); 739 | 740 | self 741 | } 742 | 743 | /// Set a callback to run after a client response is delivered 744 | /// 745 | /// # Examples 746 | /// 747 | /// ```rust 748 | /// use log::info; 749 | /// 750 | /// windmark::router::Router::new().set_post_route_callback( 751 | /// |context: windmark::context::HookContext, 752 | /// _content: &mut windmark::response::Response| { 753 | /// info!( 754 | /// "closed connection from {}", 755 | /// context.peer_address.unwrap().ip(), 756 | /// ) 757 | /// }, 758 | /// ); 759 | /// ``` 760 | pub fn set_post_route_callback( 761 | &mut self, 762 | callback: impl PostRouteHook + 'static, 763 | ) -> &mut Self { 764 | self.post_route_callback = Arc::new(Mutex::new(Box::new(callback))); 765 | 766 | self 767 | } 768 | 769 | /// Attach a stateless module to a `Router`. 770 | /// 771 | /// A module is an extension or middleware to a `Router`. Modules get full 772 | /// access to the `Router`, but can be extended by a third party. 773 | /// 774 | /// # Examples 775 | /// 776 | /// ## Integrated Module 777 | /// 778 | /// ```rust 779 | /// use windmark::response::Response; 780 | /// 781 | /// windmark::router::Router::new().attach_stateless(|r| { 782 | /// r.mount( 783 | /// "/module", 784 | /// Box::new(|_| Response::success("This is a module!")), 785 | /// ); 786 | /// r.set_error_handler(Box::new(|_| { 787 | /// Response::not_found( 788 | /// "This error handler has been implemented by a module!", 789 | /// ) 790 | /// })); 791 | /// }); 792 | /// ``` 793 | /// 794 | /// ## External Module 795 | /// 796 | /// ```rust 797 | /// use windmark::response::Response; 798 | /// 799 | /// mod windmark_example { 800 | /// pub fn module(router: &mut windmark::router::Router) { 801 | /// router.mount( 802 | /// "/module", 803 | /// Box::new(|_| { 804 | /// windmark::response::Response::success("This is a module!") 805 | /// }), 806 | /// ); 807 | /// } 808 | /// } 809 | /// 810 | /// windmark::router::Router::new().attach_stateless(windmark_example::module); 811 | /// ``` 812 | pub fn attach_stateless(&mut self, mut module: F) -> &mut Self 813 | where F: FnMut(&mut Self) { 814 | module(self); 815 | 816 | self 817 | } 818 | 819 | /// Attach a stateful module to a `Router`; with async support 820 | /// 821 | /// Like a stateless module is an extension or middleware to a `Router`. 822 | /// Modules get full access to the `Router` and can be extended by a third 823 | /// party, but also, can create hooks will be executed through various parts 824 | /// of a routes' lifecycle. Stateful modules also have state, so variables can 825 | /// be stored for further access. 826 | /// 827 | /// # Panics 828 | /// 829 | /// May panic if the stateful module cannot be attached. 830 | /// 831 | /// # Examples 832 | /// 833 | /// ```rust 834 | /// use log::info; 835 | /// use windmark::{context::HookContext, router::Router}; 836 | /// 837 | /// #[derive(Default)] 838 | /// struct Clicker { 839 | /// clicks: isize, 840 | /// } 841 | /// 842 | /// #[async_trait::async_trait] 843 | /// impl windmark::module::AsyncModule for Clicker { 844 | /// async fn on_attach(&mut self, _: &mut Router) { 845 | /// info!("clicker has been attached!"); 846 | /// } 847 | /// 848 | /// async fn on_pre_route(&mut self, context: HookContext) { 849 | /// self.clicks += 1; 850 | /// 851 | /// info!( 852 | /// "clicker has been called pre-route on {} with {} clicks!", 853 | /// context.url.path(), 854 | /// self.clicks 855 | /// ); 856 | /// } 857 | /// 858 | /// async fn on_post_route(&mut self, context: HookContext) { 859 | /// info!( 860 | /// "clicker has been called post-route on {} with {} clicks!", 861 | /// context.url.path(), 862 | /// self.clicks 863 | /// ); 864 | /// } 865 | /// } 866 | /// 867 | /// // Router::new().attach_async(Clicker::default()); 868 | /// ``` 869 | pub fn attach_async( 870 | &mut self, 871 | mut module: impl AsyncModule + 'static, 872 | ) -> &mut Self { 873 | block!({ 874 | module.on_attach(self).await; 875 | 876 | (*self.async_modules.lock().await).push(Box::new(module)); 877 | }); 878 | 879 | self 880 | } 881 | 882 | /// Attach a stateful module to a `Router`. 883 | /// 884 | /// Like a stateless module is an extension or middleware to a `Router`. 885 | /// Modules get full access to the `Router` and can be extended by a third 886 | /// party, but also, can create hooks will be executed through various parts 887 | /// of a routes' lifecycle. Stateful modules also have state, so variables can 888 | /// be stored for further access. 889 | /// 890 | /// # Panics 891 | /// 892 | /// May panic if the stateful module cannot be attached. 893 | /// 894 | /// # Examples 895 | /// 896 | /// ```rust 897 | /// use log::info; 898 | /// use windmark::{context::HookContext, response::Response, router::Router}; 899 | /// 900 | /// #[derive(Default)] 901 | /// struct Clicker { 902 | /// clicks: isize, 903 | /// } 904 | /// 905 | /// impl windmark::module::Module for Clicker { 906 | /// fn on_attach(&mut self, _: &mut Router) { 907 | /// info!("clicker has been attached!"); 908 | /// } 909 | /// 910 | /// fn on_pre_route(&mut self, context: HookContext) { 911 | /// self.clicks += 1; 912 | /// 913 | /// info!( 914 | /// "clicker has been called pre-route on {} with {} clicks!", 915 | /// context.url.path(), 916 | /// self.clicks 917 | /// ); 918 | /// } 919 | /// 920 | /// fn on_post_route(&mut self, context: HookContext) { 921 | /// info!( 922 | /// "clicker has been called post-route on {} with {} clicks!", 923 | /// context.url.path(), 924 | /// self.clicks 925 | /// ); 926 | /// } 927 | /// } 928 | /// 929 | /// Router::new().attach(Clicker::default()); 930 | /// ``` 931 | pub fn attach( 932 | &mut self, 933 | mut module: impl Module + 'static + Send, 934 | ) -> &mut Self { 935 | module.on_attach(self); 936 | 937 | (*self.modules.lock().unwrap()).push(Box::new(module)); 938 | 939 | self 940 | } 941 | 942 | /// Specify a custom character set. 943 | /// 944 | /// Will be over-ridden if a character set is specified in a [`Response`]. 945 | /// 946 | /// Defaults to `"utf-8"`. 947 | /// 948 | /// # Examples 949 | /// 950 | /// ```rust 951 | /// windmark::router::Router::new().set_character_set("utf-8"); 952 | /// ``` 953 | pub fn set_character_set( 954 | &mut self, 955 | character_set: impl Into + AsRef, 956 | ) -> &mut Self { 957 | self.character_set = character_set.into(); 958 | 959 | self 960 | } 961 | 962 | /// Specify a custom language. 963 | /// 964 | /// Will be over-ridden if a language is specified in a [`Response`]. 965 | /// 966 | /// Defaults to `"en"`. 967 | /// 968 | /// # Examples 969 | /// 970 | /// ```rust 971 | /// windmark::router::Router::new().set_languages(["en"]); 972 | /// ``` 973 | pub fn set_languages(&mut self, language: impl AsRef<[S]>) -> &mut Self 974 | where S: Into + AsRef { 975 | self.languages = language 976 | .as_ref() 977 | .iter() 978 | .map(|s| s.as_ref().to_string()) 979 | .collect::>(); 980 | 981 | self 982 | } 983 | 984 | /// Specify a custom port. 985 | /// 986 | /// Defaults to `1965`. 987 | /// 988 | /// # Examples 989 | /// 990 | /// ```rust 991 | /// windmark::router::Router::new().set_port(1965); 992 | /// ``` 993 | pub const fn set_port(&mut self, port: i32) -> &mut Self { 994 | self.port = port; 995 | 996 | self 997 | } 998 | 999 | /// Add optional features to the router 1000 | /// 1001 | /// # Examples 1002 | /// 1003 | /// ```rust 1004 | /// use windmark::router_option::RouterOption; 1005 | /// 1006 | /// windmark::router::Router::new() 1007 | /// .add_options(&[RouterOption::RemoveExtraTrailingSlash]); 1008 | /// ``` 1009 | pub fn add_options(&mut self, options: &[RouterOption]) -> &mut Self { 1010 | for option in options { 1011 | self.options.insert(*option); 1012 | } 1013 | 1014 | self 1015 | } 1016 | 1017 | /// Toggle optional features for the router 1018 | /// 1019 | /// # Examples 1020 | /// 1021 | /// ```rust 1022 | /// use windmark::router_option::RouterOption; 1023 | /// 1024 | /// windmark::router::Router::new() 1025 | /// .toggle_options(&[RouterOption::RemoveExtraTrailingSlash]); 1026 | /// ``` 1027 | pub fn toggle_options(&mut self, options: &[RouterOption]) -> &mut Self { 1028 | for option in options { 1029 | if self.options.contains(option) { 1030 | self.options.remove(option); 1031 | } else { 1032 | self.options.insert(*option); 1033 | } 1034 | } 1035 | 1036 | self 1037 | } 1038 | 1039 | /// Remove optional features from the router 1040 | /// 1041 | /// # Examples 1042 | /// 1043 | /// ```rust 1044 | /// use windmark::router_option::RouterOption; 1045 | /// 1046 | /// windmark::router::Router::new() 1047 | /// .remove_options(&[RouterOption::RemoveExtraTrailingSlash]); 1048 | /// ``` 1049 | pub fn remove_options(&mut self, options: &[RouterOption]) -> &mut Self { 1050 | for option in options { 1051 | self.options.remove(option); 1052 | } 1053 | 1054 | self 1055 | } 1056 | 1057 | /// Specify a custom listener address. 1058 | /// 1059 | /// Defaults to `"0.0.0.0"`. 1060 | /// 1061 | /// # Examples 1062 | /// 1063 | /// ```rust 1064 | /// windmark::router::Router::new().set_listener_address("[::]"); 1065 | /// ``` 1066 | pub fn set_listener_address( 1067 | &mut self, 1068 | address: impl Into + AsRef, 1069 | ) -> &mut Self { 1070 | self.listener_address = address.into(); 1071 | 1072 | self 1073 | } 1074 | } 1075 | 1076 | impl Default for Router { 1077 | fn default() -> Self { 1078 | Self { 1079 | routes: matchit::Router::new(), 1080 | error_handler: Arc::new(AsyncMutex::new(Box::new(|_| { 1081 | async { 1082 | Response::not_found( 1083 | "This capsule has not implemented an error handler...", 1084 | ) 1085 | } 1086 | }))), 1087 | private_key_file_name: String::new(), 1088 | certificate_file_name: String::new(), 1089 | headers: Arc::new(Mutex::new(vec![])), 1090 | footers: Arc::new(Mutex::new(vec![])), 1091 | ssl_acceptor: Arc::new( 1092 | SslAcceptor::mozilla_intermediate(SslMethod::tls()) 1093 | .unwrap() 1094 | .build(), 1095 | ), 1096 | #[cfg(feature = "logger")] 1097 | default_logger: false, 1098 | pre_route_callback: Arc::new(Mutex::new(Box::new(|_| {}))), 1099 | post_route_callback: Arc::new(Mutex::new(Box::new( 1100 | |_, _: &'_ mut Response| {}, 1101 | ))), 1102 | character_set: "utf-8".to_string(), 1103 | languages: vec!["en".to_string()], 1104 | port: 1965, 1105 | modules: Arc::new(Mutex::new(vec![])), 1106 | async_modules: Arc::new(AsyncMutex::new(vec![])), 1107 | options: HashSet::new(), 1108 | private_key_content: None, 1109 | certificate_content: None, 1110 | listener_address: "0.0.0.0".to_string(), 1111 | } 1112 | } 1113 | } 1114 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------