mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-04 09:56:22 +02:00
Compare commits
100 Commits
http-v0.2.
...
http-v0.2.
Author | SHA1 | Date | |
---|---|---|---|
043f763c51 | |||
8873e9b39e | |||
5e8f1c338c | |||
1d96ae9bc3 | |||
8d61fe0925 | |||
8a9fcddb3c | |||
c9400456f6 | |||
63ddd30ee4 | |||
bae29897d6 | |||
616981ecf9 | |||
98bf8ab098 | |||
c193137905 | |||
a07cdd6533 | |||
61e492e7e3 | |||
23d768a77b | |||
87b7162473 | |||
979c4d44f4 | |||
5d248cad89 | |||
b1cb72d088 | |||
55179d6ab2 | |||
192dfff680 | |||
915010e733 | |||
dbe4c9ffb5 | |||
0ee69671ba | |||
80e1d16ab8 | |||
b70de5b991 | |||
0b9e692298 | |||
cf1a60cb3a | |||
0d15861e23 | |||
cb19ebfe0c | |||
0d9ea41047 | |||
e9b4aa205f | |||
7674f1173c | |||
511026cab0 | |||
81ab37f235 | |||
6f2049ba9b | |||
52372fcbea | |||
f3751d83f8 | |||
b0b462581b | |||
8f48ed2597 | |||
c96068e78d | |||
7bca1f7d8d | |||
3618a84164 | |||
03ca408e94 | |||
e53e9c8ba3 | |||
941241c5f0 | |||
f8320fedd8 | |||
c808364c07 | |||
cccd829656 | |||
3650f6d7b8 | |||
6b7df6b242 | |||
b6ff786ed3 | |||
9c3789cbd0 | |||
29098f8397 | |||
fbdda8acb1 | |||
d03296237e | |||
b36fdc46db | |||
2a2d7f5768 | |||
4092c7f326 | |||
ef3e1037a8 | |||
baaa7b3fbb | |||
32718b7e31 | |||
c01611d8b5 | |||
7b1dcaffda | |||
c65dbaf88e | |||
c45728ac01 | |||
6f71409355 | |||
8d17c8651f | |||
b1143168e5 | |||
69456991f6 | |||
f410f3330f | |||
e1fcd203f8 | |||
0d8a4304a9 | |||
14cc5a5d6b | |||
287c2b1d18 | |||
7596ab69e0 | |||
1fdd77bffa | |||
2d424957fb | |||
dabc4fe00b | |||
5bf5b0acd2 | |||
099a8ff7d8 | |||
a28b7139e6 | |||
a0a469fe85 | |||
dbab55dd6b | |||
d2eb1edac3 | |||
5901dfee1a | |||
0e05b37082 | |||
37f4ce8604 | |||
12b5174850 | |||
b77ed193f7 | |||
50a9d9e2c5 | |||
93855b889a | |||
fa7e0fe6df | |||
382d4ca216 | |||
32a66a99bf | |||
73ae801a13 | |||
ca4ed0932e | |||
9fc7c8b1af | |||
65732197b8 | |||
959eef05ae |
12
.travis.yml
12
.travis.yml
@ -3,16 +3,16 @@ sudo: required
|
||||
dist: trusty
|
||||
|
||||
cache:
|
||||
cargo: true
|
||||
# cargo: true
|
||||
apt: true
|
||||
|
||||
matrix:
|
||||
include:
|
||||
- rust: stable
|
||||
- rust: beta
|
||||
- rust: nightly-2019-04-02
|
||||
- rust: nightly-2019-08-10
|
||||
allow_failures:
|
||||
- rust: nightly-2019-04-02
|
||||
- rust: nightly-2019-08-10
|
||||
|
||||
env:
|
||||
global:
|
||||
@ -25,7 +25,7 @@ before_install:
|
||||
- sudo apt-get install -y openssl libssl-dev libelf-dev libdw-dev cmake gcc binutils-dev libiberty-dev
|
||||
|
||||
before_cache: |
|
||||
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-04-02" ]]; then
|
||||
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-08-10" ]]; then
|
||||
RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install --version 0.6.11 cargo-tarpaulin
|
||||
fi
|
||||
|
||||
@ -37,6 +37,8 @@ script:
|
||||
- cargo update
|
||||
- cargo check --all --no-default-features
|
||||
- cargo test --all-features --all -- --nocapture
|
||||
- cd actix-http; cargo test --no-default-features --features="rust-tls" -- --nocapture; cd ..
|
||||
- cd awc; cargo test --no-default-features --features="rust-tls" -- --nocapture; cd ..
|
||||
|
||||
# Upload docs
|
||||
after_success:
|
||||
@ -49,7 +51,7 @@ after_success:
|
||||
echo "Uploaded documentation"
|
||||
fi
|
||||
- |
|
||||
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-04-02" ]]; then
|
||||
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-08-10" ]]; then
|
||||
taskset -c 0 cargo tarpaulin --out Xml --all --all-features
|
||||
bash <(curl -s https://codecov.io/bash)
|
||||
echo "Uploaded code coverage"
|
||||
|
70
CHANGES.md
70
CHANGES.md
@ -1,6 +1,74 @@
|
||||
# Changes
|
||||
## not released yet
|
||||
|
||||
## [1.0.3] - unreleased
|
||||
### Added
|
||||
|
||||
* Add `middleware::Conditon` that conditionally enables another middleware
|
||||
|
||||
### Fixed
|
||||
|
||||
* h2 will use error response #1080
|
||||
|
||||
## [1.0.7] - 2019-08-29
|
||||
|
||||
### Fixed
|
||||
|
||||
* Request Extensions leak #1062
|
||||
|
||||
|
||||
## [1.0.6] - 2019-08-28
|
||||
|
||||
### Added
|
||||
|
||||
* Re-implement Host predicate (#989)
|
||||
|
||||
* Form immplements Responder, returning a `application/x-www-form-urlencoded` response
|
||||
|
||||
* Add `into_inner` to `Data`
|
||||
|
||||
* Add `test::TestRequest::set_form()` convenience method to automatically serialize data and set
|
||||
the header in test requests.
|
||||
|
||||
### Changed
|
||||
|
||||
* `Query` payload made `pub`. Allows user to pattern-match the payload.
|
||||
|
||||
* Enable `rust-tls` feature for client #1045
|
||||
|
||||
* Update serde_urlencoded to 0.6.1
|
||||
|
||||
* Update url to 2.1
|
||||
|
||||
|
||||
## [1.0.5] - 2019-07-18
|
||||
|
||||
### Added
|
||||
|
||||
* Unix domain sockets (HttpServer::bind_uds) #92
|
||||
|
||||
* Actix now logs errors resulting in "internal server error" responses always, with the `error`
|
||||
logging level
|
||||
|
||||
### Fixed
|
||||
|
||||
* Restored logging of errors through the `Logger` middleware
|
||||
|
||||
|
||||
## [1.0.4] - 2019-07-17
|
||||
|
||||
### Added
|
||||
|
||||
* Add `Responder` impl for `(T, StatusCode) where T: Responder`
|
||||
|
||||
* Allow to access app's resource map via
|
||||
`ServiceRequest::resource_map()` and `HttpRequest::resource_map()` methods.
|
||||
|
||||
### Changed
|
||||
|
||||
* Upgrade `rand` dependency version to 0.7
|
||||
|
||||
|
||||
## [1.0.3] - 2019-06-28
|
||||
|
||||
### Added
|
||||
|
||||
|
35
Cargo.toml
35
Cargo.toml
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web"
|
||||
version = "1.0.2"
|
||||
version = "1.0.7"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
|
||||
readme = "README.md"
|
||||
@ -16,7 +16,7 @@ exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["ssl", "brotli", "flate2-zlib", "secure-cookies", "client", "rust-tls"]
|
||||
features = ["ssl", "brotli", "flate2-zlib", "secure-cookies", "client", "rust-tls", "uds"]
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "actix/actix-web", branch = "master" }
|
||||
@ -66,20 +66,23 @@ fail = ["actix-http/fail"]
|
||||
ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
|
||||
|
||||
# rustls
|
||||
rust-tls = ["rustls", "actix-server/rust-tls"]
|
||||
rust-tls = ["rustls", "actix-server/rust-tls", "awc/rust-tls"]
|
||||
|
||||
# unix domain sockets support
|
||||
uds = ["actix-server/uds"]
|
||||
|
||||
[dependencies]
|
||||
actix-codec = "0.1.2"
|
||||
actix-service = "0.4.1"
|
||||
actix-utils = "0.4.1"
|
||||
actix-utils = "0.4.4"
|
||||
actix-router = "0.1.5"
|
||||
actix-rt = "0.2.2"
|
||||
actix-rt = "0.2.4"
|
||||
actix-web-codegen = "0.1.2"
|
||||
actix-http = "0.2.4"
|
||||
actix-server = "0.5.1"
|
||||
actix-server-config = "0.1.1"
|
||||
actix-http = "0.2.9"
|
||||
actix-server = "0.6.0"
|
||||
actix-server-config = "0.1.2"
|
||||
actix-threadpool = "0.1.1"
|
||||
awc = { version = "0.2.1", optional = true }
|
||||
awc = { version = "0.2.4", optional = true }
|
||||
|
||||
bytes = "0.4"
|
||||
derive_more = "0.15.0"
|
||||
@ -89,23 +92,23 @@ hashbrown = "0.5.0"
|
||||
log = "0.4"
|
||||
mime = "0.3"
|
||||
net2 = "0.2.33"
|
||||
parking_lot = "0.8"
|
||||
parking_lot = "0.9"
|
||||
regex = "1.0"
|
||||
serde = { version = "1.0", features=["derive"] }
|
||||
serde_json = "1.0"
|
||||
serde_urlencoded = "0.5.3"
|
||||
serde_urlencoded = "0.6.1"
|
||||
time = "0.1.42"
|
||||
url = { version="1.7", features=["query_encoding"] }
|
||||
url = "2.1"
|
||||
|
||||
# ssl support
|
||||
openssl = { version="0.10", optional = true }
|
||||
rustls = { version = "0.15", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix = { version = "0.8.3" }
|
||||
actix-http = { version = "0.2.4", features=["ssl", "brotli", "flate2-zlib"] }
|
||||
actix-http-test = { version = "0.2.2", features=["ssl"] }
|
||||
rand = "0.6"
|
||||
actix = "0.8.3"
|
||||
actix-connect = "0.2.2"
|
||||
actix-http-test = "0.2.4"
|
||||
rand = "0.7"
|
||||
env_logger = "0.6"
|
||||
serde_derive = "1.0"
|
||||
tokio-timer = "0.2.8"
|
||||
|
@ -22,7 +22,7 @@ Actix web is a simple, pragmatic and extremely fast web framework for Rust.
|
||||
* [API Documentation (0.7)](https://docs.rs/actix-web/0.7.19/actix_web/)
|
||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||
* Cargo package: [actix-web](https://crates.io/crates/actix-web)
|
||||
* Minimum supported Rust version: 1.34 or later
|
||||
* Minimum supported Rust version: 1.36 or later
|
||||
|
||||
## Example
|
||||
|
||||
@ -61,7 +61,7 @@ You may consider checking out
|
||||
|
||||
## Benchmarks
|
||||
|
||||
* [TechEmpower Framework Benchmark](https://www.techempower.com/benchmarks/#section=data-r16&hw=ph&test=plaintext)
|
||||
* [TechEmpower Framework Benchmark](https://www.techempower.com/benchmarks/#section=data-r18)
|
||||
|
||||
## License
|
||||
|
||||
|
@ -1,9 +1,9 @@
|
||||
# Identity service for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-identity) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
# Cors Middleware for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-cors) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
## Documentation & community resources
|
||||
|
||||
* [User Guide](https://actix.rs/docs/)
|
||||
* [API Documentation](https://docs.rs/actix-identity/)
|
||||
* [API Documentation](https://docs.rs/actix-cors/)
|
||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||
* Cargo package: [actix-session](https://crates.io/crates/actix-identity)
|
||||
* Cargo package: [actix-cors](https://crates.io/crates/actix-cors)
|
||||
* Minimum supported Rust version: 1.34 or later
|
||||
|
@ -1,3 +1,4 @@
|
||||
#![allow(clippy::borrow_interior_mutable_const, clippy::type_complexity)]
|
||||
//! Cross-origin resource sharing (CORS) for Actix applications
|
||||
//!
|
||||
//! CORS middleware could be used with application and with resource.
|
||||
@ -162,6 +163,7 @@ impl<T> AllOrSome<T> {
|
||||
/// .max_age(3600);
|
||||
/// # }
|
||||
/// ```
|
||||
#[derive(Default)]
|
||||
pub struct Cors {
|
||||
cors: Option<Inner>,
|
||||
methods: bool,
|
||||
@ -585,10 +587,10 @@ impl Inner {
|
||||
}
|
||||
Err(CorsError::BadOrigin)
|
||||
} else {
|
||||
return match self.origins {
|
||||
match self.origins {
|
||||
AllOrSome::All => Ok(()),
|
||||
_ => Err(CorsError::MissingOrigin),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -663,7 +665,7 @@ impl Inner {
|
||||
}
|
||||
Err(CorsError::BadRequestHeaders)
|
||||
} else {
|
||||
return Ok(());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -681,7 +683,7 @@ where
|
||||
type Error = Error;
|
||||
type Future = Either<
|
||||
FutureResult<Self::Response, Error>,
|
||||
Either<S::Future, Box<Future<Item = Self::Response, Error = Error>>>,
|
||||
Either<S::Future, Box<dyn Future<Item = Self::Response, Error = Error>>>,
|
||||
>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
|
@ -1,5 +1,16 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.5] - unreleased
|
||||
|
||||
* Bump up `mime_guess` crate version to 2.0.1
|
||||
|
||||
* Bump up `percent-encoding` crate version to 2.1
|
||||
|
||||
## [0.1.4] - 2019-07-20
|
||||
|
||||
* Allow to disable `Content-Disposition` header #686
|
||||
|
||||
|
||||
## [0.1.3] - 2019-06-28
|
||||
|
||||
* Do not set `Content-Length` header, let actix-http set it #930
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-files"
|
||||
version = "0.1.3"
|
||||
version = "0.1.4"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Static files support for actix web."
|
||||
readme = "README.md"
|
||||
@ -19,7 +19,7 @@ path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = { version = "1.0.2", default-features = false }
|
||||
actix-http = "0.2.4"
|
||||
actix-http = "0.2.9"
|
||||
actix-service = "0.4.1"
|
||||
bitflags = "1"
|
||||
bytes = "0.4"
|
||||
@ -27,8 +27,8 @@ futures = "0.1.25"
|
||||
derive_more = "0.15.0"
|
||||
log = "0.4"
|
||||
mime = "0.3"
|
||||
mime_guess = "2.0.0-alpha"
|
||||
percent-encoding = "1.0"
|
||||
mime_guess = "2.0.1"
|
||||
percent-encoding = "2.1"
|
||||
v_htmlescape = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
|
@ -1,3 +1,5 @@
|
||||
#![allow(clippy::borrow_interior_mutable_const, clippy::type_complexity)]
|
||||
|
||||
//! Static files support
|
||||
use std::cell::RefCell;
|
||||
use std::fmt::Write;
|
||||
@ -20,8 +22,8 @@ use bytes::Bytes;
|
||||
use futures::future::{ok, Either, FutureResult};
|
||||
use futures::{Async, Future, Poll, Stream};
|
||||
use mime;
|
||||
use mime_guess::get_mime_type;
|
||||
use percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET};
|
||||
use mime_guess::from_ext;
|
||||
use percent_encoding::{utf8_percent_encode, CONTROLS};
|
||||
use v_htmlescape::escape as escape_html_entity;
|
||||
|
||||
mod error;
|
||||
@ -40,7 +42,7 @@ type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error
|
||||
/// the type `application/octet-stream`.
|
||||
#[inline]
|
||||
pub fn file_extension_to_mime(ext: &str) -> mime::Mime {
|
||||
get_mime_type(ext)
|
||||
from_ext(ext).first_or_octet_stream()
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
@ -50,14 +52,14 @@ pub struct ChunkedReadFile {
|
||||
size: u64,
|
||||
offset: u64,
|
||||
file: Option<File>,
|
||||
fut: Option<Box<Future<Item = (File, Bytes), Error = BlockingError<io::Error>>>>,
|
||||
fut: Option<Box<dyn Future<Item = (File, Bytes), Error = BlockingError<io::Error>>>>,
|
||||
counter: u64,
|
||||
}
|
||||
|
||||
fn handle_error(err: BlockingError<io::Error>) -> Error {
|
||||
match err {
|
||||
BlockingError::Error(err) => err.into(),
|
||||
BlockingError::Canceled => ErrorInternalServerError("Unexpected error").into(),
|
||||
BlockingError::Canceled => ErrorInternalServerError("Unexpected error"),
|
||||
}
|
||||
}
|
||||
|
||||
@ -105,7 +107,7 @@ impl Stream for ChunkedReadFile {
|
||||
}
|
||||
|
||||
type DirectoryRenderer =
|
||||
Fn(&Directory, &HttpRequest) -> Result<ServiceResponse, io::Error>;
|
||||
dyn Fn(&Directory, &HttpRequest) -> Result<ServiceResponse, io::Error>;
|
||||
|
||||
/// A directory; responds with the generated directory listing.
|
||||
#[derive(Debug)]
|
||||
@ -142,7 +144,7 @@ impl Directory {
|
||||
// show file url as relative to static path
|
||||
macro_rules! encode_file_url {
|
||||
($path:ident) => {
|
||||
utf8_percent_encode(&$path.to_string_lossy(), DEFAULT_ENCODE_SET)
|
||||
utf8_percent_encode(&$path.to_string_lossy(), CONTROLS)
|
||||
};
|
||||
}
|
||||
|
||||
@ -209,7 +211,7 @@ fn directory_listing(
|
||||
))
|
||||
}
|
||||
|
||||
type MimeOverride = Fn(&mime::Name) -> DispositionType;
|
||||
type MimeOverride = dyn Fn(&mime::Name) -> DispositionType;
|
||||
|
||||
/// Static files handling
|
||||
///
|
||||
@ -259,7 +261,7 @@ impl Files {
|
||||
pub fn new<T: Into<PathBuf>>(path: &str, dir: T) -> Files {
|
||||
let dir = dir.into().canonicalize().unwrap_or_else(|_| PathBuf::new());
|
||||
if !dir.is_dir() {
|
||||
log::error!("Specified path is not a directory");
|
||||
log::error!("Specified path is not a directory: {:?}", dir);
|
||||
}
|
||||
|
||||
Files {
|
||||
@ -312,23 +314,32 @@ impl Files {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
///Specifies whether to use ETag or not.
|
||||
/// Specifies whether to use ETag or not.
|
||||
///
|
||||
///Default is true.
|
||||
/// Default is true.
|
||||
pub fn use_etag(mut self, value: bool) -> Self {
|
||||
self.file_flags.set(named::Flags::ETAG, value);
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
///Specifies whether to use Last-Modified or not.
|
||||
/// Specifies whether to use Last-Modified or not.
|
||||
///
|
||||
///Default is true.
|
||||
/// Default is true.
|
||||
pub fn use_last_modified(mut self, value: bool) -> Self {
|
||||
self.file_flags.set(named::Flags::LAST_MD, value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Disable `Content-Disposition` header.
|
||||
///
|
||||
/// By default Content-Disposition` header is enabled.
|
||||
#[inline]
|
||||
pub fn disable_content_disposition(mut self) -> Self {
|
||||
self.file_flags.remove(named::Flags::CONTENT_DISPOSITION);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets default handler which is used when no matched file could be found.
|
||||
pub fn default_handler<F, U>(mut self, f: F) -> Self
|
||||
where
|
||||
@ -370,7 +381,7 @@ impl NewService for Files {
|
||||
type Error = Error;
|
||||
type Service = FilesService;
|
||||
type InitError = ();
|
||||
type Future = Box<Future<Item = Self::Service, Error = Self::InitError>>;
|
||||
type Future = Box<dyn Future<Item = Self::Service, Error = Self::InitError>>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
let mut srv = FilesService {
|
||||
@ -416,7 +427,7 @@ impl FilesService {
|
||||
req: ServiceRequest,
|
||||
) -> Either<
|
||||
FutureResult<ServiceResponse, Error>,
|
||||
Box<Future<Item = ServiceResponse, Error = Error>>,
|
||||
Box<dyn Future<Item = ServiceResponse, Error = Error>>,
|
||||
> {
|
||||
log::debug!("Files: Failed to handle {}: {}", req.path(), e);
|
||||
if let Some(ref mut default) = self.default {
|
||||
@ -433,7 +444,7 @@ impl Service for FilesService {
|
||||
type Error = Error;
|
||||
type Future = Either<
|
||||
FutureResult<Self::Response, Self::Error>,
|
||||
Box<Future<Item = Self::Response, Error = Self::Error>>,
|
||||
Box<dyn Future<Item = Self::Response, Error = Self::Error>>,
|
||||
>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
@ -473,7 +484,7 @@ impl Service for FilesService {
|
||||
Err(e) => ServiceResponse::from_err(e, req),
|
||||
}))
|
||||
}
|
||||
Err(e) => return self.handle_err(e, req),
|
||||
Err(e) => self.handle_err(e, req),
|
||||
}
|
||||
} else if self.show_index {
|
||||
let dir = Directory::new(self.directory.clone(), path);
|
||||
@ -481,7 +492,7 @@ impl Service for FilesService {
|
||||
let x = (self.renderer)(&dir, &req);
|
||||
match x {
|
||||
Ok(resp) => Either::A(ok(resp)),
|
||||
Err(e) => return Either::A(ok(ServiceResponse::from_err(e, req))),
|
||||
Err(e) => Either::A(ok(ServiceResponse::from_err(e, req))),
|
||||
}
|
||||
} else {
|
||||
Either::A(ok(ServiceResponse::from_err(
|
||||
@ -636,6 +647,33 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_named_file_content_disposition() {
|
||||
assert!(NamedFile::open("test--").is_err());
|
||||
let mut file = NamedFile::open("Cargo.toml").unwrap();
|
||||
{
|
||||
file.file();
|
||||
let _f: &File = &file;
|
||||
}
|
||||
{
|
||||
let _f: &mut File = &mut file;
|
||||
}
|
||||
|
||||
let req = TestRequest::default().to_http_request();
|
||||
let resp = file.respond_to(&req).unwrap();
|
||||
assert_eq!(
|
||||
resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
|
||||
"inline; filename=\"Cargo.toml\""
|
||||
);
|
||||
|
||||
let file = NamedFile::open("Cargo.toml")
|
||||
.unwrap()
|
||||
.disable_content_disposition();
|
||||
let req = TestRequest::default().to_http_request();
|
||||
let resp = file.respond_to(&req).unwrap();
|
||||
assert!(resp.headers().get(header::CONTENT_DISPOSITION).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_named_file_set_content_type() {
|
||||
let mut file = NamedFile::open("Cargo.toml")
|
||||
@ -855,7 +893,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_named_file_content_length_headers() {
|
||||
use actix_web::body::{MessageBody, ResponseBody};
|
||||
// use actix_web::body::{MessageBody, ResponseBody};
|
||||
|
||||
let mut srv = test::init_service(
|
||||
App::new().service(Files::new("test", ".").index_file("tests/test.binary")),
|
||||
@ -866,7 +904,7 @@ mod tests {
|
||||
.uri("/t%65st/tests/test.binary")
|
||||
.header(header::RANGE, "bytes=10-20")
|
||||
.to_request();
|
||||
let response = test::call_service(&mut srv, request);
|
||||
let _response = test::call_service(&mut srv, request);
|
||||
|
||||
// let contentlength = response
|
||||
// .headers()
|
||||
@ -889,7 +927,7 @@ mod tests {
|
||||
.uri("/t%65st/tests/test.binary")
|
||||
// .no_default_headers()
|
||||
.to_request();
|
||||
let response = test::call_service(&mut srv, request);
|
||||
let _response = test::call_service(&mut srv, request);
|
||||
|
||||
// let contentlength = response
|
||||
// .headers()
|
||||
@ -937,7 +975,7 @@ mod tests {
|
||||
.method(Method::HEAD)
|
||||
.uri("/t%65st/tests/test.binary")
|
||||
.to_request();
|
||||
let response = test::call_service(&mut srv, request);
|
||||
let _response = test::call_service(&mut srv, request);
|
||||
|
||||
// TODO: fix check
|
||||
// let contentlength = response
|
||||
|
@ -9,7 +9,7 @@ use std::os::unix::fs::MetadataExt;
|
||||
|
||||
use bitflags::bitflags;
|
||||
use mime;
|
||||
use mime_guess::guess_mime_type;
|
||||
use mime_guess::from_path;
|
||||
|
||||
use actix_http::body::SizedStream;
|
||||
use actix_web::http::header::{
|
||||
@ -23,9 +23,10 @@ use crate::range::HttpRange;
|
||||
use crate::ChunkedReadFile;
|
||||
|
||||
bitflags! {
|
||||
pub(crate) struct Flags: u32 {
|
||||
const ETAG = 0b00000001;
|
||||
const LAST_MD = 0b00000010;
|
||||
pub(crate) struct Flags: u8 {
|
||||
const ETAG = 0b0000_0001;
|
||||
const LAST_MD = 0b0000_0010;
|
||||
const CONTENT_DISPOSITION = 0b0000_0100;
|
||||
}
|
||||
}
|
||||
|
||||
@ -40,13 +41,13 @@ impl Default for Flags {
|
||||
pub struct NamedFile {
|
||||
path: PathBuf,
|
||||
file: File,
|
||||
modified: Option<SystemTime>,
|
||||
pub(crate) md: Metadata,
|
||||
pub(crate) flags: Flags,
|
||||
pub(crate) status_code: StatusCode,
|
||||
pub(crate) content_type: mime::Mime,
|
||||
pub(crate) content_disposition: header::ContentDisposition,
|
||||
pub(crate) md: Metadata,
|
||||
modified: Option<SystemTime>,
|
||||
pub(crate) encoding: Option<ContentEncoding>,
|
||||
pub(crate) status_code: StatusCode,
|
||||
pub(crate) flags: Flags,
|
||||
}
|
||||
|
||||
impl NamedFile {
|
||||
@ -87,7 +88,7 @@ impl NamedFile {
|
||||
}
|
||||
};
|
||||
|
||||
let ct = guess_mime_type(&path);
|
||||
let ct = from_path(&path).first_or_octet_stream();
|
||||
let disposition_type = match ct.type_() {
|
||||
mime::IMAGE | mime::TEXT | mime::VIDEO => DispositionType::Inline,
|
||||
_ => DispositionType::Attachment,
|
||||
@ -172,11 +173,21 @@ impl NamedFile {
|
||||
/// sent to the peer. By default the disposition is `inline` for text,
|
||||
/// image, and video content types, and `attachment` otherwise, and
|
||||
/// the filename is taken from the path provided in the `open` method
|
||||
/// after converting it to UTF-8 using
|
||||
/// after converting it to UTF-8 using.
|
||||
/// [to_string_lossy](https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.to_string_lossy).
|
||||
#[inline]
|
||||
pub fn set_content_disposition(mut self, cd: header::ContentDisposition) -> Self {
|
||||
self.content_disposition = cd;
|
||||
self.flags.insert(Flags::CONTENT_DISPOSITION);
|
||||
self
|
||||
}
|
||||
|
||||
/// Disable `Content-Disposition` header.
|
||||
///
|
||||
/// By default Content-Disposition` header is enabled.
|
||||
#[inline]
|
||||
pub fn disable_content_disposition(mut self) -> Self {
|
||||
self.flags.remove(Flags::CONTENT_DISPOSITION);
|
||||
self
|
||||
}
|
||||
|
||||
@ -294,10 +305,12 @@ impl Responder for NamedFile {
|
||||
if self.status_code != StatusCode::OK {
|
||||
let mut resp = HttpResponse::build(self.status_code);
|
||||
resp.set(header::ContentType(self.content_type.clone()))
|
||||
.header(
|
||||
header::CONTENT_DISPOSITION,
|
||||
self.content_disposition.to_string(),
|
||||
);
|
||||
.if_true(self.flags.contains(Flags::CONTENT_DISPOSITION), |res| {
|
||||
res.header(
|
||||
header::CONTENT_DISPOSITION,
|
||||
self.content_disposition.to_string(),
|
||||
);
|
||||
});
|
||||
if let Some(current_encoding) = self.encoding {
|
||||
resp.encoding(current_encoding);
|
||||
}
|
||||
@ -311,8 +324,8 @@ impl Responder for NamedFile {
|
||||
return Ok(resp.streaming(reader));
|
||||
}
|
||||
|
||||
match req.method() {
|
||||
&Method::HEAD | &Method::GET => (),
|
||||
match *req.method() {
|
||||
Method::HEAD | Method::GET => (),
|
||||
_ => {
|
||||
return Ok(HttpResponse::MethodNotAllowed()
|
||||
.header(header::CONTENT_TYPE, "text/plain")
|
||||
@ -368,10 +381,12 @@ impl Responder for NamedFile {
|
||||
|
||||
let mut resp = HttpResponse::build(self.status_code);
|
||||
resp.set(header::ContentType(self.content_type.clone()))
|
||||
.header(
|
||||
header::CONTENT_DISPOSITION,
|
||||
self.content_disposition.to_string(),
|
||||
);
|
||||
.if_true(self.flags.contains(Flags::CONTENT_DISPOSITION), |res| {
|
||||
res.header(
|
||||
header::CONTENT_DISPOSITION,
|
||||
self.content_disposition.to_string(),
|
||||
);
|
||||
});
|
||||
// default compressing
|
||||
if let Some(current_encoding) = self.encoding {
|
||||
resp.encoding(current_encoding);
|
||||
|
@ -5,7 +5,7 @@ pub struct HttpRange {
|
||||
pub length: u64,
|
||||
}
|
||||
|
||||
static PREFIX: &'static str = "bytes=";
|
||||
static PREFIX: &str = "bytes=";
|
||||
const PREFIX_LEN: usize = 6;
|
||||
|
||||
impl HttpRange {
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-framed"
|
||||
version = "0.2.0"
|
||||
version = "0.2.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix framed app server"
|
||||
readme = "README.md"
|
||||
@ -21,18 +21,18 @@ path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-codec = "0.1.2"
|
||||
actix-service = "0.4.0"
|
||||
actix-utils = "0.4.0"
|
||||
actix-service = "0.4.1"
|
||||
actix-router = "0.1.2"
|
||||
actix-rt = "0.2.2"
|
||||
actix-http = "0.2.0"
|
||||
actix-server-config = "0.1.1"
|
||||
actix-http = "0.2.7"
|
||||
actix-server-config = "0.1.2"
|
||||
|
||||
bytes = "0.4"
|
||||
futures = "0.1.25"
|
||||
log = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-server = { version = "0.5.0", features=["ssl"] }
|
||||
actix-server = { version = "0.6.0", features=["ssl"] }
|
||||
actix-connect = { version = "0.2.0", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.4", features=["ssl"] }
|
||||
actix-utils = "0.4.4"
|
||||
|
@ -1,5 +1,10 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.1] - 2019-07-20
|
||||
|
||||
* Remove unneeded actix-utils dependency
|
||||
|
||||
|
||||
## [0.2.0] - 2019-05-12
|
||||
|
||||
* Update dependencies
|
||||
|
@ -6,14 +6,13 @@ use actix_http::{Error, Request, Response};
|
||||
use actix_router::{Path, Router, Url};
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{IntoNewService, NewService, Service};
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use crate::helpers::{BoxedHttpNewService, BoxedHttpService, HttpNewService};
|
||||
use crate::request::FramedRequest;
|
||||
use crate::state::State;
|
||||
|
||||
type BoxedResponse = Box<Future<Item = (), Error = Error>>;
|
||||
type BoxedResponse = Box<dyn Future<Item = (), Error = Error>>;
|
||||
|
||||
pub trait HttpServiceFactory {
|
||||
type Factory: NewService;
|
||||
@ -61,7 +60,7 @@ impl<T: 'static, S: 'static> FramedApp<T, S> {
|
||||
Request = FramedRequest<T, S>,
|
||||
Response = (),
|
||||
Error = Error,
|
||||
Future = Box<Future<Item = (), Error = Error>>,
|
||||
Future = Box<dyn Future<Item = (), Error = Error>>,
|
||||
>,
|
||||
{
|
||||
let path = factory.path().to_string();
|
||||
@ -100,7 +99,7 @@ where
|
||||
type Response = ();
|
||||
type Error = Error;
|
||||
type InitError = ();
|
||||
type Service = CloneableService<FramedAppService<T, S>>;
|
||||
type Service = FramedAppService<T, S>;
|
||||
type Future = CreateService<T, S>;
|
||||
|
||||
fn new_service(&self, _: &ServerConfig) -> Self::Future {
|
||||
@ -129,7 +128,7 @@ pub struct CreateService<T, S> {
|
||||
enum CreateServiceItem<T, S> {
|
||||
Future(
|
||||
Option<String>,
|
||||
Box<Future<Item = BoxedHttpService<FramedRequest<T, S>>, Error = ()>>,
|
||||
Box<dyn Future<Item = BoxedHttpService<FramedRequest<T, S>>, Error = ()>>,
|
||||
),
|
||||
Service(String, BoxedHttpService<FramedRequest<T, S>>),
|
||||
}
|
||||
@ -138,7 +137,7 @@ impl<S: 'static, T: 'static> Future for CreateService<T, S>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
{
|
||||
type Item = CloneableService<FramedAppService<T, S>>;
|
||||
type Item = FramedAppService<T, S>;
|
||||
type Error = ();
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
@ -177,10 +176,10 @@ where
|
||||
}
|
||||
router
|
||||
});
|
||||
Ok(Async::Ready(CloneableService::new(FramedAppService {
|
||||
Ok(Async::Ready(FramedAppService {
|
||||
router: router.finish(),
|
||||
state: self.state.clone(),
|
||||
})))
|
||||
}))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
|
@ -3,23 +3,23 @@ use actix_service::{NewService, Service};
|
||||
use futures::{Future, Poll};
|
||||
|
||||
pub(crate) type BoxedHttpService<Req> = Box<
|
||||
Service<
|
||||
dyn Service<
|
||||
Request = Req,
|
||||
Response = (),
|
||||
Error = Error,
|
||||
Future = Box<Future<Item = (), Error = Error>>,
|
||||
Future = Box<dyn Future<Item = (), Error = Error>>,
|
||||
>,
|
||||
>;
|
||||
|
||||
pub(crate) type BoxedHttpNewService<Req> = Box<
|
||||
NewService<
|
||||
dyn NewService<
|
||||
Config = (),
|
||||
Request = Req,
|
||||
Response = (),
|
||||
Error = Error,
|
||||
InitError = (),
|
||||
Service = BoxedHttpService<Req>,
|
||||
Future = Box<Future<Item = BoxedHttpService<Req>, Error = ()>>,
|
||||
Future = Box<dyn Future<Item = BoxedHttpService<Req>, Error = ()>>,
|
||||
>,
|
||||
>;
|
||||
|
||||
@ -30,7 +30,7 @@ where
|
||||
T: NewService<Response = (), Error = Error>,
|
||||
T::Response: 'static,
|
||||
T::Future: 'static,
|
||||
T::Service: Service<Future = Box<Future<Item = (), Error = Error>>> + 'static,
|
||||
T::Service: Service<Future = Box<dyn Future<Item = (), Error = Error>>> + 'static,
|
||||
<T::Service as Service>::Future: 'static,
|
||||
{
|
||||
pub fn new(service: T) -> Self {
|
||||
@ -43,7 +43,7 @@ where
|
||||
T: NewService<Config = (), Response = (), Error = Error>,
|
||||
T::Request: 'static,
|
||||
T::Future: 'static,
|
||||
T::Service: Service<Future = Box<Future<Item = (), Error = Error>>> + 'static,
|
||||
T::Service: Service<Future = Box<dyn Future<Item = (), Error = Error>>> + 'static,
|
||||
<T::Service as Service>::Future: 'static,
|
||||
{
|
||||
type Config = ();
|
||||
@ -52,7 +52,7 @@ where
|
||||
type Error = Error;
|
||||
type InitError = ();
|
||||
type Service = BoxedHttpService<T::Request>;
|
||||
type Future = Box<Future<Item = Self::Service, Error = ()>>;
|
||||
type Future = Box<dyn Future<Item = Self::Service, Error = ()>>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
Box::new(self.0.new_service(&()).map_err(|_| ()).and_then(|service| {
|
||||
@ -70,7 +70,7 @@ impl<T> Service for HttpServiceWrapper<T>
|
||||
where
|
||||
T: Service<
|
||||
Response = (),
|
||||
Future = Box<Future<Item = (), Error = Error>>,
|
||||
Future = Box<dyn Future<Item = (), Error = Error>>,
|
||||
Error = Error,
|
||||
>,
|
||||
T::Request: 'static,
|
||||
@ -78,7 +78,7 @@ where
|
||||
type Request = T::Request;
|
||||
type Response = ();
|
||||
type Error = Error;
|
||||
type Future = Box<Future<Item = (), Error = Error>>;
|
||||
type Future = Box<dyn Future<Item = (), Error = Error>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.service.poll_ready()
|
||||
|
@ -1,3 +1,4 @@
|
||||
#![allow(clippy::type_complexity, clippy::new_without_default, dead_code)]
|
||||
mod app;
|
||||
mod helpers;
|
||||
mod request;
|
||||
|
@ -140,7 +140,7 @@ where
|
||||
type Request = FramedRequest<Io, S>;
|
||||
type Response = ();
|
||||
type Error = Error;
|
||||
type Future = Box<Future<Item = (), Error = Error>>;
|
||||
type Future = Box<dyn Future<Item = (), Error = Error>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
|
@ -1,5 +1,62 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.11] - 2019-09-11
|
||||
|
||||
### Added
|
||||
|
||||
* Add support for sending HTTP requests with `Rc<RequestHead>` in addition to sending HTTP requests with `RequestHead`
|
||||
|
||||
### Fixed
|
||||
|
||||
* on_connect result isn't added to request extensions for http2 requests #1009
|
||||
|
||||
|
||||
## [0.2.9] - 2019-08-13
|
||||
|
||||
### Changed
|
||||
|
||||
* Dropped the `byteorder`-dependency in favor of `stdlib`-implementation
|
||||
|
||||
* Update percent-encoding to 2.1
|
||||
|
||||
* Update serde_urlencoded to 0.6.1
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fixed a panic in the HTTP2 handshake in client HTTP requests (#1031)
|
||||
|
||||
|
||||
## [0.2.8] - 2019-08-01
|
||||
|
||||
### Added
|
||||
|
||||
* Add `rustls` support
|
||||
|
||||
* Add `Clone` impl for `HeaderMap`
|
||||
|
||||
### Fixed
|
||||
|
||||
* awc client panic #1016
|
||||
|
||||
* Invalid response with compression middleware enabled, but compression-related features disabled #997
|
||||
|
||||
|
||||
## [0.2.7] - 2019-07-18
|
||||
|
||||
### Added
|
||||
|
||||
* Add support for downcasting response errors #986
|
||||
|
||||
|
||||
## [0.2.6] - 2019-07-17
|
||||
|
||||
### Changed
|
||||
|
||||
* Replace `ClonableService` with local copy
|
||||
|
||||
* Upgrade `rand` dependency version to 0.7
|
||||
|
||||
|
||||
## [0.2.5] - 2019-06-28
|
||||
|
||||
### Added
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-http"
|
||||
version = "0.2.5"
|
||||
version = "0.2.10"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix http primitives"
|
||||
readme = "README.md"
|
||||
@ -28,6 +28,9 @@ default = []
|
||||
# openssl
|
||||
ssl = ["openssl", "actix-connect/ssl"]
|
||||
|
||||
# rustls support
|
||||
rust-tls = ["rustls", "webpki-roots", "actix-connect/rust-tls"]
|
||||
|
||||
# brotli encoding, requires c compiler
|
||||
brotli = ["brotli2"]
|
||||
|
||||
@ -46,16 +49,15 @@ secure-cookies = ["ring"]
|
||||
[dependencies]
|
||||
actix-service = "0.4.1"
|
||||
actix-codec = "0.1.2"
|
||||
actix-connect = "0.2.0"
|
||||
actix-utils = "0.4.2"
|
||||
actix-server-config = "0.1.1"
|
||||
actix-threadpool = "0.1.0"
|
||||
actix-connect = "0.2.4"
|
||||
actix-utils = "0.4.4"
|
||||
actix-server-config = "0.1.2"
|
||||
actix-threadpool = "0.1.1"
|
||||
|
||||
base64 = "0.10"
|
||||
bitflags = "1.0"
|
||||
bytes = "0.4"
|
||||
byteorder = "1.2"
|
||||
copyless = "0.1.2"
|
||||
copyless = "0.1.4"
|
||||
derive_more = "0.15.0"
|
||||
either = "1.5.2"
|
||||
encoding_rs = "0.8"
|
||||
@ -69,14 +71,14 @@ lazy_static = "1.0"
|
||||
language-tags = "0.2"
|
||||
log = "0.4"
|
||||
mime = "0.3"
|
||||
percent-encoding = "1.0"
|
||||
rand = "0.6"
|
||||
percent-encoding = "2.1"
|
||||
rand = "0.7"
|
||||
regex = "1.0"
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
sha1 = "0.6"
|
||||
slab = "0.4"
|
||||
serde_urlencoded = "0.5.5"
|
||||
serde_urlencoded = "0.6.1"
|
||||
time = "0.1.42"
|
||||
tokio-tcp = "0.1.3"
|
||||
tokio-timer = "0.2.8"
|
||||
@ -93,13 +95,15 @@ flate2 = { version="1.0.7", optional = true, default-features = false }
|
||||
# optional deps
|
||||
failure = { version = "0.1.5", optional = true }
|
||||
openssl = { version="0.10", optional = true }
|
||||
rustls = { version = "0.15.2", optional = true }
|
||||
webpki-roots = { version = "0.16", optional = true }
|
||||
chrono = "0.4.6"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.2"
|
||||
actix-server = { version = "0.5.0", features=["ssl"] }
|
||||
actix-server = { version = "0.6.0", features=["ssl", "rust-tls"] }
|
||||
actix-connect = { version = "0.2.0", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.4", features=["ssl"] }
|
||||
env_logger = "0.6"
|
||||
serde_derive = "1.0"
|
||||
openssl = { version="0.10" }
|
||||
|
@ -26,7 +26,7 @@ pub struct HttpServiceBuilder<T, S, X = ExpectHandler, U = UpgradeHandler<T>> {
|
||||
client_disconnect: u64,
|
||||
expect: X,
|
||||
upgrade: Option<U>,
|
||||
on_connect: Option<Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
_t: PhantomData<(T, S)>,
|
||||
}
|
||||
|
||||
@ -199,6 +199,7 @@ where
|
||||
self.client_disconnect,
|
||||
);
|
||||
H2Service::with_config(cfg, service.into_new_service())
|
||||
.on_connect(self.on_connect)
|
||||
}
|
||||
|
||||
/// Finish service configuration and create `HttpService` instance.
|
||||
|
@ -8,7 +8,7 @@ use h2::client::SendRequest;
|
||||
|
||||
use crate::body::MessageBody;
|
||||
use crate::h1::ClientCodec;
|
||||
use crate::message::{RequestHead, ResponseHead};
|
||||
use crate::message::{RequestHeadType, ResponseHead};
|
||||
use crate::payload::Payload;
|
||||
|
||||
use super::error::SendRequestError;
|
||||
@ -27,9 +27,9 @@ pub trait Connection {
|
||||
fn protocol(&self) -> Protocol;
|
||||
|
||||
/// Send request and body
|
||||
fn send_request<B: MessageBody + 'static>(
|
||||
fn send_request<B: MessageBody + 'static, H: Into<RequestHeadType>>(
|
||||
self,
|
||||
head: RequestHead,
|
||||
head: H,
|
||||
body: B,
|
||||
) -> Self::Future;
|
||||
|
||||
@ -39,7 +39,7 @@ pub trait Connection {
|
||||
>;
|
||||
|
||||
/// Send request, returns Response and Framed
|
||||
fn open_tunnel(self, head: RequestHead) -> Self::TunnelFuture;
|
||||
fn open_tunnel<H: Into<RequestHeadType>>(self, head: H) -> Self::TunnelFuture;
|
||||
}
|
||||
|
||||
pub(crate) trait ConnectionLifetime: AsyncRead + AsyncWrite + 'static {
|
||||
@ -94,7 +94,8 @@ where
|
||||
T: AsyncRead + AsyncWrite + 'static,
|
||||
{
|
||||
type Io = T;
|
||||
type Future = Box<Future<Item = (ResponseHead, Payload), Error = SendRequestError>>;
|
||||
type Future =
|
||||
Box<dyn Future<Item = (ResponseHead, Payload), Error = SendRequestError>>;
|
||||
|
||||
fn protocol(&self) -> Protocol {
|
||||
match self.io {
|
||||
@ -104,22 +105,22 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn send_request<B: MessageBody + 'static>(
|
||||
fn send_request<B: MessageBody + 'static, H: Into<RequestHeadType>>(
|
||||
mut self,
|
||||
head: RequestHead,
|
||||
head: H,
|
||||
body: B,
|
||||
) -> Self::Future {
|
||||
match self.io.take().unwrap() {
|
||||
ConnectionType::H1(io) => Box::new(h1proto::send_request(
|
||||
io,
|
||||
head,
|
||||
head.into(),
|
||||
body,
|
||||
self.created,
|
||||
self.pool,
|
||||
)),
|
||||
ConnectionType::H2(io) => Box::new(h2proto::send_request(
|
||||
io,
|
||||
head,
|
||||
head.into(),
|
||||
body,
|
||||
self.created,
|
||||
self.pool,
|
||||
@ -129,7 +130,7 @@ where
|
||||
|
||||
type TunnelFuture = Either<
|
||||
Box<
|
||||
Future<
|
||||
dyn Future<
|
||||
Item = (ResponseHead, Framed<Self::Io, ClientCodec>),
|
||||
Error = SendRequestError,
|
||||
>,
|
||||
@ -138,10 +139,10 @@ where
|
||||
>;
|
||||
|
||||
/// Send request, returns Response and Framed
|
||||
fn open_tunnel(mut self, head: RequestHead) -> Self::TunnelFuture {
|
||||
fn open_tunnel<H: Into<RequestHeadType>>(mut self, head: H) -> Self::TunnelFuture {
|
||||
match self.io.take().unwrap() {
|
||||
ConnectionType::H1(io) => {
|
||||
Either::A(Box::new(h1proto::open_tunnel(io, head)))
|
||||
Either::A(Box::new(h1proto::open_tunnel(io, head.into())))
|
||||
}
|
||||
ConnectionType::H2(io) => {
|
||||
if let Some(mut pool) = self.pool.take() {
|
||||
@ -169,7 +170,8 @@ where
|
||||
B: AsyncRead + AsyncWrite + 'static,
|
||||
{
|
||||
type Io = EitherIo<A, B>;
|
||||
type Future = Box<Future<Item = (ResponseHead, Payload), Error = SendRequestError>>;
|
||||
type Future =
|
||||
Box<dyn Future<Item = (ResponseHead, Payload), Error = SendRequestError>>;
|
||||
|
||||
fn protocol(&self) -> Protocol {
|
||||
match self {
|
||||
@ -178,9 +180,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn send_request<RB: MessageBody + 'static>(
|
||||
fn send_request<RB: MessageBody + 'static, H: Into<RequestHeadType>>(
|
||||
self,
|
||||
head: RequestHead,
|
||||
head: H,
|
||||
body: RB,
|
||||
) -> Self::Future {
|
||||
match self {
|
||||
@ -190,14 +192,14 @@ where
|
||||
}
|
||||
|
||||
type TunnelFuture = Box<
|
||||
Future<
|
||||
dyn Future<
|
||||
Item = (ResponseHead, Framed<Self::Io, ClientCodec>),
|
||||
Error = SendRequestError,
|
||||
>,
|
||||
>;
|
||||
|
||||
/// Send request, returns Response and Framed
|
||||
fn open_tunnel(self, head: RequestHead) -> Self::TunnelFuture {
|
||||
fn open_tunnel<H: Into<RequestHeadType>>(self, head: H) -> Self::TunnelFuture {
|
||||
match self {
|
||||
EitherConnection::A(con) => Box::new(
|
||||
con.open_tunnel(head)
|
||||
|
@ -17,9 +17,21 @@ use super::pool::{ConnectionPool, Protocol};
|
||||
use super::Connect;
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
use openssl::ssl::SslConnector;
|
||||
use openssl::ssl::SslConnector as OpensslConnector;
|
||||
|
||||
#[cfg(not(feature = "ssl"))]
|
||||
#[cfg(feature = "rust-tls")]
|
||||
use rustls::ClientConfig;
|
||||
#[cfg(feature = "rust-tls")]
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(any(feature = "ssl", feature = "rust-tls"))]
|
||||
enum SslConnector {
|
||||
#[cfg(feature = "ssl")]
|
||||
Openssl(OpensslConnector),
|
||||
#[cfg(feature = "rust-tls")]
|
||||
Rustls(Arc<ClientConfig>),
|
||||
}
|
||||
#[cfg(not(any(feature = "ssl", feature = "rust-tls")))]
|
||||
type SslConnector = ();
|
||||
|
||||
/// Manages http client network connectivity
|
||||
@ -46,7 +58,11 @@ pub struct Connector<T, U> {
|
||||
_t: PhantomData<U>,
|
||||
}
|
||||
|
||||
trait Io: AsyncRead + AsyncWrite {}
|
||||
impl<T: AsyncRead + AsyncWrite> Io for T {}
|
||||
|
||||
impl Connector<(), ()> {
|
||||
#[allow(clippy::new_ret_no_self)]
|
||||
pub fn new() -> Connector<
|
||||
impl Service<
|
||||
Request = TcpConnect<Uri>,
|
||||
@ -60,13 +76,23 @@ impl Connector<(), ()> {
|
||||
{
|
||||
use openssl::ssl::SslMethod;
|
||||
|
||||
let mut ssl = SslConnector::builder(SslMethod::tls()).unwrap();
|
||||
let mut ssl = OpensslConnector::builder(SslMethod::tls()).unwrap();
|
||||
let _ = ssl
|
||||
.set_alpn_protos(b"\x02h2\x08http/1.1")
|
||||
.map_err(|e| error!("Can not set alpn protocol: {:?}", e));
|
||||
ssl.build()
|
||||
SslConnector::Openssl(ssl.build())
|
||||
}
|
||||
#[cfg(not(feature = "ssl"))]
|
||||
#[cfg(all(not(feature = "ssl"), feature = "rust-tls"))]
|
||||
{
|
||||
let protos = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
|
||||
let mut config = ClientConfig::new();
|
||||
config.set_protocols(&protos);
|
||||
config
|
||||
.root_store
|
||||
.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
|
||||
SslConnector::Rustls(Arc::new(config))
|
||||
}
|
||||
#[cfg(not(any(feature = "ssl", feature = "rust-tls")))]
|
||||
{}
|
||||
};
|
||||
|
||||
@ -126,8 +152,14 @@ where
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
/// Use custom `SslConnector` instance.
|
||||
pub fn ssl(mut self, connector: SslConnector) -> Self {
|
||||
self.ssl = connector;
|
||||
pub fn ssl(mut self, connector: OpensslConnector) -> Self {
|
||||
self.ssl = SslConnector::Openssl(connector);
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-tls")]
|
||||
pub fn rustls(mut self, connector: Arc<ClientConfig>) -> Self {
|
||||
self.ssl = SslConnector::Rustls(connector);
|
||||
self
|
||||
}
|
||||
|
||||
@ -181,7 +213,7 @@ where
|
||||
self,
|
||||
) -> impl Service<Request = Connect, Response = impl Connection, Error = ConnectError>
|
||||
+ Clone {
|
||||
#[cfg(not(feature = "ssl"))]
|
||||
#[cfg(not(any(feature = "ssl", feature = "rust-tls")))]
|
||||
{
|
||||
let connector = TimeoutService::new(
|
||||
self.timeout,
|
||||
@ -206,10 +238,16 @@ where
|
||||
),
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "ssl")]
|
||||
#[cfg(any(feature = "ssl", feature = "rust-tls"))]
|
||||
{
|
||||
const H2: &[u8] = b"h2";
|
||||
#[cfg(feature = "ssl")]
|
||||
use actix_connect::ssl::OpensslConnector;
|
||||
#[cfg(feature = "rust-tls")]
|
||||
use actix_connect::ssl::RustlsConnector;
|
||||
use actix_service::boxed::service;
|
||||
#[cfg(feature = "rust-tls")]
|
||||
use rustls::Session;
|
||||
|
||||
let ssl_service = TimeoutService::new(
|
||||
self.timeout,
|
||||
@ -217,24 +255,46 @@ where
|
||||
srv.call(TcpConnect::new(msg.uri).set_addr(msg.addr))
|
||||
})
|
||||
.map_err(ConnectError::from)
|
||||
.and_then(
|
||||
OpensslConnector::service(self.ssl)
|
||||
.map_err(ConnectError::from)
|
||||
.map(|stream| {
|
||||
let sock = stream.into_parts().0;
|
||||
let h2 = sock
|
||||
.get_ref()
|
||||
.ssl()
|
||||
.selected_alpn_protocol()
|
||||
.map(|protos| protos.windows(2).any(|w| w == H2))
|
||||
.unwrap_or(false);
|
||||
if h2 {
|
||||
(sock, Protocol::Http2)
|
||||
} else {
|
||||
(sock, Protocol::Http1)
|
||||
}
|
||||
}),
|
||||
),
|
||||
.and_then(match self.ssl {
|
||||
#[cfg(feature = "ssl")]
|
||||
SslConnector::Openssl(ssl) => service(
|
||||
OpensslConnector::service(ssl)
|
||||
.map_err(ConnectError::from)
|
||||
.map(|stream| {
|
||||
let sock = stream.into_parts().0;
|
||||
let h2 = sock
|
||||
.get_ref()
|
||||
.ssl()
|
||||
.selected_alpn_protocol()
|
||||
.map(|protos| protos.windows(2).any(|w| w == H2))
|
||||
.unwrap_or(false);
|
||||
if h2 {
|
||||
(Box::new(sock) as Box<dyn Io>, Protocol::Http2)
|
||||
} else {
|
||||
(Box::new(sock) as Box<dyn Io>, Protocol::Http1)
|
||||
}
|
||||
}),
|
||||
),
|
||||
#[cfg(feature = "rust-tls")]
|
||||
SslConnector::Rustls(ssl) => service(
|
||||
RustlsConnector::service(ssl)
|
||||
.map_err(ConnectError::from)
|
||||
.map(|stream| {
|
||||
let sock = stream.into_parts().0;
|
||||
let h2 = sock
|
||||
.get_ref()
|
||||
.1
|
||||
.get_alpn_protocol()
|
||||
.map(|protos| protos.windows(2).any(|w| w == H2))
|
||||
.unwrap_or(false);
|
||||
if h2 {
|
||||
(Box::new(sock) as Box<dyn Io>, Protocol::Http2)
|
||||
} else {
|
||||
(Box::new(sock) as Box<dyn Io>, Protocol::Http1)
|
||||
}
|
||||
}),
|
||||
),
|
||||
}),
|
||||
)
|
||||
.map_err(|e| match e {
|
||||
TimeoutError::Service(e) => e,
|
||||
@ -274,7 +334,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "ssl"))]
|
||||
#[cfg(not(any(feature = "ssl", feature = "rust-tls")))]
|
||||
mod connect_impl {
|
||||
use futures::future::{err, Either, FutureResult};
|
||||
use futures::Poll;
|
||||
@ -336,7 +396,7 @@ mod connect_impl {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[cfg(any(feature = "ssl", feature = "rust-tls"))]
|
||||
mod connect_impl {
|
||||
use std::marker::PhantomData;
|
||||
|
||||
|
@ -128,3 +128,23 @@ impl ResponseError for SendRequestError {
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
/// A set of errors that can occur during freezing a request
|
||||
#[derive(Debug, Display, From)]
|
||||
pub enum FreezeRequestError {
|
||||
/// Invalid URL
|
||||
#[display(fmt = "Invalid URL: {}", _0)]
|
||||
Url(InvalidUrl),
|
||||
/// Http error
|
||||
#[display(fmt = "{}", _0)]
|
||||
Http(HttpError),
|
||||
}
|
||||
|
||||
impl From<FreezeRequestError> for SendRequestError {
|
||||
fn from(e: FreezeRequestError) -> Self {
|
||||
match e {
|
||||
FreezeRequestError::Url(e) => e.into(),
|
||||
FreezeRequestError::Http(e) => e.into(),
|
||||
}
|
||||
}
|
||||
}
|
@ -9,8 +9,9 @@ use futures::{Async, Future, Poll, Sink, Stream};
|
||||
use crate::error::PayloadError;
|
||||
use crate::h1;
|
||||
use crate::http::header::{IntoHeaderValue, HOST};
|
||||
use crate::message::{RequestHead, ResponseHead};
|
||||
use crate::message::{RequestHeadType, ResponseHead};
|
||||
use crate::payload::{Payload, PayloadStream};
|
||||
use crate::header::HeaderMap;
|
||||
|
||||
use super::connection::{ConnectionLifetime, ConnectionType, IoConnection};
|
||||
use super::error::{ConnectError, SendRequestError};
|
||||
@ -19,7 +20,7 @@ use crate::body::{BodySize, MessageBody};
|
||||
|
||||
pub(crate) fn send_request<T, B>(
|
||||
io: T,
|
||||
mut head: RequestHead,
|
||||
mut head: RequestHeadType,
|
||||
body: B,
|
||||
created: time::Instant,
|
||||
pool: Option<Acquired<T>>,
|
||||
@ -29,21 +30,29 @@ where
|
||||
B: MessageBody,
|
||||
{
|
||||
// set request host header
|
||||
if !head.headers.contains_key(HOST) {
|
||||
if let Some(host) = head.uri.host() {
|
||||
if !head.as_ref().headers.contains_key(HOST) && !head.extra_headers().iter().any(|h| h.contains_key(HOST)) {
|
||||
if let Some(host) = head.as_ref().uri.host() {
|
||||
let mut wrt = BytesMut::with_capacity(host.len() + 5).writer();
|
||||
|
||||
let _ = match head.uri.port_u16() {
|
||||
let _ = match head.as_ref().uri.port_u16() {
|
||||
None | Some(80) | Some(443) => write!(wrt, "{}", host),
|
||||
Some(port) => write!(wrt, "{}:{}", host, port),
|
||||
};
|
||||
|
||||
match wrt.get_mut().take().freeze().try_into() {
|
||||
Ok(value) => {
|
||||
head.headers.insert(HOST, value);
|
||||
match head {
|
||||
RequestHeadType::Owned(ref mut head) => {
|
||||
head.headers.insert(HOST, value)
|
||||
},
|
||||
RequestHeadType::Rc(_, ref mut extra_headers) => {
|
||||
let headers = extra_headers.get_or_insert(HeaderMap::new());
|
||||
headers.insert(HOST, value)
|
||||
},
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Can not set HOST header {}", e);
|
||||
log::error!("Can not set HOST header {}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -57,7 +66,7 @@ where
|
||||
|
||||
let len = body.size();
|
||||
|
||||
// create Framed and send reqest
|
||||
// create Framed and send request
|
||||
Framed::new(io, h1::ClientCodec::default())
|
||||
.send((head, len).into())
|
||||
.from_err()
|
||||
@ -95,12 +104,12 @@ where
|
||||
|
||||
pub(crate) fn open_tunnel<T>(
|
||||
io: T,
|
||||
head: RequestHead,
|
||||
head: RequestHeadType,
|
||||
) -> impl Future<Item = (ResponseHead, Framed<T, h1::ClientCodec>), Error = SendRequestError>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + 'static,
|
||||
{
|
||||
// create Framed and send reqest
|
||||
// create Framed and send request
|
||||
Framed::new(io, h1::ClientCodec::default())
|
||||
.send((head, BodySize::None).into())
|
||||
.from_err()
|
||||
|
@ -9,8 +9,9 @@ use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, TRANSFER_ENCODING};
|
||||
use http::{request::Request, HttpTryFrom, Method, Version};
|
||||
|
||||
use crate::body::{BodySize, MessageBody};
|
||||
use crate::message::{RequestHead, ResponseHead};
|
||||
use crate::message::{RequestHeadType, ResponseHead};
|
||||
use crate::payload::Payload;
|
||||
use crate::header::HeaderMap;
|
||||
|
||||
use super::connection::{ConnectionType, IoConnection};
|
||||
use super::error::SendRequestError;
|
||||
@ -18,7 +19,7 @@ use super::pool::Acquired;
|
||||
|
||||
pub(crate) fn send_request<T, B>(
|
||||
io: SendRequest<Bytes>,
|
||||
head: RequestHead,
|
||||
head: RequestHeadType,
|
||||
body: B,
|
||||
created: time::Instant,
|
||||
pool: Option<Acquired<T>>,
|
||||
@ -28,7 +29,7 @@ where
|
||||
B: MessageBody,
|
||||
{
|
||||
trace!("Sending client request: {:?} {:?}", head, body.size());
|
||||
let head_req = head.method == Method::HEAD;
|
||||
let head_req = head.as_ref().method == Method::HEAD;
|
||||
let length = body.size();
|
||||
let eof = match length {
|
||||
BodySize::None | BodySize::Empty | BodySize::Sized(0) => true,
|
||||
@ -39,8 +40,8 @@ where
|
||||
.map_err(SendRequestError::from)
|
||||
.and_then(move |mut io| {
|
||||
let mut req = Request::new(());
|
||||
*req.uri_mut() = head.uri;
|
||||
*req.method_mut() = head.method;
|
||||
*req.uri_mut() = head.as_ref().uri.clone();
|
||||
*req.method_mut() = head.as_ref().method.clone();
|
||||
*req.version_mut() = Version::HTTP_2;
|
||||
|
||||
let mut skip_len = true;
|
||||
@ -66,8 +67,21 @@ where
|
||||
),
|
||||
};
|
||||
|
||||
// Extracting extra headers from RequestHeadType. HeaderMap::new() does not allocate.
|
||||
let (head, extra_headers) = match head {
|
||||
RequestHeadType::Owned(head) => (RequestHeadType::Owned(head), HeaderMap::new()),
|
||||
RequestHeadType::Rc(head, extra_headers) => (RequestHeadType::Rc(head, None), extra_headers.unwrap_or(HeaderMap::new())),
|
||||
};
|
||||
|
||||
// merging headers from head and extra headers.
|
||||
let headers = head.as_ref().headers.iter()
|
||||
.filter(|(name, _)| {
|
||||
!extra_headers.contains_key(*name)
|
||||
})
|
||||
.chain(extra_headers.iter());
|
||||
|
||||
// copy headers
|
||||
for (key, value) in head.headers.iter() {
|
||||
for (key, value) in headers {
|
||||
match *key {
|
||||
CONNECTION | TRANSFER_ENCODING => continue, // http2 specific
|
||||
CONTENT_LENGTH if skip_len => continue,
|
||||
|
@ -10,7 +10,7 @@ mod pool;
|
||||
|
||||
pub use self::connection::Connection;
|
||||
pub use self::connector::Connector;
|
||||
pub use self::error::{ConnectError, InvalidUrl, SendRequestError};
|
||||
pub use self::error::{ConnectError, InvalidUrl, SendRequestError, FreezeRequestError};
|
||||
pub use self::pool::Protocol;
|
||||
|
||||
#[derive(Clone)]
|
||||
|
@ -305,10 +305,12 @@ pub(crate) struct Inner<Io> {
|
||||
limit: usize,
|
||||
acquired: usize,
|
||||
available: HashMap<Key, VecDeque<AvailableConnection<Io>>>,
|
||||
waiters: Slab<(
|
||||
Connect,
|
||||
oneshot::Sender<Result<IoConnection<Io>, ConnectError>>,
|
||||
)>,
|
||||
waiters: Slab<
|
||||
Option<(
|
||||
Connect,
|
||||
oneshot::Sender<Result<IoConnection<Io>, ConnectError>>,
|
||||
)>,
|
||||
>,
|
||||
waiters_queue: IndexSet<(Key, usize)>,
|
||||
task: Option<AtomicTask>,
|
||||
}
|
||||
@ -346,7 +348,7 @@ where
|
||||
let key: Key = connect.uri.authority_part().unwrap().clone().into();
|
||||
let entry = self.waiters.vacant_entry();
|
||||
let token = entry.key();
|
||||
entry.insert((connect, tx));
|
||||
entry.insert(Some((connect, tx)));
|
||||
assert!(self.waiters_queue.insert((key, token)));
|
||||
|
||||
(rx, token, self.task.is_some())
|
||||
@ -427,7 +429,9 @@ where
|
||||
|
||||
fn check_availibility(&self) {
|
||||
if !self.waiters_queue.is_empty() && self.acquired < self.limit {
|
||||
self.task.as_ref().map(|t| t.notify());
|
||||
if let Some(t) = self.task.as_ref() {
|
||||
t.notify()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -497,10 +501,14 @@ where
|
||||
break;
|
||||
}
|
||||
};
|
||||
if inner.waiters.get(token).unwrap().is_none() {
|
||||
continue;
|
||||
}
|
||||
|
||||
match inner.acquire(&key) {
|
||||
Acquire::NotAvailable => break,
|
||||
Acquire::Acquired(io, created) => {
|
||||
let (_, tx) = inner.waiters.remove(token);
|
||||
let tx = inner.waiters.get_mut(token).unwrap().take().unwrap().1;
|
||||
if let Err(conn) = tx.send(Ok(IoConnection::new(
|
||||
io,
|
||||
created,
|
||||
@ -511,7 +519,8 @@ where
|
||||
}
|
||||
}
|
||||
Acquire::Available => {
|
||||
let (connect, tx) = inner.waiters.remove(token);
|
||||
let (connect, tx) =
|
||||
inner.waiters.get_mut(token).unwrap().take().unwrap();
|
||||
OpenWaitingConnection::spawn(
|
||||
key.clone(),
|
||||
tx,
|
||||
@ -581,6 +590,29 @@ where
|
||||
type Error = ();
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Some(ref mut h2) = self.h2 {
|
||||
return match h2.poll() {
|
||||
Ok(Async::Ready((snd, connection))) => {
|
||||
tokio_current_thread::spawn(connection.map_err(|_| ()));
|
||||
let rx = self.rx.take().unwrap();
|
||||
let _ = rx.send(Ok(IoConnection::new(
|
||||
ConnectionType::H2(snd),
|
||||
Instant::now(),
|
||||
Some(Acquired(self.key.clone(), self.inner.take())),
|
||||
)));
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Err(err) => {
|
||||
let _ = self.inner.take();
|
||||
if let Some(rx) = self.rx.take() {
|
||||
let _ = rx.send(Err(ConnectError::H2(err)));
|
||||
}
|
||||
Err(())
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
match self.fut.poll() {
|
||||
Err(err) => {
|
||||
let _ = self.inner.take();
|
||||
|
42
actix-http/src/cloneable.rs
Normal file
42
actix-http/src/cloneable.rs
Normal file
@ -0,0 +1,42 @@
|
||||
use std::cell::UnsafeCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_service::Service;
|
||||
use futures::Poll;
|
||||
|
||||
#[doc(hidden)]
|
||||
/// Service that allows to turn non-clone service to a service with `Clone` impl
|
||||
pub(crate) struct CloneableService<T>(Rc<UnsafeCell<T>>);
|
||||
|
||||
impl<T> CloneableService<T> {
|
||||
pub(crate) fn new(service: T) -> Self
|
||||
where
|
||||
T: Service,
|
||||
{
|
||||
Self(Rc::new(UnsafeCell::new(service)))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for CloneableService<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Service for CloneableService<T>
|
||||
where
|
||||
T: Service,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Future = T::Future;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
unsafe { &mut *self.0.as_ref().get() }.poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: T::Request) -> Self::Future {
|
||||
unsafe { &mut *self.0.as_ref().get() }.call(req)
|
||||
}
|
||||
}
|
@ -162,16 +162,21 @@ impl ServiceConfig {
|
||||
pub fn set_date(&self, dst: &mut BytesMut) {
|
||||
let mut buf: [u8; 39] = [0; 39];
|
||||
buf[..6].copy_from_slice(b"date: ");
|
||||
buf[6..35].copy_from_slice(&self.0.timer.date().bytes);
|
||||
self.0
|
||||
.timer
|
||||
.set_date(|date| buf[6..35].copy_from_slice(&date.bytes));
|
||||
buf[35..].copy_from_slice(b"\r\n\r\n");
|
||||
dst.extend_from_slice(&buf);
|
||||
}
|
||||
|
||||
pub(crate) fn set_date_header(&self, dst: &mut BytesMut) {
|
||||
dst.extend_from_slice(&self.0.timer.date().bytes);
|
||||
self.0
|
||||
.timer
|
||||
.set_date(|date| dst.extend_from_slice(&date.bytes));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
struct Date {
|
||||
bytes: [u8; DATE_VALUE_LENGTH],
|
||||
pos: usize,
|
||||
@ -215,10 +220,6 @@ impl DateServiceInner {
|
||||
}
|
||||
}
|
||||
|
||||
fn get_ref(&self) -> &Option<(Date, Instant)> {
|
||||
unsafe { &*self.current.get() }
|
||||
}
|
||||
|
||||
fn reset(&self) {
|
||||
unsafe { (&mut *self.current.get()).take() };
|
||||
}
|
||||
@ -236,7 +237,7 @@ impl DateService {
|
||||
}
|
||||
|
||||
fn check_date(&self) {
|
||||
if self.0.get_ref().is_none() {
|
||||
if unsafe { (&*self.0.current.get()).is_none() } {
|
||||
self.0.update();
|
||||
|
||||
// periodic date update
|
||||
@ -252,14 +253,12 @@ impl DateService {
|
||||
|
||||
fn now(&self) -> Instant {
|
||||
self.check_date();
|
||||
self.0.get_ref().as_ref().unwrap().1
|
||||
unsafe { (&*self.0.current.get()).as_ref().unwrap().1 }
|
||||
}
|
||||
|
||||
fn date(&self) -> &Date {
|
||||
fn set_date<F: FnMut(&Date)>(&self, mut f: F) {
|
||||
self.check_date();
|
||||
|
||||
let item = self.0.get_ref().as_ref().unwrap();
|
||||
&item.0
|
||||
f(&unsafe { (&*self.0.current.get()).as_ref().unwrap().0 })
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -66,7 +66,7 @@ use std::fmt;
|
||||
use std::str::FromStr;
|
||||
|
||||
use chrono::Duration;
|
||||
use percent_encoding::{percent_encode, USERINFO_ENCODE_SET};
|
||||
use percent_encoding::{percent_encode, AsciiSet, CONTROLS};
|
||||
use time::Tm;
|
||||
|
||||
pub use self::builder::CookieBuilder;
|
||||
@ -75,6 +75,25 @@ pub use self::jar::{CookieJar, Delta, Iter};
|
||||
use self::parse::parse_cookie;
|
||||
pub use self::parse::ParseError;
|
||||
|
||||
/// https://url.spec.whatwg.org/#fragment-percent-encode-set
|
||||
const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
|
||||
|
||||
/// https://url.spec.whatwg.org/#path-percent-encode-set
|
||||
const PATH: &AsciiSet = &FRAGMENT.add(b'#').add(b'?').add(b'{').add(b'}');
|
||||
|
||||
/// https://url.spec.whatwg.org/#userinfo-percent-encode-set
|
||||
pub const USERINFO: &AsciiSet = &PATH
|
||||
.add(b'/')
|
||||
.add(b':')
|
||||
.add(b';')
|
||||
.add(b'=')
|
||||
.add(b'@')
|
||||
.add(b'[')
|
||||
.add(b'\\')
|
||||
.add(b']')
|
||||
.add(b'^')
|
||||
.add(b'|');
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum CookieStr {
|
||||
/// An string derived from indexes (start, end).
|
||||
@ -104,6 +123,7 @@ impl CookieStr {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::ptr_arg)]
|
||||
fn to_raw_str<'s, 'c: 's>(&'s self, string: &'s Cow<'c, str>) -> Option<&'c str> {
|
||||
match *self {
|
||||
CookieStr::Indexed(i, j) => match *string {
|
||||
@ -909,8 +929,8 @@ pub struct EncodedCookie<'a, 'c: 'a>(&'a Cookie<'c>);
|
||||
impl<'a, 'c: 'a> fmt::Display for EncodedCookie<'a, 'c> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
// Percent-encode the name and value.
|
||||
let name = percent_encode(self.0.name().as_bytes(), USERINFO_ENCODE_SET);
|
||||
let value = percent_encode(self.0.value().as_bytes(), USERINFO_ENCODE_SET);
|
||||
let name = percent_encode(self.0.name().as_bytes(), USERINFO);
|
||||
let value = percent_encode(self.0.value().as_bytes(), USERINFO);
|
||||
|
||||
// Write out the name/value pair and the cookie's parameters.
|
||||
write!(f, "{}={}", name, value)?;
|
||||
|
@ -6,8 +6,8 @@ use ring::rand::{SecureRandom, SystemRandom};
|
||||
use super::private::KEY_LEN as PRIVATE_KEY_LEN;
|
||||
use super::signed::KEY_LEN as SIGNED_KEY_LEN;
|
||||
|
||||
static HKDF_DIGEST: &'static Algorithm = &SHA256;
|
||||
const KEYS_INFO: &'static str = "COOKIE;SIGNED:HMAC-SHA256;PRIVATE:AEAD-AES-256-GCM";
|
||||
static HKDF_DIGEST: &Algorithm = &SHA256;
|
||||
const KEYS_INFO: &str = "COOKIE;SIGNED:HMAC-SHA256;PRIVATE:AEAD-AES-256-GCM";
|
||||
|
||||
/// A cryptographic master key for use with `Signed` and/or `Private` jars.
|
||||
///
|
||||
|
@ -10,7 +10,7 @@ use crate::cookie::{Cookie, CookieJar};
|
||||
|
||||
// Keep these in sync, and keep the key len synced with the `private` docs as
|
||||
// well as the `KEYS_INFO` const in secure::Key.
|
||||
static ALGO: &'static Algorithm = &AES_256_GCM;
|
||||
static ALGO: &Algorithm = &AES_256_GCM;
|
||||
const NONCE_LEN: usize = 12;
|
||||
pub const KEY_LEN: usize = 32;
|
||||
|
||||
|
@ -6,7 +6,7 @@ use crate::cookie::{Cookie, CookieJar};
|
||||
|
||||
// Keep these in sync, and keep the key len synced with the `signed` docs as
|
||||
// well as the `KEYS_INFO` const in secure::Key.
|
||||
static HMAC_DIGEST: &'static Algorithm = &SHA256;
|
||||
static HMAC_DIGEST: &Algorithm = &SHA256;
|
||||
const BASE64_DIGEST_LEN: usize = 44;
|
||||
pub const KEY_LEN: usize = 32;
|
||||
|
||||
|
@ -54,22 +54,24 @@ impl<B: MessageBody> Encoder<B> {
|
||||
};
|
||||
|
||||
if can_encode {
|
||||
update_head(encoding, head);
|
||||
head.no_chunking(false);
|
||||
ResponseBody::Body(Encoder {
|
||||
body,
|
||||
eof: false,
|
||||
fut: None,
|
||||
encoder: ContentEncoder::encoder(encoding),
|
||||
})
|
||||
} else {
|
||||
ResponseBody::Body(Encoder {
|
||||
body,
|
||||
eof: false,
|
||||
fut: None,
|
||||
encoder: None,
|
||||
})
|
||||
// Modify response body only if encoder is not None
|
||||
if let Some(enc) = ContentEncoder::encoder(encoding) {
|
||||
update_head(encoding, head);
|
||||
head.no_chunking(false);
|
||||
return ResponseBody::Body(Encoder {
|
||||
body,
|
||||
eof: false,
|
||||
fut: None,
|
||||
encoder: Some(enc),
|
||||
});
|
||||
}
|
||||
}
|
||||
ResponseBody::Body(Encoder {
|
||||
body,
|
||||
eof: false,
|
||||
fut: None,
|
||||
encoder: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,4 +1,5 @@
|
||||
//! Error and Result module
|
||||
use std::any::TypeId;
|
||||
use std::cell::RefCell;
|
||||
use std::io::Write;
|
||||
use std::str::Utf8Error;
|
||||
@ -43,14 +44,19 @@ pub type Result<T, E = Error> = result::Result<T, E>;
|
||||
/// if you have access to an actix `Error` you can always get a
|
||||
/// `ResponseError` reference from it.
|
||||
pub struct Error {
|
||||
cause: Box<ResponseError>,
|
||||
cause: Box<dyn ResponseError>,
|
||||
}
|
||||
|
||||
impl Error {
|
||||
/// Returns the reference to the underlying `ResponseError`.
|
||||
pub fn as_response_error(&self) -> &ResponseError {
|
||||
pub fn as_response_error(&self) -> &dyn ResponseError {
|
||||
self.cause.as_ref()
|
||||
}
|
||||
|
||||
/// Similar to `as_response_error` but downcasts.
|
||||
pub fn as_error<T: ResponseError + 'static>(&self) -> Option<&T> {
|
||||
ResponseError::downcast_ref(self.cause.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
/// Error that can be converted to `Response`
|
||||
@ -73,6 +79,25 @@ pub trait ResponseError: fmt::Debug + fmt::Display {
|
||||
);
|
||||
resp.set_body(Body::from(buf))
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
fn __private_get_type_id__(&self) -> TypeId
|
||||
where
|
||||
Self: 'static,
|
||||
{
|
||||
TypeId::of::<Self>()
|
||||
}
|
||||
}
|
||||
|
||||
impl dyn ResponseError + 'static {
|
||||
/// Downcasts a response error to a specific type.
|
||||
pub fn downcast_ref<T: ResponseError + 'static>(&self) -> Option<&T> {
|
||||
if self.__private_get_type_id__() == TypeId::of::<T>() {
|
||||
unsafe { Some(&*(self as *const dyn ResponseError as *const T)) }
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
@ -1044,6 +1069,16 @@ mod tests {
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_casting() {
|
||||
let err = PayloadError::Overflow;
|
||||
let resp_err: &dyn ResponseError = &err;
|
||||
let err = resp_err.downcast_ref::<PayloadError>().unwrap();
|
||||
assert_eq!(err.to_string(), "A payload reached size limit.");
|
||||
let not_err = resp_err.downcast_ref::<ContentTypeError>();
|
||||
assert!(not_err.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_helpers() {
|
||||
let r: Response = ErrorBadRequest("err").into();
|
||||
|
@ -6,7 +6,7 @@ use hashbrown::HashMap;
|
||||
#[derive(Default)]
|
||||
/// A type map of request extensions.
|
||||
pub struct Extensions {
|
||||
map: HashMap<TypeId, Box<Any>>,
|
||||
map: HashMap<TypeId, Box<dyn Any>>,
|
||||
}
|
||||
|
||||
impl Extensions {
|
||||
@ -35,14 +35,14 @@ impl Extensions {
|
||||
pub fn get<T: 'static>(&self) -> Option<&T> {
|
||||
self.map
|
||||
.get(&TypeId::of::<T>())
|
||||
.and_then(|boxed| (&**boxed as &(Any + 'static)).downcast_ref())
|
||||
.and_then(|boxed| (&**boxed as &(dyn Any + 'static)).downcast_ref())
|
||||
}
|
||||
|
||||
/// Get a mutable reference to a type previously inserted on this `Extensions`.
|
||||
pub fn get_mut<T: 'static>(&mut self) -> Option<&mut T> {
|
||||
self.map
|
||||
.get_mut(&TypeId::of::<T>())
|
||||
.and_then(|boxed| (&mut **boxed as &mut (Any + 'static)).downcast_mut())
|
||||
.and_then(|boxed| (&mut **boxed as &mut (dyn Any + 'static)).downcast_mut())
|
||||
}
|
||||
|
||||
/// Remove a type from this `Extensions`.
|
||||
@ -50,7 +50,7 @@ impl Extensions {
|
||||
/// If a extension of this type existed, it will be returned.
|
||||
pub fn remove<T: 'static>(&mut self) -> Option<T> {
|
||||
self.map.remove(&TypeId::of::<T>()).and_then(|boxed| {
|
||||
(boxed as Box<Any + 'static>)
|
||||
(boxed as Box<dyn Any + 'static>)
|
||||
.downcast()
|
||||
.ok()
|
||||
.map(|boxed| *boxed)
|
||||
|
@ -1,5 +1,6 @@
|
||||
#![allow(unused_imports, unused_variables, dead_code)]
|
||||
use std::io::{self, Write};
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_codec::{Decoder, Encoder};
|
||||
use bitflags::bitflags;
|
||||
@ -16,7 +17,8 @@ use crate::body::BodySize;
|
||||
use crate::config::ServiceConfig;
|
||||
use crate::error::{ParseError, PayloadError};
|
||||
use crate::helpers;
|
||||
use crate::message::{ConnectionType, Head, MessagePool, RequestHead, ResponseHead};
|
||||
use crate::message::{ConnectionType, Head, MessagePool, RequestHead, RequestHeadType, ResponseHead};
|
||||
use crate::header::HeaderMap;
|
||||
|
||||
bitflags! {
|
||||
struct Flags: u8 {
|
||||
@ -48,7 +50,7 @@ struct ClientCodecInner {
|
||||
// encoder part
|
||||
flags: Flags,
|
||||
headers_size: u32,
|
||||
encoder: encoder::MessageEncoder<RequestHead>,
|
||||
encoder: encoder::MessageEncoder<RequestHeadType>,
|
||||
}
|
||||
|
||||
impl Default for ClientCodec {
|
||||
@ -183,7 +185,7 @@ impl Decoder for ClientPayloadCodec {
|
||||
}
|
||||
|
||||
impl Encoder for ClientCodec {
|
||||
type Item = Message<(RequestHead, BodySize)>;
|
||||
type Item = Message<(RequestHeadType, BodySize)>;
|
||||
type Error = io::Error;
|
||||
|
||||
fn encode(
|
||||
@ -192,13 +194,13 @@ impl Encoder for ClientCodec {
|
||||
dst: &mut BytesMut,
|
||||
) -> Result<(), Self::Error> {
|
||||
match item {
|
||||
Message::Item((mut msg, length)) => {
|
||||
Message::Item((mut head, length)) => {
|
||||
let inner = &mut self.inner;
|
||||
inner.version = msg.version;
|
||||
inner.flags.set(Flags::HEAD, msg.method == Method::HEAD);
|
||||
inner.version = head.as_ref().version;
|
||||
inner.flags.set(Flags::HEAD, head.as_ref().method == Method::HEAD);
|
||||
|
||||
// connection status
|
||||
inner.ctype = match msg.connection_type() {
|
||||
inner.ctype = match head.as_ref().connection_type() {
|
||||
ConnectionType::KeepAlive => {
|
||||
if inner.flags.contains(Flags::KEEPALIVE_ENABLED) {
|
||||
ConnectionType::KeepAlive
|
||||
@ -212,7 +214,7 @@ impl Encoder for ClientCodec {
|
||||
|
||||
inner.encoder.encode(
|
||||
dst,
|
||||
&mut msg,
|
||||
&mut head,
|
||||
false,
|
||||
false,
|
||||
inner.version,
|
||||
|
@ -502,15 +502,15 @@ impl ChunkedState {
|
||||
fn read_size(rdr: &mut BytesMut, size: &mut u64) -> Poll<ChunkedState, io::Error> {
|
||||
let radix = 16;
|
||||
match byte!(rdr) {
|
||||
b @ b'0'...b'9' => {
|
||||
b @ b'0'..=b'9' => {
|
||||
*size *= radix;
|
||||
*size += u64::from(b - b'0');
|
||||
}
|
||||
b @ b'a'...b'f' => {
|
||||
b @ b'a'..=b'f' => {
|
||||
*size *= radix;
|
||||
*size += u64::from(b + 10 - b'a');
|
||||
}
|
||||
b @ b'A'...b'F' => {
|
||||
b @ b'A'..=b'F' => {
|
||||
*size *= radix;
|
||||
*size += u64::from(b + 10 - b'A');
|
||||
}
|
||||
|
@ -5,7 +5,6 @@ use std::{fmt, io, net};
|
||||
use actix_codec::{Decoder, Encoder, Framed, FramedParts};
|
||||
use actix_server_config::IoStream;
|
||||
use actix_service::Service;
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use bitflags::bitflags;
|
||||
use bytes::{BufMut, BytesMut};
|
||||
use futures::{Async, Future, Poll};
|
||||
@ -13,6 +12,7 @@ use log::{error, trace};
|
||||
use tokio_timer::Delay;
|
||||
|
||||
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
|
||||
use crate::cloneable::CloneableService;
|
||||
use crate::config::ServiceConfig;
|
||||
use crate::error::{DispatchError, Error};
|
||||
use crate::error::{ParseError, PayloadError};
|
||||
@ -502,7 +502,7 @@ where
|
||||
let pl = self.codec.message_type();
|
||||
req.head_mut().peer_addr = self.peer_addr;
|
||||
|
||||
// on_connect data
|
||||
// set on_connect data
|
||||
if let Some(ref on_connect) = self.on_connect {
|
||||
on_connect.set(&mut req.extensions_mut());
|
||||
}
|
||||
|
@ -4,6 +4,7 @@ use std::io::Write;
|
||||
use std::marker::PhantomData;
|
||||
use std::str::FromStr;
|
||||
use std::{cmp, fmt, io, mem};
|
||||
use std::rc::Rc;
|
||||
|
||||
use bytes::{BufMut, Bytes, BytesMut};
|
||||
|
||||
@ -15,7 +16,7 @@ use crate::http::header::{
|
||||
HeaderValue, ACCEPT_ENCODING, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING,
|
||||
};
|
||||
use crate::http::{HeaderMap, Method, StatusCode, Version};
|
||||
use crate::message::{ConnectionType, Head, RequestHead, ResponseHead};
|
||||
use crate::message::{ConnectionType, Head, RequestHead, ResponseHead, RequestHeadType};
|
||||
use crate::request::Request;
|
||||
use crate::response::Response;
|
||||
|
||||
@ -43,6 +44,8 @@ pub(crate) trait MessageType: Sized {
|
||||
|
||||
fn headers(&self) -> &HeaderMap;
|
||||
|
||||
fn extra_headers(&self) -> Option<&HeaderMap>;
|
||||
|
||||
fn camel_case(&self) -> bool {
|
||||
false
|
||||
}
|
||||
@ -128,12 +131,21 @@ pub(crate) trait MessageType: Sized {
|
||||
_ => (),
|
||||
}
|
||||
|
||||
// merging headers from head and extra headers. HeaderMap::new() does not allocate.
|
||||
let empty_headers = HeaderMap::new();
|
||||
let extra_headers = self.extra_headers().unwrap_or(&empty_headers);
|
||||
let headers = self.headers().inner.iter()
|
||||
.filter(|(name, _)| {
|
||||
!extra_headers.contains_key(*name)
|
||||
})
|
||||
.chain(extra_headers.inner.iter());
|
||||
|
||||
// write headers
|
||||
let mut pos = 0;
|
||||
let mut has_date = false;
|
||||
let mut remaining = dst.remaining_mut();
|
||||
let mut buf = unsafe { &mut *(dst.bytes_mut() as *mut [u8]) };
|
||||
for (key, value) in self.headers().inner.iter() {
|
||||
for (key, value) in headers {
|
||||
match *key {
|
||||
CONNECTION => continue,
|
||||
TRANSFER_ENCODING | CONTENT_LENGTH if skip_len => continue,
|
||||
@ -235,6 +247,10 @@ impl MessageType for Response<()> {
|
||||
&self.head().headers
|
||||
}
|
||||
|
||||
fn extra_headers(&self) -> Option<&HeaderMap> {
|
||||
None
|
||||
}
|
||||
|
||||
fn encode_status(&mut self, dst: &mut BytesMut) -> io::Result<()> {
|
||||
let head = self.head();
|
||||
let reason = head.reason().as_bytes();
|
||||
@ -247,31 +263,36 @@ impl MessageType for Response<()> {
|
||||
}
|
||||
}
|
||||
|
||||
impl MessageType for RequestHead {
|
||||
impl MessageType for RequestHeadType {
|
||||
fn status(&self) -> Option<StatusCode> {
|
||||
None
|
||||
}
|
||||
|
||||
fn chunked(&self) -> bool {
|
||||
self.chunked()
|
||||
self.as_ref().chunked()
|
||||
}
|
||||
|
||||
fn camel_case(&self) -> bool {
|
||||
RequestHead::camel_case_headers(self)
|
||||
self.as_ref().camel_case_headers()
|
||||
}
|
||||
|
||||
fn headers(&self) -> &HeaderMap {
|
||||
&self.headers
|
||||
self.as_ref().headers()
|
||||
}
|
||||
|
||||
fn extra_headers(&self) -> Option<&HeaderMap> {
|
||||
self.extra_headers()
|
||||
}
|
||||
|
||||
fn encode_status(&mut self, dst: &mut BytesMut) -> io::Result<()> {
|
||||
dst.reserve(256 + self.headers.len() * AVERAGE_HEADER_SIZE);
|
||||
let head = self.as_ref();
|
||||
dst.reserve(256 + head.headers.len() * AVERAGE_HEADER_SIZE);
|
||||
write!(
|
||||
Writer(dst),
|
||||
"{} {} {}",
|
||||
self.method,
|
||||
self.uri.path_and_query().map(|u| u.as_str()).unwrap_or("/"),
|
||||
match self.version {
|
||||
head.method,
|
||||
head.uri.path_and_query().map(|u| u.as_str()).unwrap_or("/"),
|
||||
match head.version {
|
||||
Version::HTTP_09 => "HTTP/0.9",
|
||||
Version::HTTP_10 => "HTTP/1.0",
|
||||
Version::HTTP_11 => "HTTP/1.1",
|
||||
@ -488,9 +509,11 @@ fn write_camel_case(value: &[u8], buffer: &mut [u8]) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use bytes::Bytes;
|
||||
//use std::rc::Rc;
|
||||
|
||||
use super::*;
|
||||
use crate::http::header::{HeaderValue, CONTENT_TYPE};
|
||||
use http::header::AUTHORIZATION;
|
||||
|
||||
#[test]
|
||||
fn test_chunked_te() {
|
||||
@ -515,6 +538,8 @@ mod tests {
|
||||
head.headers
|
||||
.insert(CONTENT_TYPE, HeaderValue::from_static("plain/text"));
|
||||
|
||||
let mut head = RequestHeadType::Owned(head);
|
||||
|
||||
let _ = head.encode_headers(
|
||||
&mut bytes,
|
||||
Version::HTTP_11,
|
||||
@ -551,21 +576,16 @@ mod tests {
|
||||
Bytes::from_static(b"\r\nContent-Length: 100\r\nDate: date\r\nContent-Type: plain/text\r\n\r\n")
|
||||
);
|
||||
|
||||
let mut head = RequestHead::default();
|
||||
head.set_camel_case_headers(false);
|
||||
head.headers.insert(DATE, HeaderValue::from_static("date"));
|
||||
head.headers
|
||||
.insert(CONTENT_TYPE, HeaderValue::from_static("plain/text"));
|
||||
head.headers
|
||||
.append(CONTENT_TYPE, HeaderValue::from_static("xml"));
|
||||
let _ = head.encode_headers(
|
||||
&mut bytes,
|
||||
Version::HTTP_11,
|
||||
BodySize::Stream,
|
||||
ConnectionType::KeepAlive,
|
||||
&ServiceConfig::default(),
|
||||
);
|
||||
assert_eq!(
|
||||
bytes.take().freeze(),
|
||||
Bytes::from_static(b"\r\nTransfer-Encoding: chunked\r\nDate: date\r\nContent-Type: xml\r\nContent-Type: plain/text\r\n\r\n")
|
||||
);
|
||||
|
||||
head.set_camel_case_headers(false);
|
||||
let mut head = RequestHeadType::Owned(head);
|
||||
|
||||
let _ = head.encode_headers(
|
||||
&mut bytes,
|
||||
Version::HTTP_11,
|
||||
@ -578,4 +598,30 @@ mod tests {
|
||||
Bytes::from_static(b"\r\ntransfer-encoding: chunked\r\ndate: date\r\ncontent-type: xml\r\ncontent-type: plain/text\r\n\r\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extra_headers() {
|
||||
let mut bytes = BytesMut::with_capacity(2048);
|
||||
|
||||
let mut head = RequestHead::default();
|
||||
head.headers.insert(AUTHORIZATION, HeaderValue::from_static("some authorization"));
|
||||
|
||||
let mut extra_headers = HeaderMap::new();
|
||||
extra_headers.insert(AUTHORIZATION,HeaderValue::from_static("another authorization"));
|
||||
extra_headers.insert(DATE, HeaderValue::from_static("date"));
|
||||
|
||||
let mut head = RequestHeadType::Rc(Rc::new(head), Some(extra_headers));
|
||||
|
||||
let _ = head.encode_headers(
|
||||
&mut bytes,
|
||||
Version::HTTP_11,
|
||||
BodySize::Empty,
|
||||
ConnectionType::Close,
|
||||
&ServiceConfig::default(),
|
||||
);
|
||||
assert_eq!(
|
||||
bytes.take().freeze(),
|
||||
Bytes::from_static(b"\r\ncontent-length: 0\r\nconnection: close\r\nauthorization: another authorization\r\ndate: date\r\n\r\n")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -5,11 +5,11 @@ use std::rc::Rc;
|
||||
use actix_codec::Framed;
|
||||
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
|
||||
use actix_service::{IntoNewService, NewService, Service};
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream};
|
||||
|
||||
use crate::body::MessageBody;
|
||||
use crate::cloneable::CloneableService;
|
||||
use crate::config::{KeepAlive, ServiceConfig};
|
||||
use crate::error::{DispatchError, Error, ParseError};
|
||||
use crate::helpers::DataFactory;
|
||||
@ -26,7 +26,7 @@ pub struct H1Service<T, P, S, B, X = ExpectHandler, U = UpgradeHandler<T>> {
|
||||
cfg: ServiceConfig,
|
||||
expect: X,
|
||||
upgrade: Option<U>,
|
||||
on_connect: Option<Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
_t: PhantomData<(T, P, B)>,
|
||||
}
|
||||
|
||||
@ -108,7 +108,7 @@ where
|
||||
/// Set on connect callback.
|
||||
pub(crate) fn on_connect(
|
||||
mut self,
|
||||
f: Option<Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
f: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
) -> Self {
|
||||
self.on_connect = f;
|
||||
self
|
||||
@ -174,7 +174,7 @@ where
|
||||
fut_upg: Option<U::Future>,
|
||||
expect: Option<X::Service>,
|
||||
upgrade: Option<U::Service>,
|
||||
on_connect: Option<Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
cfg: Option<ServiceConfig>,
|
||||
_t: PhantomData<(T, P, B)>,
|
||||
}
|
||||
@ -233,7 +233,7 @@ pub struct H1ServiceHandler<T, P, S, B, X, U> {
|
||||
srv: CloneableService<S>,
|
||||
expect: CloneableService<X>,
|
||||
upgrade: Option<CloneableService<U>>,
|
||||
on_connect: Option<Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
cfg: ServiceConfig,
|
||||
_t: PhantomData<(T, P, B)>,
|
||||
}
|
||||
@ -254,12 +254,12 @@ where
|
||||
srv: S,
|
||||
expect: X,
|
||||
upgrade: Option<U>,
|
||||
on_connect: Option<Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
) -> H1ServiceHandler<T, P, S, B, X, U> {
|
||||
H1ServiceHandler {
|
||||
srv: CloneableService::new(srv),
|
||||
expect: CloneableService::new(expect),
|
||||
upgrade: upgrade.map(|s| CloneableService::new(s)),
|
||||
upgrade: upgrade.map(CloneableService::new),
|
||||
cfg,
|
||||
on_connect,
|
||||
_t: PhantomData,
|
||||
|
@ -6,7 +6,6 @@ use std::{fmt, mem, net};
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_server_config::IoStream;
|
||||
use actix_service::Service;
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use bitflags::bitflags;
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures::{try_ready, Async, Future, Poll, Sink, Stream};
|
||||
@ -20,9 +19,11 @@ use log::{debug, error, trace};
|
||||
use tokio_timer::Delay;
|
||||
|
||||
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
|
||||
use crate::cloneable::CloneableService;
|
||||
use crate::config::ServiceConfig;
|
||||
use crate::error::{DispatchError, Error, ParseError, PayloadError, ResponseError};
|
||||
use crate::helpers::DataFactory;
|
||||
use crate::httpmessage::HttpMessage;
|
||||
use crate::message::ResponseHead;
|
||||
use crate::payload::Payload;
|
||||
use crate::request::Request;
|
||||
@ -122,6 +123,12 @@ where
|
||||
head.version = parts.version;
|
||||
head.headers = parts.headers.into();
|
||||
head.peer_addr = self.peer_addr;
|
||||
|
||||
// set on_connect data
|
||||
if let Some(ref on_connect) = self.on_connect {
|
||||
on_connect.set(&mut req.extensions_mut());
|
||||
}
|
||||
|
||||
tokio_current_thread::spawn(ServiceResponse::<S::Future, B> {
|
||||
state: ServiceResponseState::ServiceCall(
|
||||
self.service.call(req),
|
||||
@ -250,8 +257,8 @@ where
|
||||
}
|
||||
}
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Err(_e) => {
|
||||
let res: Response = Response::InternalServerError().finish();
|
||||
Err(e) => {
|
||||
let res: Response = e.into().into();
|
||||
let (res, body) = res.replace_body(());
|
||||
|
||||
let mut send = send.take().unwrap();
|
||||
|
@ -5,7 +5,6 @@ use std::{io, net, rc};
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
|
||||
use actix_service::{IntoNewService, NewService, Service};
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use bytes::Bytes;
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream};
|
||||
@ -14,6 +13,7 @@ use h2::RecvStream;
|
||||
use log::error;
|
||||
|
||||
use crate::body::MessageBody;
|
||||
use crate::cloneable::CloneableService;
|
||||
use crate::config::{KeepAlive, ServiceConfig};
|
||||
use crate::error::{DispatchError, Error, ParseError, ResponseError};
|
||||
use crate::helpers::DataFactory;
|
||||
@ -27,7 +27,7 @@ use super::dispatcher::Dispatcher;
|
||||
pub struct H2Service<T, P, S, B> {
|
||||
srv: S,
|
||||
cfg: ServiceConfig,
|
||||
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
_t: PhantomData<(T, P, B)>,
|
||||
}
|
||||
|
||||
@ -64,7 +64,7 @@ where
|
||||
/// Set on connect callback.
|
||||
pub(crate) fn on_connect(
|
||||
mut self,
|
||||
f: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
f: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
) -> Self {
|
||||
self.on_connect = f;
|
||||
self
|
||||
@ -102,7 +102,7 @@ where
|
||||
pub struct H2ServiceResponse<T, P, S: NewService, B> {
|
||||
fut: <S::Future as IntoFuture>::Future,
|
||||
cfg: Option<ServiceConfig>,
|
||||
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
_t: PhantomData<(T, P, B)>,
|
||||
}
|
||||
|
||||
@ -132,7 +132,7 @@ where
|
||||
pub struct H2ServiceHandler<T, P, S, B> {
|
||||
srv: CloneableService<S>,
|
||||
cfg: ServiceConfig,
|
||||
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
_t: PhantomData<(T, P, B)>,
|
||||
}
|
||||
|
||||
@ -146,7 +146,7 @@ where
|
||||
{
|
||||
fn new(
|
||||
cfg: ServiceConfig,
|
||||
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
srv: S,
|
||||
) -> H2ServiceHandler<T, P, S, B> {
|
||||
H2ServiceHandler {
|
||||
@ -256,7 +256,7 @@ where
|
||||
on_connect.take(),
|
||||
config.take().unwrap(),
|
||||
None,
|
||||
peer_addr.clone(),
|
||||
*peer_addr,
|
||||
));
|
||||
self.poll()
|
||||
}
|
||||
|
@ -70,6 +70,7 @@ impl<'a> From<&'a str> for DispositionType {
|
||||
/// assert_eq!(param.as_filename().unwrap(), "sample.txt");
|
||||
/// ```
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum DispositionParam {
|
||||
/// For [`DispositionType::FormData`] (i.e. *multipart/form-data*), the name of an field from
|
||||
/// the form.
|
||||
@ -719,8 +720,10 @@ mod tests {
|
||||
};
|
||||
assert_eq!(a, b);
|
||||
|
||||
let a =
|
||||
HeaderValue::from_str("form-data; name=upload; filename=\"余固知謇謇之為患兮,忍而不能舍也.pptx\"").unwrap();
|
||||
let a = HeaderValue::from_str(
|
||||
"form-data; name=upload; filename=\"余固知謇謇之為患兮,忍而不能舍也.pptx\"",
|
||||
)
|
||||
.unwrap();
|
||||
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
||||
let b = ContentDisposition {
|
||||
disposition: DispositionType::FormData,
|
||||
|
@ -9,12 +9,12 @@ use http::HttpTryFrom;
|
||||
/// `HeaderMap` is an multimap of [`HeaderName`] to values.
|
||||
///
|
||||
/// [`HeaderName`]: struct.HeaderName.html
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct HeaderMap {
|
||||
pub(crate) inner: HashMap<HeaderName, Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) enum Value {
|
||||
One(HeaderValue),
|
||||
Multi(Vec<HeaderValue>),
|
||||
|
@ -6,6 +6,7 @@ use std::{fmt, str::FromStr};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use http::Error as HttpError;
|
||||
use mime::Mime;
|
||||
use percent_encoding::{AsciiSet, CONTROLS};
|
||||
|
||||
pub use http::header::*;
|
||||
|
||||
@ -361,10 +362,8 @@ pub fn parse_extended_value(
|
||||
|
||||
impl fmt::Display for ExtendedValue {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
let encoded_value = percent_encoding::percent_encode(
|
||||
&self.value[..],
|
||||
self::percent_encoding_http::HTTP_VALUE,
|
||||
);
|
||||
let encoded_value =
|
||||
percent_encoding::percent_encode(&self.value[..], HTTP_VALUE);
|
||||
if let Some(ref lang) = self.language_tag {
|
||||
write!(f, "{}'{}'{}", self.charset, lang, encoded_value)
|
||||
} else {
|
||||
@ -378,8 +377,7 @@ impl fmt::Display for ExtendedValue {
|
||||
///
|
||||
/// [url]: https://tools.ietf.org/html/rfc5987#section-3.2
|
||||
pub fn http_percent_encode(f: &mut fmt::Formatter, bytes: &[u8]) -> fmt::Result {
|
||||
let encoded =
|
||||
percent_encoding::percent_encode(bytes, self::percent_encoding_http::HTTP_VALUE);
|
||||
let encoded = percent_encoding::percent_encode(bytes, HTTP_VALUE);
|
||||
fmt::Display::fmt(&encoded, f)
|
||||
}
|
||||
|
||||
@ -394,20 +392,29 @@ impl From<http::HeaderMap> for HeaderMap {
|
||||
}
|
||||
}
|
||||
|
||||
mod percent_encoding_http {
|
||||
use percent_encoding::{self, define_encode_set};
|
||||
|
||||
// internal module because macro is hard-coded to make a public item
|
||||
// but we don't want to public export this item
|
||||
define_encode_set! {
|
||||
// This encode set is used for HTTP header values and is defined at
|
||||
// https://tools.ietf.org/html/rfc5987#section-3.2
|
||||
pub HTTP_VALUE = [percent_encoding::SIMPLE_ENCODE_SET] | {
|
||||
' ', '"', '%', '\'', '(', ')', '*', ',', '/', ':', ';', '<', '-', '>', '?',
|
||||
'[', '\\', ']', '{', '}'
|
||||
}
|
||||
}
|
||||
}
|
||||
// This encode set is used for HTTP header values and is defined at
|
||||
// https://tools.ietf.org/html/rfc5987#section-3.2
|
||||
pub(crate) const HTTP_VALUE: &AsciiSet = &CONTROLS
|
||||
.add(b' ')
|
||||
.add(b'"')
|
||||
.add(b'%')
|
||||
.add(b'\'')
|
||||
.add(b'(')
|
||||
.add(b')')
|
||||
.add(b'*')
|
||||
.add(b',')
|
||||
.add(b'/')
|
||||
.add(b':')
|
||||
.add(b';')
|
||||
.add(b'<')
|
||||
.add(b'-')
|
||||
.add(b'>')
|
||||
.add(b'?')
|
||||
.add(b'[')
|
||||
.add(b'\\')
|
||||
.add(b']')
|
||||
.add(b'{')
|
||||
.add(b'}');
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
@ -1,8 +1,10 @@
|
||||
//! Basic http primitives for actix-net framework.
|
||||
#![allow(
|
||||
clippy::type_complexity,
|
||||
clippy::too_many_arguments,
|
||||
clippy::new_without_default,
|
||||
clippy::borrow_interior_mutable_const
|
||||
clippy::borrow_interior_mutable_const,
|
||||
clippy::write_with_newline
|
||||
)]
|
||||
|
||||
#[macro_use]
|
||||
@ -11,6 +13,7 @@ extern crate log;
|
||||
pub mod body;
|
||||
mod builder;
|
||||
pub mod client;
|
||||
mod cloneable;
|
||||
mod config;
|
||||
pub mod encoding;
|
||||
mod extensions;
|
||||
@ -36,7 +39,7 @@ pub use self::config::{KeepAlive, ServiceConfig};
|
||||
pub use self::error::{Error, ResponseError, Result};
|
||||
pub use self::extensions::Extensions;
|
||||
pub use self::httpmessage::HttpMessage;
|
||||
pub use self::message::{Message, RequestHead, ResponseHead};
|
||||
pub use self::message::{Message, RequestHead, RequestHeadType, ResponseHead};
|
||||
pub use self::payload::{Payload, PayloadStream};
|
||||
pub use self::request::Request;
|
||||
pub use self::response::{Response, ResponseBuilder};
|
||||
|
@ -181,6 +181,36 @@ impl RequestHead {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum RequestHeadType {
|
||||
Owned(RequestHead),
|
||||
Rc(Rc<RequestHead>, Option<HeaderMap>),
|
||||
}
|
||||
|
||||
impl RequestHeadType {
|
||||
pub fn extra_headers(&self) -> Option<&HeaderMap> {
|
||||
match self {
|
||||
RequestHeadType::Owned(_) => None,
|
||||
RequestHeadType::Rc(_, headers) => headers.as_ref(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<RequestHead> for RequestHeadType {
|
||||
fn as_ref(&self) -> &RequestHead {
|
||||
match self {
|
||||
RequestHeadType::Owned(head) => &head,
|
||||
RequestHeadType::Rc(head, _) => head.as_ref(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RequestHead> for RequestHeadType {
|
||||
fn from(head: RequestHead) -> Self {
|
||||
RequestHeadType::Owned(head)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ResponseHead {
|
||||
pub version: Version,
|
||||
@ -385,6 +415,7 @@ impl Drop for BoxedResponseHead {
|
||||
pub struct MessagePool<T: Head>(RefCell<Vec<Rc<T>>>);
|
||||
|
||||
#[doc(hidden)]
|
||||
#[allow(clippy::vec_box)]
|
||||
/// Request's objects pool
|
||||
pub struct BoxedResponsePool(RefCell<Vec<Box<ResponseHead>>>);
|
||||
|
||||
|
@ -52,6 +52,9 @@ impl Response<Body> {
|
||||
#[inline]
|
||||
pub fn from_error(error: Error) -> Response {
|
||||
let mut resp = error.as_response_error().render_response();
|
||||
if resp.head.status == StatusCode::INTERNAL_SERVER_ERROR {
|
||||
error!("Internal Server Error: {:?}", error);
|
||||
}
|
||||
resp.error = Some(error);
|
||||
resp
|
||||
}
|
||||
|
@ -6,13 +6,13 @@ use actix_server_config::{
|
||||
Io as ServerIo, IoStream, Protocol, ServerConfig as SrvConfig,
|
||||
};
|
||||
use actix_service::{IntoNewService, NewService, Service};
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use bytes::{Buf, BufMut, Bytes, BytesMut};
|
||||
use futures::{try_ready, Async, Future, IntoFuture, Poll};
|
||||
use h2::server::{self, Handshake};
|
||||
|
||||
use crate::body::MessageBody;
|
||||
use crate::builder::HttpServiceBuilder;
|
||||
use crate::cloneable::CloneableService;
|
||||
use crate::config::{KeepAlive, ServiceConfig};
|
||||
use crate::error::{DispatchError, Error};
|
||||
use crate::helpers::DataFactory;
|
||||
@ -26,7 +26,7 @@ pub struct HttpService<T, P, S, B, X = h1::ExpectHandler, U = h1::UpgradeHandler
|
||||
cfg: ServiceConfig,
|
||||
expect: X,
|
||||
upgrade: Option<U>,
|
||||
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
_t: PhantomData<(T, P, B)>,
|
||||
}
|
||||
|
||||
@ -140,7 +140,7 @@ where
|
||||
/// Set on connect callback.
|
||||
pub(crate) fn on_connect(
|
||||
mut self,
|
||||
f: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
f: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
) -> Self {
|
||||
self.on_connect = f;
|
||||
self
|
||||
@ -196,7 +196,7 @@ pub struct HttpServiceResponse<T, P, S: NewService, B, X: NewService, U: NewServ
|
||||
fut_upg: Option<U::Future>,
|
||||
expect: Option<X::Service>,
|
||||
upgrade: Option<U::Service>,
|
||||
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
cfg: Option<ServiceConfig>,
|
||||
_t: PhantomData<(T, P, B)>,
|
||||
}
|
||||
@ -257,7 +257,7 @@ pub struct HttpServiceHandler<T, P, S, B, X, U> {
|
||||
expect: CloneableService<X>,
|
||||
upgrade: Option<CloneableService<U>>,
|
||||
cfg: ServiceConfig,
|
||||
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
_t: PhantomData<(T, P, B, X)>,
|
||||
}
|
||||
|
||||
@ -278,14 +278,14 @@ where
|
||||
srv: S,
|
||||
expect: X,
|
||||
upgrade: Option<U>,
|
||||
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
) -> HttpServiceHandler<T, P, S, B, X, U> {
|
||||
HttpServiceHandler {
|
||||
cfg,
|
||||
on_connect,
|
||||
srv: CloneableService::new(srv),
|
||||
expect: CloneableService::new(expect),
|
||||
upgrade: upgrade.map(|s| CloneableService::new(s)),
|
||||
upgrade: upgrade.map(CloneableService::new),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@ -466,16 +466,18 @@ where
|
||||
State::Unknown(ref mut data) => {
|
||||
if let Some(ref mut item) = data {
|
||||
loop {
|
||||
unsafe {
|
||||
let b = item.1.bytes_mut();
|
||||
let n = try_ready!(item.0.poll_read(b));
|
||||
if n == 0 {
|
||||
return Ok(Async::Ready(()));
|
||||
}
|
||||
item.1.advance_mut(n);
|
||||
if item.1.len() >= HTTP2_PREFACE.len() {
|
||||
break;
|
||||
}
|
||||
// Safety - we only write to the returned slice.
|
||||
let b = unsafe { item.1.bytes_mut() };
|
||||
let n = try_ready!(item.0.poll_read(b));
|
||||
if n == 0 {
|
||||
return Ok(Async::Ready(()));
|
||||
}
|
||||
// Safety - we know that 'n' bytes have
|
||||
// been initialized via the contract of
|
||||
// 'poll_read'
|
||||
unsafe { item.1.advance_mut(n) };
|
||||
if item.1.len() >= HTTP2_PREFACE.len() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
@ -9,9 +9,9 @@ use bytes::{Buf, Bytes, BytesMut};
|
||||
use futures::{Async, Poll};
|
||||
use http::header::{self, HeaderName, HeaderValue};
|
||||
use http::{HttpTryFrom, Method, Uri, Version};
|
||||
use percent_encoding::{percent_encode, USERINFO_ENCODE_SET};
|
||||
use percent_encoding::percent_encode;
|
||||
|
||||
use crate::cookie::{Cookie, CookieJar};
|
||||
use crate::cookie::{Cookie, CookieJar, USERINFO};
|
||||
use crate::header::HeaderMap;
|
||||
use crate::header::{Header, IntoHeaderValue};
|
||||
use crate::payload::Payload;
|
||||
@ -166,8 +166,8 @@ impl TestRequest {
|
||||
|
||||
let mut cookie = String::new();
|
||||
for c in inner.cookies.delta() {
|
||||
let name = percent_encode(c.name().as_bytes(), USERINFO_ENCODE_SET);
|
||||
let value = percent_encode(c.value().as_bytes(), USERINFO_ENCODE_SET);
|
||||
let name = percent_encode(c.name().as_bytes(), USERINFO);
|
||||
let value = percent_encode(c.value().as_bytes(), USERINFO);
|
||||
let _ = write!(&mut cookie, "; {}={}", name, value);
|
||||
}
|
||||
if !cookie.is_empty() {
|
||||
|
@ -1,4 +1,5 @@
|
||||
use byteorder::{ByteOrder, LittleEndian, NetworkEndian};
|
||||
use std::convert::TryFrom;
|
||||
|
||||
use bytes::{BufMut, Bytes, BytesMut};
|
||||
use log::debug;
|
||||
use rand;
|
||||
@ -48,14 +49,16 @@ impl Parser {
|
||||
if chunk_len < 4 {
|
||||
return Ok(None);
|
||||
}
|
||||
let len = NetworkEndian::read_uint(&src[idx..], 2) as usize;
|
||||
let len = usize::from(u16::from_be_bytes(
|
||||
TryFrom::try_from(&src[idx..idx + 2]).unwrap(),
|
||||
));
|
||||
idx += 2;
|
||||
len
|
||||
} else if len == 127 {
|
||||
if chunk_len < 10 {
|
||||
return Ok(None);
|
||||
}
|
||||
let len = NetworkEndian::read_uint(&src[idx..], 8);
|
||||
let len = u64::from_be_bytes(TryFrom::try_from(&src[idx..idx + 8]).unwrap());
|
||||
if len > max_size as u64 {
|
||||
return Err(ProtocolError::Overflow);
|
||||
}
|
||||
@ -75,10 +78,10 @@ impl Parser {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let mask: &[u8] = &src[idx..idx + 4];
|
||||
let mask_u32 = LittleEndian::read_u32(mask);
|
||||
let mask =
|
||||
u32::from_le_bytes(TryFrom::try_from(&src[idx..idx + 4]).unwrap());
|
||||
idx += 4;
|
||||
Some(mask_u32)
|
||||
Some(mask)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@ -137,7 +140,7 @@ impl Parser {
|
||||
/// Parse the payload of a close frame.
|
||||
pub fn parse_close_payload(payload: &[u8]) -> Option<CloseReason> {
|
||||
if payload.len() >= 2 {
|
||||
let raw_code = NetworkEndian::read_u16(payload);
|
||||
let raw_code = u16::from_be_bytes(TryFrom::try_from(&payload[..2]).unwrap());
|
||||
let code = CloseCode::from(raw_code);
|
||||
let description = if payload.len() > 2 {
|
||||
Some(String::from_utf8_lossy(&payload[2..]).into())
|
||||
@ -201,10 +204,7 @@ impl Parser {
|
||||
let payload = match reason {
|
||||
None => Vec::new(),
|
||||
Some(reason) => {
|
||||
let mut code_bytes = [0; 2];
|
||||
NetworkEndian::write_u16(&mut code_bytes, reason.code.into());
|
||||
|
||||
let mut payload = Vec::from(&code_bytes[..]);
|
||||
let mut payload = Into::<u16>::into(reason.code).to_be_bytes().to_vec();
|
||||
if let Some(description) = reason.description {
|
||||
payload.extend(description.as_bytes());
|
||||
}
|
||||
|
@ -105,7 +105,6 @@ fn align_buf(buf: &mut [u8]) -> (ShortSlice, &mut [u64], ShortSlice) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::apply_mask;
|
||||
use byteorder::{ByteOrder, LittleEndian};
|
||||
|
||||
/// A safe unoptimized mask application.
|
||||
fn apply_mask_fallback(buf: &mut [u8], mask: &[u8; 4]) {
|
||||
@ -117,7 +116,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_apply_mask() {
|
||||
let mask = [0x6d, 0xb6, 0xb2, 0x80];
|
||||
let mask_u32: u32 = LittleEndian::read_u32(&mask);
|
||||
let mask_u32 = u32::from_le_bytes(mask);
|
||||
|
||||
let unmasked = vec![
|
||||
0xf3, 0x00, 0x01, 0x02, 0x03, 0x80, 0x81, 0x82, 0xff, 0xfe, 0x00, 0x17,
|
||||
|
@ -47,10 +47,7 @@ impl Into<u8> for OpCode {
|
||||
Ping => 9,
|
||||
Pong => 10,
|
||||
Bad => {
|
||||
debug_assert!(
|
||||
false,
|
||||
"Attempted to convert invalid opcode to u8. This is a bug."
|
||||
);
|
||||
log::error!("Attempted to convert invalid opcode to u8. This is a bug.");
|
||||
8 // if this somehow happens, a close frame will help us tear down quickly
|
||||
}
|
||||
}
|
||||
@ -206,7 +203,7 @@ impl<T: Into<String>> From<(CloseCode, T)> for CloseReason {
|
||||
}
|
||||
}
|
||||
|
||||
static WS_GUID: &'static str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
||||
static WS_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
||||
|
||||
// TODO: hash is always same size, we dont need String
|
||||
pub fn hash_key(key: &[u8]) -> String {
|
||||
|
@ -1,20 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDPjCCAiYCCQCmkoCBehOyYTANBgkqhkiG9w0BAQsFADBhMQswCQYDVQQGEwJV
|
||||
UzELMAkGA1UECAwCQ0ExCzAJBgNVBAcMAlNGMRAwDgYDVQQKDAdDb21wYW55MQww
|
||||
CgYDVQQLDANPcmcxGDAWBgNVBAMMD3d3dy5leGFtcGxlLmNvbTAeFw0xOTAzMjky
|
||||
MzE5MDlaFw0yMDAzMjgyMzE5MDlaMGExCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJD
|
||||
QTELMAkGA1UEBwwCU0YxEDAOBgNVBAoMB0NvbXBhbnkxDDAKBgNVBAsMA09yZzEY
|
||||
MBYGA1UEAwwPd3d3LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
|
||||
MIIBCgKCAQEA2uFoWm74qumqIIsBBf/rgP3ZtZw6dRQhVoYjIwYk00T1RLmmbt8r
|
||||
YNh3lehmnrQlM/YC3dzcspucGqIfvs5FEReh/vgvsqY3lfy47Q1zzdtBrKq2ZBro
|
||||
AuJUe4ayMYz/L/2jAtPtGDQqWyzhKv6x/oz6N/tKqlzoGbjSGSJUqKAV+Tuo4YI4
|
||||
xw3r/RJg3I3+ruXOgM65GBdja7usI/BhseEOp9VXotoTEItGmvG2RFZ4A7cN124x
|
||||
giFl2IeYuC60jteZ+bnhPiqxcdzf3K4dnZlzrYma+FxwWbaow4wlpQcZVFdZ+K/Y
|
||||
p/Bbm/FDKoUHnEdn/QAanTruRxSGdai0owIDAQABMA0GCSqGSIb3DQEBCwUAA4IB
|
||||
AQAEWn3WAwAbd64f5jo2w4076s2qFiCJjPWoxO6bO75FgFFtw/NNev8pxGVw1ehg
|
||||
HiTO6VRYolL5S/RKOchjA83AcDEBjgf8fKtvTmE9kxZSUIo4kIvv8V9ZM72gJhDN
|
||||
8D/lXduTZ9JMwLOa1NUB8/I6CbaU3VzWkfodArKKpQF3M+LLgK03i12PD0KPQ5zv
|
||||
bwaNoQo6cTmPNIdsVZETRvPqONiCUaQV57G74dGtjeirCh/DO5EYRtb1thgS7TGm
|
||||
+Xg8OC5vZ6g0+xsrSqDBmWNtlI7S3bsL5C3LIEOOAL1ZJHRy2KvIGQ9ipb3XjnKS
|
||||
N7/wlQduRyPH7oaD/o4xf5Gt
|
||||
-----END CERTIFICATE-----
|
@ -1,27 +0,0 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEpQIBAAKCAQEA2uFoWm74qumqIIsBBf/rgP3ZtZw6dRQhVoYjIwYk00T1RLmm
|
||||
bt8rYNh3lehmnrQlM/YC3dzcspucGqIfvs5FEReh/vgvsqY3lfy47Q1zzdtBrKq2
|
||||
ZBroAuJUe4ayMYz/L/2jAtPtGDQqWyzhKv6x/oz6N/tKqlzoGbjSGSJUqKAV+Tuo
|
||||
4YI4xw3r/RJg3I3+ruXOgM65GBdja7usI/BhseEOp9VXotoTEItGmvG2RFZ4A7cN
|
||||
124xgiFl2IeYuC60jteZ+bnhPiqxcdzf3K4dnZlzrYma+FxwWbaow4wlpQcZVFdZ
|
||||
+K/Yp/Bbm/FDKoUHnEdn/QAanTruRxSGdai0owIDAQABAoIBAQC4lzyQd+ITEbi+
|
||||
dTxJuQj94hgHB1htgKqU888SLI5F9nP6n67y9hb5N9WygSp6UWbGqYTFYwxlPMKr
|
||||
22p2WjL5NTsTcm+XdIKQZW/3y06Mn4qFefsT9XURaZriCjihfU2BRaCCNARSUzwd
|
||||
ZH4I6n9mM7KaH71aa7v6ZVoahE9tXPR6hM+SHQEySW4pWkEu98VpNNeIt6vP7WF9
|
||||
ONGbRa+0En4xgkuaxem2ZYa/GZFFtdQRkroNMhIRlfcPpkjy8DCc8E5RAkOzKC3O
|
||||
lnxQwt+tdNNkGZz02ed2hx/YHPwFYy76y6hK5dxq74iKIaOc8U5t0HjB1zVfwiR0
|
||||
5mcxMncxAoGBAP+RivwXZ4FcxDY1uyziF+rwlC/1RujQFEWXIxsXCnba5DH3yKul
|
||||
iKEIZPZtGhpsnQe367lcXcn7tztuoVjpAnk5L+hQY64tLwYbHeRcOMJ75C2y8FFC
|
||||
NeG5sQsrk3IU1+jhGvrbE7UgOeAuWJmv0M1vPNB/+hGoZBW5W5uU1x89AoGBANtA
|
||||
AhLtAcqQ/Qh2SpVhLljh7U85Be9tbCGua09clkYFzh3bcoBolXKH18Veww0TP0yF
|
||||
0748CKw1A+ITbTVFV+vKvi4jzIxS7mr4wYtVCMssbttQN7y3l30IDxJwa9j3zTJx
|
||||
IUn5OMMLv1JyitLId8HdOy1AdU3MkpJzdLyi1mFfAoGBAL3kL4fGABM/kU7SN6RO
|
||||
zgS0AvdrYOeljBp1BRGg2hab58g02vamxVEZgqMTR7zwjPDqOIz+03U7wda4Ccyd
|
||||
PUhDNJSB/r6xNepshZZi642eLlnCRguqjYyNw72QADtYv2B6uehAlXEUY8xtw0lW
|
||||
OGgcSeyF2pH6M3tswWNlgT3lAoGAQ/BttBelOnP7NKgTLH7Usc4wjyAIaszpePZn
|
||||
Ykw6dLBP0oixzoCZ7seRYSOgJWkVcEz39Db+KP60mVWTvbIjMHm+vOVy+Pip0JQM
|
||||
xXQwKWU3ZNZSrzPkyWW55ejYQn9nIn5T5mxH3ojBXHcJ9Y8RLQ20zKzwrI77zE3i
|
||||
mqGK9NkCgYEAq3dzHI0DGAJrR19sWl2LcqI19sj5a91tHx4cl1dJXS/iApOLLieU
|
||||
zyUGkwfsqjHPAZ7GacICeBojIn/7KdPdlSKAbGVAU3d4qzvFS0qmWzObplBz3niT
|
||||
Xnep2XLaVXqwlFJZZ6AHeKzYmMH0d0raiou2bpEUBqYizy2fi3NI4mA=
|
||||
-----END RSA PRIVATE KEY-----
|
462
actix-http/tests/test_rustls_server.rs
Normal file
462
actix-http/tests/test_rustls_server.rs
Normal file
@ -0,0 +1,462 @@
|
||||
#![cfg(feature = "rust-tls")]
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_http::error::PayloadError;
|
||||
use actix_http::http::header::{self, HeaderName, HeaderValue};
|
||||
use actix_http::http::{Method, StatusCode, Version};
|
||||
use actix_http::{body, error, Error, HttpService, Request, Response};
|
||||
use actix_http_test::TestServer;
|
||||
use actix_server::ssl::RustlsAcceptor;
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{new_service_cfg, NewService};
|
||||
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures::future::{self, ok, Future};
|
||||
use futures::stream::{once, Stream};
|
||||
use rustls::{
|
||||
internal::pemfile::{certs, pkcs8_private_keys},
|
||||
NoClientAuth, ServerConfig as RustlsServerConfig,
|
||||
};
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{BufReader, Result};
|
||||
|
||||
fn load_body<S>(stream: S) -> impl Future<Item = BytesMut, Error = PayloadError>
|
||||
where
|
||||
S: Stream<Item = Bytes, Error = PayloadError>,
|
||||
{
|
||||
stream.fold(BytesMut::new(), move |mut body, chunk| {
|
||||
body.extend_from_slice(&chunk);
|
||||
Ok::<_, PayloadError>(body)
|
||||
})
|
||||
}
|
||||
|
||||
fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<RustlsAcceptor<T, ()>> {
|
||||
// load ssl keys
|
||||
let mut config = RustlsServerConfig::new(NoClientAuth::new());
|
||||
let cert_file = &mut BufReader::new(File::open("../tests/cert.pem").unwrap());
|
||||
let key_file = &mut BufReader::new(File::open("../tests/key.pem").unwrap());
|
||||
let cert_chain = certs(cert_file).unwrap();
|
||||
let mut keys = pkcs8_private_keys(key_file).unwrap();
|
||||
config.set_single_cert(cert_chain, keys.remove(0)).unwrap();
|
||||
|
||||
let protos = vec![b"h2".to_vec()];
|
||||
config.set_protocols(&protos);
|
||||
Ok(RustlsAcceptor::new(config))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2() -> Result<()> {
|
||||
let rustls = ssl_acceptor()?;
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| future::ok::<_, Error>(Response::Ok().finish()))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_1() -> Result<()> {
|
||||
let rustls = ssl_acceptor()?;
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.finish(|req: Request| {
|
||||
assert!(req.peer_addr().is_some());
|
||||
assert_eq!(req.version(), Version::HTTP_2);
|
||||
future::ok::<_, Error>(Response::Ok().finish())
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_body() -> Result<()> {
|
||||
let data = "HELLOWORLD".to_owned().repeat(64 * 1024);
|
||||
let rustls = ssl_acceptor()?;
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|mut req: Request<_>| {
|
||||
load_body(req.take_payload())
|
||||
.and_then(|body| Ok(Response::Ok().body(body)))
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send_body(data.clone())).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let body = srv.load_body(response).unwrap();
|
||||
assert_eq!(&body, data.as_bytes());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_content_length() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|req: Request| {
|
||||
let indx: usize = req.uri().path()[1..].parse().unwrap();
|
||||
let statuses = [
|
||||
StatusCode::NO_CONTENT,
|
||||
StatusCode::CONTINUE,
|
||||
StatusCode::SWITCHING_PROTOCOLS,
|
||||
StatusCode::PROCESSING,
|
||||
StatusCode::OK,
|
||||
StatusCode::NOT_FOUND,
|
||||
];
|
||||
future::ok::<_, ()>(Response::new(statuses[indx]))
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let header = HeaderName::from_static("content-length");
|
||||
let value = HeaderValue::from_static("0");
|
||||
|
||||
{
|
||||
for i in 0..4 {
|
||||
let req = srv
|
||||
.request(Method::GET, srv.surl(&format!("/{}", i)))
|
||||
.send();
|
||||
let response = srv.block_on(req).unwrap();
|
||||
assert_eq!(response.headers().get(&header), None);
|
||||
|
||||
let req = srv
|
||||
.request(Method::HEAD, srv.surl(&format!("/{}", i)))
|
||||
.send();
|
||||
let response = srv.block_on(req).unwrap();
|
||||
assert_eq!(response.headers().get(&header), None);
|
||||
}
|
||||
|
||||
for i in 4..6 {
|
||||
let req = srv
|
||||
.request(Method::GET, srv.surl(&format!("/{}", i)))
|
||||
.send();
|
||||
let response = srv.block_on(req).unwrap();
|
||||
assert_eq!(response.headers().get(&header), Some(&value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_headers() {
|
||||
let data = STR.repeat(10);
|
||||
let data2 = data.clone();
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let data = data.clone();
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build().h2(move |_| {
|
||||
let mut config = Response::Ok();
|
||||
for idx in 0..90 {
|
||||
config.header(
|
||||
format!("X-TEST-{}", idx).as_str(),
|
||||
"TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST ",
|
||||
);
|
||||
}
|
||||
future::ok::<_, ()>(config.body(data.clone()))
|
||||
}).map_err(|_| ()))
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from(data2));
|
||||
}
|
||||
|
||||
const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World";
|
||||
|
||||
#[test]
|
||||
fn test_h2_body2() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| future::ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_head_empty() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.shead("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
assert_eq!(response.version(), Version::HTTP_2);
|
||||
|
||||
{
|
||||
let len = response
|
||||
.headers()
|
||||
.get(http::header::CONTENT_LENGTH)
|
||||
.unwrap();
|
||||
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
|
||||
}
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert!(bytes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_head_binary() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| {
|
||||
ok::<_, ()>(
|
||||
Response::Ok().content_length(STR.len() as u64).body(STR),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.shead("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
{
|
||||
let len = response
|
||||
.headers()
|
||||
.get(http::header::CONTENT_LENGTH)
|
||||
.unwrap();
|
||||
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
|
||||
}
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert!(bytes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_head_binary2() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.shead("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
{
|
||||
let len = response
|
||||
.headers()
|
||||
.get(http::header::CONTENT_LENGTH)
|
||||
.unwrap();
|
||||
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_body_length() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| {
|
||||
let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.body(body::SizedStream::new(STR.len() as u64, body)),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_body_chunked_explicit() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| {
|
||||
let body =
|
||||
once::<_, Error>(Ok(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.header(header::TRANSFER_ENCODING, "chunked")
|
||||
.streaming(body),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
assert!(!response.headers().contains_key(header::TRANSFER_ENCODING));
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
|
||||
// decode
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_response_http_error_handling() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(new_service_cfg(|_: &ServerConfig| {
|
||||
Ok::<_, ()>(|_| {
|
||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.header(http::header::CONTENT_TYPE, broken_header)
|
||||
.body(STR),
|
||||
)
|
||||
})
|
||||
}))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert_eq!(response.status(), http::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_service_error() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| Err::<Response, Error>(error::ErrorBadRequest("error")))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert_eq!(response.status(), http::StatusCode::BAD_REQUEST);
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(b"error"));
|
||||
}
|
@ -2,32 +2,20 @@ use std::io::{Read, Write};
|
||||
use std::time::Duration;
|
||||
use std::{net, thread};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_http_test::TestServer;
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{new_service_cfg, service_fn, NewService};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use bytes::Bytes;
|
||||
use futures::future::{self, ok, Future};
|
||||
use futures::stream::{once, Stream};
|
||||
use regex::Regex;
|
||||
use tokio_timer::sleep;
|
||||
|
||||
use actix_http::error::PayloadError;
|
||||
use actix_http::httpmessage::HttpMessage;
|
||||
use actix_http::{
|
||||
body, error, http, http::header, Error, HttpService, KeepAlive, Request, Response,
|
||||
};
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
fn load_body<S>(stream: S) -> impl Future<Item = BytesMut, Error = PayloadError>
|
||||
where
|
||||
S: Stream<Item = Bytes, Error = PayloadError>,
|
||||
{
|
||||
stream.fold(BytesMut::new(), move |mut body, chunk| {
|
||||
body.extend_from_slice(&chunk);
|
||||
Ok::<_, PayloadError>(body)
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h1() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
@ -64,101 +52,6 @@ fn test_h1_2() {
|
||||
assert!(response.status().is_success());
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
fn ssl_acceptor<T: AsyncRead + AsyncWrite>(
|
||||
) -> std::io::Result<actix_server::ssl::OpensslAcceptor<T, ()>> {
|
||||
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
|
||||
// load ssl keys
|
||||
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
|
||||
builder
|
||||
.set_private_key_file("tests/key.pem", SslFiletype::PEM)
|
||||
.unwrap();
|
||||
builder
|
||||
.set_certificate_chain_file("tests/cert.pem")
|
||||
.unwrap();
|
||||
builder.set_alpn_select_callback(|_, protos| {
|
||||
const H2: &[u8] = b"\x02h2";
|
||||
if protos.windows(3).any(|window| window == H2) {
|
||||
Ok(b"h2")
|
||||
} else {
|
||||
Err(openssl::ssl::AlpnError::NOACK)
|
||||
}
|
||||
});
|
||||
builder.set_alpn_protos(b"\x02h2")?;
|
||||
Ok(actix_server::ssl::OpensslAcceptor::new(builder.build()))
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2() -> std::io::Result<()> {
|
||||
let openssl = ssl_acceptor()?;
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| future::ok::<_, Error>(Response::Ok().finish()))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_1() -> std::io::Result<()> {
|
||||
let openssl = ssl_acceptor()?;
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.finish(|req: Request| {
|
||||
assert!(req.peer_addr().is_some());
|
||||
assert_eq!(req.version(), http::Version::HTTP_2);
|
||||
future::ok::<_, Error>(Response::Ok().finish())
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_body() -> std::io::Result<()> {
|
||||
let data = "HELLOWORLD".to_owned().repeat(64 * 1024);
|
||||
let openssl = ssl_acceptor()?;
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|mut req: Request<_>| {
|
||||
load_body(req.take_payload())
|
||||
.and_then(|body| Ok(Response::Ok().body(body)))
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send_body(data.clone())).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let body = srv.load_body(response).unwrap();
|
||||
assert_eq!(&body, data.as_bytes());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expect_continue() {
|
||||
let srv = TestServer::new(|| {
|
||||
@ -457,65 +350,6 @@ fn test_content_length() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_content_length() {
|
||||
use actix_http::http::{
|
||||
header::{HeaderName, HeaderValue},
|
||||
StatusCode,
|
||||
};
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|req: Request| {
|
||||
let indx: usize = req.uri().path()[1..].parse().unwrap();
|
||||
let statuses = [
|
||||
StatusCode::NO_CONTENT,
|
||||
StatusCode::CONTINUE,
|
||||
StatusCode::SWITCHING_PROTOCOLS,
|
||||
StatusCode::PROCESSING,
|
||||
StatusCode::OK,
|
||||
StatusCode::NOT_FOUND,
|
||||
];
|
||||
future::ok::<_, ()>(Response::new(statuses[indx]))
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let header = HeaderName::from_static("content-length");
|
||||
let value = HeaderValue::from_static("0");
|
||||
|
||||
{
|
||||
for i in 0..4 {
|
||||
let req = srv
|
||||
.request(http::Method::GET, srv.surl(&format!("/{}", i)))
|
||||
.send();
|
||||
let response = srv.block_on(req).unwrap();
|
||||
assert_eq!(response.headers().get(&header), None);
|
||||
|
||||
let req = srv
|
||||
.request(http::Method::HEAD, srv.surl(&format!("/{}", i)))
|
||||
.send();
|
||||
let response = srv.block_on(req).unwrap();
|
||||
assert_eq!(response.headers().get(&header), None);
|
||||
}
|
||||
|
||||
for i in 4..6 {
|
||||
let req = srv
|
||||
.request(http::Method::GET, srv.surl(&format!("/{}", i)))
|
||||
.send();
|
||||
let response = srv.block_on(req).unwrap();
|
||||
assert_eq!(response.headers().get(&header), Some(&value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h1_headers() {
|
||||
let data = STR.repeat(10);
|
||||
@ -555,51 +389,6 @@ fn test_h1_headers() {
|
||||
assert_eq!(bytes, Bytes::from(data2));
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_headers() {
|
||||
let data = STR.repeat(10);
|
||||
let data2 = data.clone();
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let data = data.clone();
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build().h2(move |_| {
|
||||
let mut builder = Response::Ok();
|
||||
for idx in 0..90 {
|
||||
builder.header(
|
||||
format!("X-TEST-{}", idx).as_str(),
|
||||
"TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST ",
|
||||
);
|
||||
}
|
||||
future::ok::<_, ()>(builder.body(data.clone()))
|
||||
}).map_err(|_| ()))
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from(data2));
|
||||
}
|
||||
|
||||
const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
@ -636,29 +425,6 @@ fn test_h1_body() {
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_body2() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| future::ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h1_head_empty() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
@ -681,38 +447,6 @@ fn test_h1_head_empty() {
|
||||
assert!(bytes.is_empty());
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_head_empty() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.shead("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
assert_eq!(response.version(), http::Version::HTTP_2);
|
||||
|
||||
{
|
||||
let len = response
|
||||
.headers()
|
||||
.get(http::header::CONTENT_LENGTH)
|
||||
.unwrap();
|
||||
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
|
||||
}
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert!(bytes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h1_head_binary() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
@ -737,41 +471,6 @@ fn test_h1_head_binary() {
|
||||
assert!(bytes.is_empty());
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_head_binary() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| {
|
||||
ok::<_, ()>(
|
||||
Response::Ok().content_length(STR.len() as u64).body(STR),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.shead("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
{
|
||||
let len = response
|
||||
.headers()
|
||||
.get(http::header::CONTENT_LENGTH)
|
||||
.unwrap();
|
||||
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
|
||||
}
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert!(bytes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h1_head_binary2() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
@ -790,33 +489,6 @@ fn test_h1_head_binary2() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_head_binary2() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.shead("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
{
|
||||
let len = response
|
||||
.headers()
|
||||
.get(http::header::CONTENT_LENGTH)
|
||||
.unwrap();
|
||||
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h1_body_length() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
@ -836,35 +508,6 @@ fn test_h1_body_length() {
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_body_length() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| {
|
||||
let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.body(body::SizedStream::new(STR.len() as u64, body)),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h1_body_chunked_explicit() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
@ -897,40 +540,6 @@ fn test_h1_body_chunked_explicit() {
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_body_chunked_explicit() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| {
|
||||
let body =
|
||||
once::<_, Error>(Ok(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.header(header::TRANSFER_ENCODING, "chunked")
|
||||
.streaming(body),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
assert!(!response.headers().contains_key(header::TRANSFER_ENCODING));
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
|
||||
// decode
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h1_body_chunked_implicit() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
@ -980,39 +589,6 @@ fn test_h1_response_http_error_handling() {
|
||||
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_response_http_error_handling() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(new_service_cfg(|_: &ServerConfig| {
|
||||
Ok::<_, ()>(|_| {
|
||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.header(http::header::CONTENT_TYPE, broken_header)
|
||||
.body(STR),
|
||||
)
|
||||
})
|
||||
}))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert_eq!(response.status(), http::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h1_service_error() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
@ -1028,26 +604,17 @@ fn test_h1_service_error() {
|
||||
assert_eq!(bytes, Bytes::from_static(b"error"));
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_service_error() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| Err::<Response, Error>(error::ErrorBadRequest("error")))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
fn test_h1_on_connect() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
HttpService::build()
|
||||
.on_connect(|_| 10usize)
|
||||
.h1(|req: Request| {
|
||||
assert!(req.extensions().contains::<usize>());
|
||||
future::ok::<_, ()>(Response::Ok().finish())
|
||||
})
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert_eq!(response.status(), http::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert!(bytes.is_empty());
|
||||
let response = srv.block_on(srv.get("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
}
|
||||
|
480
actix-http/tests/test_ssl_server.rs
Normal file
480
actix-http/tests/test_ssl_server.rs
Normal file
@ -0,0 +1,480 @@
|
||||
#![cfg(feature = "ssl")]
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_http_test::TestServer;
|
||||
use actix_server::ssl::OpensslAcceptor;
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{new_service_cfg, NewService};
|
||||
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures::future::{ok, Future};
|
||||
use futures::stream::{once, Stream};
|
||||
use openssl::ssl::{AlpnError, SslAcceptor, SslFiletype, SslMethod};
|
||||
use std::io::Result;
|
||||
|
||||
use actix_http::error::{ErrorBadRequest, PayloadError};
|
||||
use actix_http::http::header::{self, HeaderName, HeaderValue};
|
||||
use actix_http::http::{Method, StatusCode, Version};
|
||||
use actix_http::httpmessage::HttpMessage;
|
||||
use actix_http::{body, Error, HttpService, Request, Response};
|
||||
|
||||
fn load_body<S>(stream: S) -> impl Future<Item = BytesMut, Error = PayloadError>
|
||||
where
|
||||
S: Stream<Item = Bytes, Error = PayloadError>,
|
||||
{
|
||||
stream.fold(BytesMut::new(), move |mut body, chunk| {
|
||||
body.extend_from_slice(&chunk);
|
||||
Ok::<_, PayloadError>(body)
|
||||
})
|
||||
}
|
||||
|
||||
fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<OpensslAcceptor<T, ()>> {
|
||||
// load ssl keys
|
||||
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
|
||||
builder
|
||||
.set_private_key_file("../tests/key.pem", SslFiletype::PEM)
|
||||
.unwrap();
|
||||
builder
|
||||
.set_certificate_chain_file("../tests/cert.pem")
|
||||
.unwrap();
|
||||
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(b"\x02h2")?;
|
||||
Ok(OpensslAcceptor::new(builder.build()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2() -> Result<()> {
|
||||
let openssl = ssl_acceptor()?;
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, Error>(Response::Ok().finish()))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_1() -> Result<()> {
|
||||
let openssl = ssl_acceptor()?;
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.finish(|req: Request| {
|
||||
assert!(req.peer_addr().is_some());
|
||||
assert_eq!(req.version(), Version::HTTP_2);
|
||||
ok::<_, Error>(Response::Ok().finish())
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_body() -> Result<()> {
|
||||
let data = "HELLOWORLD".to_owned().repeat(64 * 1024);
|
||||
let openssl = ssl_acceptor()?;
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|mut req: Request<_>| {
|
||||
load_body(req.take_payload())
|
||||
.and_then(|body| Ok(Response::Ok().body(body)))
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send_body(data.clone())).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let body = srv.load_body(response).unwrap();
|
||||
assert_eq!(&body, data.as_bytes());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_content_length() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|req: Request| {
|
||||
let indx: usize = req.uri().path()[1..].parse().unwrap();
|
||||
let statuses = [
|
||||
StatusCode::NO_CONTENT,
|
||||
StatusCode::CONTINUE,
|
||||
StatusCode::SWITCHING_PROTOCOLS,
|
||||
StatusCode::PROCESSING,
|
||||
StatusCode::OK,
|
||||
StatusCode::NOT_FOUND,
|
||||
];
|
||||
ok::<_, ()>(Response::new(statuses[indx]))
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let header = HeaderName::from_static("content-length");
|
||||
let value = HeaderValue::from_static("0");
|
||||
|
||||
{
|
||||
for i in 0..4 {
|
||||
let req = srv
|
||||
.request(Method::GET, srv.surl(&format!("/{}", i)))
|
||||
.send();
|
||||
let response = srv.block_on(req).unwrap();
|
||||
assert_eq!(response.headers().get(&header), None);
|
||||
|
||||
let req = srv
|
||||
.request(Method::HEAD, srv.surl(&format!("/{}", i)))
|
||||
.send();
|
||||
let response = srv.block_on(req).unwrap();
|
||||
assert_eq!(response.headers().get(&header), None);
|
||||
}
|
||||
|
||||
for i in 4..6 {
|
||||
let req = srv
|
||||
.request(Method::GET, srv.surl(&format!("/{}", i)))
|
||||
.send();
|
||||
let response = srv.block_on(req).unwrap();
|
||||
assert_eq!(response.headers().get(&header), Some(&value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_headers() {
|
||||
let data = STR.repeat(10);
|
||||
let data2 = data.clone();
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let data = data.clone();
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build().h2(move |_| {
|
||||
let mut builder = Response::Ok();
|
||||
for idx in 0..90 {
|
||||
builder.header(
|
||||
format!("X-TEST-{}", idx).as_str(),
|
||||
"TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST ",
|
||||
);
|
||||
}
|
||||
ok::<_, ()>(builder.body(data.clone()))
|
||||
}).map_err(|_| ()))
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from(data2));
|
||||
}
|
||||
|
||||
const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World";
|
||||
|
||||
#[test]
|
||||
fn test_h2_body2() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_head_empty() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.shead("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
assert_eq!(response.version(), Version::HTTP_2);
|
||||
|
||||
{
|
||||
let len = response.headers().get(header::CONTENT_LENGTH).unwrap();
|
||||
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
|
||||
}
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert!(bytes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_head_binary() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| {
|
||||
ok::<_, ()>(
|
||||
Response::Ok().content_length(STR.len() as u64).body(STR),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.shead("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
{
|
||||
let len = response.headers().get(header::CONTENT_LENGTH).unwrap();
|
||||
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
|
||||
}
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert!(bytes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_head_binary2() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.shead("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
{
|
||||
let len = response.headers().get(header::CONTENT_LENGTH).unwrap();
|
||||
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_body_length() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| {
|
||||
let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.body(body::SizedStream::new(STR.len() as u64, body)),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_body_chunked_explicit() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| {
|
||||
let body =
|
||||
once::<_, Error>(Ok(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.header(header::TRANSFER_ENCODING, "chunked")
|
||||
.streaming(body),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
assert!(!response.headers().contains_key(header::TRANSFER_ENCODING));
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
|
||||
// decode
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_response_http_error_handling() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(new_service_cfg(|_: &ServerConfig| {
|
||||
Ok::<_, ()>(|_| {
|
||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.header(header::CONTENT_TYPE, broken_header)
|
||||
.body(STR),
|
||||
)
|
||||
})
|
||||
}))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_service_error() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| Err::<Response, Error>(ErrorBadRequest("error")))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(b"error"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_on_connect() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.on_connect(|_| 10usize)
|
||||
.h2(|req: Request| {
|
||||
assert!(req.extensions().contains::<usize>());
|
||||
ok::<_, ()>(Response::Ok().finish())
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
}
|
@ -261,7 +261,7 @@ where
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = Error;
|
||||
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
|
||||
type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.service.borrow_mut().poll_ready()
|
||||
@ -283,7 +283,7 @@ where
|
||||
res.request().extensions_mut().remove::<IdentityItem>();
|
||||
|
||||
if let Some(id) = id {
|
||||
return Either::A(
|
||||
Either::A(
|
||||
backend
|
||||
.to_response(id.id, id.changed, &mut res)
|
||||
.into_future()
|
||||
@ -291,7 +291,7 @@ where
|
||||
Ok(_) => Ok(res),
|
||||
Err(e) => Ok(res.error_response(e)),
|
||||
}),
|
||||
);
|
||||
)
|
||||
} else {
|
||||
Either::B(ok(res))
|
||||
}
|
||||
@ -333,8 +333,7 @@ struct CookieIdentityExtention {
|
||||
|
||||
impl CookieIdentityInner {
|
||||
fn new(key: &[u8]) -> CookieIdentityInner {
|
||||
let key_v2: Vec<u8> =
|
||||
key.iter().chain([1, 0, 0, 0].iter()).map(|e| *e).collect();
|
||||
let key_v2: Vec<u8> = key.iter().chain([1, 0, 0, 0].iter()).cloned().collect();
|
||||
CookieIdentityInner {
|
||||
key: Key::from_master(key),
|
||||
key_v2: Key::from_master(&key_v2),
|
||||
@ -585,13 +584,14 @@ impl IdentityPolicy for CookieIdentityPolicy {
|
||||
)
|
||||
} else if self.0.always_update_cookie() && id.is_some() {
|
||||
let visit_timestamp = SystemTime::now();
|
||||
let mut login_timestamp = None;
|
||||
if self.0.requires_oob_data() {
|
||||
let login_timestamp = if self.0.requires_oob_data() {
|
||||
let CookieIdentityExtention {
|
||||
login_timestamp: lt,
|
||||
} = res.request().extensions_mut().remove().unwrap();
|
||||
login_timestamp = lt;
|
||||
}
|
||||
lt
|
||||
} else {
|
||||
None
|
||||
};
|
||||
self.0.set_cookie(
|
||||
res,
|
||||
Some(CookieValue {
|
||||
|
@ -1,6 +1,9 @@
|
||||
# Changes
|
||||
## [0.1.4] - 2019-xx-xx
|
||||
|
||||
## [0.1.3] - 2019-06-06
|
||||
* Multipart handling now parses requests which do not end in CRLF #1038
|
||||
|
||||
## [0.1.3] - 2019-08-18
|
||||
|
||||
* Fix ring dependency from actix-web default features for #741.
|
||||
|
||||
|
@ -1,3 +1,5 @@
|
||||
#![allow(clippy::borrow_interior_mutable_const)]
|
||||
|
||||
mod error;
|
||||
mod extractor;
|
||||
mod server;
|
||||
|
@ -1,5 +1,5 @@
|
||||
//! Multipart payload support
|
||||
use std::cell::{Cell, RefCell, UnsafeCell};
|
||||
use std::cell::{Cell, RefCell, RefMut};
|
||||
use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
use std::{cmp, fmt};
|
||||
@ -112,7 +112,7 @@ impl Stream for Multipart {
|
||||
Err(err)
|
||||
} else if self.safety.current() {
|
||||
let mut inner = self.inner.as_mut().unwrap().borrow_mut();
|
||||
if let Some(payload) = inner.payload.get_mut(&self.safety) {
|
||||
if let Some(mut payload) = inner.payload.get_mut(&self.safety) {
|
||||
payload.poll_stream()?;
|
||||
}
|
||||
inner.poll(&self.safety)
|
||||
@ -167,7 +167,7 @@ impl InnerMultipart {
|
||||
boundary: &str,
|
||||
) -> Result<Option<bool>, MultipartError> {
|
||||
// TODO: need to read epilogue
|
||||
match payload.readline()? {
|
||||
match payload.readline_or_eof()? {
|
||||
None => {
|
||||
if payload.eof {
|
||||
Ok(Some(true))
|
||||
@ -176,16 +176,15 @@ impl InnerMultipart {
|
||||
}
|
||||
}
|
||||
Some(chunk) => {
|
||||
if chunk.len() == boundary.len() + 4
|
||||
&& &chunk[..2] == b"--"
|
||||
&& &chunk[2..boundary.len() + 2] == boundary.as_bytes()
|
||||
{
|
||||
if chunk.len() < boundary.len() + 4
|
||||
|| &chunk[..2] != b"--"
|
||||
|| &chunk[2..boundary.len() + 2] != boundary.as_bytes() {
|
||||
Err(MultipartError::Boundary)
|
||||
} else if &chunk[boundary.len() + 2..] == b"\r\n" {
|
||||
Ok(Some(false))
|
||||
} else if chunk.len() == boundary.len() + 6
|
||||
&& &chunk[..2] == b"--"
|
||||
&& &chunk[2..boundary.len() + 2] == boundary.as_bytes()
|
||||
&& &chunk[boundary.len() + 2..boundary.len() + 4] == b"--"
|
||||
{
|
||||
} else if &chunk[boundary.len() + 2..boundary.len() + 4] == b"--"
|
||||
&& (chunk.len() == boundary.len() + 4
|
||||
|| &chunk[boundary.len() + 4..] == b"\r\n") {
|
||||
Ok(Some(true))
|
||||
} else {
|
||||
Err(MultipartError::Boundary)
|
||||
@ -265,12 +264,12 @@ impl InnerMultipart {
|
||||
}
|
||||
}
|
||||
|
||||
let headers = if let Some(payload) = self.payload.get_mut(safety) {
|
||||
let headers = if let Some(mut payload) = self.payload.get_mut(safety) {
|
||||
match self.state {
|
||||
// read until first boundary
|
||||
InnerState::FirstBoundary => {
|
||||
match InnerMultipart::skip_until_boundary(
|
||||
payload,
|
||||
&mut *payload,
|
||||
&self.boundary,
|
||||
)? {
|
||||
Some(eof) => {
|
||||
@ -286,7 +285,10 @@ impl InnerMultipart {
|
||||
}
|
||||
// read boundary
|
||||
InnerState::Boundary => {
|
||||
match InnerMultipart::read_boundary(payload, &self.boundary)? {
|
||||
match InnerMultipart::read_boundary(
|
||||
&mut *payload,
|
||||
&self.boundary,
|
||||
)? {
|
||||
None => return Ok(Async::NotReady),
|
||||
Some(eof) => {
|
||||
if eof {
|
||||
@ -303,7 +305,7 @@ impl InnerMultipart {
|
||||
|
||||
// read field headers for next field
|
||||
if self.state == InnerState::Headers {
|
||||
if let Some(headers) = InnerMultipart::read_headers(payload)? {
|
||||
if let Some(headers) = InnerMultipart::read_headers(&mut *payload)? {
|
||||
self.state = InnerState::Boundary;
|
||||
headers
|
||||
} else {
|
||||
@ -411,14 +413,15 @@ impl Stream for Field {
|
||||
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
|
||||
if self.safety.current() {
|
||||
let mut inner = self.inner.borrow_mut();
|
||||
if let Some(payload) = inner.payload.as_ref().unwrap().get_mut(&self.safety)
|
||||
if let Some(mut payload) =
|
||||
inner.payload.as_ref().unwrap().get_mut(&self.safety)
|
||||
{
|
||||
payload.poll_stream()?;
|
||||
}
|
||||
|
||||
inner.poll(&self.safety)
|
||||
} else if !self.safety.is_clean() {
|
||||
return Err(MultipartError::NotConsumed);
|
||||
Err(MultipartError::NotConsumed)
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
@ -533,11 +536,9 @@ impl InnerField {
|
||||
let b_size = boundary.len() + b_len;
|
||||
if len < b_size {
|
||||
return Ok(Async::NotReady);
|
||||
} else {
|
||||
if &payload.buf[b_len..b_size] == boundary.as_bytes() {
|
||||
// found boundary
|
||||
return Ok(Async::Ready(None));
|
||||
}
|
||||
} else if &payload.buf[b_len..b_size] == boundary.as_bytes() {
|
||||
// found boundary
|
||||
return Ok(Async::Ready(None));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -557,7 +558,7 @@ impl InnerField {
|
||||
// check boundary
|
||||
if (&payload.buf[cur..cur + 2] == b"\r\n"
|
||||
&& &payload.buf[cur + 2..cur + 4] == b"--")
|
||||
|| (&payload.buf[cur..cur + 1] == b"\r"
|
||||
|| (&payload.buf[cur..=cur] == b"\r"
|
||||
&& &payload.buf[cur + 1..cur + 3] == b"--")
|
||||
{
|
||||
if cur != 0 {
|
||||
@ -584,12 +585,13 @@ impl InnerField {
|
||||
return Ok(Async::Ready(None));
|
||||
}
|
||||
|
||||
let result = if let Some(payload) = self.payload.as_ref().unwrap().get_mut(s) {
|
||||
let result = if let Some(mut payload) = self.payload.as_ref().unwrap().get_mut(s)
|
||||
{
|
||||
if !self.eof {
|
||||
let res = if let Some(ref mut len) = self.length {
|
||||
InnerField::read_len(payload, len)?
|
||||
InnerField::read_len(&mut *payload, len)?
|
||||
} else {
|
||||
InnerField::read_stream(payload, &self.boundary)?
|
||||
InnerField::read_stream(&mut *payload, &self.boundary)?
|
||||
};
|
||||
|
||||
match res {
|
||||
@ -620,7 +622,7 @@ impl InnerField {
|
||||
}
|
||||
|
||||
struct PayloadRef {
|
||||
payload: Rc<UnsafeCell<PayloadBuffer>>,
|
||||
payload: Rc<RefCell<PayloadBuffer>>,
|
||||
}
|
||||
|
||||
impl PayloadRef {
|
||||
@ -630,15 +632,12 @@ impl PayloadRef {
|
||||
}
|
||||
}
|
||||
|
||||
fn get_mut<'a, 'b>(&'a self, s: &'b Safety) -> Option<&'a mut PayloadBuffer>
|
||||
fn get_mut<'a, 'b>(&'a self, s: &'b Safety) -> Option<RefMut<'a, PayloadBuffer>>
|
||||
where
|
||||
'a: 'b,
|
||||
{
|
||||
// Unsafe: Invariant is inforced by Safety Safety is used as ref counter,
|
||||
// only top most ref can have mutable access to payload.
|
||||
if s.current() {
|
||||
let payload: &mut PayloadBuffer = unsafe { &mut *self.payload.get() };
|
||||
Some(payload)
|
||||
Some(self.payload.borrow_mut())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@ -779,6 +778,14 @@ impl PayloadBuffer {
|
||||
self.read_until(b"\n")
|
||||
}
|
||||
|
||||
/// Read bytes until new line delimiter or eof
|
||||
pub fn readline_or_eof(&mut self) -> Result<Option<Bytes>, MultipartError> {
|
||||
match self.readline() {
|
||||
Err(MultipartError::Incomplete) if self.eof => Ok(Some(self.buf.take().freeze())),
|
||||
line => line
|
||||
}
|
||||
}
|
||||
|
||||
/// Put unprocessed data back to the buffer
|
||||
pub fn unprocessed(&mut self, data: Bytes) {
|
||||
let buf = BytesMut::from(data);
|
||||
@ -849,32 +856,65 @@ mod tests {
|
||||
(tx, rx.map_err(|_| panic!()).and_then(|res| res))
|
||||
}
|
||||
|
||||
fn create_simple_request_with_header() -> (Bytes, HeaderMap) {
|
||||
let bytes = Bytes::from(
|
||||
"testasdadsad\r\n\
|
||||
--abbc761f78ff4d7cb7573b5a23f96ef0\r\n\
|
||||
Content-Disposition: form-data; name=\"file\"; filename=\"fn.txt\"\r\n\
|
||||
Content-Type: text/plain; charset=utf-8\r\nContent-Length: 4\r\n\r\n\
|
||||
test\r\n\
|
||||
--abbc761f78ff4d7cb7573b5a23f96ef0\r\n\
|
||||
Content-Type: text/plain; charset=utf-8\r\nContent-Length: 4\r\n\r\n\
|
||||
data\r\n\
|
||||
--abbc761f78ff4d7cb7573b5a23f96ef0--\r\n"
|
||||
);
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::CONTENT_TYPE,
|
||||
header::HeaderValue::from_static(
|
||||
"multipart/mixed; boundary=\"abbc761f78ff4d7cb7573b5a23f96ef0\"",
|
||||
),
|
||||
);
|
||||
(bytes, headers)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multipart_no_end_crlf() {
|
||||
run_on(|| {
|
||||
let (sender, payload) = create_stream();
|
||||
let (bytes, headers) = create_simple_request_with_header();
|
||||
let bytes_stripped = bytes.slice_to(bytes.len()); // strip crlf
|
||||
|
||||
sender.unbounded_send(Ok(bytes_stripped)).unwrap();
|
||||
drop(sender); // eof
|
||||
|
||||
let mut multipart = Multipart::new(&headers, payload);
|
||||
|
||||
match multipart.poll().unwrap() {
|
||||
Async::Ready(Some(_)) => (),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
|
||||
match multipart.poll().unwrap() {
|
||||
Async::Ready(Some(_)) => (),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
|
||||
match multipart.poll().unwrap() {
|
||||
Async::Ready(None) => (),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multipart() {
|
||||
run_on(|| {
|
||||
let (sender, payload) = create_stream();
|
||||
let (bytes, headers) = create_simple_request_with_header();
|
||||
|
||||
let bytes = Bytes::from(
|
||||
"testasdadsad\r\n\
|
||||
--abbc761f78ff4d7cb7573b5a23f96ef0\r\n\
|
||||
Content-Disposition: form-data; name=\"file\"; filename=\"fn.txt\"\r\n\
|
||||
Content-Type: text/plain; charset=utf-8\r\nContent-Length: 4\r\n\r\n\
|
||||
test\r\n\
|
||||
--abbc761f78ff4d7cb7573b5a23f96ef0\r\n\
|
||||
Content-Type: text/plain; charset=utf-8\r\nContent-Length: 4\r\n\r\n\
|
||||
data\r\n\
|
||||
--abbc761f78ff4d7cb7573b5a23f96ef0--\r\n",
|
||||
);
|
||||
sender.unbounded_send(Ok(bytes)).unwrap();
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::CONTENT_TYPE,
|
||||
header::HeaderValue::from_static(
|
||||
"multipart/mixed; boundary=\"abbc761f78ff4d7cb7573b5a23f96ef0\"",
|
||||
),
|
||||
);
|
||||
|
||||
let mut multipart = Multipart::new(&headers, payload);
|
||||
match multipart.poll().unwrap() {
|
||||
Async::Ready(Some(mut field)) => {
|
||||
@ -925,28 +965,10 @@ mod tests {
|
||||
fn test_stream() {
|
||||
run_on(|| {
|
||||
let (sender, payload) = create_stream();
|
||||
let (bytes, headers) = create_simple_request_with_header();
|
||||
|
||||
let bytes = Bytes::from(
|
||||
"testasdadsad\r\n\
|
||||
--abbc761f78ff4d7cb7573b5a23f96ef0\r\n\
|
||||
Content-Disposition: form-data; name=\"file\"; filename=\"fn.txt\"\r\n\
|
||||
Content-Type: text/plain; charset=utf-8\r\n\r\n\
|
||||
test\r\n\
|
||||
--abbc761f78ff4d7cb7573b5a23f96ef0\r\n\
|
||||
Content-Type: text/plain; charset=utf-8\r\n\r\n\
|
||||
data\r\n\
|
||||
--abbc761f78ff4d7cb7573b5a23f96ef0--\r\n",
|
||||
);
|
||||
sender.unbounded_send(Ok(bytes)).unwrap();
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::CONTENT_TYPE,
|
||||
header::HeaderValue::from_static(
|
||||
"multipart/mixed; boundary=\"abbc761f78ff4d7cb7573b5a23f96ef0\"",
|
||||
),
|
||||
);
|
||||
|
||||
let mut multipart = Multipart::new(&headers, payload);
|
||||
match multipart.poll().unwrap() {
|
||||
Async::Ready(Some(mut field)) => {
|
||||
|
@ -1,5 +1,12 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.0] - 2019-07-08
|
||||
|
||||
* Enhanced ``actix-session`` to facilitate state changes. Use ``Session.renew()``
|
||||
at successful login to cycle a session (new key/cookie but keeps state).
|
||||
Use ``Session.purge()`` at logout to invalid a session cookie (and remove
|
||||
from redis cache, if applicable).
|
||||
|
||||
## [0.1.1] - 2019-06-03
|
||||
|
||||
* Fix optional cookie session support
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-session"
|
||||
version = "0.1.1"
|
||||
version = "0.2.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Session for actix web framework."
|
||||
readme = "README.md"
|
||||
|
@ -6,4 +6,4 @@
|
||||
* [API Documentation](https://docs.rs/actix-session/)
|
||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||
* Cargo package: [actix-session](https://crates.io/crates/actix-session)
|
||||
* Minimum supported Rust version: 1.33 or later
|
||||
* Minimum supported Rust version: 1.34 or later
|
||||
|
@ -28,7 +28,7 @@ use futures::future::{ok, Future, FutureResult};
|
||||
use futures::Poll;
|
||||
use serde_json::error::Error as JsonError;
|
||||
|
||||
use crate::Session;
|
||||
use crate::{Session, SessionStatus};
|
||||
|
||||
/// Errors that can occur during handling cookie session
|
||||
#[derive(Debug, From, Display)]
|
||||
@ -119,7 +119,20 @@ impl CookieSessionInner {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load(&self, req: &ServiceRequest) -> HashMap<String, String> {
|
||||
/// invalidates session cookie
|
||||
fn remove_cookie<B>(&self, res: &mut ServiceResponse<B>) -> Result<(), Error> {
|
||||
let mut cookie = Cookie::named(self.name.clone());
|
||||
cookie.set_value("");
|
||||
cookie.set_max_age(time::Duration::seconds(0));
|
||||
cookie.set_expires(time::now() - time::Duration::days(365));
|
||||
|
||||
let val = HeaderValue::from_str(&cookie.to_string())?;
|
||||
res.headers_mut().append(SET_COOKIE, val);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load(&self, req: &ServiceRequest) -> (bool, HashMap<String, String>) {
|
||||
if let Ok(cookies) = req.cookies() {
|
||||
for cookie in cookies.iter() {
|
||||
if cookie.name() == self.name {
|
||||
@ -134,13 +147,13 @@ impl CookieSessionInner {
|
||||
};
|
||||
if let Some(cookie) = cookie_opt {
|
||||
if let Ok(val) = serde_json::from_str(cookie.value()) {
|
||||
return val;
|
||||
return (false, val);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
HashMap::new()
|
||||
(true, HashMap::new())
|
||||
}
|
||||
}
|
||||
|
||||
@ -296,22 +309,43 @@ where
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = S::Error;
|
||||
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
|
||||
type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.service.poll_ready()
|
||||
}
|
||||
|
||||
/// On first request, a new session cookie is returned in response, regardless
|
||||
/// of whether any session state is set. With subsequent requests, if the
|
||||
/// session state changes, then set-cookie is returned in response. As
|
||||
/// a user logs out, call session.purge() to set SessionStatus accordingly
|
||||
/// and this will trigger removal of the session cookie in the response.
|
||||
fn call(&mut self, mut req: ServiceRequest) -> Self::Future {
|
||||
let inner = self.inner.clone();
|
||||
let state = self.inner.load(&req);
|
||||
let (is_new, state) = self.inner.load(&req);
|
||||
Session::set_session(state.into_iter(), &mut req);
|
||||
|
||||
Box::new(self.service.call(req).map(move |mut res| {
|
||||
if let Some(state) = Session::get_changes(&mut res) {
|
||||
res.checked_expr(|res| inner.set_cookie(res, state))
|
||||
} else {
|
||||
res
|
||||
match Session::get_changes(&mut res) {
|
||||
(SessionStatus::Changed, Some(state))
|
||||
| (SessionStatus::Renewed, Some(state)) => {
|
||||
res.checked_expr(|res| inner.set_cookie(res, state))
|
||||
}
|
||||
(SessionStatus::Unchanged, _) =>
|
||||
// set a new session cookie upon first request (new client)
|
||||
{
|
||||
if is_new {
|
||||
let state: HashMap<String, String> = HashMap::new();
|
||||
res.checked_expr(|res| inner.set_cookie(res, state.into_iter()))
|
||||
} else {
|
||||
res
|
||||
}
|
||||
}
|
||||
(SessionStatus::Purged, _) => {
|
||||
let _ = inner.remove_cookie(&mut res);
|
||||
res
|
||||
}
|
||||
_ => res,
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
@ -98,10 +98,23 @@ impl UserSession for ServiceRequest {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Clone, Debug)]
|
||||
pub enum SessionStatus {
|
||||
Changed,
|
||||
Purged,
|
||||
Renewed,
|
||||
Unchanged,
|
||||
}
|
||||
impl Default for SessionStatus {
|
||||
fn default() -> SessionStatus {
|
||||
SessionStatus::Unchanged
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SessionInner {
|
||||
state: HashMap<String, String>,
|
||||
changed: bool,
|
||||
pub status: SessionStatus,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@ -117,25 +130,46 @@ impl Session {
|
||||
/// Set a `value` from the session.
|
||||
pub fn set<T: Serialize>(&self, key: &str, value: T) -> Result<(), Error> {
|
||||
let mut inner = self.0.borrow_mut();
|
||||
inner.changed = true;
|
||||
inner
|
||||
.state
|
||||
.insert(key.to_owned(), serde_json::to_string(&value)?);
|
||||
if inner.status != SessionStatus::Purged {
|
||||
inner.status = SessionStatus::Changed;
|
||||
inner
|
||||
.state
|
||||
.insert(key.to_owned(), serde_json::to_string(&value)?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove value from the session.
|
||||
pub fn remove(&self, key: &str) {
|
||||
let mut inner = self.0.borrow_mut();
|
||||
inner.changed = true;
|
||||
inner.state.remove(key);
|
||||
if inner.status != SessionStatus::Purged {
|
||||
inner.status = SessionStatus::Changed;
|
||||
inner.state.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear the session.
|
||||
pub fn clear(&self) {
|
||||
let mut inner = self.0.borrow_mut();
|
||||
inner.changed = true;
|
||||
inner.state.clear()
|
||||
if inner.status != SessionStatus::Purged {
|
||||
inner.status = SessionStatus::Changed;
|
||||
inner.state.clear()
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes session, both client and server side.
|
||||
pub fn purge(&self) {
|
||||
let mut inner = self.0.borrow_mut();
|
||||
inner.status = SessionStatus::Purged;
|
||||
inner.state.clear();
|
||||
}
|
||||
|
||||
/// Renews the session key, assigning existing session state to new key.
|
||||
pub fn renew(&self) {
|
||||
let mut inner = self.0.borrow_mut();
|
||||
if inner.status != SessionStatus::Purged {
|
||||
inner.status = SessionStatus::Renewed;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_session(
|
||||
@ -149,7 +183,10 @@ impl Session {
|
||||
|
||||
pub fn get_changes<B>(
|
||||
res: &mut ServiceResponse<B>,
|
||||
) -> Option<impl Iterator<Item = (String, String)>> {
|
||||
) -> (
|
||||
SessionStatus,
|
||||
Option<impl Iterator<Item = (String, String)>>,
|
||||
) {
|
||||
if let Some(s_impl) = res
|
||||
.request()
|
||||
.extensions()
|
||||
@ -157,9 +194,9 @@ impl Session {
|
||||
{
|
||||
let state =
|
||||
std::mem::replace(&mut s_impl.borrow_mut().state, HashMap::new());
|
||||
Some(state.into_iter())
|
||||
(s_impl.borrow().status.clone(), Some(state.into_iter()))
|
||||
} else {
|
||||
None
|
||||
(SessionStatus::Unchanged, None)
|
||||
}
|
||||
}
|
||||
|
||||
@ -224,7 +261,8 @@ mod tests {
|
||||
session.remove("key");
|
||||
|
||||
let mut res = req.into_response(HttpResponse::Ok().finish());
|
||||
let changes: Vec<_> = Session::get_changes(&mut res).unwrap().collect();
|
||||
let (_status, state) = Session::get_changes(&mut res);
|
||||
let changes: Vec<_> = state.unwrap().collect();
|
||||
assert_eq!(changes, [("key2".to_string(), "\"value2\"".to_string())]);
|
||||
}
|
||||
|
||||
@ -241,4 +279,22 @@ mod tests {
|
||||
let res = session.get::<String>("key").unwrap();
|
||||
assert_eq!(res, Some("value".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn purge_session() {
|
||||
let req = test::TestRequest::default().to_srv_request();
|
||||
let session = Session::get_session(&mut *req.extensions_mut());
|
||||
assert_eq!(session.0.borrow().status, SessionStatus::Unchanged);
|
||||
session.purge();
|
||||
assert_eq!(session.0.borrow().status, SessionStatus::Purged);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renew_session() {
|
||||
let req = test::TestRequest::default().to_srv_request();
|
||||
let session = Session::get_session(&mut *req.extensions_mut());
|
||||
assert_eq!(session.0.borrow().status, SessionStatus::Unchanged);
|
||||
session.renew();
|
||||
assert_eq!(session.0.borrow().status, SessionStatus::Renewed);
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,12 @@
|
||||
# Changes
|
||||
|
||||
## [1.0.2] - 2019-07-20
|
||||
|
||||
* Add `ws::start_with_addr()`, returning the address of the created actor, along
|
||||
with the `HttpResponse`.
|
||||
|
||||
* Add support for specifying protocols on websocket handshake #835
|
||||
|
||||
## [1.0.1] - 2019-06-28
|
||||
|
||||
* Allow to use custom ws codec with `WebsocketContext` #925
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web-actors"
|
||||
version = "1.0.1"
|
||||
version = "1.0.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix actors support for actix web framework."
|
||||
readme = "README.md"
|
||||
@ -19,12 +19,12 @@ path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix = "0.8.3"
|
||||
actix-web = "1.0.2"
|
||||
actix-http = "0.2.4"
|
||||
actix-web = "1.0.3"
|
||||
actix-http = "0.2.5"
|
||||
actix-codec = "0.1.2"
|
||||
bytes = "0.4"
|
||||
futures = "0.1.25"
|
||||
|
||||
[dev-dependencies]
|
||||
env_logger = "0.6"
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.4", features=["ssl"] }
|
||||
|
@ -1,3 +1,4 @@
|
||||
#![allow(clippy::borrow_interior_mutable_const)]
|
||||
//! Actix actors integration for Actix web framework
|
||||
mod context;
|
||||
pub mod ws;
|
||||
|
@ -35,15 +35,68 @@ where
|
||||
Ok(res.streaming(WebsocketContext::create(actor, stream)))
|
||||
}
|
||||
|
||||
/// Do websocket handshake and start ws actor.
|
||||
///
|
||||
/// `req` is an HTTP Request that should be requesting a websocket protocol
|
||||
/// change. `stream` should be a `Bytes` stream (such as
|
||||
/// `actix_web::web::Payload`) that contains a stream of the body request.
|
||||
///
|
||||
/// If there is a problem with the handshake, an error is returned.
|
||||
///
|
||||
/// If successful, returns a pair where the first item is an address for the
|
||||
/// created actor and the second item is the response that should be returned
|
||||
/// from the websocket request.
|
||||
pub fn start_with_addr<A, T>(
|
||||
actor: A,
|
||||
req: &HttpRequest,
|
||||
stream: T,
|
||||
) -> Result<(Addr<A>, HttpResponse), Error>
|
||||
where
|
||||
A: Actor<Context = WebsocketContext<A>> + StreamHandler<Message, ProtocolError>,
|
||||
T: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
||||
{
|
||||
let mut res = handshake(req)?;
|
||||
let (addr, out_stream) = WebsocketContext::create_with_addr(actor, stream);
|
||||
Ok((addr, res.streaming(out_stream)))
|
||||
}
|
||||
|
||||
/// Do websocket handshake and start ws actor.
|
||||
///
|
||||
/// `protocols` is a sequence of known protocols.
|
||||
pub fn start_with_protocols<A, T>(
|
||||
actor: A,
|
||||
protocols: &[&str],
|
||||
req: &HttpRequest,
|
||||
stream: T,
|
||||
) -> Result<HttpResponse, Error>
|
||||
where
|
||||
A: Actor<Context = WebsocketContext<A>> + StreamHandler<Message, ProtocolError>,
|
||||
T: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
||||
{
|
||||
let mut res = handshake_with_protocols(req, protocols)?;
|
||||
Ok(res.streaming(WebsocketContext::create(actor, stream)))
|
||||
}
|
||||
|
||||
/// Prepare `WebSocket` handshake response.
|
||||
///
|
||||
/// This function returns handshake `HttpResponse`, ready to send to peer.
|
||||
/// It does not perform any IO.
|
||||
pub fn handshake(req: &HttpRequest) -> Result<HttpResponseBuilder, HandshakeError> {
|
||||
handshake_with_protocols(req, &[])
|
||||
}
|
||||
|
||||
/// Prepare `WebSocket` handshake response.
|
||||
///
|
||||
/// This function returns handshake `HttpResponse`, ready to send to peer.
|
||||
/// It does not perform any IO.
|
||||
///
|
||||
// /// `protocols` is a sequence of known protocols. On successful handshake,
|
||||
// /// the returned response headers contain the first protocol in this list
|
||||
// /// which the server also knows.
|
||||
pub fn handshake(req: &HttpRequest) -> Result<HttpResponseBuilder, HandshakeError> {
|
||||
/// `protocols` is a sequence of known protocols. On successful handshake,
|
||||
/// the returned response headers contain the first protocol in this list
|
||||
/// which the server also knows.
|
||||
pub fn handshake_with_protocols(
|
||||
req: &HttpRequest,
|
||||
protocols: &[&str],
|
||||
) -> Result<HttpResponseBuilder, HandshakeError> {
|
||||
// WebSocket accepts only GET
|
||||
if *req.method() != Method::GET {
|
||||
return Err(HandshakeError::GetMethodRequired);
|
||||
@ -92,11 +145,28 @@ pub fn handshake(req: &HttpRequest) -> Result<HttpResponseBuilder, HandshakeErro
|
||||
hash_key(key.as_ref())
|
||||
};
|
||||
|
||||
Ok(HttpResponse::build(StatusCode::SWITCHING_PROTOCOLS)
|
||||
// check requested protocols
|
||||
let protocol =
|
||||
req.headers()
|
||||
.get(&header::SEC_WEBSOCKET_PROTOCOL)
|
||||
.and_then(|req_protocols| {
|
||||
let req_protocols = req_protocols.to_str().ok()?;
|
||||
req_protocols
|
||||
.split(", ")
|
||||
.find(|req_p| protocols.iter().any(|p| p == req_p))
|
||||
});
|
||||
|
||||
let mut response = HttpResponse::build(StatusCode::SWITCHING_PROTOCOLS)
|
||||
.upgrade("websocket")
|
||||
.header(header::TRANSFER_ENCODING, "chunked")
|
||||
.header(header::SEC_WEBSOCKET_ACCEPT, key.as_str())
|
||||
.take())
|
||||
.take();
|
||||
|
||||
if let Some(protocol) = protocol {
|
||||
response.header(&header::SEC_WEBSOCKET_PROTOCOL, protocol);
|
||||
}
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
/// Execution context for `WebSockets` actors
|
||||
@ -168,6 +238,24 @@ where
|
||||
#[inline]
|
||||
/// Create a new Websocket context from a request and an actor
|
||||
pub fn create<S>(actor: A, stream: S) -> impl Stream<Item = Bytes, Error = Error>
|
||||
where
|
||||
A: StreamHandler<Message, ProtocolError>,
|
||||
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
||||
{
|
||||
let (_, stream) = WebsocketContext::create_with_addr(actor, stream);
|
||||
stream
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// Create a new Websocket context from a request and an actor.
|
||||
///
|
||||
/// Returns a pair, where the first item is an addr for the created actor,
|
||||
/// and the second item is a stream intended to be set as part of the
|
||||
/// response via `HttpResponseBuilder::streaming()`.
|
||||
pub fn create_with_addr<S>(
|
||||
actor: A,
|
||||
stream: S,
|
||||
) -> (Addr<A>, impl Stream<Item = Bytes, Error = Error>)
|
||||
where
|
||||
A: StreamHandler<Message, ProtocolError>,
|
||||
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
||||
@ -179,7 +267,9 @@ where
|
||||
};
|
||||
ctx.add_stream(WsStream::new(stream, Codec::new()));
|
||||
|
||||
WebsocketContextFut::new(ctx, actor, mb, Codec::new())
|
||||
let addr = ctx.address();
|
||||
|
||||
(addr, WebsocketContextFut::new(ctx, actor, mb, Codec::new()))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@ -435,7 +525,7 @@ where
|
||||
}
|
||||
}
|
||||
Frame::Binary(data) => Message::Binary(
|
||||
data.map(|b| b.freeze()).unwrap_or_else(|| Bytes::new()),
|
||||
data.map(|b| b.freeze()).unwrap_or_else(Bytes::new),
|
||||
),
|
||||
Frame::Ping(s) => Message::Ping(s),
|
||||
Frame::Pong(s) => Message::Pong(s),
|
||||
@ -564,5 +654,87 @@ mod tests {
|
||||
StatusCode::SWITCHING_PROTOCOLS,
|
||||
handshake(&req).unwrap().finish().status()
|
||||
);
|
||||
|
||||
let req = TestRequest::default()
|
||||
.header(
|
||||
header::UPGRADE,
|
||||
header::HeaderValue::from_static("websocket"),
|
||||
)
|
||||
.header(
|
||||
header::CONNECTION,
|
||||
header::HeaderValue::from_static("upgrade"),
|
||||
)
|
||||
.header(
|
||||
header::SEC_WEBSOCKET_VERSION,
|
||||
header::HeaderValue::from_static("13"),
|
||||
)
|
||||
.header(
|
||||
header::SEC_WEBSOCKET_KEY,
|
||||
header::HeaderValue::from_static("13"),
|
||||
)
|
||||
.header(
|
||||
header::SEC_WEBSOCKET_PROTOCOL,
|
||||
header::HeaderValue::from_static("graphql"),
|
||||
)
|
||||
.to_http_request();
|
||||
|
||||
let protocols = ["graphql"];
|
||||
|
||||
assert_eq!(
|
||||
StatusCode::SWITCHING_PROTOCOLS,
|
||||
handshake_with_protocols(&req, &protocols)
|
||||
.unwrap()
|
||||
.finish()
|
||||
.status()
|
||||
);
|
||||
assert_eq!(
|
||||
Some(&header::HeaderValue::from_static("graphql")),
|
||||
handshake_with_protocols(&req, &protocols)
|
||||
.unwrap()
|
||||
.finish()
|
||||
.headers()
|
||||
.get(&header::SEC_WEBSOCKET_PROTOCOL)
|
||||
);
|
||||
|
||||
let req = TestRequest::default()
|
||||
.header(
|
||||
header::UPGRADE,
|
||||
header::HeaderValue::from_static("websocket"),
|
||||
)
|
||||
.header(
|
||||
header::CONNECTION,
|
||||
header::HeaderValue::from_static("upgrade"),
|
||||
)
|
||||
.header(
|
||||
header::SEC_WEBSOCKET_VERSION,
|
||||
header::HeaderValue::from_static("13"),
|
||||
)
|
||||
.header(
|
||||
header::SEC_WEBSOCKET_KEY,
|
||||
header::HeaderValue::from_static("13"),
|
||||
)
|
||||
.header(
|
||||
header::SEC_WEBSOCKET_PROTOCOL,
|
||||
header::HeaderValue::from_static("p1, p2, p3"),
|
||||
)
|
||||
.to_http_request();
|
||||
|
||||
let protocols = vec!["p3", "p2"];
|
||||
|
||||
assert_eq!(
|
||||
StatusCode::SWITCHING_PROTOCOLS,
|
||||
handshake_with_protocols(&req, &protocols)
|
||||
.unwrap()
|
||||
.finish()
|
||||
.status()
|
||||
);
|
||||
assert_eq!(
|
||||
Some(&header::HeaderValue::from_static("p2")),
|
||||
handshake_with_protocols(&req, &protocols)
|
||||
.unwrap()
|
||||
.finish()
|
||||
.headers()
|
||||
.get(&header::SEC_WEBSOCKET_PROTOCOL)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -12,9 +12,9 @@ enum ResourceType {
|
||||
|
||||
impl fmt::Display for ResourceType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
&ResourceType::Async => write!(f, "to_async"),
|
||||
&ResourceType::Sync => write!(f, "to"),
|
||||
match *self {
|
||||
ResourceType::Async => write!(f, "to_async"),
|
||||
ResourceType::Sync => write!(f, "to"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -34,16 +34,16 @@ pub enum GuardType {
|
||||
|
||||
impl fmt::Display for GuardType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
&GuardType::Get => write!(f, "Get"),
|
||||
&GuardType::Post => write!(f, "Post"),
|
||||
&GuardType::Put => write!(f, "Put"),
|
||||
&GuardType::Delete => write!(f, "Delete"),
|
||||
&GuardType::Head => write!(f, "Head"),
|
||||
&GuardType::Connect => write!(f, "Connect"),
|
||||
&GuardType::Options => write!(f, "Options"),
|
||||
&GuardType::Trace => write!(f, "Trace"),
|
||||
&GuardType::Patch => write!(f, "Patch"),
|
||||
match *self {
|
||||
GuardType::Get => write!(f, "Get"),
|
||||
GuardType::Post => write!(f, "Post"),
|
||||
GuardType::Put => write!(f, "Put"),
|
||||
GuardType::Delete => write!(f, "Delete"),
|
||||
GuardType::Head => write!(f, "Head"),
|
||||
GuardType::Connect => write!(f, "Connect"),
|
||||
GuardType::Options => write!(f, "Options"),
|
||||
GuardType::Trace => write!(f, "Trace"),
|
||||
GuardType::Patch => write!(f, "Patch"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -92,37 +92,27 @@ impl actix_web::dev::HttpServiceFactory for {name} {{
|
||||
fn guess_resource_type(typ: &syn::Type) -> ResourceType {
|
||||
let mut guess = ResourceType::Sync;
|
||||
|
||||
match typ {
|
||||
syn::Type::ImplTrait(typ) => {
|
||||
for bound in typ.bounds.iter() {
|
||||
match bound {
|
||||
syn::TypeParamBound::Trait(bound) => {
|
||||
for bound in bound.path.segments.iter() {
|
||||
if bound.ident == "Future" {
|
||||
guess = ResourceType::Async;
|
||||
break;
|
||||
} else if bound.ident == "Responder" {
|
||||
guess = ResourceType::Sync;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let syn::Type::ImplTrait(typ) = typ {
|
||||
for bound in typ.bounds.iter() {
|
||||
if let syn::TypeParamBound::Trait(bound) = bound {
|
||||
for bound in bound.path.segments.iter() {
|
||||
if bound.ident == "Future" {
|
||||
guess = ResourceType::Async;
|
||||
break;
|
||||
} else if bound.ident == "Responder" {
|
||||
guess = ResourceType::Sync;
|
||||
break;
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
|
||||
guess
|
||||
}
|
||||
|
||||
impl Args {
|
||||
pub fn new(
|
||||
args: &Vec<syn::NestedMeta>,
|
||||
input: TokenStream,
|
||||
guard: GuardType,
|
||||
) -> Self {
|
||||
pub fn new(args: &[syn::NestedMeta], input: TokenStream, guard: GuardType) -> Self {
|
||||
if args.is_empty() {
|
||||
panic!(
|
||||
"invalid server definition, expected: #[{}(\"some path\")]",
|
||||
@ -164,9 +154,10 @@ impl Args {
|
||||
ResourceType::Async
|
||||
} else {
|
||||
match ast.decl.output {
|
||||
syn::ReturnType::Default => {
|
||||
panic!("Function {} has no return type. Cannot be used as handler")
|
||||
}
|
||||
syn::ReturnType::Default => panic!(
|
||||
"Function {} has no return type. Cannot be used as handler",
|
||||
name
|
||||
),
|
||||
syn::ReturnType::Type(_, ref typ) => guess_resource_type(typ.as_ref()),
|
||||
}
|
||||
};
|
||||
|
@ -142,7 +142,6 @@ fn test_body() {
|
||||
assert!(response.status().is_success());
|
||||
assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
|
||||
|
||||
let mut srv = TestServer::new(|| HttpService::new(App::new().service(auto_sync)));
|
||||
let request = srv.request(http::Method::GET, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
@ -1,5 +1,44 @@
|
||||
# Changes
|
||||
|
||||
##
|
||||
|
||||
### Added
|
||||
|
||||
* Add `FrozenClientRequest` to support retries for sending HTTP requests
|
||||
|
||||
|
||||
## [0.2.5] - 2019-09-06
|
||||
|
||||
### Changed
|
||||
|
||||
* Ensure that the `Host` header is set when initiating a WebSocket client connection.
|
||||
|
||||
|
||||
## [0.2.4] - 2019-08-13
|
||||
|
||||
### Changed
|
||||
|
||||
* Update percent-encoding to "2.1"
|
||||
|
||||
* Update serde_urlencoded to "0.6.1"
|
||||
|
||||
|
||||
## [0.2.3] - 2019-08-01
|
||||
|
||||
### Added
|
||||
|
||||
* Add `rustls` support
|
||||
|
||||
|
||||
## [0.2.2] - 2019-07-01
|
||||
|
||||
### Changed
|
||||
|
||||
* Always append a colon after username in basic auth
|
||||
|
||||
* Upgrade `rand` dependency version to 0.7
|
||||
|
||||
|
||||
## [0.2.1] - 2019-06-05
|
||||
|
||||
### Added
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "awc"
|
||||
version = "0.2.1"
|
||||
version = "0.2.4"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix http client."
|
||||
readme = "README.md"
|
||||
@ -29,6 +29,9 @@ default = ["brotli", "flate2-zlib"]
|
||||
# openssl
|
||||
ssl = ["openssl", "actix-http/ssl"]
|
||||
|
||||
# rustls
|
||||
rust-tls = ["rustls", "actix-http/rust-tls"]
|
||||
|
||||
# brotli encoding, requires c compiler
|
||||
brotli = ["actix-http/brotli"]
|
||||
|
||||
@ -41,20 +44,21 @@ flate2-rust = ["actix-http/flate2-rust"]
|
||||
[dependencies]
|
||||
actix-codec = "0.1.2"
|
||||
actix-service = "0.4.1"
|
||||
actix-http = "0.2.4"
|
||||
actix-http = "0.2.9"
|
||||
base64 = "0.10.1"
|
||||
bytes = "0.4"
|
||||
derive_more = "0.15.0"
|
||||
futures = "0.1.25"
|
||||
log =" 0.4"
|
||||
mime = "0.3"
|
||||
percent-encoding = "1.0"
|
||||
rand = "0.6"
|
||||
percent-encoding = "2.1"
|
||||
rand = "0.7"
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
serde_urlencoded = "0.5.3"
|
||||
serde_urlencoded = "0.6.1"
|
||||
tokio-timer = "0.2.8"
|
||||
openssl = { version="0.10", optional = true }
|
||||
rustls = { version = "0.15.2", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.2"
|
||||
@ -62,9 +66,11 @@ actix-web = { version = "1.0.0", features=["ssl"] }
|
||||
actix-http = { version = "0.2.4", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
actix-utils = "0.4.1"
|
||||
actix-server = { version = "0.5.1", features=["ssl"] }
|
||||
actix-server = { version = "0.6.0", features=["ssl", "rust-tls"] }
|
||||
brotli2 = { version="0.3.2" }
|
||||
flate2 = { version="1.0.2" }
|
||||
env_logger = "0.6"
|
||||
rand = "0.6"
|
||||
rand = "0.7"
|
||||
tokio-tcp = "0.1"
|
||||
webpki = "0.19"
|
||||
rustls = { version = "0.15.2", features = ["dangerous_configuration"] }
|
||||
|
@ -21,6 +21,12 @@ pub struct ClientBuilder {
|
||||
max_redirects: usize,
|
||||
}
|
||||
|
||||
impl Default for ClientBuilder {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientBuilder {
|
||||
pub fn new() -> Self {
|
||||
ClientBuilder {
|
||||
@ -115,7 +121,7 @@ impl ClientBuilder {
|
||||
{
|
||||
let auth = match password {
|
||||
Some(password) => format!("{}:{}", username, password),
|
||||
None => format!("{}", username),
|
||||
None => format!("{}:", username),
|
||||
};
|
||||
self.header(
|
||||
header::AUTHORIZATION,
|
||||
@ -164,7 +170,7 @@ mod tests {
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
"Basic dXNlcm5hbWU="
|
||||
"Basic dXNlcm5hbWU6"
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -1,4 +1,5 @@
|
||||
use std::{fmt, io, net};
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||
use actix_http::body::Body;
|
||||
@ -6,7 +7,8 @@ use actix_http::client::{
|
||||
Connect as ClientConnect, ConnectError, Connection, SendRequestError,
|
||||
};
|
||||
use actix_http::h1::ClientCodec;
|
||||
use actix_http::{RequestHead, ResponseHead};
|
||||
use actix_http::{RequestHead, RequestHeadType, ResponseHead};
|
||||
use actix_http::http::HeaderMap;
|
||||
use actix_service::Service;
|
||||
use futures::{Future, Poll};
|
||||
|
||||
@ -20,7 +22,15 @@ pub(crate) trait Connect {
|
||||
head: RequestHead,
|
||||
body: Body,
|
||||
addr: Option<net::SocketAddr>,
|
||||
) -> Box<Future<Item = ClientResponse, Error = SendRequestError>>;
|
||||
) -> Box<dyn Future<Item = ClientResponse, Error = SendRequestError>>;
|
||||
|
||||
fn send_request_extra(
|
||||
&mut self,
|
||||
head: Rc<RequestHead>,
|
||||
extra_headers: Option<HeaderMap>,
|
||||
body: Body,
|
||||
addr: Option<net::SocketAddr>,
|
||||
) -> Box<dyn Future<Item = ClientResponse, Error = SendRequestError>>;
|
||||
|
||||
/// Send request, returns Response and Framed
|
||||
fn open_tunnel(
|
||||
@ -28,7 +38,20 @@ pub(crate) trait Connect {
|
||||
head: RequestHead,
|
||||
addr: Option<net::SocketAddr>,
|
||||
) -> Box<
|
||||
Future<
|
||||
dyn Future<
|
||||
Item = (ResponseHead, Framed<BoxedSocket, ClientCodec>),
|
||||
Error = SendRequestError,
|
||||
>,
|
||||
>;
|
||||
|
||||
/// Send request and extra headers, returns Response and Framed
|
||||
fn open_tunnel_extra(
|
||||
&mut self,
|
||||
head: Rc<RequestHead>,
|
||||
extra_headers: Option<HeaderMap>,
|
||||
addr: Option<net::SocketAddr>,
|
||||
) -> Box<
|
||||
dyn Future<
|
||||
Item = (ResponseHead, Framed<BoxedSocket, ClientCodec>),
|
||||
Error = SendRequestError,
|
||||
>,
|
||||
@ -49,7 +72,7 @@ where
|
||||
head: RequestHead,
|
||||
body: Body,
|
||||
addr: Option<net::SocketAddr>,
|
||||
) -> Box<Future<Item = ClientResponse, Error = SendRequestError>> {
|
||||
) -> Box<dyn Future<Item = ClientResponse, Error = SendRequestError>> {
|
||||
Box::new(
|
||||
self.0
|
||||
// connect to the host
|
||||
@ -59,7 +82,28 @@ where
|
||||
})
|
||||
.from_err()
|
||||
// send request
|
||||
.and_then(move |connection| connection.send_request(head, body))
|
||||
.and_then(move |connection| connection.send_request(RequestHeadType::from(head), body))
|
||||
.map(|(head, payload)| ClientResponse::new(head, payload)),
|
||||
)
|
||||
}
|
||||
|
||||
fn send_request_extra(
|
||||
&mut self,
|
||||
head: Rc<RequestHead>,
|
||||
extra_headers: Option<HeaderMap>,
|
||||
body: Body,
|
||||
addr: Option<net::SocketAddr>,
|
||||
) -> Box<dyn Future<Item = ClientResponse, Error = SendRequestError>> {
|
||||
Box::new(
|
||||
self.0
|
||||
// connect to the host
|
||||
.call(ClientConnect {
|
||||
uri: head.uri.clone(),
|
||||
addr,
|
||||
})
|
||||
.from_err()
|
||||
// send request
|
||||
.and_then(move |connection| connection.send_request(RequestHeadType::Rc(head, extra_headers), body))
|
||||
.map(|(head, payload)| ClientResponse::new(head, payload)),
|
||||
)
|
||||
}
|
||||
@ -69,7 +113,7 @@ where
|
||||
head: RequestHead,
|
||||
addr: Option<net::SocketAddr>,
|
||||
) -> Box<
|
||||
Future<
|
||||
dyn Future<
|
||||
Item = (ResponseHead, Framed<BoxedSocket, ClientCodec>),
|
||||
Error = SendRequestError,
|
||||
>,
|
||||
@ -83,7 +127,35 @@ where
|
||||
})
|
||||
.from_err()
|
||||
// send request
|
||||
.and_then(move |connection| connection.open_tunnel(head))
|
||||
.and_then(move |connection| connection.open_tunnel(RequestHeadType::from(head)))
|
||||
.map(|(head, framed)| {
|
||||
let framed = framed.map_io(|io| BoxedSocket(Box::new(Socket(io))));
|
||||
(head, framed)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn open_tunnel_extra(
|
||||
&mut self,
|
||||
head: Rc<RequestHead>,
|
||||
extra_headers: Option<HeaderMap>,
|
||||
addr: Option<net::SocketAddr>,
|
||||
) -> Box<
|
||||
dyn Future<
|
||||
Item = (ResponseHead, Framed<BoxedSocket, ClientCodec>),
|
||||
Error = SendRequestError,
|
||||
>,
|
||||
> {
|
||||
Box::new(
|
||||
self.0
|
||||
// connect to the host
|
||||
.call(ClientConnect {
|
||||
uri: head.uri.clone(),
|
||||
addr,
|
||||
})
|
||||
.from_err()
|
||||
// send request
|
||||
.and_then(move |connection| connection.open_tunnel(RequestHeadType::Rc(head, extra_headers)))
|
||||
.map(|(head, framed)| {
|
||||
let framed = framed.map_io(|io| BoxedSocket(Box::new(Socket(io))));
|
||||
(head, framed)
|
||||
@ -93,21 +165,21 @@ where
|
||||
}
|
||||
|
||||
trait AsyncSocket {
|
||||
fn as_read(&self) -> &AsyncRead;
|
||||
fn as_read_mut(&mut self) -> &mut AsyncRead;
|
||||
fn as_write(&mut self) -> &mut AsyncWrite;
|
||||
fn as_read(&self) -> &dyn AsyncRead;
|
||||
fn as_read_mut(&mut self) -> &mut dyn AsyncRead;
|
||||
fn as_write(&mut self) -> &mut dyn AsyncWrite;
|
||||
}
|
||||
|
||||
struct Socket<T: AsyncRead + AsyncWrite>(T);
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite> AsyncSocket for Socket<T> {
|
||||
fn as_read(&self) -> &AsyncRead {
|
||||
fn as_read(&self) -> &dyn AsyncRead {
|
||||
&self.0
|
||||
}
|
||||
fn as_read_mut(&mut self) -> &mut AsyncRead {
|
||||
fn as_read_mut(&mut self) -> &mut dyn AsyncRead {
|
||||
&mut self.0
|
||||
}
|
||||
fn as_write(&mut self) -> &mut AsyncWrite {
|
||||
fn as_write(&mut self) -> &mut dyn AsyncWrite {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,5 @@
|
||||
//! Http client errors
|
||||
pub use actix_http::client::{ConnectError, InvalidUrl, SendRequestError};
|
||||
pub use actix_http::client::{ConnectError, InvalidUrl, SendRequestError, FreezeRequestError};
|
||||
pub use actix_http::error::PayloadError;
|
||||
pub use actix_http::ws::HandshakeError as WsHandshakeError;
|
||||
pub use actix_http::ws::ProtocolError as WsProtocolError;
|
||||
|
@ -1,7 +1,8 @@
|
||||
#![allow(clippy::borrow_interior_mutable_const)]
|
||||
//! An HTTP Client
|
||||
//!
|
||||
//! ```rust
|
||||
//! # use futures::future::{Future, lazy};
|
||||
//! use futures::future::{lazy, Future};
|
||||
//! use actix_rt::System;
|
||||
//! use awc::Client;
|
||||
//!
|
||||
|
@ -1,28 +1,28 @@
|
||||
use std::fmt::Write as FmtWrite;
|
||||
use std::io::Write;
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
use std::{fmt, net};
|
||||
|
||||
use bytes::{BufMut, Bytes, BytesMut};
|
||||
use futures::future::{err, Either};
|
||||
use futures::{Future, Stream};
|
||||
use percent_encoding::{percent_encode, USERINFO_ENCODE_SET};
|
||||
use futures::{Async, Future, Poll, Stream, try_ready};
|
||||
use percent_encoding::percent_encode;
|
||||
use serde::Serialize;
|
||||
use serde_json;
|
||||
use tokio_timer::Timeout;
|
||||
use tokio_timer::Delay;
|
||||
use derive_more::From;
|
||||
|
||||
use actix_http::body::{Body, BodyStream};
|
||||
use actix_http::cookie::{Cookie, CookieJar};
|
||||
use actix_http::cookie::{Cookie, CookieJar, USERINFO};
|
||||
use actix_http::encoding::Decoder;
|
||||
use actix_http::http::header::{self, ContentEncoding, Header, IntoHeaderValue};
|
||||
use actix_http::http::{
|
||||
uri, ConnectionType, Error as HttpError, HeaderMap, HeaderName, HeaderValue,
|
||||
HttpTryFrom, Method, Uri, Version,
|
||||
};
|
||||
use actix_http::{Error, Payload, RequestHead};
|
||||
use actix_http::{Error, Payload, PayloadStream, RequestHead};
|
||||
|
||||
use crate::error::{InvalidUrl, PayloadError, SendRequestError};
|
||||
use crate::error::{InvalidUrl, SendRequestError, FreezeRequestError};
|
||||
use crate::response::ClientResponse;
|
||||
use crate::ClientConfig;
|
||||
|
||||
@ -99,6 +99,11 @@ impl ClientRequest {
|
||||
self
|
||||
}
|
||||
|
||||
/// Get HTTP URI of request
|
||||
pub fn get_uri(&self) -> &Uri {
|
||||
&self.head.uri
|
||||
}
|
||||
|
||||
/// Set socket address of the server.
|
||||
///
|
||||
/// This address is used for connection. If address is not
|
||||
@ -115,6 +120,11 @@ impl ClientRequest {
|
||||
self
|
||||
}
|
||||
|
||||
/// Get HTTP method of this request
|
||||
pub fn get_method(&self) -> &Method {
|
||||
&self.head.method
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
/// Set HTTP version of this request.
|
||||
///
|
||||
@ -185,9 +195,7 @@ impl ClientRequest {
|
||||
{
|
||||
match HeaderName::try_from(key) {
|
||||
Ok(key) => match value.try_into() {
|
||||
Ok(value) => {
|
||||
let _ = self.head.headers.append(key, value);
|
||||
}
|
||||
Ok(value) => self.head.headers.append(key, value),
|
||||
Err(e) => self.err = Some(e.into()),
|
||||
},
|
||||
Err(e) => self.err = Some(e.into()),
|
||||
@ -203,9 +211,7 @@ impl ClientRequest {
|
||||
{
|
||||
match HeaderName::try_from(key) {
|
||||
Ok(key) => match value.try_into() {
|
||||
Ok(value) => {
|
||||
let _ = self.head.headers.insert(key, value);
|
||||
}
|
||||
Ok(value) => self.head.headers.insert(key, value),
|
||||
Err(e) => self.err = Some(e.into()),
|
||||
},
|
||||
Err(e) => self.err = Some(e.into()),
|
||||
@ -223,9 +229,7 @@ impl ClientRequest {
|
||||
Ok(key) => {
|
||||
if !self.head.headers.contains_key(&key) {
|
||||
match value.try_into() {
|
||||
Ok(value) => {
|
||||
let _ = self.head.headers.insert(key, value);
|
||||
}
|
||||
Ok(value) => self.head.headers.insert(key, value),
|
||||
Err(e) => self.err = Some(e.into()),
|
||||
}
|
||||
}
|
||||
@ -257,9 +261,7 @@ impl ClientRequest {
|
||||
HeaderValue: HttpTryFrom<V>,
|
||||
{
|
||||
match HeaderValue::try_from(value) {
|
||||
Ok(value) => {
|
||||
let _ = self.head.headers.insert(header::CONTENT_TYPE, value);
|
||||
}
|
||||
Ok(value) => self.head.headers.insert(header::CONTENT_TYPE, value),
|
||||
Err(e) => self.err = Some(e.into()),
|
||||
}
|
||||
self
|
||||
@ -280,7 +282,7 @@ impl ClientRequest {
|
||||
{
|
||||
let auth = match password {
|
||||
Some(password) => format!("{}:{}", username, password),
|
||||
None => format!("{}", username),
|
||||
None => format!("{}:", username),
|
||||
};
|
||||
self.header(
|
||||
header::AUTHORIZATION,
|
||||
@ -321,7 +323,7 @@ impl ClientRequest {
|
||||
/// }));
|
||||
/// }
|
||||
/// ```
|
||||
pub fn cookie<'c>(mut self, cookie: Cookie<'c>) -> Self {
|
||||
pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {
|
||||
if self.cookies.is_none() {
|
||||
let mut jar = CookieJar::new();
|
||||
jar.add(cookie.into_owned());
|
||||
@ -373,42 +375,130 @@ impl ClientRequest {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn freeze(self) -> Result<FrozenClientRequest, FreezeRequestError> {
|
||||
let slf = match self.prep_for_sending() {
|
||||
Ok(slf) => slf,
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
|
||||
let request = FrozenClientRequest {
|
||||
head: Rc::new(slf.head),
|
||||
addr: slf.addr,
|
||||
response_decompress: slf.response_decompress,
|
||||
timeout: slf.timeout,
|
||||
config: slf.config,
|
||||
};
|
||||
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
/// Complete request construction and send body.
|
||||
pub fn send_body<B>(
|
||||
mut self,
|
||||
self,
|
||||
body: B,
|
||||
) -> impl Future<
|
||||
Item = ClientResponse<impl Stream<Item = Bytes, Error = PayloadError>>,
|
||||
Error = SendRequestError,
|
||||
>
|
||||
) -> SendBody
|
||||
where
|
||||
B: Into<Body>,
|
||||
{
|
||||
if let Some(e) = self.err.take() {
|
||||
return Either::A(err(e.into()));
|
||||
let slf = match self.prep_for_sending() {
|
||||
Ok(slf) => slf,
|
||||
Err(e) => return e.into(),
|
||||
};
|
||||
|
||||
RequestSender::Owned(slf.head)
|
||||
.send_body(slf.addr, slf.response_decompress, slf.timeout, slf.config.as_ref(), body)
|
||||
}
|
||||
|
||||
/// Set a JSON body and generate `ClientRequest`
|
||||
pub fn send_json<T: Serialize>(
|
||||
self,
|
||||
value: &T,
|
||||
) -> SendBody
|
||||
{
|
||||
let slf = match self.prep_for_sending() {
|
||||
Ok(slf) => slf,
|
||||
Err(e) => return e.into(),
|
||||
};
|
||||
|
||||
RequestSender::Owned(slf.head)
|
||||
.send_json(slf.addr, slf.response_decompress, slf.timeout, slf.config.as_ref(), value)
|
||||
}
|
||||
|
||||
/// Set a urlencoded body and generate `ClientRequest`
|
||||
///
|
||||
/// `ClientRequestBuilder` can not be used after this call.
|
||||
pub fn send_form<T: Serialize>(
|
||||
self,
|
||||
value: &T,
|
||||
) -> SendBody
|
||||
{
|
||||
let slf = match self.prep_for_sending() {
|
||||
Ok(slf) => slf,
|
||||
Err(e) => return e.into(),
|
||||
};
|
||||
|
||||
RequestSender::Owned(slf.head)
|
||||
.send_form(slf.addr, slf.response_decompress, slf.timeout, slf.config.as_ref(), value)
|
||||
}
|
||||
|
||||
/// Set an streaming body and generate `ClientRequest`.
|
||||
pub fn send_stream<S, E>(
|
||||
self,
|
||||
stream: S,
|
||||
) -> SendBody
|
||||
where
|
||||
S: Stream<Item = Bytes, Error = E> + 'static,
|
||||
E: Into<Error> + 'static,
|
||||
{
|
||||
let slf = match self.prep_for_sending() {
|
||||
Ok(slf) => slf,
|
||||
Err(e) => return e.into(),
|
||||
};
|
||||
|
||||
RequestSender::Owned(slf.head)
|
||||
.send_stream(slf.addr, slf.response_decompress, slf.timeout, slf.config.as_ref(), stream)
|
||||
}
|
||||
|
||||
/// Set an empty body and generate `ClientRequest`.
|
||||
pub fn send(
|
||||
self,
|
||||
) -> SendBody
|
||||
{
|
||||
let slf = match self.prep_for_sending() {
|
||||
Ok(slf) => slf,
|
||||
Err(e) => return e.into(),
|
||||
};
|
||||
|
||||
RequestSender::Owned(slf.head)
|
||||
.send(slf.addr, slf.response_decompress, slf.timeout, slf.config.as_ref())
|
||||
}
|
||||
|
||||
fn prep_for_sending(mut self) -> Result<Self, PrepForSendingError> {
|
||||
if let Some(e) = self.err {
|
||||
return Err(e.into());
|
||||
}
|
||||
|
||||
// validate uri
|
||||
let uri = &self.head.uri;
|
||||
if uri.host().is_none() {
|
||||
return Either::A(err(InvalidUrl::MissingHost.into()));
|
||||
return Err(InvalidUrl::MissingHost.into());
|
||||
} else if uri.scheme_part().is_none() {
|
||||
return Either::A(err(InvalidUrl::MissingScheme.into()));
|
||||
return Err(InvalidUrl::MissingScheme.into());
|
||||
} else if let Some(scheme) = uri.scheme_part() {
|
||||
match scheme.as_str() {
|
||||
"http" | "ws" | "https" | "wss" => (),
|
||||
_ => return Either::A(err(InvalidUrl::UnknownScheme.into())),
|
||||
_ => return Err(InvalidUrl::UnknownScheme.into()),
|
||||
}
|
||||
} else {
|
||||
return Either::A(err(InvalidUrl::UnknownScheme.into()));
|
||||
return Err(InvalidUrl::UnknownScheme.into());
|
||||
}
|
||||
|
||||
// set cookies
|
||||
if let Some(ref mut jar) = self.cookies {
|
||||
let mut cookie = String::new();
|
||||
for c in jar.delta() {
|
||||
let name = percent_encode(c.name().as_bytes(), USERINFO_ENCODE_SET);
|
||||
let value = percent_encode(c.value().as_bytes(), USERINFO_ENCODE_SET);
|
||||
let name = percent_encode(c.name().as_bytes(), USERINFO);
|
||||
let value = percent_encode(c.value().as_bytes(), USERINFO);
|
||||
let _ = write!(&mut cookie, "; {}={}", name, value);
|
||||
}
|
||||
self.head.headers.insert(
|
||||
@ -438,112 +528,15 @@ impl ClientRequest {
|
||||
slf = slf.set_header_if_none(header::ACCEPT_ENCODING, HTTPS_ENCODING)
|
||||
} else {
|
||||
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]
|
||||
{
|
||||
slf = slf
|
||||
.set_header_if_none(header::ACCEPT_ENCODING, "gzip, deflate")
|
||||
}
|
||||
{
|
||||
slf = slf
|
||||
.set_header_if_none(header::ACCEPT_ENCODING, "gzip, deflate")
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let head = slf.head;
|
||||
let config = slf.config.as_ref();
|
||||
let response_decompress = slf.response_decompress;
|
||||
|
||||
let fut = config
|
||||
.connector
|
||||
.borrow_mut()
|
||||
.send_request(head, body.into(), slf.addr)
|
||||
.map(move |res| {
|
||||
res.map_body(|head, payload| {
|
||||
if response_decompress {
|
||||
Payload::Stream(Decoder::from_headers(payload, &head.headers))
|
||||
} else {
|
||||
Payload::Stream(Decoder::new(payload, ContentEncoding::Identity))
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
// set request timeout
|
||||
if let Some(timeout) = slf.timeout.or_else(|| config.timeout.clone()) {
|
||||
Either::B(Either::A(Timeout::new(fut, timeout).map_err(|e| {
|
||||
if let Some(e) = e.into_inner() {
|
||||
e
|
||||
} else {
|
||||
SendRequestError::Timeout
|
||||
}
|
||||
})))
|
||||
} else {
|
||||
Either::B(Either::B(fut))
|
||||
}
|
||||
}
|
||||
|
||||
/// Set a JSON body and generate `ClientRequest`
|
||||
pub fn send_json<T: Serialize>(
|
||||
self,
|
||||
value: &T,
|
||||
) -> impl Future<
|
||||
Item = ClientResponse<impl Stream<Item = Bytes, Error = PayloadError>>,
|
||||
Error = SendRequestError,
|
||||
> {
|
||||
let body = match serde_json::to_string(value) {
|
||||
Ok(body) => body,
|
||||
Err(e) => return Either::A(err(Error::from(e).into())),
|
||||
};
|
||||
|
||||
// set content-type
|
||||
let slf = self.set_header_if_none(header::CONTENT_TYPE, "application/json");
|
||||
|
||||
Either::B(slf.send_body(Body::Bytes(Bytes::from(body))))
|
||||
}
|
||||
|
||||
/// Set a urlencoded body and generate `ClientRequest`
|
||||
///
|
||||
/// `ClientRequestBuilder` can not be used after this call.
|
||||
pub fn send_form<T: Serialize>(
|
||||
self,
|
||||
value: &T,
|
||||
) -> impl Future<
|
||||
Item = ClientResponse<impl Stream<Item = Bytes, Error = PayloadError>>,
|
||||
Error = SendRequestError,
|
||||
> {
|
||||
let body = match serde_urlencoded::to_string(value) {
|
||||
Ok(body) => body,
|
||||
Err(e) => return Either::A(err(Error::from(e).into())),
|
||||
};
|
||||
|
||||
// set content-type
|
||||
let slf = self.set_header_if_none(
|
||||
header::CONTENT_TYPE,
|
||||
"application/x-www-form-urlencoded",
|
||||
);
|
||||
|
||||
Either::B(slf.send_body(Body::Bytes(Bytes::from(body))))
|
||||
}
|
||||
|
||||
/// Set an streaming body and generate `ClientRequest`.
|
||||
pub fn send_stream<S, E>(
|
||||
self,
|
||||
stream: S,
|
||||
) -> impl Future<
|
||||
Item = ClientResponse<impl Stream<Item = Bytes, Error = PayloadError>>,
|
||||
Error = SendRequestError,
|
||||
>
|
||||
where
|
||||
S: Stream<Item = Bytes, Error = E> + 'static,
|
||||
E: Into<Error> + 'static,
|
||||
{
|
||||
self.send_body(Body::from_message(BodyStream::new(stream)))
|
||||
}
|
||||
|
||||
/// Set an empty body and generate `ClientRequest`.
|
||||
pub fn send(
|
||||
self,
|
||||
) -> impl Future<
|
||||
Item = ClientResponse<impl Stream<Item = Bytes, Error = PayloadError>>,
|
||||
Error = SendRequestError,
|
||||
> {
|
||||
self.send_body(Body::Empty)
|
||||
Ok(slf)
|
||||
}
|
||||
}
|
||||
|
||||
@ -562,6 +555,441 @@ impl fmt::Debug for ClientRequest {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct FrozenClientRequest {
|
||||
pub(crate) head: Rc<RequestHead>,
|
||||
pub(crate) addr: Option<net::SocketAddr>,
|
||||
pub(crate) response_decompress: bool,
|
||||
pub(crate) timeout: Option<Duration>,
|
||||
pub(crate) config: Rc<ClientConfig>,
|
||||
}
|
||||
|
||||
impl FrozenClientRequest {
|
||||
/// Get HTTP URI of request
|
||||
pub fn get_uri(&self) -> &Uri {
|
||||
&self.head.uri
|
||||
}
|
||||
|
||||
/// Get HTTP method of this request
|
||||
pub fn get_method(&self) -> &Method {
|
||||
&self.head.method
|
||||
}
|
||||
|
||||
/// Returns request's headers.
|
||||
pub fn headers(&self) -> &HeaderMap {
|
||||
&self.head.headers
|
||||
}
|
||||
|
||||
/// Send a body.
|
||||
pub fn send_body<B>(
|
||||
&self,
|
||||
body: B,
|
||||
) -> SendBody
|
||||
where
|
||||
B: Into<Body>,
|
||||
{
|
||||
RequestSender::Rc(self.head.clone(), None)
|
||||
.send_body(self.addr, self.response_decompress, self.timeout, self.config.as_ref(), body)
|
||||
}
|
||||
|
||||
/// Send a json body.
|
||||
pub fn send_json<T: Serialize>(
|
||||
&self,
|
||||
value: &T,
|
||||
) -> SendBody
|
||||
{
|
||||
RequestSender::Rc(self.head.clone(), None)
|
||||
.send_json(self.addr, self.response_decompress, self.timeout, self.config.as_ref(), value)
|
||||
}
|
||||
|
||||
/// Send an urlencoded body.
|
||||
pub fn send_form<T: Serialize>(
|
||||
&self,
|
||||
value: &T,
|
||||
) -> SendBody
|
||||
{
|
||||
RequestSender::Rc(self.head.clone(), None)
|
||||
.send_form(self.addr, self.response_decompress, self.timeout, self.config.as_ref(), value)
|
||||
}
|
||||
|
||||
/// Send a streaming body.
|
||||
pub fn send_stream<S, E>(
|
||||
&self,
|
||||
stream: S,
|
||||
) -> SendBody
|
||||
where
|
||||
S: Stream<Item = Bytes, Error = E> + 'static,
|
||||
E: Into<Error> + 'static,
|
||||
{
|
||||
RequestSender::Rc(self.head.clone(), None)
|
||||
.send_stream(self.addr, self.response_decompress, self.timeout, self.config.as_ref(), stream)
|
||||
}
|
||||
|
||||
/// Send an empty body.
|
||||
pub fn send(
|
||||
&self,
|
||||
) -> SendBody
|
||||
{
|
||||
RequestSender::Rc(self.head.clone(), None)
|
||||
.send(self.addr, self.response_decompress, self.timeout, self.config.as_ref())
|
||||
}
|
||||
|
||||
/// Create a `FrozenSendBuilder` with extra headers
|
||||
pub fn extra_headers(&self, extra_headers: HeaderMap) -> FrozenSendBuilder {
|
||||
FrozenSendBuilder::new(self.clone(), extra_headers)
|
||||
}
|
||||
|
||||
/// Create a `FrozenSendBuilder` with an extra header
|
||||
pub fn extra_header<K, V>(&self, key: K, value: V) -> FrozenSendBuilder
|
||||
where
|
||||
HeaderName: HttpTryFrom<K>,
|
||||
V: IntoHeaderValue,
|
||||
{
|
||||
self.extra_headers(HeaderMap::new()).extra_header(key, value)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FrozenSendBuilder {
|
||||
req: FrozenClientRequest,
|
||||
extra_headers: HeaderMap,
|
||||
err: Option<HttpError>,
|
||||
}
|
||||
|
||||
impl FrozenSendBuilder {
|
||||
pub(crate) fn new(req: FrozenClientRequest, extra_headers: HeaderMap) -> Self {
|
||||
Self {
|
||||
req,
|
||||
extra_headers,
|
||||
err: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert a header, it overrides existing header in `FrozenClientRequest`.
|
||||
pub fn extra_header<K, V>(mut self, key: K, value: V) -> Self
|
||||
where
|
||||
HeaderName: HttpTryFrom<K>,
|
||||
V: IntoHeaderValue,
|
||||
{
|
||||
match HeaderName::try_from(key) {
|
||||
Ok(key) => match value.try_into() {
|
||||
Ok(value) => self.extra_headers.insert(key, value),
|
||||
Err(e) => self.err = Some(e.into()),
|
||||
},
|
||||
Err(e) => self.err = Some(e.into()),
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Complete request construction and send a body.
|
||||
pub fn send_body<B>(
|
||||
self,
|
||||
body: B,
|
||||
) -> SendBody
|
||||
where
|
||||
B: Into<Body>,
|
||||
{
|
||||
if let Some(e) = self.err {
|
||||
return e.into()
|
||||
}
|
||||
|
||||
RequestSender::Rc(self.req.head, Some(self.extra_headers))
|
||||
.send_body(self.req.addr, self.req.response_decompress, self.req.timeout, self.req.config.as_ref(), body)
|
||||
}
|
||||
|
||||
/// Complete request construction and send a json body.
|
||||
pub fn send_json<T: Serialize>(
|
||||
self,
|
||||
value: &T,
|
||||
) -> SendBody
|
||||
{
|
||||
if let Some(e) = self.err {
|
||||
return e.into()
|
||||
}
|
||||
|
||||
RequestSender::Rc(self.req.head, Some(self.extra_headers))
|
||||
.send_json(self.req.addr, self.req.response_decompress, self.req.timeout, self.req.config.as_ref(), value)
|
||||
}
|
||||
|
||||
/// Complete request construction and send an urlencoded body.
|
||||
pub fn send_form<T: Serialize>(
|
||||
self,
|
||||
value: &T,
|
||||
) -> SendBody
|
||||
{
|
||||
if let Some(e) = self.err {
|
||||
return e.into()
|
||||
}
|
||||
|
||||
RequestSender::Rc(self.req.head, Some(self.extra_headers))
|
||||
.send_form(self.req.addr, self.req.response_decompress, self.req.timeout, self.req.config.as_ref(), value)
|
||||
}
|
||||
|
||||
/// Complete request construction and send a streaming body.
|
||||
pub fn send_stream<S, E>(
|
||||
self,
|
||||
stream: S,
|
||||
) -> SendBody
|
||||
where
|
||||
S: Stream<Item = Bytes, Error = E> + 'static,
|
||||
E: Into<Error> + 'static,
|
||||
{
|
||||
if let Some(e) = self.err {
|
||||
return e.into()
|
||||
}
|
||||
|
||||
RequestSender::Rc(self.req.head, Some(self.extra_headers))
|
||||
.send_stream(self.req.addr, self.req.response_decompress, self.req.timeout, self.req.config.as_ref(), stream)
|
||||
}
|
||||
|
||||
/// Complete request construction and send an empty body.
|
||||
pub fn send(
|
||||
self,
|
||||
) -> SendBody
|
||||
{
|
||||
if let Some(e) = self.err {
|
||||
return e.into()
|
||||
}
|
||||
|
||||
RequestSender::Rc(self.req.head, Some(self.extra_headers))
|
||||
.send(self.req.addr, self.req.response_decompress, self.req.timeout, self.req.config.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, From)]
|
||||
enum PrepForSendingError {
|
||||
Url(InvalidUrl),
|
||||
Http(HttpError),
|
||||
}
|
||||
|
||||
impl Into<FreezeRequestError> for PrepForSendingError {
|
||||
fn into(self) -> FreezeRequestError {
|
||||
match self {
|
||||
PrepForSendingError::Url(e) => FreezeRequestError::Url(e),
|
||||
PrepForSendingError::Http(e) => FreezeRequestError::Http(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<SendRequestError> for PrepForSendingError {
|
||||
fn into(self) -> SendRequestError {
|
||||
match self {
|
||||
PrepForSendingError::Url(e) => SendRequestError::Url(e),
|
||||
PrepForSendingError::Http(e) => SendRequestError::Http(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum SendBody
|
||||
{
|
||||
Fut(Box<dyn Future<Item = ClientResponse, Error = SendRequestError>>, Option<Delay>, bool),
|
||||
Err(Option<SendRequestError>),
|
||||
}
|
||||
|
||||
impl SendBody
|
||||
{
|
||||
pub fn new(
|
||||
send: Box<dyn Future<Item = ClientResponse, Error = SendRequestError>>,
|
||||
response_decompress: bool,
|
||||
timeout: Option<Duration>,
|
||||
) -> SendBody
|
||||
{
|
||||
let delay = timeout.map(|t| Delay::new(Instant::now() + t));
|
||||
SendBody::Fut(send, delay, response_decompress)
|
||||
}
|
||||
}
|
||||
|
||||
impl Future for SendBody
|
||||
{
|
||||
type Item = ClientResponse<Decoder<Payload<PayloadStream>>>;
|
||||
type Error = SendRequestError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match self {
|
||||
SendBody::Fut(send, delay, response_decompress) => {
|
||||
if delay.is_some() {
|
||||
match delay.poll() {
|
||||
Ok(Async::NotReady) => (),
|
||||
_ => return Err(SendRequestError::Timeout),
|
||||
}
|
||||
}
|
||||
|
||||
let res = try_ready!(send.poll())
|
||||
.map_body(|head, payload| {
|
||||
if *response_decompress {
|
||||
Payload::Stream(Decoder::from_headers(payload, &head.headers))
|
||||
} else {
|
||||
Payload::Stream(Decoder::new(payload, ContentEncoding::Identity))
|
||||
}
|
||||
});
|
||||
|
||||
Ok(Async::Ready(res))
|
||||
},
|
||||
SendBody::Err(ref mut e) => {
|
||||
match e.take() {
|
||||
Some(e) => Err(e.into()),
|
||||
None => panic!("Attempting to call completed future"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl From<SendRequestError> for SendBody
|
||||
{
|
||||
fn from(e: SendRequestError) -> Self {
|
||||
SendBody::Err(Some(e))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Error> for SendBody
|
||||
{
|
||||
fn from(e: Error) -> Self {
|
||||
SendBody::Err(Some(e.into()))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<HttpError> for SendBody
|
||||
{
|
||||
fn from(e: HttpError) -> Self {
|
||||
SendBody::Err(Some(e.into()))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PrepForSendingError> for SendBody
|
||||
{
|
||||
fn from(e: PrepForSendingError) -> Self {
|
||||
SendBody::Err(Some(e.into()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum RequestSender {
|
||||
Owned(RequestHead),
|
||||
Rc(Rc<RequestHead>, Option<HeaderMap>),
|
||||
}
|
||||
|
||||
impl RequestSender {
|
||||
pub fn send_body<B>(
|
||||
self,
|
||||
addr: Option<net::SocketAddr>,
|
||||
response_decompress: bool,
|
||||
timeout: Option<Duration>,
|
||||
config: &ClientConfig,
|
||||
body: B,
|
||||
) -> SendBody
|
||||
where
|
||||
B: Into<Body>,
|
||||
{
|
||||
let mut connector = config.connector.borrow_mut();
|
||||
|
||||
let fut = match self {
|
||||
RequestSender::Owned(head) => connector.send_request(head, body.into(), addr),
|
||||
RequestSender::Rc(head, extra_headers) => connector.send_request_extra(head, extra_headers, body.into(), addr),
|
||||
};
|
||||
|
||||
SendBody::new(fut, response_decompress, timeout.or_else(|| config.timeout.clone()))
|
||||
}
|
||||
|
||||
pub fn send_json<T: Serialize>(
|
||||
mut self,
|
||||
addr: Option<net::SocketAddr>,
|
||||
response_decompress: bool,
|
||||
timeout: Option<Duration>,
|
||||
config: &ClientConfig,
|
||||
value: &T,
|
||||
) -> SendBody
|
||||
{
|
||||
let body = match serde_json::to_string(value) {
|
||||
Ok(body) => body,
|
||||
Err(e) => return Error::from(e).into(),
|
||||
};
|
||||
|
||||
if let Err(e) = self.set_header_if_none(header::CONTENT_TYPE, "application/json") {
|
||||
return e.into();
|
||||
}
|
||||
|
||||
self.send_body(addr, response_decompress, timeout, config, Body::Bytes(Bytes::from(body)))
|
||||
}
|
||||
|
||||
pub fn send_form<T: Serialize>(
|
||||
mut self,
|
||||
addr: Option<net::SocketAddr>,
|
||||
response_decompress: bool,
|
||||
timeout: Option<Duration>,
|
||||
config: &ClientConfig,
|
||||
value: &T,
|
||||
) -> SendBody
|
||||
{
|
||||
let body = match serde_urlencoded::to_string(value) {
|
||||
Ok(body) => body,
|
||||
Err(e) => return Error::from(e).into(),
|
||||
};
|
||||
|
||||
// set content-type
|
||||
if let Err(e) = self.set_header_if_none(header::CONTENT_TYPE, "application/x-www-form-urlencoded") {
|
||||
return e.into();
|
||||
}
|
||||
|
||||
self.send_body(addr, response_decompress, timeout, config, Body::Bytes(Bytes::from(body)))
|
||||
}
|
||||
|
||||
pub fn send_stream<S, E>(
|
||||
self,
|
||||
addr: Option<net::SocketAddr>,
|
||||
response_decompress: bool,
|
||||
timeout: Option<Duration>,
|
||||
config: &ClientConfig,
|
||||
stream: S,
|
||||
) -> SendBody
|
||||
where
|
||||
S: Stream<Item = Bytes, Error = E> + 'static,
|
||||
E: Into<Error> + 'static,
|
||||
{
|
||||
self.send_body(addr, response_decompress, timeout, config, Body::from_message(BodyStream::new(stream)))
|
||||
}
|
||||
|
||||
pub fn send(
|
||||
self,
|
||||
addr: Option<net::SocketAddr>,
|
||||
response_decompress: bool,
|
||||
timeout: Option<Duration>,
|
||||
config: &ClientConfig,
|
||||
) -> SendBody
|
||||
{
|
||||
self.send_body(addr, response_decompress, timeout, config, Body::Empty)
|
||||
}
|
||||
|
||||
fn set_header_if_none<V>(&mut self, key: HeaderName, value: V) -> Result<(), HttpError>
|
||||
where
|
||||
V: IntoHeaderValue,
|
||||
{
|
||||
match self {
|
||||
RequestSender::Owned(head) => {
|
||||
if !head.headers.contains_key(&key) {
|
||||
match value.try_into() {
|
||||
Ok(value) => head.headers.insert(key, value),
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
},
|
||||
RequestSender::Rc(head, extra_headers) => {
|
||||
if !head.headers.contains_key(&key) && !extra_headers.iter().any(|h| h.contains_key(&key)) {
|
||||
match value.try_into(){
|
||||
Ok(v) => {
|
||||
let h = extra_headers.get_or_insert(HeaderMap::new());
|
||||
h.insert(key, v)
|
||||
},
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::SystemTime;
|
||||
@ -664,7 +1092,7 @@ mod tests {
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
"Basic dXNlcm5hbWU="
|
||||
"Basic dXNlcm5hbWU6"
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -1,12 +1,12 @@
|
||||
//! Test helpers for actix http client to use during testing.
|
||||
use std::fmt::Write as FmtWrite;
|
||||
|
||||
use actix_http::cookie::{Cookie, CookieJar};
|
||||
use actix_http::cookie::{Cookie, CookieJar, USERINFO};
|
||||
use actix_http::http::header::{self, Header, HeaderValue, IntoHeaderValue};
|
||||
use actix_http::http::{HeaderName, HttpTryFrom, StatusCode, Version};
|
||||
use actix_http::{h1, Payload, ResponseHead};
|
||||
use bytes::Bytes;
|
||||
use percent_encoding::{percent_encode, USERINFO_ENCODE_SET};
|
||||
use percent_encoding::percent_encode;
|
||||
|
||||
use crate::ClientResponse;
|
||||
|
||||
@ -68,7 +68,7 @@ impl TestResponse {
|
||||
}
|
||||
|
||||
/// Set cookie for this response
|
||||
pub fn cookie<'a>(mut self, cookie: Cookie<'a>) -> Self {
|
||||
pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {
|
||||
self.cookies.add(cookie.into_owned());
|
||||
self
|
||||
}
|
||||
@ -87,8 +87,8 @@ impl TestResponse {
|
||||
|
||||
let mut cookie = String::new();
|
||||
for c in self.cookies.delta() {
|
||||
let name = percent_encode(c.name().as_bytes(), USERINFO_ENCODE_SET);
|
||||
let value = percent_encode(c.value().as_bytes(), USERINFO_ENCODE_SET);
|
||||
let name = percent_encode(c.name().as_bytes(), USERINFO);
|
||||
let value = percent_encode(c.value().as_bytes(), USERINFO);
|
||||
let _ = write!(&mut cookie, "; {}={}", name, value);
|
||||
}
|
||||
if !cookie.is_empty() {
|
||||
|
@ -8,9 +8,10 @@ use actix_codec::Framed;
|
||||
use actix_http::cookie::{Cookie, CookieJar};
|
||||
use actix_http::{ws, Payload, RequestHead};
|
||||
use futures::future::{err, Either, Future};
|
||||
use percent_encoding::{percent_encode, USERINFO_ENCODE_SET};
|
||||
use percent_encoding::percent_encode;
|
||||
use tokio_timer::Timeout;
|
||||
|
||||
use actix_http::cookie::USERINFO;
|
||||
pub use actix_http::ws::{CloseCode, CloseReason, Codec, Frame, Message};
|
||||
|
||||
use crate::connect::BoxedSocket;
|
||||
@ -90,7 +91,7 @@ impl WebsocketsRequest {
|
||||
}
|
||||
|
||||
/// Set a cookie
|
||||
pub fn cookie<'c>(mut self, cookie: Cookie<'c>) -> Self {
|
||||
pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {
|
||||
if self.cookies.is_none() {
|
||||
let mut jar = CookieJar::new();
|
||||
jar.add(cookie.into_owned());
|
||||
@ -195,7 +196,7 @@ impl WebsocketsRequest {
|
||||
{
|
||||
let auth = match password {
|
||||
Some(password) => format!("{}:{}", username, password),
|
||||
None => format!("{}", username),
|
||||
None => format!("{}:", username),
|
||||
};
|
||||
self.header(AUTHORIZATION, format!("Basic {}", base64::encode(&auth)))
|
||||
}
|
||||
@ -232,12 +233,16 @@ impl WebsocketsRequest {
|
||||
return Either::A(err(InvalidUrl::UnknownScheme.into()));
|
||||
}
|
||||
|
||||
if !self.head.headers.contains_key(header::HOST) {
|
||||
self.head.headers.insert(header::HOST, HeaderValue::from_str(uri.host().unwrap()).unwrap());
|
||||
}
|
||||
|
||||
// set cookies
|
||||
if let Some(ref mut jar) = self.cookies {
|
||||
let mut cookie = String::new();
|
||||
for c in jar.delta() {
|
||||
let name = percent_encode(c.name().as_bytes(), USERINFO_ENCODE_SET);
|
||||
let value = percent_encode(c.value().as_bytes(), USERINFO_ENCODE_SET);
|
||||
let name = percent_encode(c.name().as_bytes(), USERINFO);
|
||||
let value = percent_encode(c.value().as_bytes(), USERINFO);
|
||||
let _ = write!(&mut cookie, "; {}={}", name, value);
|
||||
}
|
||||
self.head.headers.insert(
|
||||
@ -443,7 +448,7 @@ mod tests {
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
"Basic dXNlcm5hbWU="
|
||||
"Basic dXNlcm5hbWU6"
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -12,11 +12,10 @@ use flate2::Compression;
|
||||
use futures::Future;
|
||||
use rand::Rng;
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_http::HttpService;
|
||||
use actix_http_test::TestServer;
|
||||
use actix_service::{service_fn, NewService};
|
||||
use actix_web::http::{Cookie, Version};
|
||||
use actix_web::http::Cookie;
|
||||
use actix_web::middleware::{BodyEncoding, Compress};
|
||||
use actix_web::{http::header, web, App, Error, HttpMessage, HttpRequest, HttpResponse};
|
||||
use awc::error::SendRequestError;
|
||||
@ -43,30 +42,6 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World";
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
fn ssl_acceptor<T: AsyncRead + AsyncWrite>(
|
||||
) -> std::io::Result<actix_server::ssl::OpensslAcceptor<T, ()>> {
|
||||
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
|
||||
// load ssl keys
|
||||
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
|
||||
builder
|
||||
.set_private_key_file("../tests/key.pem", SslFiletype::PEM)
|
||||
.unwrap();
|
||||
builder
|
||||
.set_certificate_chain_file("../tests/cert.pem")
|
||||
.unwrap();
|
||||
builder.set_alpn_select_callback(|_, protos| {
|
||||
const H2: &[u8] = b"\x02h2";
|
||||
if protos.windows(3).any(|window| window == H2) {
|
||||
Ok(b"h2")
|
||||
} else {
|
||||
Err(openssl::ssl::AlpnError::NOACK)
|
||||
}
|
||||
});
|
||||
builder.set_alpn_protos(b"\x02h2")?;
|
||||
Ok(actix_server::ssl::OpensslAcceptor::new(builder.build()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_simple() {
|
||||
let mut srv =
|
||||
@ -207,60 +182,6 @@ fn test_connection_reuse() {
|
||||
assert_eq!(num.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_connection_reuse_h2() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let num = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = num.clone();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
service_fn(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
.and_then(
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e)),
|
||||
)
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(App::new()
|
||||
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
// disable ssl verification
|
||||
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
|
||||
|
||||
let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
|
||||
builder.set_verify(SslVerifyMode::NONE);
|
||||
let _ = builder
|
||||
.set_alpn_protos(b"\x02h2\x08http/1.1")
|
||||
.map_err(|e| log::error!("Can not set alpn protocol: {:?}", e));
|
||||
|
||||
let client = awc::Client::build()
|
||||
.connector(awc::Connector::new().ssl(builder.build()).finish())
|
||||
.finish();
|
||||
|
||||
// req 1
|
||||
let request = client.get(srv.surl("/")).send();
|
||||
let response = srv.block_on(request).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// req 2
|
||||
let req = client.post(srv.surl("/"));
|
||||
let response = srv.block_on_fn(move || req.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
assert_eq!(response.version(), Version::HTTP_2);
|
||||
|
||||
// one connection
|
||||
assert_eq!(num.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_connection_force_close() {
|
||||
let num = Arc::new(AtomicUsize::new(0));
|
||||
|
96
awc/tests/test_rustls_client.rs
Normal file
96
awc/tests/test_rustls_client.rs
Normal file
@ -0,0 +1,96 @@
|
||||
#![cfg(feature = "rust-tls")]
|
||||
use rustls::{
|
||||
internal::pemfile::{certs, pkcs8_private_keys},
|
||||
ClientConfig, NoClientAuth,
|
||||
};
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{BufReader, Result};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_http::HttpService;
|
||||
use actix_http_test::TestServer;
|
||||
use actix_server::ssl::RustlsAcceptor;
|
||||
use actix_service::{service_fn, NewService};
|
||||
use actix_web::http::Version;
|
||||
use actix_web::{web, App, HttpResponse};
|
||||
|
||||
fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<RustlsAcceptor<T, ()>> {
|
||||
use rustls::ServerConfig;
|
||||
// load ssl keys
|
||||
let mut config = ServerConfig::new(NoClientAuth::new());
|
||||
let cert_file = &mut BufReader::new(File::open("../tests/cert.pem").unwrap());
|
||||
let key_file = &mut BufReader::new(File::open("../tests/key.pem").unwrap());
|
||||
let cert_chain = certs(cert_file).unwrap();
|
||||
let mut keys = pkcs8_private_keys(key_file).unwrap();
|
||||
config.set_single_cert(cert_chain, keys.remove(0)).unwrap();
|
||||
let protos = vec![b"h2".to_vec()];
|
||||
config.set_protocols(&protos);
|
||||
Ok(RustlsAcceptor::new(config))
|
||||
}
|
||||
|
||||
mod danger {
|
||||
pub struct NoCertificateVerification {}
|
||||
|
||||
impl rustls::ServerCertVerifier for NoCertificateVerification {
|
||||
fn verify_server_cert(
|
||||
&self,
|
||||
_roots: &rustls::RootCertStore,
|
||||
_presented_certs: &[rustls::Certificate],
|
||||
_dns_name: webpki::DNSNameRef<'_>,
|
||||
_ocsp: &[u8],
|
||||
) -> Result<rustls::ServerCertVerified, rustls::TLSError> {
|
||||
Ok(rustls::ServerCertVerified::assertion())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_connection_reuse_h2() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
let num = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = num.clone();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
service_fn(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
.and_then(rustls.clone().map_err(|e| println!("Rustls error: {}", e)))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(App::new()
|
||||
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
// disable ssl verification
|
||||
let mut config = ClientConfig::new();
|
||||
let protos = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
|
||||
config.set_protocols(&protos);
|
||||
config
|
||||
.dangerous()
|
||||
.set_certificate_verifier(Arc::new(danger::NoCertificateVerification {}));
|
||||
|
||||
let client = awc::Client::build()
|
||||
.connector(awc::Connector::new().rustls(Arc::new(config)).finish())
|
||||
.finish();
|
||||
|
||||
// req 1
|
||||
let request = client.get(srv.surl("/")).send();
|
||||
let response = srv.block_on(request).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// req 2
|
||||
let req = client.post(srv.surl("/"));
|
||||
let response = srv.block_on_fn(move || req.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
assert_eq!(response.version(), Version::HTTP_2);
|
||||
|
||||
// one connection
|
||||
assert_eq!(num.load(Ordering::Relaxed), 1);
|
||||
}
|
86
awc/tests/test_ssl_client.rs
Normal file
86
awc/tests/test_ssl_client.rs
Normal file
@ -0,0 +1,86 @@
|
||||
#![cfg(feature = "ssl")]
|
||||
use openssl::ssl::{SslAcceptor, SslConnector, SslFiletype, SslMethod, SslVerifyMode};
|
||||
|
||||
use std::io::Result;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_http::HttpService;
|
||||
use actix_http_test::TestServer;
|
||||
use actix_server::ssl::OpensslAcceptor;
|
||||
use actix_service::{service_fn, NewService};
|
||||
use actix_web::http::Version;
|
||||
use actix_web::{web, App, HttpResponse};
|
||||
|
||||
fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<OpensslAcceptor<T, ()>> {
|
||||
// load ssl keys
|
||||
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
|
||||
builder
|
||||
.set_private_key_file("../tests/key.pem", SslFiletype::PEM)
|
||||
.unwrap();
|
||||
builder
|
||||
.set_certificate_chain_file("../tests/cert.pem")
|
||||
.unwrap();
|
||||
builder.set_alpn_select_callback(|_, protos| {
|
||||
const H2: &[u8] = b"\x02h2";
|
||||
if protos.windows(3).any(|window| window == H2) {
|
||||
Ok(b"h2")
|
||||
} else {
|
||||
Err(openssl::ssl::AlpnError::NOACK)
|
||||
}
|
||||
});
|
||||
builder.set_alpn_protos(b"\x02h2")?;
|
||||
Ok(actix_server::ssl::OpensslAcceptor::new(builder.build()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_connection_reuse_h2() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let num = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = num.clone();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
service_fn(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
.and_then(
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e)),
|
||||
)
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(App::new()
|
||||
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
// disable ssl verification
|
||||
let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
|
||||
builder.set_verify(SslVerifyMode::NONE);
|
||||
let _ = builder
|
||||
.set_alpn_protos(b"\x02h2\x08http/1.1")
|
||||
.map_err(|e| log::error!("Can not set alpn protocol: {:?}", e));
|
||||
|
||||
let client = awc::Client::build()
|
||||
.connector(awc::Connector::new().ssl(builder.build()).finish())
|
||||
.finish();
|
||||
|
||||
// req 1
|
||||
let request = client.get(srv.surl("/")).send();
|
||||
let response = srv.block_on(request).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// req 2
|
||||
let req = client.post(srv.surl("/"));
|
||||
let response = srv.block_on_fn(move || req.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
assert_eq!(response.version(), Version::HTTP_2);
|
||||
|
||||
// one connection
|
||||
assert_eq!(num.load(Ordering::Relaxed), 1);
|
||||
}
|
53
examples/uds.rs
Normal file
53
examples/uds.rs
Normal file
@ -0,0 +1,53 @@
|
||||
use futures::IntoFuture;
|
||||
|
||||
use actix_web::{
|
||||
get, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer,
|
||||
};
|
||||
|
||||
#[get("/resource1/{name}/index.html")]
|
||||
fn index(req: HttpRequest, name: web::Path<String>) -> String {
|
||||
println!("REQ: {:?}", req);
|
||||
format!("Hello: {}!\r\n", name)
|
||||
}
|
||||
|
||||
fn index_async(req: HttpRequest) -> impl IntoFuture<Item = &'static str, Error = Error> {
|
||||
println!("REQ: {:?}", req);
|
||||
Ok("Hello world!\r\n")
|
||||
}
|
||||
|
||||
#[get("/")]
|
||||
fn no_params() -> &'static str {
|
||||
"Hello world!\r\n"
|
||||
}
|
||||
|
||||
#[cfg(feature = "uds")]
|
||||
fn main() -> std::io::Result<()> {
|
||||
std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info");
|
||||
env_logger::init();
|
||||
|
||||
HttpServer::new(|| {
|
||||
App::new()
|
||||
.wrap(middleware::DefaultHeaders::new().header("X-Version", "0.2"))
|
||||
.wrap(middleware::Compress::default())
|
||||
.wrap(middleware::Logger::default())
|
||||
.service(index)
|
||||
.service(no_params)
|
||||
.service(
|
||||
web::resource("/resource2/index.html")
|
||||
.wrap(
|
||||
middleware::DefaultHeaders::new().header("X-Version-R2", "0.3"),
|
||||
)
|
||||
.default_service(
|
||||
web::route().to(|| HttpResponse::MethodNotAllowed()),
|
||||
)
|
||||
.route(web::get().to_async(index_async)),
|
||||
)
|
||||
.service(web::resource("/test1.html").to(|| "Test\r\n"))
|
||||
})
|
||||
.bind_uds("/Users/fafhrd91/uds-test")?
|
||||
.workers(1)
|
||||
.run()
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "uds"))]
|
||||
fn main() {}
|
@ -23,16 +23,17 @@ use crate::service::{
|
||||
};
|
||||
|
||||
type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>;
|
||||
type FnDataFactory = Box<Fn() -> Box<dyn Future<Item = Box<DataFactory>, Error = ()>>>;
|
||||
type FnDataFactory =
|
||||
Box<dyn Fn() -> Box<dyn Future<Item = Box<dyn DataFactory>, Error = ()>>>;
|
||||
|
||||
/// Application builder - structure that follows the builder pattern
|
||||
/// for building application instances.
|
||||
pub struct App<T, B> {
|
||||
endpoint: T,
|
||||
services: Vec<Box<ServiceFactory>>,
|
||||
services: Vec<Box<dyn ServiceFactory>>,
|
||||
default: Option<Rc<HttpNewService>>,
|
||||
factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
|
||||
data: Vec<Box<DataFactory>>,
|
||||
data: Vec<Box<dyn DataFactory>>,
|
||||
data_factories: Vec<FnDataFactory>,
|
||||
config: AppConfigInner,
|
||||
external: Vec<ResourceDef>,
|
||||
|
@ -18,14 +18,15 @@ use crate::request::{HttpRequest, HttpRequestPool};
|
||||
use crate::rmap::ResourceMap;
|
||||
use crate::service::{ServiceFactory, ServiceRequest, ServiceResponse};
|
||||
|
||||
type Guards = Vec<Box<Guard>>;
|
||||
type Guards = Vec<Box<dyn Guard>>;
|
||||
type HttpService = BoxedService<ServiceRequest, ServiceResponse, Error>;
|
||||
type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>;
|
||||
type BoxedResponse = Either<
|
||||
FutureResult<ServiceResponse, Error>,
|
||||
Box<Future<Item = ServiceResponse, Error = Error>>,
|
||||
Box<dyn Future<Item = ServiceResponse, Error = Error>>,
|
||||
>;
|
||||
type FnDataFactory = Box<Fn() -> Box<dyn Future<Item = Box<DataFactory>, Error = ()>>>;
|
||||
type FnDataFactory =
|
||||
Box<dyn Fn() -> Box<dyn Future<Item = Box<dyn DataFactory>, Error = ()>>>;
|
||||
|
||||
/// Service factory to convert `Request` to a `ServiceRequest<S>`.
|
||||
/// It also executes data factories.
|
||||
@ -40,10 +41,10 @@ where
|
||||
>,
|
||||
{
|
||||
pub(crate) endpoint: T,
|
||||
pub(crate) data: Rc<Vec<Box<DataFactory>>>,
|
||||
pub(crate) data: Rc<Vec<Box<dyn DataFactory>>>,
|
||||
pub(crate) data_factories: Rc<Vec<FnDataFactory>>,
|
||||
pub(crate) config: RefCell<AppConfig>,
|
||||
pub(crate) services: Rc<RefCell<Vec<Box<ServiceFactory>>>>,
|
||||
pub(crate) services: Rc<RefCell<Vec<Box<dyn ServiceFactory>>>>,
|
||||
pub(crate) default: Option<Rc<HttpNewService>>,
|
||||
pub(crate) factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
|
||||
pub(crate) external: RefCell<Vec<ResourceDef>>,
|
||||
@ -142,9 +143,9 @@ where
|
||||
endpoint_fut: T::Future,
|
||||
rmap: Rc<ResourceMap>,
|
||||
config: AppConfig,
|
||||
data: Rc<Vec<Box<DataFactory>>>,
|
||||
data_factories: Vec<Box<DataFactory>>,
|
||||
data_factories_fut: Vec<Box<dyn Future<Item = Box<DataFactory>, Error = ()>>>,
|
||||
data: Rc<Vec<Box<dyn DataFactory>>>,
|
||||
data_factories: Vec<Box<dyn DataFactory>>,
|
||||
data_factories_fut: Vec<Box<dyn Future<Item = Box<dyn DataFactory>, Error = ()>>>,
|
||||
_t: PhantomData<B>,
|
||||
}
|
||||
|
||||
@ -297,14 +298,14 @@ impl NewService for AppRoutingFactory {
|
||||
}
|
||||
}
|
||||
|
||||
type HttpServiceFut = Box<Future<Item = HttpService, Error = ()>>;
|
||||
type HttpServiceFut = Box<dyn Future<Item = HttpService, Error = ()>>;
|
||||
|
||||
/// Create app service
|
||||
#[doc(hidden)]
|
||||
pub struct AppRoutingFactoryResponse {
|
||||
fut: Vec<CreateAppRoutingItem>,
|
||||
default: Option<HttpService>,
|
||||
default_fut: Option<Box<Future<Item = HttpService, Error = ()>>>,
|
||||
default_fut: Option<Box<dyn Future<Item = HttpService, Error = ()>>>,
|
||||
}
|
||||
|
||||
enum CreateAppRoutingItem {
|
||||
|
@ -16,7 +16,7 @@ use crate::service::{
|
||||
ServiceResponse,
|
||||
};
|
||||
|
||||
type Guards = Vec<Box<Guard>>;
|
||||
type Guards = Vec<Box<dyn Guard>>;
|
||||
type HttpNewService =
|
||||
boxed::BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>;
|
||||
|
||||
@ -31,7 +31,7 @@ pub struct AppService {
|
||||
Option<Guards>,
|
||||
Option<Rc<ResourceMap>>,
|
||||
)>,
|
||||
service_data: Rc<Vec<Box<DataFactory>>>,
|
||||
service_data: Rc<Vec<Box<dyn DataFactory>>>,
|
||||
}
|
||||
|
||||
impl AppService {
|
||||
@ -39,7 +39,7 @@ impl AppService {
|
||||
pub(crate) fn new(
|
||||
config: AppConfig,
|
||||
default: Rc<HttpNewService>,
|
||||
service_data: Rc<Vec<Box<DataFactory>>>,
|
||||
service_data: Rc<Vec<Box<dyn DataFactory>>>,
|
||||
) -> Self {
|
||||
AppService {
|
||||
config,
|
||||
@ -101,7 +101,7 @@ impl AppService {
|
||||
pub fn register_service<F, S>(
|
||||
&mut self,
|
||||
rdef: ResourceDef,
|
||||
guards: Option<Vec<Box<Guard>>>,
|
||||
guards: Option<Vec<Box<dyn Guard>>>,
|
||||
service: F,
|
||||
nested: Option<Rc<ResourceMap>>,
|
||||
) where
|
||||
@ -133,7 +133,7 @@ impl AppConfig {
|
||||
|
||||
/// Set server host name.
|
||||
///
|
||||
/// Host name is used by application router aa a hostname for url
|
||||
/// Host name is used by application router as a hostname for url
|
||||
/// generation. Check [ConnectionInfo](./dev/struct.ConnectionInfo.
|
||||
/// html#method.host) documentation for more information.
|
||||
///
|
||||
@ -174,8 +174,8 @@ impl Default for AppConfigInner {
|
||||
/// to set of external methods. This could help with
|
||||
/// modularization of big application configuration.
|
||||
pub struct ServiceConfig {
|
||||
pub(crate) services: Vec<Box<ServiceFactory>>,
|
||||
pub(crate) data: Vec<Box<DataFactory>>,
|
||||
pub(crate) services: Vec<Box<dyn ServiceFactory>>,
|
||||
pub(crate) data: Vec<Box<dyn DataFactory>>,
|
||||
pub(crate) external: Vec<ResourceDef>,
|
||||
}
|
||||
|
||||
|
@ -77,6 +77,11 @@ impl<T> Data<T> {
|
||||
pub fn get_ref(&self) -> &T {
|
||||
self.0.as_ref()
|
||||
}
|
||||
|
||||
/// Convert to the internal Arc<T>
|
||||
pub fn into_inner(self) -> Arc<T> {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deref for Data<T> {
|
||||
@ -118,7 +123,7 @@ impl<T: 'static> FromRequest for Data<T> {
|
||||
impl<T: 'static> DataFactory for Data<T> {
|
||||
fn create(&self, extensions: &mut Extensions) -> bool {
|
||||
if !extensions.contains::<Data<T>>() {
|
||||
let _ = extensions.insert(Data(self.0.clone()));
|
||||
extensions.insert(Data(self.0.clone()));
|
||||
true
|
||||
} else {
|
||||
false
|
||||
|
@ -94,7 +94,7 @@ where
|
||||
{
|
||||
type Config = T::Config;
|
||||
type Error = Error;
|
||||
type Future = Box<Future<Item = Option<T>, Error = Error>>;
|
||||
type Future = Box<dyn Future<Item = Option<T>, Error = Error>>;
|
||||
|
||||
#[inline]
|
||||
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
||||
@ -165,7 +165,7 @@ where
|
||||
{
|
||||
type Config = T::Config;
|
||||
type Error = Error;
|
||||
type Future = Box<Future<Item = Result<T, T::Error>, Error = Error>>;
|
||||
type Future = Box<dyn Future<Item = Result<T, T::Error>, Error = Error>>;
|
||||
|
||||
#[inline]
|
||||
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
||||
|
172
src/guard.rs
172
src/guard.rs
@ -26,7 +26,7 @@
|
||||
//! ```
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
use actix_http::http::{self, header, HttpTryFrom};
|
||||
use actix_http::http::{self, header, uri::Uri, HttpTryFrom};
|
||||
use actix_http::RequestHead;
|
||||
|
||||
/// Trait defines resource guards. Guards are used for routes selection.
|
||||
@ -100,7 +100,7 @@ pub fn Any<F: Guard + 'static>(guard: F) -> AnyGuard {
|
||||
}
|
||||
|
||||
/// Matches if any of supplied guards matche.
|
||||
pub struct AnyGuard(Vec<Box<Guard>>);
|
||||
pub struct AnyGuard(Vec<Box<dyn Guard>>);
|
||||
|
||||
impl AnyGuard {
|
||||
/// Add guard to a list of guards to check
|
||||
@ -140,7 +140,7 @@ pub fn All<F: Guard + 'static>(guard: F) -> AllGuard {
|
||||
}
|
||||
|
||||
/// Matches if all of supplied guards.
|
||||
pub struct AllGuard(Vec<Box<Guard>>);
|
||||
pub struct AllGuard(Vec<Box<dyn Guard>>);
|
||||
|
||||
impl AllGuard {
|
||||
/// Add new guard to the list of guards to check
|
||||
@ -167,7 +167,7 @@ pub fn Not<F: Guard + 'static>(guard: F) -> NotGuard {
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct NotGuard(Box<Guard>);
|
||||
pub struct NotGuard(Box<dyn Guard>);
|
||||
|
||||
impl Guard for NotGuard {
|
||||
fn check(&self, request: &RequestHead) -> bool {
|
||||
@ -256,45 +256,68 @@ impl Guard for HeaderGuard {
|
||||
}
|
||||
}
|
||||
|
||||
// /// Return predicate that matches if request contains specified Host name.
|
||||
// ///
|
||||
// /// ```rust,ignore
|
||||
// /// # extern crate actix_web;
|
||||
// /// use actix_web::{pred, App, HttpResponse};
|
||||
// ///
|
||||
// /// fn main() {
|
||||
// /// App::new().resource("/index.html", |r| {
|
||||
// /// r.route()
|
||||
// /// .guard(pred::Host("www.rust-lang.org"))
|
||||
// /// .f(|_| HttpResponse::MethodNotAllowed())
|
||||
// /// });
|
||||
// /// }
|
||||
// /// ```
|
||||
// pub fn Host<H: AsRef<str>>(host: H) -> HostGuard {
|
||||
// HostGuard(host.as_ref().to_string(), None)
|
||||
// }
|
||||
/// Return predicate that matches if request contains specified Host name.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// # extern crate actix_web;
|
||||
/// use actix_web::{guard::Host, App, HttpResponse};
|
||||
///
|
||||
/// fn main() {
|
||||
/// App::new().resource("/index.html", |r| {
|
||||
/// r.route()
|
||||
/// .guard(Host("www.rust-lang.org"))
|
||||
/// .f(|_| HttpResponse::MethodNotAllowed())
|
||||
/// });
|
||||
/// }
|
||||
/// ```
|
||||
pub fn Host<H: AsRef<str>>(host: H) -> HostGuard {
|
||||
HostGuard(host.as_ref().to_string(), None)
|
||||
}
|
||||
|
||||
// #[doc(hidden)]
|
||||
// pub struct HostGuard(String, Option<String>);
|
||||
fn get_host_uri(req: &RequestHead) -> Option<Uri> {
|
||||
use core::str::FromStr;
|
||||
let host_value = req.headers.get(header::HOST)?;
|
||||
let host = host_value.to_str().ok()?;
|
||||
let uri = Uri::from_str(host).ok()?;
|
||||
Some(uri)
|
||||
}
|
||||
|
||||
// impl HostGuard {
|
||||
// /// Set reuest scheme to match
|
||||
// pub fn scheme<H: AsRef<str>>(&mut self, scheme: H) {
|
||||
// self.1 = Some(scheme.as_ref().to_string())
|
||||
// }
|
||||
// }
|
||||
#[doc(hidden)]
|
||||
pub struct HostGuard(String, Option<String>);
|
||||
|
||||
// impl Guard for HostGuard {
|
||||
// fn check(&self, _req: &RequestHead) -> bool {
|
||||
// // let info = req.connection_info();
|
||||
// // if let Some(ref scheme) = self.1 {
|
||||
// // self.0 == info.host() && scheme == info.scheme()
|
||||
// // } else {
|
||||
// // self.0 == info.host()
|
||||
// // }
|
||||
// false
|
||||
// }
|
||||
// }
|
||||
impl HostGuard {
|
||||
/// Set request scheme to match
|
||||
pub fn scheme<H: AsRef<str>>(mut self, scheme: H) -> HostGuard {
|
||||
self.1 = Some(scheme.as_ref().to_string());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Guard for HostGuard {
|
||||
fn check(&self, req: &RequestHead) -> bool {
|
||||
let req_host_uri = if let Some(uri) = get_host_uri(req) {
|
||||
uri
|
||||
} else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if let Some(uri_host) = req_host_uri.host() {
|
||||
if self.0 != uri_host {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
if let Some(ref scheme) = self.1 {
|
||||
if let Some(ref req_host_uri_scheme) = req_host_uri.scheme_str() {
|
||||
return scheme == req_host_uri_scheme;
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@ -318,21 +341,64 @@ mod tests {
|
||||
assert!(!pred.check(req.head()));
|
||||
}
|
||||
|
||||
// #[test]
|
||||
// fn test_host() {
|
||||
// let req = TestServiceRequest::default()
|
||||
// .header(
|
||||
// header::HOST,
|
||||
// header::HeaderValue::from_static("www.rust-lang.org"),
|
||||
// )
|
||||
// .request();
|
||||
#[test]
|
||||
fn test_host() {
|
||||
let req = TestRequest::default()
|
||||
.header(
|
||||
header::HOST,
|
||||
header::HeaderValue::from_static("www.rust-lang.org"),
|
||||
)
|
||||
.to_http_request();
|
||||
|
||||
// let pred = Host("www.rust-lang.org");
|
||||
// assert!(pred.check(&req));
|
||||
let pred = Host("www.rust-lang.org");
|
||||
assert!(pred.check(req.head()));
|
||||
|
||||
// let pred = Host("localhost");
|
||||
// assert!(!pred.check(&req));
|
||||
// }
|
||||
let pred = Host("www.rust-lang.org").scheme("https");
|
||||
assert!(pred.check(req.head()));
|
||||
|
||||
let pred = Host("blog.rust-lang.org");
|
||||
assert!(!pred.check(req.head()));
|
||||
|
||||
let pred = Host("blog.rust-lang.org").scheme("https");
|
||||
assert!(!pred.check(req.head()));
|
||||
|
||||
let pred = Host("crates.io");
|
||||
assert!(!pred.check(req.head()));
|
||||
|
||||
let pred = Host("localhost");
|
||||
assert!(!pred.check(req.head()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_host_scheme() {
|
||||
let req = TestRequest::default()
|
||||
.header(
|
||||
header::HOST,
|
||||
header::HeaderValue::from_static("https://www.rust-lang.org"),
|
||||
)
|
||||
.to_http_request();
|
||||
|
||||
let pred = Host("www.rust-lang.org").scheme("https");
|
||||
assert!(pred.check(req.head()));
|
||||
|
||||
let pred = Host("www.rust-lang.org");
|
||||
assert!(pred.check(req.head()));
|
||||
|
||||
let pred = Host("www.rust-lang.org").scheme("http");
|
||||
assert!(!pred.check(req.head()));
|
||||
|
||||
let pred = Host("blog.rust-lang.org");
|
||||
assert!(!pred.check(req.head()));
|
||||
|
||||
let pred = Host("blog.rust-lang.org").scheme("https");
|
||||
assert!(!pred.check(req.head()));
|
||||
|
||||
let pred = Host("crates.io").scheme("https");
|
||||
assert!(!pred.check(req.head()));
|
||||
|
||||
let pred = Host("localhost");
|
||||
assert!(!pred.check(req.head()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_methods() {
|
||||
|
@ -250,7 +250,7 @@ where
|
||||
Ok(Async::Ready(res)) => {
|
||||
self.fut2 =
|
||||
Some(res.respond_to(self.req.as_ref().unwrap()).into_future());
|
||||
return self.poll();
|
||||
self.poll()
|
||||
}
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Err(e) => {
|
||||
|
@ -25,7 +25,7 @@ impl ConnectionInfo {
|
||||
Ref::map(req.extensions(), |e| e.get().unwrap())
|
||||
}
|
||||
|
||||
#[allow(clippy::cyclomatic_complexity)]
|
||||
#[allow(clippy::cognitive_complexity)]
|
||||
fn new(req: &RequestHead, cfg: &AppConfig) -> ConnectionInfo {
|
||||
let mut host = None;
|
||||
let mut scheme = None;
|
||||
|
@ -1,3 +1,4 @@
|
||||
#![allow(clippy::borrow_interior_mutable_const)]
|
||||
//! Actix web is a small, pragmatic, and extremely fast web framework
|
||||
//! for Rust.
|
||||
//!
|
||||
@ -60,9 +61,9 @@
|
||||
//! * Configurable request routing
|
||||
//! * Multipart streams
|
||||
//! * SSL support with OpenSSL or `native-tls`
|
||||
//! * Middlewares (`Logger`, `Session`, `CORS`, `CSRF`, `DefaultHeaders`)
|
||||
//! * Middlewares (`Logger`, `Session`, `CORS`, `DefaultHeaders`)
|
||||
//! * Supports [Actix actor framework](https://github.com/actix/actix)
|
||||
//! * Supported Rust version: 1.31 or later
|
||||
//! * Supported Rust version: 1.36 or later
|
||||
//!
|
||||
//! ## Package feature
|
||||
//!
|
||||
@ -77,6 +78,7 @@
|
||||
//! `c` compiler (default enabled)
|
||||
//! * `flate2-rust` - experimental rust based implementation for
|
||||
//! `gzip`, `deflate` compression.
|
||||
//! * `uds` - Unix domain support, enables `HttpServer::bind_uds()` method.
|
||||
//!
|
||||
#![allow(clippy::type_complexity, clippy::new_without_default)]
|
||||
|
||||
@ -134,6 +136,8 @@ pub mod dev {
|
||||
//! ```
|
||||
|
||||
pub use crate::config::{AppConfig, AppService};
|
||||
#[doc(hidden)]
|
||||
pub use crate::handler::{AsyncFactory, Factory};
|
||||
pub use crate::info::ConnectionInfo;
|
||||
pub use crate::rmap::ResourceMap;
|
||||
pub use crate::service::{
|
||||
|
143
src/middleware/condition.rs
Normal file
143
src/middleware/condition.rs
Normal file
@ -0,0 +1,143 @@
|
||||
//! `Middleware` for conditionally enables another middleware.
|
||||
use actix_service::{Service, Transform};
|
||||
use futures::future::{ok, Either, FutureResult, Map};
|
||||
use futures::{Future, Poll};
|
||||
|
||||
/// `Middleware` for conditionally enables another middleware.
|
||||
/// The controled middleware must not change the `Service` interfaces.
|
||||
/// This means you cannot control such middlewares like `Logger` or `Compress`.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_web::middleware::{Condition, NormalizePath};
|
||||
/// use actix_web::App;
|
||||
///
|
||||
/// fn main() {
|
||||
/// let enable_normalize = std::env::var("NORMALIZE_PATH") == Ok("true".into());
|
||||
/// let app = App::new()
|
||||
/// .wrap(Condition::new(enable_normalize, NormalizePath));
|
||||
/// }
|
||||
/// ```
|
||||
pub struct Condition<T> {
|
||||
trans: T,
|
||||
enable: bool,
|
||||
}
|
||||
|
||||
impl<T> Condition<T> {
|
||||
pub fn new(enable: bool, trans: T) -> Self {
|
||||
Self { trans, enable }
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T> Transform<S> for Condition<T>
|
||||
where
|
||||
S: Service,
|
||||
T: Transform<S, Request = S::Request, Response = S::Response, Error = S::Error>,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type InitError = T::InitError;
|
||||
type Transform = ConditionMiddleware<T::Transform, S>;
|
||||
type Future = Either<
|
||||
Map<T::Future, fn(T::Transform) -> Self::Transform>,
|
||||
FutureResult<Self::Transform, Self::InitError>,
|
||||
>;
|
||||
|
||||
fn new_transform(&self, service: S) -> Self::Future {
|
||||
if self.enable {
|
||||
let f = self
|
||||
.trans
|
||||
.new_transform(service)
|
||||
.map(ConditionMiddleware::Enable as fn(T::Transform) -> Self::Transform);
|
||||
Either::A(f)
|
||||
} else {
|
||||
Either::B(ok(ConditionMiddleware::Disable(service)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum ConditionMiddleware<E, D> {
|
||||
Enable(E),
|
||||
Disable(D),
|
||||
}
|
||||
|
||||
impl<E, D> Service for ConditionMiddleware<E, D>
|
||||
where
|
||||
E: Service,
|
||||
D: Service<Request = E::Request, Response = E::Response, Error = E::Error>,
|
||||
{
|
||||
type Request = E::Request;
|
||||
type Response = E::Response;
|
||||
type Error = E::Error;
|
||||
type Future = Either<E::Future, D::Future>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
use ConditionMiddleware::*;
|
||||
match self {
|
||||
Enable(service) => service.poll_ready(),
|
||||
Disable(service) => service.poll_ready(),
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, req: E::Request) -> Self::Future {
|
||||
use ConditionMiddleware::*;
|
||||
match self {
|
||||
Enable(service) => Either::A(service.call(req)),
|
||||
Disable(service) => Either::B(service.call(req)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_service::IntoService;
|
||||
|
||||
use super::*;
|
||||
use crate::dev::{ServiceRequest, ServiceResponse};
|
||||
use crate::error::Result;
|
||||
use crate::http::{header::CONTENT_TYPE, HeaderValue, StatusCode};
|
||||
use crate::middleware::errhandlers::*;
|
||||
use crate::test::{self, TestRequest};
|
||||
use crate::HttpResponse;
|
||||
|
||||
fn render_500<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
|
||||
res.response_mut()
|
||||
.headers_mut()
|
||||
.insert(CONTENT_TYPE, HeaderValue::from_static("0001"));
|
||||
Ok(ErrorHandlerResponse::Response(res))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_handler_enabled() {
|
||||
let srv = |req: ServiceRequest| {
|
||||
req.into_response(HttpResponse::InternalServerError().finish())
|
||||
};
|
||||
|
||||
let mw =
|
||||
ErrorHandlers::new().handler(StatusCode::INTERNAL_SERVER_ERROR, render_500);
|
||||
|
||||
let mut mw =
|
||||
test::block_on(Condition::new(true, mw).new_transform(srv.into_service()))
|
||||
.unwrap();
|
||||
let resp = test::call_service(&mut mw, TestRequest::default().to_srv_request());
|
||||
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001");
|
||||
}
|
||||
#[test]
|
||||
fn test_handler_disabled() {
|
||||
let srv = |req: ServiceRequest| {
|
||||
req.into_response(HttpResponse::InternalServerError().finish())
|
||||
};
|
||||
|
||||
let mw =
|
||||
ErrorHandlers::new().handler(StatusCode::INTERNAL_SERVER_ERROR, render_500);
|
||||
|
||||
let mut mw =
|
||||
test::block_on(Condition::new(false, mw).new_transform(srv.into_service()))
|
||||
.unwrap();
|
||||
|
||||
let resp = test::call_service(&mut mw, TestRequest::default().to_srv_request());
|
||||
assert_eq!(resp.headers().get(CONTENT_TYPE), None);
|
||||
}
|
||||
}
|
@ -119,7 +119,7 @@ where
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = Error;
|
||||
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
|
||||
type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.service.poll_ready()
|
||||
|
@ -15,10 +15,10 @@ pub enum ErrorHandlerResponse<B> {
|
||||
/// New http response got generated
|
||||
Response(ServiceResponse<B>),
|
||||
/// Result is a future that resolves to a new http response
|
||||
Future(Box<Future<Item = ServiceResponse<B>, Error = Error>>),
|
||||
Future(Box<dyn Future<Item = ServiceResponse<B>, Error = Error>>),
|
||||
}
|
||||
|
||||
type ErrorHandler<B> = Fn(ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>>;
|
||||
type ErrorHandler<B> = dyn Fn(ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>>;
|
||||
|
||||
/// `Middleware` for allowing custom handlers for responses.
|
||||
///
|
||||
@ -117,7 +117,7 @@ where
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = Error;
|
||||
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
|
||||
type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.service.poll_ready()
|
||||
|
@ -9,12 +9,13 @@ use actix_service::{Service, Transform};
|
||||
use bytes::Bytes;
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
use log::debug;
|
||||
use regex::Regex;
|
||||
use time;
|
||||
|
||||
use crate::dev::{BodySize, MessageBody, ResponseBody};
|
||||
use crate::error::{Error, Result};
|
||||
use crate::http::{HeaderName, HttpTryFrom};
|
||||
use crate::http::{HeaderName, HttpTryFrom, StatusCode};
|
||||
use crate::service::{ServiceRequest, ServiceResponse};
|
||||
use crate::HttpResponse;
|
||||
|
||||
@ -202,6 +203,12 @@ where
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
let res = futures::try_ready!(self.fut.poll());
|
||||
|
||||
if let Some(error) = res.response().error() {
|
||||
if res.response().head().status != StatusCode::INTERNAL_SERVER_ERROR {
|
||||
debug!("Error in response: {:?}", error);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref mut format) = self.format {
|
||||
for unit in &mut format.0 {
|
||||
unit.render_response(res.response());
|
||||
@ -415,9 +422,9 @@ impl FormatText {
|
||||
))
|
||||
};
|
||||
}
|
||||
FormatText::UrlPath => *self = FormatText::Str(format!("{}", req.path())),
|
||||
FormatText::UrlPath => *self = FormatText::Str(req.path().to_string()),
|
||||
FormatText::RequestTime => {
|
||||
*self = FormatText::Str(format!("{}", now.rfc3339()))
|
||||
*self = FormatText::Str(now.rfc3339().to_string())
|
||||
}
|
||||
FormatText::RequestHeader(ref name) => {
|
||||
let s = if let Some(val) = req.headers().get(name) {
|
||||
@ -444,7 +451,9 @@ impl FormatText {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct FormatDisplay<'a>(&'a Fn(&mut Formatter) -> Result<(), fmt::Error>);
|
||||
pub(crate) struct FormatDisplay<'a>(
|
||||
&'a dyn Fn(&mut Formatter) -> Result<(), fmt::Error>,
|
||||
);
|
||||
|
||||
impl<'a> fmt::Display for FormatDisplay<'a> {
|
||||
fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> {
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user