From 1a496f4fda3231c9482e9ca061bfa7b264ee4b66 Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Sun, 19 Aug 2018 10:47:04 -0700 Subject: [PATCH] initial import --- .appveyor.yml | 40 +++ .gitignore | 14 ++ .travis.yml | 54 ++++ CODE_OF_CONDUCT.md | 46 ++++ Cargo.toml | 83 +++++++ LICENSE-APACHE | 201 +++++++++++++++ LICENSE-MIT | 25 ++ examples/cert.pem | 31 +++ examples/key.pem | 51 ++++ examples/ssl.rs | 56 +++++ rustfmt.toml | 5 + src/accept.rs | 468 +++++++++++++++++++++++++++++++++++ src/extensions.rs | 115 +++++++++ src/lib.rs | 162 ++++++++++++ src/server.rs | 556 ++++++++++++++++++++++++++++++++++++++++++ src/server_service.rs | 106 ++++++++ src/service.rs | 521 +++++++++++++++++++++++++++++++++++++++ src/ssl/mod.rs | 15 ++ src/ssl/openssl.rs | 125 ++++++++++ src/worker.rs | 152 ++++++++++++ 20 files changed, 2826 insertions(+) create mode 100644 .appveyor.yml create mode 100644 .gitignore create mode 100644 .travis.yml create mode 100644 CODE_OF_CONDUCT.md create mode 100644 Cargo.toml create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT create mode 100644 examples/cert.pem create mode 100644 examples/key.pem create mode 100644 examples/ssl.rs create mode 100644 rustfmt.toml create mode 100644 src/accept.rs create mode 100644 src/extensions.rs create mode 100644 src/lib.rs create mode 100644 src/server.rs create mode 100644 src/server_service.rs create mode 100644 src/service.rs create mode 100644 src/ssl/mod.rs create mode 100644 src/ssl/openssl.rs create mode 100644 src/worker.rs diff --git a/.appveyor.yml b/.appveyor.yml new file mode 100644 index 00000000..7addc8c0 --- /dev/null +++ b/.appveyor.yml @@ -0,0 +1,40 @@ +environment: + global: + PROJECT_NAME: actix + matrix: + # Stable channel + - TARGET: i686-pc-windows-msvc + CHANNEL: stable + - TARGET: x86_64-pc-windows-gnu + CHANNEL: stable + - TARGET: x86_64-pc-windows-msvc + CHANNEL: stable + # Nightly channel + - TARGET: i686-pc-windows-msvc + CHANNEL: nightly + - TARGET: x86_64-pc-windows-gnu + CHANNEL: nightly + - TARGET: x86_64-pc-windows-msvc + CHANNEL: nightly + +# Install Rust and Cargo +# (Based on from https://github.com/rust-lang/libc/blob/master/appveyor.yml) +install: + - ps: >- + If ($Env:TARGET -eq 'x86_64-pc-windows-gnu') { + $Env:PATH += ';C:\msys64\mingw64\bin' + } ElseIf ($Env:TARGET -eq 'i686-pc-windows-gnu') { + $Env:PATH += ';C:\MinGW\bin' + } + - curl -sSf -o rustup-init.exe https://win.rustup.rs + - rustup-init.exe --default-host %TARGET% --default-toolchain %CHANNEL% -y + - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin + - rustc -Vv + - cargo -V + +# 'cargo test' takes care of building for us, so disable Appveyor's build stage. +build: false + +# Equivalent to Travis' `script` phase +test_script: + - cargo test --no-default-features --features="flate2-rust" diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..42d0755d --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +Cargo.lock +target/ +guide/build/ +/gh-pages + +*.so +*.out +*.pyc +*.pid +*.sock +*~ + +# These are backup files generated by rustfmt +**/*.rs.bk diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..f03c9523 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,54 @@ +language: rust +sudo: required +dist: trusty + +cache: + cargo: true + apt: true + +matrix: + include: + - rust: stable + - rust: beta + - rust: nightly + allow_failures: + - rust: nightly + +env: + global: + # - RUSTFLAGS="-C link-dead-code" + - OPENSSL_VERSION=openssl-1.0.2 + +before_install: + - sudo add-apt-repository -y ppa:0k53d-karl-f830m/openssl + - sudo apt-get update -qq + - sudo apt-get install -y openssl libssl-dev libelf-dev libdw-dev cmake gcc binutils-dev libiberty-dev + +# Add clippy +before_script: + - export PATH=$PATH:~/.cargo/bin + +script: + - | + if [[ "$TRAVIS_RUST_VERSION" != "stable" ]]; then + cargo clean + cargo test --features="alpn,tls,rust-tls" -- --nocapture + fi + - | + if [[ "$TRAVIS_RUST_VERSION" == "stable" ]]; then + RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install -f cargo-tarpaulin + cargo tarpaulin --features="alpn,tls,rust-tls" --out Xml --no-count + bash <(curl -s https://codecov.io/bash) + echo "Uploaded code coverage" + fi + +# Upload docs +after_success: + - | + if [[ "$TRAVIS_OS_NAME" == "linux" && "$TRAVIS_PULL_REQUEST" = "false" && "$TRAVIS_BRANCH" == "master" && "$TRAVIS_RUST_VERSION" == "beta" ]]; then + cargo doc --features "alpn, tls, rust-tls, session" --no-deps && + echo "" > target/doc/index.html && + git clone https://github.com/davisp/ghp-import.git && + ./ghp-import/ghp_import.py -n -p -f -m "Documentation upload" -r https://"$GH_TOKEN"@github.com/"$TRAVIS_REPO_SLUG.git" target/doc && + echo "Uploaded documentation" + fi diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..599b28c0 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,46 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at fafhrd91@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 00000000..5075711f --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,83 @@ +[package] +name = "actix-net" +version = "0.1.0" +authors = ["Nikolay Kim "] +description = "Actix net utils" +readme = "README.md" +keywords = ["http", "framework", "async", "futures"] +homepage = "https://actix.rs" +repository = "https://github.com/actix/actix-net.git" +documentation = "https://actix.rs/api/actix-net/stable/actix_web/" +categories = ["network-programming", "asynchronous", + "web-programming::http-server", + "web-programming::http-client", + "web-programming::websocket"] +license = "MIT/Apache-2.0" +exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"] + +[package.metadata.docs.rs] +features = ["ssl", "tls", "rust-tls"] + +[badges] +travis-ci = { repository = "actix/actix-net", branch = "master" } +appveyor = { repository = "fafhrd91/actix-web-hdy9d" } +codecov = { repository = "actix/actix-net", branch = "master", service = "github" } + +[lib] +name = "actix_net" +path = "src/lib.rs" + +[features] +default = [] + +# tls +tls = ["native-tls"] + +# openssl +ssl = ["openssl", "tokio-openssl"] + +# rustls +rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"] + +[dependencies] +actix = "0.7.0" + +log = "0.4" +num_cpus = "1.0" +rand = "0.5" +time = "0.1" +parking_lot = "0.6" +failure = "^0.1.2" + +# io +mio = "^0.6.13" +net2 = "0.2" +bytes = "0.4" +byteorder = "1.2" +futures = "0.1" +slab = "0.4" +tokio = "0.1" +tokio-io = "0.1" +tokio-tcp = "0.1" +tokio-timer = "0.2" +tokio-reactor = "0.1" + +tower-service = "0.1" + +# native-tls +native-tls = { version="0.2", optional = true } + +# openssl +openssl = { version="0.10", optional = true } +tokio-openssl = { version="0.2", optional = true } + +#rustls +rustls = { version = "^0.13.1", optional = true } +tokio-rustls = { version = "^0.7.2", optional = true } +webpki = { version = "0.18", optional = true } +webpki-roots = { version = "0.15", optional = true } + +[profile.release] +lto = true +opt-level = 3 +codegen-units = 1 diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 00000000..6cdf2d16 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017-NOW Nikolay Kim + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 00000000..0f80296a --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2017 Nikolay Kim + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/examples/cert.pem b/examples/cert.pem new file mode 100644 index 00000000..159aacea --- /dev/null +++ b/examples/cert.pem @@ -0,0 +1,31 @@ +-----BEGIN CERTIFICATE----- +MIIFPjCCAyYCCQDvLYiYD+jqeTANBgkqhkiG9w0BAQsFADBhMQswCQYDVQQGEwJV +UzELMAkGA1UECAwCQ0ExCzAJBgNVBAcMAlNGMRAwDgYDVQQKDAdDb21wYW55MQww +CgYDVQQLDANPcmcxGDAWBgNVBAMMD3d3dy5leGFtcGxlLmNvbTAeFw0xODAxMjUx +NzQ2MDFaFw0xOTAxMjUxNzQ2MDFaMGExCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJD +QTELMAkGA1UEBwwCU0YxEDAOBgNVBAoMB0NvbXBhbnkxDDAKBgNVBAsMA09yZzEY +MBYGA1UEAwwPd3d3LmV4YW1wbGUuY29tMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A +MIICCgKCAgEA2WzIA2IpVR9Tb9EFhITlxuhE5rY2a3S6qzYNzQVgSFggxXEPn8k1 +sQEcer5BfAP986Sck3H0FvB4Bt/I8PwOtUCmhwcc8KtB5TcGPR4fjXnrpC+MIK5U +NLkwuyBDKziYzTdBj8kUFX1WxmvEHEgqToPOZfBgsS71cJAR/zOWraDLSRM54jXy +voLZN4Ti9rQagQrvTQ44Vz5ycDQy7UxtbUGh1CVv69vNVr7/SOOh/Nw5FNOZWLWr +odGyoec5wh9iqRZgRqiTUc6Lt7V2RWc2X2gjwST2UfI+U46Ip3oaQ7ZD4eAkoqND +xdniBZAykVG3c/99ux4BAESTF8fsNch6UticBxYMuTu+ouvP0psfI9wwwNliJDmA +CRUTB9AgRynbL1AzhqQoDfsb98IZfjfNOpwnwuLwpMAPhbgd5KNdZaIJ4Hb6/stI +yFElOExxd3TAxF2Gshd/lq1JcNHAZ1DSXV5MvOWT/NWgXwbIzUgQ8eIi+HuDYX2U +UuaB6R8tbd52H7rbUv6HrfinuSlKWqjSYLkiKHkwUpoMw8y9UycRSzs1E9nPwPTO +vRXb0mNCQeBCV9FvStNVXdCUTT8LGPv87xSD2pmt7LijlE6mHLG8McfcWkzA69un +CEHIFAFDimTuN7EBljc119xWFTcHMyoZAfFF+oTqwSbBGImruCxnaJECAwEAATAN +BgkqhkiG9w0BAQsFAAOCAgEApavsgsn7SpPHfhDSN5iZs1ILZQRewJg0Bty0xPfk +3tynSW6bNH3nSaKbpsdmxxomthNSQgD2heOq1By9YzeOoNR+7Pk3s4FkASnf3ToI +JNTUasBFFfaCG96s4Yvs8KiWS/k84yaWuU8c3Wb1jXs5Rv1qE1Uvuwat1DSGXSoD +JNluuIkCsC4kWkyq5pWCGQrabWPRTWsHwC3PTcwSRBaFgYLJaR72SloHB1ot02zL +d2age9dmFRFLLCBzP+D7RojBvL37qS/HR+rQ4SoQwiVc/JzaeqSe7ZbvEH9sZYEu +ALowJzgbwro7oZflwTWunSeSGDSltkqKjvWvZI61pwfHKDahUTmZ5h2y67FuGEaC +CIOUI8dSVSPKITxaq3JL4ze2e9/0Lt7hj19YK2uUmtMAW5Tirz4Yx5lyGH9U8Wur +y/X8VPxTc4A9TMlJgkyz0hqvhbPOT/zSWB10zXh0glKAsSBryAOEDxV1UygmSir7 +YV8Qaq+oyKUTMc1MFq5vZ07M51EPaietn85t8V2Y+k/8XYltRp32NxsypxAJuyxh +g/ko6RVTrWa1sMvz/F9LFqAdKiK5eM96lh9IU4xiLg4ob8aS/GRAA8oIFkZFhLrt +tOwjIUPmEPyHWFi8dLpNuQKYalLYhuwZftG/9xV+wqhKGZO9iPrpHSYBRTap8w2y +1QU= +-----END CERTIFICATE----- diff --git a/examples/key.pem b/examples/key.pem new file mode 100644 index 00000000..aac387c6 --- /dev/null +++ b/examples/key.pem @@ -0,0 +1,51 @@ +-----BEGIN RSA PRIVATE KEY----- +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 +-----END RSA PRIVATE KEY----- diff --git a/examples/ssl.rs b/examples/ssl.rs new file mode 100644 index 00000000..5feb37c3 --- /dev/null +++ b/examples/ssl.rs @@ -0,0 +1,56 @@ +extern crate actix; +extern crate actix_net; +extern crate futures; +extern crate openssl; +extern crate tokio_io; +extern crate tokio_tcp; + +use std::io; +use std::sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, +}; + +use futures::{future, Future}; +use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod}; +use tokio_io::{AsyncRead, AsyncWrite}; + +use actix_net::service::NewServiceExt; +use actix_net::{ssl, Server}; + +#[derive(Debug)] +struct ServiceState { + num: Arc, +} + +fn service( + st: &mut ServiceState, stream: T, +) -> impl Future { + let num = st.num.fetch_add(1, Ordering::Relaxed); + println!("got ssl connection {:?}", num); + future::ok(()) +} + +fn main() { + let sys = actix::System::new("test"); + + // load ssl keys + let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); + builder + .set_private_key_file("./examples/key.pem", SslFiletype::PEM) + .unwrap(); + builder + .set_certificate_chain_file("./examples/cert.pem") + .unwrap(); + + let num = Arc::new(AtomicUsize::new(0)); + + // configure service + let srv = ssl::OpensslService::new(builder).and_then((service, move || { + Ok::<_, io::Error>(ServiceState { num: num.clone() }) + })); + + Server::new().bind("0.0.0.0:8443", srv).unwrap().start(); + + sys.run(); +} diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 00000000..63cb0114 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,5 @@ +max_width = 96 +reorder_imports = true +wrap_comments = true +fn_args_density = "Compressed" +#use_small_heuristics = false diff --git a/src/accept.rs b/src/accept.rs new file mode 100644 index 00000000..681e988c --- /dev/null +++ b/src/accept.rs @@ -0,0 +1,468 @@ +use std::sync::mpsc as sync_mpsc; +use std::time::{Duration, Instant}; +use std::{io, net, thread}; + +use futures::{sync::mpsc, Future}; +use mio; +use slab::Slab; +use tokio_timer::Delay; + +use actix::{msgs::Execute, Arbiter, System}; + +use super::server::ServerCommand; +use super::worker::{Conn, WorkerClient}; +use super::Token; + +pub(crate) enum Command { + Pause, + Resume, + Stop, + Worker(WorkerClient), +} + +struct ServerSocketInfo { + addr: net::SocketAddr, + token: Token, + handler: Token, + sock: mio::net::TcpListener, + timeout: Option, +} + +#[derive(Clone)] +pub(crate) struct AcceptNotify(mio::SetReadiness); + +impl AcceptNotify { + pub(crate) fn new(ready: mio::SetReadiness) -> Self { + AcceptNotify(ready) + } + + pub(crate) fn notify(&self) { + let _ = self.0.set_readiness(mio::Ready::readable()); + } +} + +impl Default for AcceptNotify { + fn default() -> Self { + AcceptNotify::new(mio::Registration::new2().1) + } +} + +pub(crate) struct AcceptLoop { + cmd_reg: Option, + cmd_ready: mio::SetReadiness, + notify_reg: Option, + notify_ready: mio::SetReadiness, + tx: sync_mpsc::Sender, + rx: Option>, + srv: Option<( + mpsc::UnboundedSender, + mpsc::UnboundedReceiver, + )>, +} + +impl AcceptLoop { + pub fn new() -> AcceptLoop { + let (tx, rx) = sync_mpsc::channel(); + let (cmd_reg, cmd_ready) = mio::Registration::new2(); + let (notify_reg, notify_ready) = mio::Registration::new2(); + + AcceptLoop { + tx, + cmd_ready, + cmd_reg: Some(cmd_reg), + notify_ready, + notify_reg: Some(notify_reg), + rx: Some(rx), + srv: Some(mpsc::unbounded()), + } + } + + pub fn send(&self, msg: Command) { + let _ = self.tx.send(msg); + let _ = self.cmd_ready.set_readiness(mio::Ready::readable()); + } + + pub fn get_notify(&self) -> AcceptNotify { + AcceptNotify::new(self.notify_ready.clone()) + } + + pub(crate) fn start( + &mut self, socks: Vec<(Token, net::TcpListener)>, workers: Vec, + ) -> mpsc::UnboundedReceiver { + let (tx, rx) = self.srv.take().expect("Can not re-use AcceptInfo"); + + Accept::start( + self.rx.take().expect("Can not re-use AcceptInfo"), + self.cmd_reg.take().expect("Can not re-use AcceptInfo"), + self.notify_reg.take().expect("Can not re-use AcceptInfo"), + socks, + tx, + workers, + ); + rx + } +} + +struct Accept { + poll: mio::Poll, + rx: sync_mpsc::Receiver, + sockets: Slab, + workers: Vec, + srv: mpsc::UnboundedSender, + timer: (mio::Registration, mio::SetReadiness), + next: usize, + backpressure: bool, +} + +const DELTA: usize = 100; +const CMD: mio::Token = mio::Token(0); +const TIMER: mio::Token = mio::Token(1); +const NOTIFY: mio::Token = mio::Token(2); + +/// This function defines errors that are per-connection. Which basically +/// means that if we get this error from `accept()` system call it means +/// next connection might be ready to be accepted. +/// +/// All other errors will incur a timeout before next `accept()` is performed. +/// The timeout is useful to handle resource exhaustion errors like ENFILE +/// and EMFILE. Otherwise, could enter into tight loop. +fn connection_error(e: &io::Error) -> bool { + e.kind() == io::ErrorKind::ConnectionRefused + || e.kind() == io::ErrorKind::ConnectionAborted + || e.kind() == io::ErrorKind::ConnectionReset +} + +impl Accept { + #![cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))] + pub(crate) fn start( + rx: sync_mpsc::Receiver, cmd_reg: mio::Registration, + notify_reg: mio::Registration, socks: Vec<(Token, net::TcpListener)>, + srv: mpsc::UnboundedSender, workers: Vec, + ) { + let sys = System::current(); + + // start accept thread + let _ = thread::Builder::new() + .name("actix-web accept loop".to_owned()) + .spawn(move || { + System::set_current(sys); + let mut accept = Accept::new(rx, socks, workers, srv); + + // Start listening for incoming commands + if let Err(err) = accept.poll.register( + &cmd_reg, + CMD, + mio::Ready::readable(), + mio::PollOpt::edge(), + ) { + panic!("Can not register Registration: {}", err); + } + + // Start listening for notify updates + if let Err(err) = accept.poll.register( + ¬ify_reg, + NOTIFY, + mio::Ready::readable(), + mio::PollOpt::edge(), + ) { + panic!("Can not register Registration: {}", err); + } + + accept.poll(); + }); + } + + fn new( + rx: sync_mpsc::Receiver, socks: Vec<(Token, net::TcpListener)>, + workers: Vec, srv: mpsc::UnboundedSender, + ) -> Accept { + // Create a poll instance + let poll = match mio::Poll::new() { + Ok(poll) => poll, + Err(err) => panic!("Can not create mio::Poll: {}", err), + }; + + // Start accept + let mut sockets = Slab::new(); + for (idx, (hnd_token, lst)) in socks.into_iter().enumerate() { + let addr = lst.local_addr().unwrap(); + let server = mio::net::TcpListener::from_std(lst) + .expect("Can not create mio::net::TcpListener"); + + let entry = sockets.vacant_entry(); + let token = entry.key(); + + // Start listening for incoming connections + if let Err(err) = poll.register( + &server, + mio::Token(token + DELTA), + mio::Ready::readable(), + mio::PollOpt::edge(), + ) { + panic!("Can not register io: {}", err); + } + + entry.insert(ServerSocketInfo { + addr, + token: hnd_token, + handler: Token(idx), + sock: server, + timeout: None, + }); + } + + // Timer + let (tm, tmr) = mio::Registration::new2(); + if let Err(err) = + poll.register(&tm, TIMER, mio::Ready::readable(), mio::PollOpt::edge()) + { + panic!("Can not register Registration: {}", err); + } + + Accept { + poll, + rx, + sockets, + workers, + srv, + next: 0, + timer: (tm, tmr), + backpressure: false, + } + } + + fn poll(&mut self) { + // Create storage for events + let mut events = mio::Events::with_capacity(128); + + loop { + if let Err(err) = self.poll.poll(&mut events, None) { + panic!("Poll error: {}", err); + } + + for event in events.iter() { + let token = event.token(); + match token { + CMD => if !self.process_cmd() { + return; + }, + TIMER => self.process_timer(), + NOTIFY => self.backpressure(false), + _ => { + let token = usize::from(token); + if token < DELTA { + continue; + } + self.accept(token - DELTA); + } + } + } + } + } + + fn process_timer(&mut self) { + let now = Instant::now(); + for (token, info) in self.sockets.iter_mut() { + if let Some(inst) = info.timeout.take() { + if now > inst { + if let Err(err) = self.poll.register( + &info.sock, + mio::Token(token + DELTA), + mio::Ready::readable(), + mio::PollOpt::edge(), + ) { + error!("Can not register server socket {}", err); + } else { + info!("Resume accepting connections on {}", info.addr); + } + } else { + info.timeout = Some(inst); + } + } + } + } + + fn process_cmd(&mut self) -> bool { + loop { + match self.rx.try_recv() { + Ok(cmd) => match cmd { + Command::Pause => { + for (_, info) in self.sockets.iter_mut() { + if let Err(err) = self.poll.deregister(&info.sock) { + error!("Can not deregister server socket {}", err); + } else { + info!("Paused accepting connections on {}", info.addr); + } + } + } + Command::Resume => { + for (token, info) in self.sockets.iter() { + if let Err(err) = self.poll.register( + &info.sock, + mio::Token(token + DELTA), + mio::Ready::readable(), + mio::PollOpt::edge(), + ) { + error!("Can not resume socket accept process: {}", err); + } else { + info!( + "Accepting connections on {} has been resumed", + info.addr + ); + } + } + } + Command::Stop => { + for (_, info) in self.sockets.iter() { + let _ = self.poll.deregister(&info.sock); + } + return false; + } + Command::Worker(worker) => { + self.backpressure(false); + self.workers.push(worker); + } + }, + Err(err) => match err { + sync_mpsc::TryRecvError::Empty => break, + sync_mpsc::TryRecvError::Disconnected => { + for (_, info) in self.sockets.iter() { + let _ = self.poll.deregister(&info.sock); + } + return false; + } + }, + } + } + true + } + + fn backpressure(&mut self, on: bool) { + if self.backpressure { + if !on { + self.backpressure = false; + for (token, info) in self.sockets.iter() { + if let Err(err) = self.poll.register( + &info.sock, + mio::Token(token + DELTA), + mio::Ready::readable(), + mio::PollOpt::edge(), + ) { + error!("Can not resume socket accept process: {}", err); + } else { + info!("Accepting connections on {} has been resumed", info.addr); + } + } + } + } else if on { + self.backpressure = true; + for (_, info) in self.sockets.iter() { + let _ = self.poll.deregister(&info.sock); + } + } + } + + fn accept_one(&mut self, mut msg: Conn) { + if self.backpressure { + while !self.workers.is_empty() { + match self.workers[self.next].send(msg) { + Ok(_) => (), + Err(err) => { + let _ = self.srv.unbounded_send(ServerCommand::WorkerDied( + self.workers[self.next].idx, + )); + msg = err.into_inner(); + self.workers.swap_remove(self.next); + if self.workers.is_empty() { + error!("No workers"); + return; + } else if self.workers.len() <= self.next { + self.next = 0; + } + continue; + } + } + self.next = (self.next + 1) % self.workers.len(); + break; + } + } else { + let mut idx = 0; + while idx < self.workers.len() { + idx += 1; + if self.workers[self.next].available() { + match self.workers[self.next].send(msg) { + Ok(_) => { + self.next = (self.next + 1) % self.workers.len(); + return; + } + Err(err) => { + let _ = self.srv.unbounded_send(ServerCommand::WorkerDied( + self.workers[self.next].idx, + )); + msg = err.into_inner(); + self.workers.swap_remove(self.next); + if self.workers.is_empty() { + error!("No workers"); + self.backpressure(true); + return; + } else if self.workers.len() <= self.next { + self.next = 0; + } + continue; + } + } + } + self.next = (self.next + 1) % self.workers.len(); + } + // enable backpressure + self.backpressure(true); + self.accept_one(msg); + } + } + + fn accept(&mut self, token: usize) { + loop { + let msg = if let Some(info) = self.sockets.get_mut(token) { + match info.sock.accept_std() { + Ok((io, addr)) => Conn { + io, + token: info.token, + handler: info.handler, + peer: Some(addr), + }, + Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => return, + Err(ref e) if connection_error(e) => continue, + Err(e) => { + error!("Error accepting connection: {}", e); + if let Err(err) = self.poll.deregister(&info.sock) { + error!("Can not deregister server socket {}", err); + } + + // sleep after error + info.timeout = Some(Instant::now() + Duration::from_millis(500)); + + let r = self.timer.1.clone(); + System::current().arbiter().do_send(Execute::new( + move || -> Result<(), ()> { + Arbiter::spawn( + Delay::new(Instant::now() + Duration::from_millis(510)) + .map_err(|_| ()) + .and_then(move |_| { + let _ = r.set_readiness(mio::Ready::readable()); + Ok(()) + }), + ); + Ok(()) + }, + )); + return; + } + } + } else { + return; + }; + + self.accept_one(msg); + } + } +} diff --git a/src/extensions.rs b/src/extensions.rs new file mode 100644 index 00000000..35cd69db --- /dev/null +++ b/src/extensions.rs @@ -0,0 +1,115 @@ +use std::any::{Any, TypeId}; +use std::collections::HashMap; +use std::fmt; +use std::hash::{BuildHasherDefault, Hasher}; + +struct IdHasher { + id: u64, +} + +impl Default for IdHasher { + fn default() -> IdHasher { + IdHasher { id: 0 } + } +} + +impl Hasher for IdHasher { + fn write(&mut self, bytes: &[u8]) { + for &x in bytes { + self.id.wrapping_add(u64::from(x)); + } + } + + fn write_u64(&mut self, u: u64) { + self.id = u; + } + + fn finish(&self) -> u64 { + self.id + } +} + +type AnyMap = HashMap, BuildHasherDefault>; + +/// A type map of request extensions. +#[derive(Default)] +pub struct Extensions { + map: AnyMap, +} + +impl Extensions { + /// Create an empty `Extensions`. + #[inline] + pub fn new() -> Extensions { + Extensions { + map: HashMap::default(), + } + } + + /// Insert a type into this `Extensions`. + /// + /// If a extension of this type already existed, it will + /// be returned. + pub fn insert(&mut self, val: T) { + self.map.insert(TypeId::of::(), Box::new(val)); + } + + /// Get a reference to a type previously inserted on this `Extensions`. + pub fn get(&self) -> Option<&T> { + self.map + .get(&TypeId::of::()) + .and_then(|boxed| (&**boxed as &(Any + 'static)).downcast_ref()) + } + + /// Get a mutable reference to a type previously inserted on this + /// `Extensions`. + pub fn get_mut(&mut self) -> Option<&mut T> { + self.map + .get_mut(&TypeId::of::()) + .and_then(|boxed| (&mut **boxed as &mut (Any + 'static)).downcast_mut()) + } + + /// Remove a type from this `Extensions`. + /// + /// If a extension of this type existed, it will be returned. + pub fn remove(&mut self) -> Option { + self.map.remove(&TypeId::of::()).and_then(|boxed| { + (boxed as Box) + .downcast() + .ok() + .map(|boxed| *boxed) + }) + } + + /// Clear the `Extensions` of all inserted extensions. + #[inline] + pub fn clear(&mut self) { + self.map.clear(); + } +} + +impl fmt::Debug for Extensions { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Extensions").finish() + } +} + +#[test] +fn test_extensions() { + #[derive(Debug, PartialEq)] + struct MyType(i32); + + let mut extensions = Extensions::new(); + + extensions.insert(5i32); + extensions.insert(MyType(10)); + + assert_eq!(extensions.get(), Some(&5i32)); + assert_eq!(extensions.get_mut(), Some(&mut 5i32)); + + assert_eq!(extensions.remove::(), Some(5i32)); + assert!(extensions.get::().is_none()); + + assert_eq!(extensions.get::(), None); + assert_eq!(extensions.get(), Some(&MyType(10))); +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 00000000..b59065b3 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,162 @@ +//! Actix web is a small, pragmatic, and extremely fast web framework +//! for Rust. +//! +//! ## Package feature +//! +//! * `tls` - enables ssl support via `native-tls` crate +//! * `alpn` - enables ssl support via `openssl` crate, require for `http/2` +//! support +//! * `rust-tls` - enables ssl support via `rustls` crate +//! + +// #![warn(missing_docs)] +// #![allow( +// dead_code, +// unused_variables, +// unused_imports, +// patterns_in_fns_without_body +// )] + +#[macro_use] +extern crate log; +extern crate byteorder; +extern crate bytes; +extern crate failure; +extern crate futures; +extern crate mio; +extern crate net2; +extern crate num_cpus; +extern crate parking_lot; +extern crate slab; +extern crate time; +extern crate tokio; +extern crate tokio_io; +extern crate tokio_reactor; +extern crate tokio_tcp; +extern crate tokio_timer; +extern crate tower_service; + +#[macro_use] +extern crate actix; + +#[cfg(feature = "tls")] +extern crate native_tls; + +#[cfg(feature = "ssl")] +extern crate openssl; +#[cfg(feature = "ssl")] +extern crate tokio_openssl; + +#[cfg(feature = "rust-tls")] +extern crate rustls; +#[cfg(feature = "rust-tls")] +extern crate tokio_rustls; +#[cfg(feature = "rust-tls")] +extern crate webpki; +#[cfg(feature = "rust-tls")] +extern crate webpki_roots; + +use std::io; +use std::net::Shutdown; +use std::rc::Rc; + +use actix::Message; +use bytes::{BufMut, BytesMut}; +use futures::{Async, Poll}; +use tokio_io::{AsyncRead, AsyncWrite}; + +pub(crate) mod accept; +mod extensions; +mod server; +mod server_service; +pub mod service; +pub mod ssl; +mod worker; + +pub use self::server::{ConnectionRateTag, ConnectionTag, Connections, Server}; +pub use service::{IntoNewService, IntoService}; + +pub use extensions::Extensions; + +/// Pause accepting incoming connections +/// +/// If socket contains some pending connection, they might be dropped. +/// All opened connection remains active. +#[derive(Message)] +pub struct PauseServer; + +/// Resume accepting incoming connections +#[derive(Message)] +pub struct ResumeServer; + +/// Stop incoming connection processing, stop all workers and exit. +/// +/// If server starts with `spawn()` method, then spawned thread get terminated. +pub struct StopServer { + /// Whether to try and shut down gracefully + pub graceful: bool, +} + +impl Message for StopServer { + type Result = Result<(), ()>; +} + +/// Socket id token +#[derive(Clone, Copy)] +pub struct Token(usize); + +// impl Token { +// pub(crate) fn new(val: usize) -> Token { +// Token(val) +// } +// } + +const LW_BUFFER_SIZE: usize = 4096; +const HW_BUFFER_SIZE: usize = 32_768; + +#[doc(hidden)] +/// Low-level io stream operations +pub trait IoStream: AsyncRead + AsyncWrite + 'static { + fn shutdown(&mut self, how: Shutdown) -> io::Result<()>; + + fn set_nodelay(&mut self, nodelay: bool) -> io::Result<()>; + + fn set_linger(&mut self, dur: Option) -> io::Result<()>; + + fn read_available(&mut self, buf: &mut BytesMut) -> Poll { + let mut read_some = false; + loop { + if buf.remaining_mut() < LW_BUFFER_SIZE { + buf.reserve(HW_BUFFER_SIZE); + } + unsafe { + match self.read(buf.bytes_mut()) { + Ok(n) => { + if n == 0 { + return Ok(Async::Ready(!read_some)); + } else { + read_some = true; + buf.advance_mut(n); + } + } + Err(e) => { + return if e.kind() == io::ErrorKind::WouldBlock { + if read_some { + Ok(Async::Ready(false)) + } else { + Ok(Async::NotReady) + } + } else { + Err(e) + }; + } + } + } + } + } + + /// Extra io stream extensions + fn extensions(&self) -> Option> { + None + } +} diff --git a/src/server.rs b/src/server.rs new file mode 100644 index 00000000..e92ac017 --- /dev/null +++ b/src/server.rs @@ -0,0 +1,556 @@ +use std::sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, +}; +use std::time::Duration; +use std::{fmt, io, mem, net}; + +use futures::sync::{mpsc, mpsc::unbounded}; +use futures::{Future, Sink, Stream}; +use net2::TcpBuilder; +use num_cpus; +use tokio_tcp::TcpStream; +use tower_service::NewService; + +use actix::{ + actors::signal, fut, Actor, ActorFuture, Addr, Arbiter, AsyncContext, Context, Handler, + Response, StreamHandler, System, WrapFuture, +}; + +use super::accept::{AcceptLoop, AcceptNotify, Command}; +use super::server_service::{ServerNewService, ServerServiceFactory}; +use super::service::IntoNewService; +use super::worker::{Conn, StopWorker, Worker, WorkerClient}; +use super::{PauseServer, ResumeServer, StopServer, Token}; + +pub(crate) enum ServerCommand { + WorkerDied(usize), +} + +/// Server +pub struct Server { + threads: usize, + workers: Vec<(usize, Addr)>, + services: Vec>, + sockets: Vec<(Token, net::TcpListener)>, + accept: AcceptLoop, + exit: bool, + shutdown_timeout: u16, + signals: Option>, + no_signals: bool, + maxconn: usize, + maxconnrate: usize, +} + +impl Default for Server { + fn default() -> Self { + Self::new() + } +} + +impl Server { + /// Create new Server instance + pub fn new() -> Server { + Server { + threads: num_cpus::get(), + workers: Vec::new(), + services: Vec::new(), + sockets: Vec::new(), + accept: AcceptLoop::new(), + exit: false, + shutdown_timeout: 30, + signals: None, + no_signals: false, + maxconn: 102_400, + maxconnrate: 256, + } + } + + /// Set number of workers to start. + /// + /// By default http server uses number of available logical cpu as threads + /// count. + pub fn workers(mut self, num: usize) -> Self { + self.threads = num; + self + } + + /// Sets the maximum per-worker number of concurrent connections. + /// + /// All socket listeners will stop accepting connections when this limit is + /// reached for each worker. + /// + /// By default max connections is set to a 100k. + pub fn maxconn(mut self, num: usize) -> Self { + self.maxconn = num; + self + } + + /// Sets the maximum per-worker concurrent connection establish process. + /// + /// All listeners will stop accepting connections when this limit is + /// reached. It can be used to limit the global SSL CPU usage. + /// + /// By default max connections is set to a 256. + pub fn maxconnrate(mut self, num: usize) -> Self { + self.maxconnrate = num; + self + } + + /// Stop actix system. + /// + /// `SystemExit` message stops currently running system. + pub fn system_exit(mut self) -> Self { + self.exit = true; + self + } + + #[doc(hidden)] + /// Set alternative address for `ProcessSignals` actor. + pub fn signals(mut self, addr: Addr) -> Self { + self.signals = Some(addr); + self + } + + /// Disable signal handling + pub fn disable_signals(mut self) -> Self { + self.no_signals = true; + self + } + + /// Timeout for graceful workers shutdown. + /// + /// After receiving a stop signal, workers have this much time to finish + /// serving requests. Workers still alive after the timeout are force + /// dropped. + /// + /// By default shutdown timeout sets to 30 seconds. + pub fn shutdown_timeout(mut self, sec: u16) -> Self { + self.shutdown_timeout = sec; + self + } + + /// Add new service to server + pub fn bind(mut self, addr: U, srv: T) -> io::Result + where + U: net::ToSocketAddrs, + T: IntoNewService + Clone, + N: NewService + + Clone + + Send + + 'static, + N::Service: 'static, + N::Future: 'static, + N::Error: fmt::Display, + { + let sockets = bind_addr(addr)?; + + for lst in sockets { + self = self.listen(lst, srv.clone()) + } + Ok(self) + } + + /// Add new service to server + pub fn listen(mut self, lst: net::TcpListener, srv: T) -> Self + where + T: IntoNewService, + N: NewService + + Clone + + Send + + 'static, + N::Service: 'static, + N::Future: 'static, + N::Error: fmt::Display, + { + let token = Token(self.services.len()); + self.services.push(ServerNewService::create(srv.into())); + self.sockets.push((token, lst)); + self + } + + /// Spawn new thread and start listening for incoming connections. + /// + /// This method spawns new thread and starts new actix system. Other than + /// that it is similar to `start()` method. This method blocks. + /// + /// This methods panics if no socket addresses get bound. + /// + /// ```rust,ignore + /// # extern crate futures; + /// # extern crate actix_web; + /// # use futures::Future; + /// use actix_web::*; + /// + /// fn main() { + /// Server::new(). + /// .service( + /// HttpServer::new(|| App::new().resource("/", |r| r.h(|_| HttpResponse::Ok()))) + /// .bind("127.0.0.1:0") + /// .expect("Can not bind to 127.0.0.1:0")) + /// .run(); + /// } + /// ``` + pub fn run(self) { + let sys = System::new("http-server"); + self.start(); + sys.run(); + } + + /// Starts Server Actor and returns its address + pub fn start(mut self) -> Addr { + if self.sockets.is_empty() { + panic!("Service should have at least one bound socket"); + } else { + info!("Starting {} http workers", self.threads); + + // start workers + let mut workers = Vec::new(); + for idx in 0..self.threads { + let (addr, worker) = self.start_worker(idx, self.accept.get_notify()); + workers.push(worker); + self.workers.push((idx, addr)); + } + + // start accept thread + for sock in &self.sockets { + info!("Starting server on http://{:?}", sock.1.local_addr().ok()); + } + let rx = self + .accept + .start(mem::replace(&mut self.sockets, Vec::new()), workers); + + // start http server actor + let signals = self.subscribe_to_signals(); + let addr = Actor::create(move |ctx| { + ctx.add_stream(rx); + self + }); + if let Some(signals) = signals { + signals.do_send(signal::Subscribe(addr.clone().recipient())) + } + addr + } + } + + // subscribe to os signals + fn subscribe_to_signals(&self) -> Option> { + if !self.no_signals { + if let Some(ref signals) = self.signals { + Some(signals.clone()) + } else { + Some(System::current().registry().get::()) + } + } else { + None + } + } + + fn start_worker(&self, idx: usize, notify: AcceptNotify) -> (Addr, WorkerClient) { + let (tx, rx) = unbounded::(); + let conns = Connections::new(notify, self.maxconn, self.maxconnrate); + let worker = WorkerClient::new(idx, tx, conns.clone()); + let services: Vec> = + self.services.iter().map(|v| v.clone_factory()).collect(); + + let addr = Arbiter::start(move |ctx: &mut Context<_>| { + ctx.add_message_stream(rx); + Worker::new(ctx, services) + }); + + (addr, worker) + } +} + +impl Actor for Server { + type Context = Context; +} + +/// Signals support +/// Handle `SIGINT`, `SIGTERM`, `SIGQUIT` signals and stop actix system +/// message to `System` actor. +impl Handler for Server { + type Result = (); + + fn handle(&mut self, msg: signal::Signal, ctx: &mut Context) { + match msg.0 { + signal::SignalType::Int => { + info!("SIGINT received, exiting"); + self.exit = true; + Handler::::handle(self, StopServer { graceful: false }, ctx); + } + signal::SignalType::Term => { + info!("SIGTERM received, stopping"); + self.exit = true; + Handler::::handle(self, StopServer { graceful: true }, ctx); + } + signal::SignalType::Quit => { + info!("SIGQUIT received, exiting"); + self.exit = true; + Handler::::handle(self, StopServer { graceful: false }, ctx); + } + _ => (), + } + } +} + +impl Handler for Server { + type Result = (); + + fn handle(&mut self, _: PauseServer, _: &mut Context) { + self.accept.send(Command::Pause); + } +} + +impl Handler for Server { + type Result = (); + + fn handle(&mut self, _: ResumeServer, _: &mut Context) { + self.accept.send(Command::Resume); + } +} + +impl Handler for Server { + type Result = Response<(), ()>; + + fn handle(&mut self, msg: StopServer, ctx: &mut Context) -> Self::Result { + // stop accept thread + self.accept.send(Command::Stop); + + // stop workers + let (tx, rx) = mpsc::channel(1); + + let dur = if msg.graceful { + Some(Duration::new(u64::from(self.shutdown_timeout), 0)) + } else { + None + }; + for worker in &self.workers { + let tx2 = tx.clone(); + ctx.spawn( + worker + .1 + .send(StopWorker { graceful: dur }) + .into_actor(self) + .then(move |_, slf, ctx| { + slf.workers.pop(); + if slf.workers.is_empty() { + let _ = tx2.send(()); + + // we need to stop system if server was spawned + if slf.exit { + ctx.run_later(Duration::from_millis(300), |_, _| { + System::current().stop(); + }); + } + } + + fut::ok(()) + }), + ); + } + + if !self.workers.is_empty() { + Response::async(rx.into_future().map(|_| ()).map_err(|_| ())) + } else { + // we need to stop system if server was spawned + if self.exit { + ctx.run_later(Duration::from_millis(300), |_, _| { + System::current().stop(); + }); + } + Response::reply(Ok(())) + } + } +} + +/// Commands from accept threads +impl StreamHandler for Server { + fn finished(&mut self, _: &mut Context) {} + + fn handle(&mut self, msg: ServerCommand, _: &mut Context) { + match msg { + ServerCommand::WorkerDied(idx) => { + let mut found = false; + for i in 0..self.workers.len() { + if self.workers[i].0 == idx { + self.workers.swap_remove(i); + found = true; + break; + } + } + + if found { + error!("Worker has died {:?}, restarting", idx); + + let mut new_idx = self.workers.len(); + 'found: loop { + for i in 0..self.workers.len() { + if self.workers[i].0 == new_idx { + new_idx += 1; + continue 'found; + } + } + break; + } + + let (addr, worker) = self.start_worker(new_idx, self.accept.get_notify()); + self.workers.push((new_idx, addr)); + self.accept.send(Command::Worker(worker)); + } + } + } + } +} + +#[derive(Clone, Default)] +/// Contains information about connection. +pub struct Connections(Arc); + +impl Connections { + fn new(notify: AcceptNotify, maxconn: usize, maxconnrate: usize) -> Self { + let maxconn_low = if maxconn > 10 { maxconn - 10 } else { 0 }; + let maxconnrate_low = if maxconnrate > 10 { + maxconnrate - 10 + } else { + 0 + }; + + Connections(Arc::new(ConnectionsInner { + notify, + maxconn, + maxconnrate, + maxconn_low, + maxconnrate_low, + conn: AtomicUsize::new(0), + connrate: AtomicUsize::new(0), + })) + } + + pub(crate) fn available(&self) -> bool { + self.0.available() + } + + pub(crate) fn num_connections(&self) -> usize { + self.0.conn.load(Ordering::Relaxed) + } + + /// Report opened connection + pub fn connection(&self) -> ConnectionTag { + ConnectionTag::new(self.0.clone()) + } + + /// Report rate connection, rate is usually ssl handshake + pub fn connection_rate(&self) -> ConnectionRateTag { + ConnectionRateTag::new(self.0.clone()) + } +} + +#[derive(Default)] +struct ConnectionsInner { + notify: AcceptNotify, + conn: AtomicUsize, + connrate: AtomicUsize, + maxconn: usize, + maxconnrate: usize, + maxconn_low: usize, + maxconnrate_low: usize, +} + +impl ConnectionsInner { + fn available(&self) -> bool { + if self.maxconnrate <= self.connrate.load(Ordering::Relaxed) { + false + } else { + self.maxconn > self.conn.load(Ordering::Relaxed) + } + } + + fn notify_maxconn(&self, maxconn: usize) { + if maxconn > self.maxconn_low && maxconn <= self.maxconn { + self.notify.notify(); + } + } + + fn notify_maxconnrate(&self, connrate: usize) { + if connrate > self.maxconnrate_low && connrate <= self.maxconnrate { + self.notify.notify(); + } + } +} + +/// Type responsible for max connection stat. +/// +/// Max connections stat get updated on drop. +pub struct ConnectionTag(Arc); + +impl ConnectionTag { + fn new(inner: Arc) -> Self { + inner.conn.fetch_add(1, Ordering::Relaxed); + ConnectionTag(inner) + } +} + +impl Drop for ConnectionTag { + fn drop(&mut self) { + let conn = self.0.conn.fetch_sub(1, Ordering::Relaxed); + self.0.notify_maxconn(conn); + } +} + +/// Type responsible for max connection rate stat. +/// +/// Max connections rate stat get updated on drop. +pub struct ConnectionRateTag(Arc); + +impl ConnectionRateTag { + fn new(inner: Arc) -> Self { + inner.connrate.fetch_add(1, Ordering::Relaxed); + ConnectionRateTag(inner) + } +} + +impl Drop for ConnectionRateTag { + fn drop(&mut self) { + let connrate = self.0.connrate.fetch_sub(1, Ordering::Relaxed); + self.0.notify_maxconnrate(connrate); + } +} + +fn bind_addr(addr: S) -> io::Result> { + let mut err = None; + let mut succ = false; + let mut sockets = Vec::new(); + for addr in addr.to_socket_addrs()? { + match create_tcp_listener(addr) { + Ok(lst) => { + succ = true; + sockets.push(lst); + } + Err(e) => err = Some(e), + } + } + + if !succ { + if let Some(e) = err.take() { + Err(e) + } else { + Err(io::Error::new( + io::ErrorKind::Other, + "Can not bind to address.", + )) + } + } else { + Ok(sockets) + } +} + +fn create_tcp_listener(addr: net::SocketAddr) -> io::Result { + let builder = match addr { + net::SocketAddr::V4(_) => TcpBuilder::new_v4()?, + net::SocketAddr::V6(_) => TcpBuilder::new_v6()?, + }; + builder.reuse_address(true)?; + builder.bind(addr)?; + Ok(builder.listen(1024)?) +} diff --git a/src/server_service.rs b/src/server_service.rs new file mode 100644 index 00000000..c18cc62f --- /dev/null +++ b/src/server_service.rs @@ -0,0 +1,106 @@ +use std::{fmt, io, net}; + +use futures::{future, Future, Poll}; +use tokio_reactor::Handle; +use tokio_tcp::TcpStream; +use tower_service::{NewService, Service}; + +pub(crate) type BoxedServerService = Box< + Service< + Request = net::TcpStream, + Response = (), + Error = (), + Future = Box>, + >, +>; + +pub(crate) struct ServerService { + inner: T, +} + +impl Service for ServerService +where + T: Service, + T::Future: 'static, + T::Error: fmt::Display + 'static, +{ + type Request = net::TcpStream; + type Response = (); + type Error = (); + type Future = Box>; + + fn poll_ready(&mut self) -> Poll<(), Self::Error> { + self.inner.poll_ready().map_err(|_| ()) + } + + fn call(&mut self, stream: net::TcpStream) -> Self::Future { + let stream = TcpStream::from_std(stream, &Handle::default()).map_err(|e| { + error!("Can not convert to an async tcp stream: {}", e); + }); + + if let Ok(stream) = stream { + Box::new(self.inner.call(stream).map_err(|_| ())) + } else { + Box::new(future::err(())) + } + } +} + +pub(crate) struct ServerNewService { + inner: T, +} + +impl ServerNewService +where + T: NewService + + Clone + + Send + + 'static, + T::Service: 'static, + T::Future: 'static, + T::Error: fmt::Display, +{ + pub(crate) fn create(inner: T) -> Box { + Box::new(Self { inner }) + } +} + +pub trait ServerServiceFactory { + fn clone_factory(&self) -> Box; + + fn create(&self) -> Box>; +} + +impl ServerServiceFactory for ServerNewService +where + T: NewService + + Clone + + Send + + 'static, + T::Service: 'static, + T::Future: 'static, + T::Error: fmt::Display, +{ + fn clone_factory(&self) -> Box { + Box::new(Self { + inner: self.inner.clone(), + }) + } + + fn create(&self) -> Box> { + Box::new(self.inner.new_service().map_err(|_| ()).map(|inner| { + let service: BoxedServerService = Box::new(ServerService { inner }); + service + })) + } +} + +impl ServerServiceFactory for Box { + fn clone_factory(&self) -> Box { + self.as_ref().clone_factory() + } + + fn create(&self) -> Box> { + self.as_ref().create() + } +} diff --git a/src/service.rs b/src/service.rs new file mode 100644 index 00000000..f680d3c0 --- /dev/null +++ b/src/service.rs @@ -0,0 +1,521 @@ +use std::cell::RefCell; +use std::marker; +use std::rc::Rc; + +use futures::{future, future::FutureResult, Async, Future, IntoFuture, Poll}; +use tower_service::{NewService, Service}; + +pub trait NewServiceExt: NewService { + fn and_then(self, new_service: F) -> AndThenNewService + where + Self: Sized, + F: IntoNewService, + B: NewService< + Request = Self::Response, + Error = Self::Error, + InitError = Self::InitError, + >; +} + +impl NewServiceExt for T +where + T: NewService, +{ + fn and_then(self, new_service: F) -> AndThenNewService + where + F: IntoNewService, + B: NewService< + Request = Self::Response, + Error = Self::Error, + InitError = Self::InitError, + >, + { + AndThenNewService::new(self, new_service) + } +} + +/// Trait for types that can be converted to a Service +pub trait IntoService +where + T: Service, +{ + /// Create service + fn into(self) -> T; +} + +/// Trait for types that can be converted to a Service +pub trait IntoNewService +where + T: NewService, +{ + /// Create service + fn into(self) -> T; +} + +impl IntoService for T +where + T: Service, +{ + fn into(self) -> T { + self + } +} + +impl IntoNewService for T +where + T: NewService, +{ + fn into(self) -> T { + self + } +} + +impl IntoService> for F +where + F: Fn(Req) -> Fut + 'static, + Fut: IntoFuture, +{ + fn into(self) -> FnService { + FnService::new(self) + } +} + +pub struct FnService +where + F: Fn(Req) -> Fut, + Fut: IntoFuture, +{ + f: F, + req: marker::PhantomData, + resp: marker::PhantomData, + err: marker::PhantomData, +} + +impl FnService +where + F: Fn(Req) -> Fut, + Fut: IntoFuture, +{ + pub fn new(f: F) -> Self { + FnService { + f, + req: marker::PhantomData, + resp: marker::PhantomData, + err: marker::PhantomData, + } + } +} + +impl Service for FnService +where + F: Fn(Req) -> Fut, + Fut: IntoFuture, +{ + type Request = Req; + type Response = Resp; + type Error = E; + type Future = Fut::Future; + + fn poll_ready(&mut self) -> Poll<(), Self::Error> { + Ok(Async::Ready(())) + } + + fn call(&mut self, req: Req) -> Self::Future { + (self.f)(req).into_future() + } +} + +pub struct FnNewService +where + F: Fn(Req) -> Fut, + Fut: IntoFuture, +{ + f: F, + req: marker::PhantomData, + resp: marker::PhantomData, + err: marker::PhantomData, +} + +impl FnNewService +where + F: Fn(Req) -> Fut + Clone, + Fut: IntoFuture, +{ + fn new(f: F) -> Self { + FnNewService { + f, + req: marker::PhantomData, + resp: marker::PhantomData, + err: marker::PhantomData, + } + } +} + +impl NewService for FnNewService +where + F: Fn(Req) -> Fut + Clone, + Fut: IntoFuture, +{ + type Request = Req; + type Response = Resp; + type Error = Err; + type Service = FnService; + type InitError = (); + type Future = FutureResult; + + fn new_service(&self) -> Self::Future { + future::ok(FnService::new(self.f.clone())) + } +} + +impl IntoNewService> for F +where + F: Fn(Req) -> Fut + Clone + 'static, + Fut: IntoFuture, +{ + fn into(self) -> FnNewService { + FnNewService::new(self) + } +} + +impl Clone for FnNewService +where + F: Fn(Req) -> Fut + Clone, + Fut: IntoFuture, +{ + fn clone(&self) -> Self { + Self::new(self.f.clone()) + } +} + +pub struct FnStateService +where + F: Fn(&mut S, Req) -> Fut, + Fut: IntoFuture, +{ + f: F, + state: S, + req: marker::PhantomData, + resp: marker::PhantomData, + err: marker::PhantomData, +} + +impl FnStateService +where + F: Fn(&mut S, Req) -> Fut, + Fut: IntoFuture, +{ + pub fn new(state: S, f: F) -> Self { + FnStateService { + f, + state, + req: marker::PhantomData, + resp: marker::PhantomData, + err: marker::PhantomData, + } + } +} + +impl Service for FnStateService +where + F: Fn(&mut S, Req) -> Fut, + Fut: IntoFuture, +{ + type Request = Req; + type Response = Resp; + type Error = Err; + type Future = Fut::Future; + + fn poll_ready(&mut self) -> Poll<(), Self::Error> { + Ok(Async::Ready(())) + } + + fn call(&mut self, req: Req) -> Self::Future { + (self.f)(&mut self.state, req).into_future() + } +} + +/// `NewService` for state and handler functions +pub struct FnStateNewService { + f: F1, + state: F2, + s: marker::PhantomData, + req: marker::PhantomData, + resp: marker::PhantomData, + err1: marker::PhantomData, + err2: marker::PhantomData, + fut1: marker::PhantomData, + fut2: marker::PhantomData, +} + +impl + FnStateNewService +{ + fn new(f: F1, state: F2) -> Self { + FnStateNewService { + f, + state, + s: marker::PhantomData, + req: marker::PhantomData, + resp: marker::PhantomData, + err1: marker::PhantomData, + err2: marker::PhantomData, + fut1: marker::PhantomData, + fut2: marker::PhantomData, + } + } +} + +impl NewService + for FnStateNewService +where + S: 'static, + F1: Fn(&mut S, Req) -> Fut1 + Clone + 'static, + F2: Fn() -> Fut2, + Fut1: IntoFuture + 'static, + Fut2: IntoFuture + 'static, + Req: 'static, + Resp: 'static, + Err1: 'static, + Err2: 'static, +{ + type Request = Req; + type Response = Resp; + type Error = Err1; + type Service = FnStateService; + type InitError = Err2; + type Future = Box>; + + fn new_service(&self) -> Self::Future { + let f = self.f.clone(); + Box::new( + (self.state)() + .into_future() + .and_then(move |state| Ok(FnStateService::new(state, f))), + ) + } +} + +impl + IntoNewService> for (F1, F2) +where + S: 'static, + F1: Fn(&mut S, Req) -> Fut1 + Clone + 'static, + F2: Fn() -> Fut2, + Fut1: IntoFuture + 'static, + Fut2: IntoFuture + 'static, + Req: 'static, + Resp: 'static, + Err1: 'static, + Err2: 'static, +{ + fn into(self) -> FnStateNewService { + FnStateNewService::new(self.0, self.1) + } +} + +impl Clone + for FnStateNewService +where + F1: Fn(&mut S, Req) -> Fut1 + Clone + 'static, + F2: Fn() -> Fut2 + Clone, + Fut1: IntoFuture, + Fut2: IntoFuture, +{ + fn clone(&self) -> Self { + Self::new(self.f.clone(), self.state.clone()) + } +} + +/// `AndThen` service combinator +pub struct AndThen { + a: A, + b: Rc>, +} + +impl AndThen +where + A: Service, + B: Service, +{ + /// Create new `AndThen` combinator + pub fn new(a: A, b: B) -> Self { + Self { + a, + b: Rc::new(RefCell::new(b)), + } + } +} + +impl Service for AndThen +where + A: Service, + B: Service, +{ + type Request = A::Request; + type Response = B::Response; + type Error = B::Error; + type Future = AndThenFuture; + + fn poll_ready(&mut self) -> Poll<(), Self::Error> { + let res = self.a.poll_ready(); + if let Ok(Async::Ready(_)) = res { + self.b.borrow_mut().poll_ready() + } else { + res + } + } + + fn call(&mut self, req: Self::Request) -> Self::Future { + AndThenFuture::new(self.a.call(req), self.b.clone()) + } +} + +pub struct AndThenFuture +where + A: Service, + B: Service, +{ + b: Rc>, + fut_b: Option, + fut_a: A::Future, +} + +impl AndThenFuture +where + A: Service, + B: Service, +{ + fn new(fut_a: A::Future, b: Rc>) -> Self { + AndThenFuture { + b, + fut_a, + fut_b: None, + } + } +} + +impl Future for AndThenFuture +where + A: Service, + B: Service, +{ + type Item = B::Response; + type Error = B::Error; + + fn poll(&mut self) -> Poll { + if let Some(ref mut fut) = self.fut_b { + return fut.poll(); + } + + match self.fut_a.poll()? { + Async::Ready(resp) => { + self.fut_b = Some(self.b.borrow_mut().call(resp)); + self.poll() + } + Async::NotReady => Ok(Async::NotReady), + } + } +} + +/// `AndThenNewService` new service combinator +pub struct AndThenNewService { + a: A, + b: B, +} + +impl AndThenNewService +where + A: NewService, + B: NewService, +{ + /// Create new `AndThen` combinator + pub fn new>(a: A, f: F) -> Self { + Self { a, b: f.into() } + } +} + +impl NewService for AndThenNewService +where + A: NewService, + B: NewService, +{ + type Request = A::Request; + type Response = B::Response; + type Error = A::Error; + type Service = AndThen; + + type InitError = A::InitError; + type Future = AndThenNewServiceFuture; + + fn new_service(&self) -> Self::Future { + AndThenNewServiceFuture::new(self.a.new_service(), self.b.new_service()) + } +} + +impl Clone for AndThenNewService +where + A: NewService + Clone, + B: NewService + Clone, +{ + fn clone(&self) -> Self { + Self { + a: self.a.clone(), + b: self.b.clone(), + } + } +} + +pub struct AndThenNewServiceFuture +where + A: NewService, + B: NewService, +{ + fut_b: B::Future, + fut_a: A::Future, + a: Option, + b: Option, +} + +impl AndThenNewServiceFuture +where + A: NewService, + B: NewService, +{ + fn new(fut_a: A::Future, fut_b: B::Future) -> Self { + AndThenNewServiceFuture { + fut_a, + fut_b, + a: None, + b: None, + } + } +} + +impl Future for AndThenNewServiceFuture +where + A: NewService, + B: NewService, +{ + type Item = AndThen; + type Error = B::InitError; + + fn poll(&mut self) -> Poll { + if let Async::Ready(service) = self.fut_a.poll()? { + self.a = Some(service); + } + + if let Async::Ready(service) = self.fut_b.poll()? { + self.b = Some(service); + } + + if self.a.is_some() && self.b.is_some() { + Ok(Async::Ready(AndThen::new( + self.a.take().unwrap(), + self.b.take().unwrap(), + ))) + } else { + Ok(Async::NotReady) + } + } +} diff --git a/src/ssl/mod.rs b/src/ssl/mod.rs new file mode 100644 index 00000000..2fb85e16 --- /dev/null +++ b/src/ssl/mod.rs @@ -0,0 +1,15 @@ +//! SSL Services +#[cfg(feature = "ssl")] +mod openssl; +#[cfg(feature = "ssl")] +pub use self::openssl::OpensslService; + +// #[cfg(feature = "tls")] +// mod nativetls; +// #[cfg(feature = "tls")] +// pub use self::nativetls::{NativeTlsAcceptor, TlsStream}; + +// #[cfg(feature = "rust-tls")] +// mod rustls; +// #[cfg(feature = "rust-tls")] +// pub use self::rustls::RustlsAcceptor; diff --git a/src/ssl/openssl.rs b/src/ssl/openssl.rs new file mode 100644 index 00000000..bf9c47fd --- /dev/null +++ b/src/ssl/openssl.rs @@ -0,0 +1,125 @@ +use std::marker::PhantomData; +use std::net::Shutdown; +use std::{io, time}; + +use futures::{future, future::FutureResult, Async, Future, Poll}; +use openssl::ssl::{AlpnError, SslAcceptor, SslAcceptorBuilder}; +use tokio_io::{AsyncRead, AsyncWrite}; +use tokio_openssl::{AcceptAsync, SslAcceptorExt, SslStream}; +use tokio_tcp::TcpStream; +use tower_service::{NewService, Service}; + +use {IntoNewService, IoStream}; + +/// Support `SSL` connections via openssl package +/// +/// `alpn` feature enables `OpensslAcceptor` type +pub struct OpensslService { + acceptor: SslAcceptor, + io: PhantomData, +} + +impl OpensslService { + /// Create default `OpensslService` + pub fn new(builder: SslAcceptorBuilder) -> Self { + OpensslService { + acceptor: builder.build(), + io: PhantomData, + } + } + + /// Create `OpensslWith` with `HTTP1.1` and `HTTP2`. + pub fn for_http(mut builder: SslAcceptorBuilder) -> io::Result { + let protos = b"\x08http/1.1\x02h2"; + + builder.set_alpn_select_callback(|_, protos| { + const H2: &[u8] = b"\x02h2"; + if protos.windows(3).any(|window| window == H2) { + Ok(b"h2") + } else { + Err(AlpnError::NOACK) + } + }); + builder.set_alpn_protos(&protos[..])?; + + Ok(OpensslService { + acceptor: builder.build(), + io: PhantomData, + }) + } +} +impl Clone for OpensslService { + fn clone(&self) -> Self { + Self { + acceptor: self.acceptor.clone(), + io: PhantomData, + } + } +} + +impl NewService for OpensslService { + type Request = T; + type Response = SslStream; + type Error = io::Error; + type Service = OpensslAcceptor; + type InitError = io::Error; + type Future = FutureResult; + + fn new_service(&self) -> Self::Future { + future::ok(OpensslAcceptor { + acceptor: self.acceptor.clone(), + io: PhantomData, + }) + } +} + +pub struct OpensslAcceptor { + acceptor: SslAcceptor, + io: PhantomData, +} + +impl Service for OpensslAcceptor { + type Request = T; + type Response = SslStream; + type Error = io::Error; + type Future = AcceptorFuture; + + fn poll_ready(&mut self) -> Poll<(), Self::Error> { + Ok(Async::Ready(())) + } + + fn call(&mut self, req: Self::Request) -> Self::Future { + AcceptorFuture(SslAcceptorExt::accept_async(&self.acceptor, req)) + } +} + +pub struct AcceptorFuture(AcceptAsync); + +impl Future for AcceptorFuture { + type Item = SslStream; + type Error = io::Error; + + fn poll(&mut self) -> Poll { + self.0 + .poll() + .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) + } +} + +// impl IoStream for SslStream { +// #[inline] +// fn shutdown(&mut self, _how: Shutdown) -> io::Result<()> { +// let _ = self.get_mut().shutdown(); +// Ok(()) +// } + +// #[inline] +// fn set_nodelay(&mut self, nodelay: bool) -> io::Result<()> { +// self.get_mut().get_mut().set_nodelay(nodelay) +// } + +// #[inline] +// fn set_linger(&mut self, dur: Option) -> io::Result<()> { +// self.get_mut().get_mut().set_linger(dur) +// } +// } diff --git a/src/worker.rs b/src/worker.rs new file mode 100644 index 00000000..32b97887 --- /dev/null +++ b/src/worker.rs @@ -0,0 +1,152 @@ +use std::{net, time}; + +use futures::future; +use futures::sync::mpsc::{SendError, UnboundedSender}; +use futures::sync::oneshot; + +use actix::msgs::StopArbiter; +use actix::{ + fut, Actor, ActorContext, ActorFuture, Arbiter, AsyncContext, Context, Handler, Message, + Response, WrapFuture, +}; + +use super::server_service::{BoxedServerService, ServerServiceFactory}; +use super::{server::Connections, Token}; + +#[derive(Message)] +pub(crate) struct Conn { + pub io: net::TcpStream, + pub handler: Token, + pub token: Token, + pub peer: Option, +} + +#[derive(Clone)] +pub(crate) struct WorkerClient { + pub idx: usize, + tx: UnboundedSender, + conns: Connections, +} + +impl WorkerClient { + pub fn new(idx: usize, tx: UnboundedSender, conns: Connections) -> Self { + WorkerClient { idx, tx, conns } + } + + pub fn send(&self, msg: Conn) -> Result<(), SendError> { + self.tx.unbounded_send(msg) + } + + pub fn available(&self) -> bool { + self.conns.available() + } +} + +/// Stop worker message. Returns `true` on successful shutdown +/// and `false` if some connections still alive. +pub(crate) struct StopWorker { + pub graceful: Option, +} + +impl Message for StopWorker { + type Result = Result; +} + +/// Http worker +/// +/// Worker accepts Socket objects via unbounded channel and start requests +/// processing. +pub(crate) struct Worker { + // conns: Connections, + services: Vec, +} + +impl Actor for Worker { + type Context = Context; +} + +impl Worker { + pub(crate) fn new( + ctx: &mut Context, services: Vec>, + ) -> Self { + let wrk = Worker { + services: Vec::new(), + }; + + ctx.wait( + future::join_all(services.into_iter().map(|s| s.create())) + .into_actor(&wrk) + .map_err(|e, _, ctx| { + error!("Can not start worker: {:?}", e); + Arbiter::current().do_send(StopArbiter(0)); + ctx.stop(); + }).and_then(|services, act, _| { + act.services.extend(services); + fut::ok(()) + }), + ); + + wrk + } + + fn shutdown(&self, _force: bool) { + // self.services.iter().for_each(|h| h.shutdown(force)); + } + + fn shutdown_timeout( + &self, _ctx: &mut Context, _tx: oneshot::Sender, _dur: time::Duration, + ) { + // sleep for 1 second and then check again + // ctx.run_later(time::Duration::new(1, 0), move |slf, ctx| { + // let num = slf.conns.num_connections(); + // if num == 0 { + // let _ = tx.send(true); + // Arbiter::current().do_send(StopArbiter(0)); + // } else if let Some(d) = dur.checked_sub(time::Duration::new(1, 0)) { + // slf.shutdown_timeout(ctx, tx, d); + // } else { + // info!("Force shutdown http worker, {} connections", num); + // slf.shutdown(true); + // let _ = tx.send(false); + // Arbiter::current().do_send(StopArbiter(0)); + // } + // }); + } +} + +impl Handler for Worker { + type Result = (); + + fn handle(&mut self, msg: Conn, _: &mut Context) { + Arbiter::spawn(self.services[msg.handler.0].call(msg.io)) + } +} + +/// `StopWorker` message handler +impl Handler for Worker { + type Result = Response; + + fn handle(&mut self, _msg: StopWorker, _ctx: &mut Context) -> Self::Result { + unimplemented!() + // let num = self.conns.num_connections(); + // if num == 0 { + // info!("Shutting down http worker, 0 connections"); + // Response::reply(Ok(true)) + // } else if let Some(dur) = msg.graceful { + // self.shutdown(false); + // let (tx, rx) = oneshot::channel(); + // let num = self.conns.num_connections(); + // if num != 0 { + // info!("Graceful http worker shutdown, {} connections", num); + // self.shutdown_timeout(ctx, tx, dur); + // Response::reply(Ok(true)) + // } else { + // Response::async(rx.map_err(|_| ())) + // } + // } else { + // info!("Force shutdown http worker, {} connections", num); + // self.shutdown(true); + // Response::reply(Ok(false)) + // } + } +}