mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-04 18:06:23 +02:00
Compare commits
203 Commits
http-v0.2.
...
multipart-
Author | SHA1 | Date | |
---|---|---|---|
1d45639bed | |||
6a672c9097 | |||
5cb2d500d1 | |||
0212c618c6 | |||
88110ed268 | |||
fba02fdd8c | |||
b2934ad8d2 | |||
f7f410d033 | |||
885ff7396e | |||
61b38e8d0d | |||
edcde67076 | |||
f0612f7570 | |||
ace98e3a1e | |||
1ca9d87f0a | |||
967f965405 | |||
062e51e8ce | |||
a48e616def | |||
effa96f5e4 | |||
cc0b4be5b7 | |||
a464ffc23d | |||
4de2e8a898 | |||
0f09415469 | |||
f089cf185b | |||
15d3c1ae81 | |||
fba31d4e0a | |||
f81ae37677 | |||
5169d306ae | |||
4f3e97fff8 | |||
3ff01a9fc4 | |||
3d4e45a0e5 | |||
c659c33919 | |||
959f7754b2 | |||
23f04c4f38 | |||
d9af8f66ba | |||
aa39b8ca6f | |||
58c7065f08 | |||
b3783b403e | |||
e4503046de | |||
32a1c36597 | |||
7c9f9afc46 | |||
c1f99e0775 | |||
a32573bb58 | |||
e35d930ef9 | |||
60b7aebd0a | |||
45d2fd4299 | |||
71f8577713 | |||
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 | |||
d286ccb4f5 | |||
cac162aed7 | |||
a3a78ac6fb | |||
596483ff55 | |||
768859513a | |||
44bb79cd07 | |||
af9fb5d190 | |||
50a9d9e2c5 | |||
c0c71f82c0 | |||
93855b889a | |||
fa7e0fe6df | |||
b948f74b54 | |||
1a24ff8717 | |||
47fab0e393 | |||
313ac48765 | |||
d7780d53c9 | |||
ad0e6f73b3 | |||
546a8a58db | |||
acda1c075a | |||
686e5f1595 | |||
d2b6502c7a | |||
7c0f570845 | |||
382d4ca216 | |||
eaa371db8b | |||
d293ae2a69 | |||
d7ec241fd0 | |||
cd323f2ff1 | |||
32a66a99bf | |||
73ae801a13 | |||
ca4ed0932e | |||
bf48798bce | |||
9fc7c8b1af | |||
c8118e8411 | |||
65732197b8 | |||
959eef05ae | |||
e7ba67e1a8 | |||
13e618b128 | |||
36e6f0cb4b | |||
7450ae37a7 | |||
2ffda29f9b | |||
ff724e239d | |||
ee769832cf | |||
c4b7980b4f | |||
bfbac4f875 | |||
53e2f8090f | |||
e399e01a22 | |||
d9a62c4bbf | |||
a548b69679 | |||
ae64475d98 | |||
a342b1289d | |||
38f04b75a7 | |||
a771540b16 | |||
cf217d35a8 | |||
0e138e111f | |||
1fce4876f3 | |||
4a179d1ae1 | |||
a780ea10e9 | |||
6d2e190c8e | |||
b1cfbdcf7a | |||
24180f9014 | |||
15cdc680f6 | |||
666756bfbe | |||
a1b40f4314 | |||
29a0fe76d5 | |||
7753b9da6d | |||
f1764bba43 | |||
c2d7db7e06 |
14
.travis.yml
14
.travis.yml
@ -3,16 +3,16 @@ sudo: required
|
|||||||
dist: trusty
|
dist: trusty
|
||||||
|
|
||||||
cache:
|
cache:
|
||||||
cargo: true
|
# cargo: true
|
||||||
apt: true
|
apt: true
|
||||||
|
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
- rust: stable
|
- rust: stable
|
||||||
- rust: beta
|
- rust: beta
|
||||||
- rust: nightly-2019-04-02
|
- rust: nightly-2019-08-10
|
||||||
allow_failures:
|
allow_failures:
|
||||||
- rust: nightly-2019-04-02
|
- rust: nightly-2019-08-10
|
||||||
|
|
||||||
env:
|
env:
|
||||||
global:
|
global:
|
||||||
@ -25,8 +25,8 @@ before_install:
|
|||||||
- sudo apt-get install -y openssl libssl-dev libelf-dev libdw-dev cmake gcc binutils-dev libiberty-dev
|
- sudo apt-get install -y openssl libssl-dev libelf-dev libdw-dev cmake gcc binutils-dev libiberty-dev
|
||||||
|
|
||||||
before_cache: |
|
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 cargo-tarpaulin
|
RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install --version 0.6.11 cargo-tarpaulin
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Add clippy
|
# Add clippy
|
||||||
@ -37,6 +37,8 @@ script:
|
|||||||
- cargo update
|
- cargo update
|
||||||
- cargo check --all --no-default-features
|
- cargo check --all --no-default-features
|
||||||
- cargo test --all-features --all -- --nocapture
|
- 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
|
# Upload docs
|
||||||
after_success:
|
after_success:
|
||||||
@ -49,7 +51,7 @@ after_success:
|
|||||||
echo "Uploaded documentation"
|
echo "Uploaded documentation"
|
||||||
fi
|
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
|
taskset -c 0 cargo tarpaulin --out Xml --all --all-features
|
||||||
bash <(curl -s https://codecov.io/bash)
|
bash <(curl -s https://codecov.io/bash)
|
||||||
echo "Uploaded code coverage"
|
echo "Uploaded code coverage"
|
||||||
|
152
CHANGES.md
152
CHANGES.md
@ -1,20 +1,162 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## [1.0.0] - 2019-05-xx
|
## [1.0.9] - 2019-11-14
|
||||||
|
|
||||||
### Add
|
### Added
|
||||||
|
|
||||||
|
* Add `Payload::into_inner` method and make stored `def::Payload` public. (#1110)
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Support `Host` guards when the `Host` header is unset (e.g. HTTP/2 requests) (#1129)
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.8] - 2019-09-25
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Add `Scope::register_data` and `Resource::register_data` methods, parallel to
|
||||||
|
`App::register_data`.
|
||||||
|
|
||||||
|
* Add `middleware::Condition` that conditionally enables another middleware
|
||||||
|
|
||||||
|
* Allow to re-construct `ServiceRequest` from `HttpRequest` and `Payload`
|
||||||
|
|
||||||
|
* Add `HttpServer::listen_uds` for ability to listen on UDS FD rather than path,
|
||||||
|
which is useful for example with systemd.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Make UrlEncodedError::Overflow more informativve
|
||||||
|
|
||||||
|
* Use actix-testing for testing utils
|
||||||
|
|
||||||
|
|
||||||
|
## [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
|
||||||
|
|
||||||
|
* Support asynchronous data factories #850
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Use `encoding_rs` crate instead of unmaintained `encoding` crate
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.2] - 2019-06-17
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Move cors middleware to `actix-cors` crate.
|
||||||
|
|
||||||
|
* Move identity middleware to `actix-identity` crate.
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.1] - 2019-06-17
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Add support for PathConfig #903
|
||||||
|
|
||||||
|
* Add `middleware::identity::RequestIdentity` trait to `get_identity` from `HttpMessage`.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Move cors middleware to `actix-cors` crate.
|
||||||
|
|
||||||
|
* Move identity middleware to `actix-identity` crate.
|
||||||
|
|
||||||
|
* Disable default feature `secure-cookies`.
|
||||||
|
|
||||||
|
* Allow to test an app that uses async actors #897
|
||||||
|
|
||||||
|
* Re-apply patch from #637 #894
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* HttpRequest::url_for is broken with nested scopes #915
|
||||||
|
|
||||||
|
|
||||||
|
## [1.0.0] - 2019-06-05
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Add `Scope::configure()` method.
|
||||||
|
|
||||||
* Add `ServiceRequest::set_payload()` method.
|
* Add `ServiceRequest::set_payload()` method.
|
||||||
|
|
||||||
* Add `test::TestRequest::set_json()` convenience method to automatically
|
* Add `test::TestRequest::set_json()` convenience method to automatically
|
||||||
serialize data and set header in test requests.
|
serialize data and set header in test requests.
|
||||||
|
|
||||||
### Changes
|
* Add macros for head, options, trace, connect and patch http methods
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
* Drop an unnecessary `Option<_>` indirection around `ServerBuilder` from `HttpServer`. #863
|
* Drop an unnecessary `Option<_>` indirection around `ServerBuilder` from `HttpServer`. #863
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
|
* Fix Logger request time format, and use rfc3339. #867
|
||||||
|
|
||||||
* Clear http requests pool on app service drop #860
|
* Clear http requests pool on app service drop #860
|
||||||
|
|
||||||
|
|
||||||
@ -25,7 +167,7 @@
|
|||||||
* Add `Query<T>::from_query()` to extract parameters from a query string. #846
|
* Add `Query<T>::from_query()` to extract parameters from a query string. #846
|
||||||
* `QueryConfig`, similar to `JsonConfig` for customizing error handling of query extractors.
|
* `QueryConfig`, similar to `JsonConfig` for customizing error handling of query extractors.
|
||||||
|
|
||||||
### Changes
|
### Changed
|
||||||
|
|
||||||
* `JsonConfig` is now `Send + Sync`, this implies that `error_handler` must be `Send + Sync` too.
|
* `JsonConfig` is now `Send + Sync`, this implies that `error_handler` must be `Send + Sync` too.
|
||||||
|
|
||||||
@ -40,7 +182,7 @@
|
|||||||
|
|
||||||
* Allow to set/override app data on scope level
|
* Allow to set/override app data on scope level
|
||||||
|
|
||||||
### Changes
|
### Changed
|
||||||
|
|
||||||
* `App::configure` take an `FnOnce` instead of `Fn`
|
* `App::configure` take an `FnOnce` instead of `Fn`
|
||||||
* Upgrade actix-net crates
|
* Upgrade actix-net crates
|
||||||
|
52
Cargo.toml
52
Cargo.toml
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-web"
|
name = "actix-web"
|
||||||
version = "1.0.0"
|
version = "1.0.9"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
|
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -16,7 +16,7 @@ exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
|||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
[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]
|
[badges]
|
||||||
travis-ci = { repository = "actix/actix-web", branch = "master" }
|
travis-ci = { repository = "actix/actix-web", branch = "master" }
|
||||||
@ -31,9 +31,11 @@ members = [
|
|||||||
".",
|
".",
|
||||||
"awc",
|
"awc",
|
||||||
"actix-http",
|
"actix-http",
|
||||||
|
"actix-cors",
|
||||||
"actix-files",
|
"actix-files",
|
||||||
"actix-framed",
|
"actix-framed",
|
||||||
"actix-session",
|
"actix-session",
|
||||||
|
"actix-identity",
|
||||||
"actix-multipart",
|
"actix-multipart",
|
||||||
"actix-web-actors",
|
"actix-web-actors",
|
||||||
"actix-web-codegen",
|
"actix-web-codegen",
|
||||||
@ -41,7 +43,7 @@ members = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["brotli", "flate2-zlib", "secure-cookies", "client", "fail"]
|
default = ["brotli", "flate2-zlib", "client", "fail"]
|
||||||
|
|
||||||
# http client
|
# http client
|
||||||
client = ["awc"]
|
client = ["awc"]
|
||||||
@ -64,46 +66,50 @@ fail = ["actix-http/fail"]
|
|||||||
ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
|
ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
|
||||||
|
|
||||||
# rustls
|
# 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]
|
[dependencies]
|
||||||
actix-codec = "0.1.2"
|
actix-codec = "0.1.2"
|
||||||
actix-service = "0.4.0"
|
actix-service = "0.4.1"
|
||||||
actix-utils = "0.4.1"
|
actix-utils = "0.4.4"
|
||||||
actix-router = "0.1.5"
|
actix-router = "0.1.5"
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.4"
|
||||||
actix-web-codegen = "0.1.0"
|
actix-web-codegen = "0.1.2"
|
||||||
actix-http = "0.2.0"
|
actix-http = "0.2.11"
|
||||||
actix-server = "0.5.1"
|
actix-server = "0.6.1"
|
||||||
actix-server-config = "0.1.1"
|
actix-server-config = "0.1.2"
|
||||||
actix-threadpool = "0.1.0"
|
actix-testing = "0.1.0"
|
||||||
awc = { version = "0.2.0", optional = true }
|
actix-threadpool = "0.1.1"
|
||||||
|
awc = { version = "0.2.7", optional = true }
|
||||||
|
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
derive_more = "0.14"
|
derive_more = "0.15.0"
|
||||||
encoding = "0.2"
|
encoding_rs = "0.8"
|
||||||
futures = "0.1.25"
|
futures = "0.1.25"
|
||||||
hashbrown = "0.3.0"
|
hashbrown = "0.6.3"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
mime = "0.3"
|
mime = "0.3"
|
||||||
net2 = "0.2.33"
|
net2 = "0.2.33"
|
||||||
parking_lot = "0.8"
|
parking_lot = "0.9"
|
||||||
regex = "1.0"
|
regex = "1.0"
|
||||||
serde = { version = "1.0", features=["derive"] }
|
serde = { version = "1.0", features=["derive"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
serde_urlencoded = "0.5.3"
|
serde_urlencoded = "0.6.1"
|
||||||
time = "0.1.42"
|
time = "0.1.42"
|
||||||
url = { version="1.7", features=["query_encoding"] }
|
url = "2.1"
|
||||||
|
|
||||||
# ssl support
|
# ssl support
|
||||||
openssl = { version="0.10", optional = true }
|
openssl = { version="0.10", optional = true }
|
||||||
rustls = { version = "0.15", optional = true }
|
rustls = { version = "0.15", optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-http = { version = "0.2.0", features=["ssl", "brotli", "flate2-zlib"] }
|
actix = "0.8.3"
|
||||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
actix-connect = "0.2.2"
|
||||||
actix-files = { version = "0.1.0" }
|
actix-http-test = "0.2.4"
|
||||||
rand = "0.6"
|
rand = "0.7"
|
||||||
env_logger = "0.6"
|
env_logger = "0.6"
|
||||||
serde_derive = "1.0"
|
serde_derive = "1.0"
|
||||||
tokio-timer = "0.2.8"
|
tokio-timer = "0.2.8"
|
||||||
|
91
MIGRATION.md
91
MIGRATION.md
@ -1,4 +1,93 @@
|
|||||||
## 1.0
|
## 1.0.1
|
||||||
|
|
||||||
|
* Cors middleware has been moved to `actix-cors` crate
|
||||||
|
|
||||||
|
instead of
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use actix_web::middleware::cors::Cors;
|
||||||
|
```
|
||||||
|
|
||||||
|
use
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use actix_cors::Cors;
|
||||||
|
```
|
||||||
|
|
||||||
|
* Identity middleware has been moved to `actix-identity` crate
|
||||||
|
|
||||||
|
instead of
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use actix_web::middleware::identity::{Identity, CookieIdentityPolicy, IdentityService};
|
||||||
|
```
|
||||||
|
|
||||||
|
use
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use actix_identity::{Identity, CookieIdentityPolicy, IdentityService};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## 1.0.0
|
||||||
|
|
||||||
|
* Extractor configuration. In version 1.0 this is handled with the new `Data` mechanism for both setting and retrieving the configuration
|
||||||
|
|
||||||
|
instead of
|
||||||
|
|
||||||
|
```rust
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct ExtractorConfig {
|
||||||
|
config: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromRequest for YourExtractor {
|
||||||
|
type Config = ExtractorConfig;
|
||||||
|
type Result = Result<YourExtractor, Error>;
|
||||||
|
|
||||||
|
fn from_request(req: &HttpRequest, cfg: &Self::Config) -> Self::Result {
|
||||||
|
println!("use the config: {:?}", cfg.config);
|
||||||
|
...
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
App::new().resource("/route_with_config", |r| {
|
||||||
|
r.post().with_config(handler_fn, |cfg| {
|
||||||
|
cfg.0.config = "test".to_string();
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
use the HttpRequest to get the configuration like any other `Data` with `req.app_data::<C>()` and set it with the `data()` method on the `resource`
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#[derive(Default)]
|
||||||
|
struct ExtractorConfig {
|
||||||
|
config: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromRequest for YourExtractor {
|
||||||
|
type Error = Error;
|
||||||
|
type Future = Result<Self, Self::Error>;
|
||||||
|
type Config = ExtractorConfig;
|
||||||
|
|
||||||
|
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
||||||
|
let cfg = req.app_data::<ExtractorConfig>();
|
||||||
|
println!("config data?: {:?}", cfg.unwrap().role);
|
||||||
|
...
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
App::new().service(
|
||||||
|
resource("/route_with_config")
|
||||||
|
.data(ExtractorConfig {
|
||||||
|
config: "test".to_string(),
|
||||||
|
})
|
||||||
|
.route(post().to(handler_fn)),
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
* Resource registration. 1.0 version uses generalized resource
|
* Resource registration. 1.0 version uses generalized resource
|
||||||
registration via `.service()` method.
|
registration via `.service()` method.
|
||||||
|
@ -11,7 +11,7 @@ Actix web is a simple, pragmatic and extremely fast web framework for Rust.
|
|||||||
* Multipart streams
|
* Multipart streams
|
||||||
* Static assets
|
* Static assets
|
||||||
* SSL support with OpenSSL or Rustls
|
* SSL support with OpenSSL or Rustls
|
||||||
* Middlewares ([Logger, Session, CORS, CSRF, etc](https://actix.rs/docs/middleware/))
|
* Middlewares ([Logger, Session, CORS, etc](https://actix.rs/docs/middleware/))
|
||||||
* Includes an asynchronous [HTTP client](https://actix.rs/actix-web/actix_web/client/index.html)
|
* Includes an asynchronous [HTTP client](https://actix.rs/actix-web/actix_web/client/index.html)
|
||||||
* Supports [Actix actor framework](https://github.com/actix/actix)
|
* Supports [Actix actor framework](https://github.com/actix/actix)
|
||||||
|
|
||||||
@ -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/)
|
* [API Documentation (0.7)](https://docs.rs/actix-web/0.7.19/actix_web/)
|
||||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||||
* Cargo package: [actix-web](https://crates.io/crates/actix-web)
|
* Cargo package: [actix-web](https://crates.io/crates/actix-web)
|
||||||
* Minimum supported Rust version: 1.32 or later
|
* Minimum supported Rust version: 1.36 or later
|
||||||
|
|
||||||
## Example
|
## Example
|
||||||
|
|
||||||
@ -61,7 +61,7 @@ You may consider checking out
|
|||||||
|
|
||||||
## Benchmarks
|
## 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
|
## License
|
||||||
|
|
||||||
|
9
actix-cors/CHANGES.md
Normal file
9
actix-cors/CHANGES.md
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
# Changes
|
||||||
|
|
||||||
|
## [0.1.1] - unreleased
|
||||||
|
|
||||||
|
* Bump `derive_more` crate version to 0.15.0
|
||||||
|
|
||||||
|
## [0.1.0] - 2019-06-15
|
||||||
|
|
||||||
|
* Move cors middleware to separate crate
|
23
actix-cors/Cargo.toml
Normal file
23
actix-cors/Cargo.toml
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
[package]
|
||||||
|
name = "actix-cors"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
|
description = "Cross-origin resource sharing (CORS) for Actix applications."
|
||||||
|
readme = "README.md"
|
||||||
|
keywords = ["web", "framework"]
|
||||||
|
homepage = "https://actix.rs"
|
||||||
|
repository = "https://github.com/actix/actix-web.git"
|
||||||
|
documentation = "https://docs.rs/actix-cors/"
|
||||||
|
license = "MIT/Apache-2.0"
|
||||||
|
edition = "2018"
|
||||||
|
#workspace = ".."
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "actix_cors"
|
||||||
|
path = "src/lib.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
actix-web = "1.0.0"
|
||||||
|
actix-service = "0.4.0"
|
||||||
|
derive_more = "0.15.0"
|
||||||
|
futures = "0.1.25"
|
1
actix-cors/LICENSE-APACHE
Symbolic link
1
actix-cors/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-APACHE
|
1
actix-cors/LICENSE-MIT
Symbolic link
1
actix-cors/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-MIT
|
9
actix-cors/README.md
Normal file
9
actix-cors/README.md
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
# 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-cors/)
|
||||||
|
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||||
|
* 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
|
//! Cross-origin resource sharing (CORS) for Actix applications
|
||||||
//!
|
//!
|
||||||
//! CORS middleware could be used with application and with resource.
|
//! CORS middleware could be used with application and with resource.
|
||||||
@ -7,7 +8,7 @@
|
|||||||
//! # Example
|
//! # Example
|
||||||
//!
|
//!
|
||||||
//! ```rust
|
//! ```rust
|
||||||
//! use actix_web::middleware::cors::Cors;
|
//! use actix_cors::Cors;
|
||||||
//! use actix_web::{http, web, App, HttpRequest, HttpResponse, HttpServer};
|
//! use actix_web::{http, web, App, HttpRequest, HttpResponse, HttpServer};
|
||||||
//!
|
//!
|
||||||
//! fn index(req: HttpRequest) -> &'static str {
|
//! fn index(req: HttpRequest) -> &'static str {
|
||||||
@ -42,17 +43,15 @@ use std::iter::FromIterator;
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_service::{IntoTransform, Service, Transform};
|
use actix_service::{IntoTransform, Service, Transform};
|
||||||
|
use actix_web::dev::{RequestHead, ServiceRequest, ServiceResponse};
|
||||||
|
use actix_web::error::{Error, ResponseError, Result};
|
||||||
|
use actix_web::http::header::{self, HeaderName, HeaderValue};
|
||||||
|
use actix_web::http::{self, HttpTryFrom, Method, StatusCode, Uri};
|
||||||
|
use actix_web::HttpResponse;
|
||||||
use derive_more::Display;
|
use derive_more::Display;
|
||||||
use futures::future::{ok, Either, Future, FutureResult};
|
use futures::future::{ok, Either, Future, FutureResult};
|
||||||
use futures::Poll;
|
use futures::Poll;
|
||||||
|
|
||||||
use crate::dev::RequestHead;
|
|
||||||
use crate::error::{Error, ResponseError, Result};
|
|
||||||
use crate::http::header::{self, HeaderName, HeaderValue};
|
|
||||||
use crate::http::{self, HttpTryFrom, Method, StatusCode, Uri};
|
|
||||||
use crate::service::{ServiceRequest, ServiceResponse};
|
|
||||||
use crate::HttpResponse;
|
|
||||||
|
|
||||||
/// A set of errors that can occur during processing CORS
|
/// A set of errors that can occur during processing CORS
|
||||||
#[derive(Debug, Display)]
|
#[derive(Debug, Display)]
|
||||||
pub enum CorsError {
|
pub enum CorsError {
|
||||||
@ -152,11 +151,11 @@ impl<T> AllOrSome<T> {
|
|||||||
/// # Example
|
/// # Example
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
|
/// use actix_cors::Cors;
|
||||||
/// use actix_web::http::header;
|
/// use actix_web::http::header;
|
||||||
/// use actix_web::middleware::cors;
|
|
||||||
///
|
///
|
||||||
/// # fn main() {
|
/// # fn main() {
|
||||||
/// let cors = cors::Cors::new()
|
/// let cors = Cors::new()
|
||||||
/// .allowed_origin("https://www.rust-lang.org/")
|
/// .allowed_origin("https://www.rust-lang.org/")
|
||||||
/// .allowed_methods(vec!["GET", "POST"])
|
/// .allowed_methods(vec!["GET", "POST"])
|
||||||
/// .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
|
/// .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
|
||||||
@ -164,6 +163,7 @@ impl<T> AllOrSome<T> {
|
|||||||
/// .max_age(3600);
|
/// .max_age(3600);
|
||||||
/// # }
|
/// # }
|
||||||
/// ```
|
/// ```
|
||||||
|
#[derive(Default)]
|
||||||
pub struct Cors {
|
pub struct Cors {
|
||||||
cors: Option<Inner>,
|
cors: Option<Inner>,
|
||||||
methods: bool,
|
methods: bool,
|
||||||
@ -587,10 +587,10 @@ impl Inner {
|
|||||||
}
|
}
|
||||||
Err(CorsError::BadOrigin)
|
Err(CorsError::BadOrigin)
|
||||||
} else {
|
} else {
|
||||||
return match self.origins {
|
match self.origins {
|
||||||
AllOrSome::All => Ok(()),
|
AllOrSome::All => Ok(()),
|
||||||
_ => Err(CorsError::MissingOrigin),
|
_ => Err(CorsError::MissingOrigin),
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -665,7 +665,7 @@ impl Inner {
|
|||||||
}
|
}
|
||||||
Err(CorsError::BadRequestHeaders)
|
Err(CorsError::BadRequestHeaders)
|
||||||
} else {
|
} else {
|
||||||
return Ok(());
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -683,7 +683,7 @@ where
|
|||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Future = Either<
|
type Future = Either<
|
||||||
FutureResult<Self::Response, Error>,
|
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> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
@ -806,9 +806,9 @@ where
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use actix_service::{IntoService, Transform};
|
use actix_service::{IntoService, Transform};
|
||||||
|
use actix_web::test::{self, block_on, TestRequest};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::test::{self, block_on, TestRequest};
|
|
||||||
|
|
||||||
impl Cors {
|
impl Cors {
|
||||||
fn finish<F, S, B>(self, srv: F) -> CorsMiddleware<S>
|
fn finish<F, S, B>(self, srv: F) -> CorsMiddleware<S>
|
@ -1,5 +1,39 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.1.7] - 2019-11-06
|
||||||
|
|
||||||
|
* Add an additional `filename*` param in the `Content-Disposition` header of `actix_files::NamedFile` to be more compatible. (#1151)
|
||||||
|
|
||||||
|
## [0.1.6] - 2019-10-14
|
||||||
|
|
||||||
|
* Add option to redirect to a slash-ended path `Files` #1132
|
||||||
|
|
||||||
|
## [0.1.5] - 2019-10-08
|
||||||
|
|
||||||
|
* Bump up `mime_guess` crate version to 2.0.1
|
||||||
|
|
||||||
|
* Bump up `percent-encoding` crate version to 2.1
|
||||||
|
|
||||||
|
* Allow user defined request guards for `Files` #1113
|
||||||
|
|
||||||
|
## [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
|
||||||
|
|
||||||
|
## [0.1.2] - 2019-06-13
|
||||||
|
|
||||||
|
* Content-Length is 0 for NamedFile HEAD request #914
|
||||||
|
|
||||||
|
* Fix ring dependency from actix-web default features for #741
|
||||||
|
|
||||||
|
## [0.1.1] - 2019-06-01
|
||||||
|
|
||||||
|
* Static files are incorrectly served as both chunked and with length #812
|
||||||
|
|
||||||
## [0.1.0] - 2019-05-25
|
## [0.1.0] - 2019-05-25
|
||||||
|
|
||||||
* NamedFile last-modified check always fails due to nano-seconds
|
* NamedFile last-modified check always fails due to nano-seconds
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-files"
|
name = "actix-files"
|
||||||
version = "0.1.0"
|
version = "0.1.7"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Static files support for actix web."
|
description = "Static files support for actix web."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -18,17 +18,18 @@ name = "actix_files"
|
|||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = "1.0.0-rc"
|
actix-web = { version = "1.0.8", default-features = false }
|
||||||
actix-service = "0.4.0"
|
actix-http = "0.2.11"
|
||||||
|
actix-service = "0.4.1"
|
||||||
bitflags = "1"
|
bitflags = "1"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
futures = "0.1.25"
|
futures = "0.1.25"
|
||||||
derive_more = "0.14"
|
derive_more = "0.15.0"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
mime = "0.3"
|
mime = "0.3"
|
||||||
mime_guess = "2.0.0-alpha"
|
mime_guess = "2.0.1"
|
||||||
percent-encoding = "1.0"
|
percent-encoding = "2.1"
|
||||||
v_htmlescape = "0.4"
|
v_htmlescape = "0.4"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-web = { version = "1.0.0-rc", features=["ssl"] }
|
actix-web = { version = "1.0.8", features=["ssl"] }
|
||||||
|
1
actix-files/LICENSE-APACHE
Symbolic link
1
actix-files/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-APACHE
|
1
actix-files/LICENSE-MIT
Symbolic link
1
actix-files/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-MIT
|
@ -1,3 +1,5 @@
|
|||||||
|
#![allow(clippy::borrow_interior_mutable_const, clippy::type_complexity)]
|
||||||
|
|
||||||
//! Static files support
|
//! Static files support
|
||||||
use std::cell::RefCell;
|
use std::cell::RefCell;
|
||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
@ -14,14 +16,16 @@ use actix_web::dev::{
|
|||||||
ServiceResponse,
|
ServiceResponse,
|
||||||
};
|
};
|
||||||
use actix_web::error::{BlockingError, Error, ErrorInternalServerError};
|
use actix_web::error::{BlockingError, Error, ErrorInternalServerError};
|
||||||
use actix_web::http::header::DispositionType;
|
use actix_web::guard::Guard;
|
||||||
|
use actix_web::http::header::{self, DispositionType};
|
||||||
|
use actix_web::http::Method;
|
||||||
use actix_web::{web, FromRequest, HttpRequest, HttpResponse, Responder};
|
use actix_web::{web, FromRequest, HttpRequest, HttpResponse, Responder};
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use futures::future::{ok, Either, FutureResult};
|
use futures::future::{ok, Either, FutureResult};
|
||||||
use futures::{Async, Future, Poll, Stream};
|
use futures::{Async, Future, Poll, Stream};
|
||||||
use mime;
|
use mime;
|
||||||
use mime_guess::get_mime_type;
|
use mime_guess::from_ext;
|
||||||
use percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET};
|
use percent_encoding::{utf8_percent_encode, CONTROLS};
|
||||||
use v_htmlescape::escape as escape_html_entity;
|
use v_htmlescape::escape as escape_html_entity;
|
||||||
|
|
||||||
mod error;
|
mod error;
|
||||||
@ -40,7 +44,7 @@ type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error
|
|||||||
/// the type `application/octet-stream`.
|
/// the type `application/octet-stream`.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn file_extension_to_mime(ext: &str) -> mime::Mime {
|
pub fn file_extension_to_mime(ext: &str) -> mime::Mime {
|
||||||
get_mime_type(ext)
|
from_ext(ext).first_or_octet_stream()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
@ -50,14 +54,14 @@ pub struct ChunkedReadFile {
|
|||||||
size: u64,
|
size: u64,
|
||||||
offset: u64,
|
offset: u64,
|
||||||
file: Option<File>,
|
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,
|
counter: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle_error(err: BlockingError<io::Error>) -> Error {
|
fn handle_error(err: BlockingError<io::Error>) -> Error {
|
||||||
match err {
|
match err {
|
||||||
BlockingError::Error(err) => err.into(),
|
BlockingError::Error(err) => err.into(),
|
||||||
BlockingError::Canceled => ErrorInternalServerError("Unexpected error").into(),
|
BlockingError::Canceled => ErrorInternalServerError("Unexpected error"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -105,7 +109,7 @@ impl Stream for ChunkedReadFile {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type DirectoryRenderer =
|
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.
|
/// A directory; responds with the generated directory listing.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@ -142,7 +146,7 @@ impl Directory {
|
|||||||
// show file url as relative to static path
|
// show file url as relative to static path
|
||||||
macro_rules! encode_file_url {
|
macro_rules! encode_file_url {
|
||||||
($path:ident) => {
|
($path:ident) => {
|
||||||
utf8_percent_encode(&$path.to_string_lossy(), DEFAULT_ENCODE_SET)
|
utf8_percent_encode(&$path.to_string_lossy(), CONTROLS)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -209,7 +213,7 @@ fn directory_listing(
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
type MimeOverride = Fn(&mime::Name) -> DispositionType;
|
type MimeOverride = dyn Fn(&mime::Name) -> DispositionType;
|
||||||
|
|
||||||
/// Static files handling
|
/// Static files handling
|
||||||
///
|
///
|
||||||
@ -229,10 +233,12 @@ pub struct Files {
|
|||||||
directory: PathBuf,
|
directory: PathBuf,
|
||||||
index: Option<String>,
|
index: Option<String>,
|
||||||
show_index: bool,
|
show_index: bool,
|
||||||
|
redirect_to_slash: bool,
|
||||||
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
|
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
|
||||||
renderer: Rc<DirectoryRenderer>,
|
renderer: Rc<DirectoryRenderer>,
|
||||||
mime_override: Option<Rc<MimeOverride>>,
|
mime_override: Option<Rc<MimeOverride>>,
|
||||||
file_flags: named::Flags,
|
file_flags: named::Flags,
|
||||||
|
guards: Option<Rc<Box<dyn Guard>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Clone for Files {
|
impl Clone for Files {
|
||||||
@ -241,11 +247,13 @@ impl Clone for Files {
|
|||||||
directory: self.directory.clone(),
|
directory: self.directory.clone(),
|
||||||
index: self.index.clone(),
|
index: self.index.clone(),
|
||||||
show_index: self.show_index,
|
show_index: self.show_index,
|
||||||
|
redirect_to_slash: self.redirect_to_slash,
|
||||||
default: self.default.clone(),
|
default: self.default.clone(),
|
||||||
renderer: self.renderer.clone(),
|
renderer: self.renderer.clone(),
|
||||||
file_flags: self.file_flags,
|
file_flags: self.file_flags,
|
||||||
path: self.path.clone(),
|
path: self.path.clone(),
|
||||||
mime_override: self.mime_override.clone(),
|
mime_override: self.mime_override.clone(),
|
||||||
|
guards: self.guards.clone(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -259,7 +267,7 @@ impl Files {
|
|||||||
pub fn new<T: Into<PathBuf>>(path: &str, dir: T) -> Files {
|
pub fn new<T: Into<PathBuf>>(path: &str, dir: T) -> Files {
|
||||||
let dir = dir.into().canonicalize().unwrap_or_else(|_| PathBuf::new());
|
let dir = dir.into().canonicalize().unwrap_or_else(|_| PathBuf::new());
|
||||||
if !dir.is_dir() {
|
if !dir.is_dir() {
|
||||||
log::error!("Specified path is not a directory");
|
log::error!("Specified path is not a directory: {:?}", dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
Files {
|
Files {
|
||||||
@ -267,10 +275,12 @@ impl Files {
|
|||||||
directory: dir,
|
directory: dir,
|
||||||
index: None,
|
index: None,
|
||||||
show_index: false,
|
show_index: false,
|
||||||
|
redirect_to_slash: false,
|
||||||
default: Rc::new(RefCell::new(None)),
|
default: Rc::new(RefCell::new(None)),
|
||||||
renderer: Rc::new(directory_listing),
|
renderer: Rc::new(directory_listing),
|
||||||
mime_override: None,
|
mime_override: None,
|
||||||
file_flags: named::Flags::default(),
|
file_flags: named::Flags::default(),
|
||||||
|
guards: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -282,6 +292,14 @@ impl Files {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Redirects to a slash-ended path when browsing a directory.
|
||||||
|
///
|
||||||
|
/// By default never redirect.
|
||||||
|
pub fn redirect_to_slash_directory(mut self) -> Self {
|
||||||
|
self.redirect_to_slash = true;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Set custom directory renderer
|
/// Set custom directory renderer
|
||||||
pub fn files_listing_renderer<F>(mut self, f: F) -> Self
|
pub fn files_listing_renderer<F>(mut self, f: F) -> Self
|
||||||
where
|
where
|
||||||
@ -329,6 +347,24 @@ impl Files {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Specifies custom guards to use for directory listings and files.
|
||||||
|
///
|
||||||
|
/// Default behaviour allows GET and HEAD.
|
||||||
|
#[inline]
|
||||||
|
pub fn use_guards<G: Guard + 'static>(mut self, guards: G) -> Self {
|
||||||
|
self.guards = Some(Rc::new(Box::new(guards)));
|
||||||
|
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.
|
/// Sets default handler which is used when no matched file could be found.
|
||||||
pub fn default_handler<F, U>(mut self, f: F) -> Self
|
pub fn default_handler<F, U>(mut self, f: F) -> Self
|
||||||
where
|
where
|
||||||
@ -364,23 +400,25 @@ impl HttpServiceFactory for Files {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl NewService for Files {
|
impl NewService for Files {
|
||||||
type Config = ();
|
|
||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse;
|
type Response = ServiceResponse;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
type Config = ();
|
||||||
type Service = FilesService;
|
type Service = FilesService;
|
||||||
type InitError = ();
|
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 {
|
fn new_service(&self, _: &()) -> Self::Future {
|
||||||
let mut srv = FilesService {
|
let mut srv = FilesService {
|
||||||
directory: self.directory.clone(),
|
directory: self.directory.clone(),
|
||||||
index: self.index.clone(),
|
index: self.index.clone(),
|
||||||
show_index: self.show_index,
|
show_index: self.show_index,
|
||||||
|
redirect_to_slash: self.redirect_to_slash,
|
||||||
default: None,
|
default: None,
|
||||||
renderer: self.renderer.clone(),
|
renderer: self.renderer.clone(),
|
||||||
mime_override: self.mime_override.clone(),
|
mime_override: self.mime_override.clone(),
|
||||||
file_flags: self.file_flags,
|
file_flags: self.file_flags,
|
||||||
|
guards: self.guards.clone(),
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Some(ref default) = *self.default.borrow() {
|
if let Some(ref default) = *self.default.borrow() {
|
||||||
@ -403,10 +441,12 @@ pub struct FilesService {
|
|||||||
directory: PathBuf,
|
directory: PathBuf,
|
||||||
index: Option<String>,
|
index: Option<String>,
|
||||||
show_index: bool,
|
show_index: bool,
|
||||||
|
redirect_to_slash: bool,
|
||||||
default: Option<HttpService>,
|
default: Option<HttpService>,
|
||||||
renderer: Rc<DirectoryRenderer>,
|
renderer: Rc<DirectoryRenderer>,
|
||||||
mime_override: Option<Rc<MimeOverride>>,
|
mime_override: Option<Rc<MimeOverride>>,
|
||||||
file_flags: named::Flags,
|
file_flags: named::Flags,
|
||||||
|
guards: Option<Rc<Box<dyn Guard>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FilesService {
|
impl FilesService {
|
||||||
@ -416,7 +456,7 @@ impl FilesService {
|
|||||||
req: ServiceRequest,
|
req: ServiceRequest,
|
||||||
) -> Either<
|
) -> Either<
|
||||||
FutureResult<ServiceResponse, Error>,
|
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);
|
log::debug!("Files: Failed to handle {}: {}", req.path(), e);
|
||||||
if let Some(ref mut default) = self.default {
|
if let Some(ref mut default) = self.default {
|
||||||
@ -433,7 +473,7 @@ impl Service for FilesService {
|
|||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Future = Either<
|
type Future = Either<
|
||||||
FutureResult<Self::Response, Self::Error>,
|
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> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
@ -443,6 +483,25 @@ impl Service for FilesService {
|
|||||||
fn call(&mut self, req: ServiceRequest) -> Self::Future {
|
fn call(&mut self, req: ServiceRequest) -> Self::Future {
|
||||||
// let (req, pl) = req.into_parts();
|
// let (req, pl) = req.into_parts();
|
||||||
|
|
||||||
|
let is_method_valid = if let Some(guard) = &self.guards {
|
||||||
|
// execute user defined guards
|
||||||
|
(**guard).check(req.head())
|
||||||
|
} else {
|
||||||
|
// default behaviour
|
||||||
|
match *req.method() {
|
||||||
|
Method::HEAD | Method::GET => true,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if !is_method_valid {
|
||||||
|
return Either::A(ok(req.into_response(
|
||||||
|
actix_web::HttpResponse::MethodNotAllowed()
|
||||||
|
.header(header::CONTENT_TYPE, "text/plain")
|
||||||
|
.body("Request did not meet this resource's requirements."),
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
let real_path = match PathBufWrp::get_pathbuf(req.match_info().path()) {
|
let real_path = match PathBufWrp::get_pathbuf(req.match_info().path()) {
|
||||||
Ok(item) => item,
|
Ok(item) => item,
|
||||||
Err(e) => return Either::A(ok(req.error_response(e))),
|
Err(e) => return Either::A(ok(req.error_response(e))),
|
||||||
@ -456,6 +515,16 @@ impl Service for FilesService {
|
|||||||
|
|
||||||
if path.is_dir() {
|
if path.is_dir() {
|
||||||
if let Some(ref redir_index) = self.index {
|
if let Some(ref redir_index) = self.index {
|
||||||
|
if self.redirect_to_slash && !req.path().ends_with('/') {
|
||||||
|
let redirect_to = format!("{}/", req.path());
|
||||||
|
return Either::A(ok(req.into_response(
|
||||||
|
HttpResponse::Found()
|
||||||
|
.header(header::LOCATION, redirect_to)
|
||||||
|
.body("")
|
||||||
|
.into_body(),
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
let path = path.join(redir_index);
|
let path = path.join(redir_index);
|
||||||
|
|
||||||
match NamedFile::open(path) {
|
match NamedFile::open(path) {
|
||||||
@ -473,7 +542,7 @@ impl Service for FilesService {
|
|||||||
Err(e) => ServiceResponse::from_err(e, req),
|
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 {
|
} else if self.show_index {
|
||||||
let dir = Directory::new(self.directory.clone(), path);
|
let dir = Directory::new(self.directory.clone(), path);
|
||||||
@ -481,7 +550,7 @@ impl Service for FilesService {
|
|||||||
let x = (self.renderer)(&dir, &req);
|
let x = (self.renderer)(&dir, &req);
|
||||||
match x {
|
match x {
|
||||||
Ok(resp) => Either::A(ok(resp)),
|
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 {
|
} else {
|
||||||
Either::A(ok(ServiceResponse::from_err(
|
Either::A(ok(ServiceResponse::from_err(
|
||||||
@ -565,6 +634,7 @@ mod tests {
|
|||||||
use bytes::BytesMut;
|
use bytes::BytesMut;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use actix_web::guard;
|
||||||
use actix_web::http::header::{
|
use actix_web::http::header::{
|
||||||
self, ContentDisposition, DispositionParam, DispositionType,
|
self, ContentDisposition, DispositionParam, DispositionType,
|
||||||
};
|
};
|
||||||
@ -636,6 +706,58 @@ 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_non_ascii_file_name() {
|
||||||
|
let mut file =
|
||||||
|
NamedFile::from_file(File::open("Cargo.toml").unwrap(), "貨物.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_TYPE).unwrap(),
|
||||||
|
"text/x-toml"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
|
||||||
|
"inline; filename=\"貨物.toml\"; filename*=UTF-8''%E8%B2%A8%E7%89%A9.toml"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_named_file_set_content_type() {
|
fn test_named_file_set_content_type() {
|
||||||
let mut file = NamedFile::open("Cargo.toml")
|
let mut file = NamedFile::open("Cargo.toml")
|
||||||
@ -855,6 +977,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_named_file_content_length_headers() {
|
fn test_named_file_content_length_headers() {
|
||||||
|
// use actix_web::body::{MessageBody, ResponseBody};
|
||||||
|
|
||||||
let mut srv = test::init_service(
|
let mut srv = test::init_service(
|
||||||
App::new().service(Files::new("test", ".").index_file("tests/test.binary")),
|
App::new().service(Files::new("test", ".").index_file("tests/test.binary")),
|
||||||
);
|
);
|
||||||
@ -864,16 +988,15 @@ mod tests {
|
|||||||
.uri("/t%65st/tests/test.binary")
|
.uri("/t%65st/tests/test.binary")
|
||||||
.header(header::RANGE, "bytes=10-20")
|
.header(header::RANGE, "bytes=10-20")
|
||||||
.to_request();
|
.to_request();
|
||||||
let response = test::call_service(&mut srv, request);
|
let _response = test::call_service(&mut srv, request);
|
||||||
|
|
||||||
let contentlength = response
|
// let contentlength = response
|
||||||
.headers()
|
// .headers()
|
||||||
.get(header::CONTENT_LENGTH)
|
// .get(header::CONTENT_LENGTH)
|
||||||
.unwrap()
|
// .unwrap()
|
||||||
.to_str()
|
// .to_str()
|
||||||
.unwrap();
|
// .unwrap();
|
||||||
|
// assert_eq!(contentlength, "11");
|
||||||
assert_eq!(contentlength, "11");
|
|
||||||
|
|
||||||
// Invalid range header
|
// Invalid range header
|
||||||
let request = TestRequest::get()
|
let request = TestRequest::get()
|
||||||
@ -888,16 +1011,15 @@ mod tests {
|
|||||||
.uri("/t%65st/tests/test.binary")
|
.uri("/t%65st/tests/test.binary")
|
||||||
// .no_default_headers()
|
// .no_default_headers()
|
||||||
.to_request();
|
.to_request();
|
||||||
let response = test::call_service(&mut srv, request);
|
let _response = test::call_service(&mut srv, request);
|
||||||
|
|
||||||
let contentlength = response
|
// let contentlength = response
|
||||||
.headers()
|
// .headers()
|
||||||
.get(header::CONTENT_LENGTH)
|
// .get(header::CONTENT_LENGTH)
|
||||||
.unwrap()
|
// .unwrap()
|
||||||
.to_str()
|
// .to_str()
|
||||||
.unwrap();
|
// .unwrap();
|
||||||
|
// assert_eq!(contentlength, "100");
|
||||||
assert_eq!(contentlength, "100");
|
|
||||||
|
|
||||||
// chunked
|
// chunked
|
||||||
let request = TestRequest::get()
|
let request = TestRequest::get()
|
||||||
@ -926,6 +1048,29 @@ mod tests {
|
|||||||
assert_eq!(bytes.freeze(), data);
|
assert_eq!(bytes.freeze(), data);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_head_content_length_headers() {
|
||||||
|
let mut srv = test::init_service(
|
||||||
|
App::new().service(Files::new("test", ".").index_file("tests/test.binary")),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Valid range header
|
||||||
|
let request = TestRequest::default()
|
||||||
|
.method(Method::HEAD)
|
||||||
|
.uri("/t%65st/tests/test.binary")
|
||||||
|
.to_request();
|
||||||
|
let _response = test::call_service(&mut srv, request);
|
||||||
|
|
||||||
|
// TODO: fix check
|
||||||
|
// let contentlength = response
|
||||||
|
// .headers()
|
||||||
|
// .get(header::CONTENT_LENGTH)
|
||||||
|
// .unwrap()
|
||||||
|
// .to_str()
|
||||||
|
// .unwrap();
|
||||||
|
// assert_eq!(contentlength, "100");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_static_files_with_spaces() {
|
fn test_static_files_with_spaces() {
|
||||||
let mut srv = test::init_service(
|
let mut srv = test::init_service(
|
||||||
@ -949,20 +1094,41 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_named_file_not_allowed() {
|
fn test_files_not_allowed() {
|
||||||
let file = NamedFile::open("Cargo.toml").unwrap();
|
let mut srv = test::init_service(App::new().service(Files::new("/", ".")));
|
||||||
|
|
||||||
let req = TestRequest::default()
|
let req = TestRequest::default()
|
||||||
|
.uri("/Cargo.toml")
|
||||||
.method(Method::POST)
|
.method(Method::POST)
|
||||||
.to_http_request();
|
.to_request();
|
||||||
let resp = file.respond_to(&req).unwrap();
|
|
||||||
|
let resp = test::call_service(&mut srv, req);
|
||||||
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
|
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
|
||||||
|
|
||||||
let file = NamedFile::open("Cargo.toml").unwrap();
|
let mut srv = test::init_service(App::new().service(Files::new("/", ".")));
|
||||||
let req = TestRequest::default().method(Method::PUT).to_http_request();
|
let req = TestRequest::default()
|
||||||
let resp = file.respond_to(&req).unwrap();
|
.method(Method::PUT)
|
||||||
|
.uri("/Cargo.toml")
|
||||||
|
.to_request();
|
||||||
|
let resp = test::call_service(&mut srv, req);
|
||||||
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
|
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_files_guards() {
|
||||||
|
let mut srv = test::init_service(
|
||||||
|
App::new().service(Files::new("/", ".").use_guards(guard::Post())),
|
||||||
|
);
|
||||||
|
|
||||||
|
let req = TestRequest::default()
|
||||||
|
.uri("/Cargo.toml")
|
||||||
|
.method(Method::POST)
|
||||||
|
.to_request();
|
||||||
|
|
||||||
|
let resp = test::call_service(&mut srv, req);
|
||||||
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_named_file_content_encoding() {
|
fn test_named_file_content_encoding() {
|
||||||
let mut srv = test::init_service(App::new().wrap(Compress::default()).service(
|
let mut srv = test::init_service(App::new().wrap(Compress::default()).service(
|
||||||
@ -1051,6 +1217,34 @@ mod tests {
|
|||||||
assert!(format!("{:?}", bytes).contains("/tests/test.png"));
|
assert!(format!("{:?}", bytes).contains("/tests/test.png"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_redirect_to_slash_directory() {
|
||||||
|
// should not redirect if no index
|
||||||
|
let mut srv = test::init_service(
|
||||||
|
App::new().service(Files::new("/", ".").redirect_to_slash_directory()),
|
||||||
|
);
|
||||||
|
let req = TestRequest::with_uri("/tests").to_request();
|
||||||
|
let resp = test::call_service(&mut srv, req);
|
||||||
|
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
|
||||||
|
|
||||||
|
// should redirect if index present
|
||||||
|
let mut srv = test::init_service(
|
||||||
|
App::new().service(
|
||||||
|
Files::new("/", ".")
|
||||||
|
.index_file("test.png")
|
||||||
|
.redirect_to_slash_directory(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
let req = TestRequest::with_uri("/tests").to_request();
|
||||||
|
let resp = test::call_service(&mut srv, req);
|
||||||
|
assert_eq!(resp.status(), StatusCode::FOUND);
|
||||||
|
|
||||||
|
// should not redirect if the path is wrong
|
||||||
|
let req = TestRequest::with_uri("/not_existing").to_request();
|
||||||
|
let resp = test::call_service(&mut srv, req);
|
||||||
|
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_static_files_bad_directory() {
|
fn test_static_files_bad_directory() {
|
||||||
let _st: Files = Files::new("/", "missing");
|
let _st: Files = Files::new("/", "missing");
|
||||||
|
@ -9,12 +9,13 @@ use std::os::unix::fs::MetadataExt;
|
|||||||
|
|
||||||
use bitflags::bitflags;
|
use bitflags::bitflags;
|
||||||
use mime;
|
use mime;
|
||||||
use mime_guess::guess_mime_type;
|
use mime_guess::from_path;
|
||||||
|
|
||||||
|
use actix_http::body::SizedStream;
|
||||||
use actix_web::http::header::{
|
use actix_web::http::header::{
|
||||||
self, ContentDisposition, DispositionParam, DispositionType,
|
self, Charset, ContentDisposition, DispositionParam, DispositionType, ExtendedValue,
|
||||||
};
|
};
|
||||||
use actix_web::http::{ContentEncoding, Method, StatusCode};
|
use actix_web::http::{ContentEncoding, StatusCode};
|
||||||
use actix_web::middleware::BodyEncoding;
|
use actix_web::middleware::BodyEncoding;
|
||||||
use actix_web::{Error, HttpMessage, HttpRequest, HttpResponse, Responder};
|
use actix_web::{Error, HttpMessage, HttpRequest, HttpResponse, Responder};
|
||||||
|
|
||||||
@ -22,9 +23,10 @@ use crate::range::HttpRange;
|
|||||||
use crate::ChunkedReadFile;
|
use crate::ChunkedReadFile;
|
||||||
|
|
||||||
bitflags! {
|
bitflags! {
|
||||||
pub(crate) struct Flags: u32 {
|
pub(crate) struct Flags: u8 {
|
||||||
const ETAG = 0b00000001;
|
const ETAG = 0b0000_0001;
|
||||||
const LAST_MD = 0b00000010;
|
const LAST_MD = 0b0000_0010;
|
||||||
|
const CONTENT_DISPOSITION = 0b0000_0100;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -39,13 +41,13 @@ impl Default for Flags {
|
|||||||
pub struct NamedFile {
|
pub struct NamedFile {
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
file: File,
|
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_type: mime::Mime,
|
||||||
pub(crate) content_disposition: header::ContentDisposition,
|
pub(crate) content_disposition: header::ContentDisposition,
|
||||||
pub(crate) md: Metadata,
|
|
||||||
modified: Option<SystemTime>,
|
|
||||||
pub(crate) encoding: Option<ContentEncoding>,
|
pub(crate) encoding: Option<ContentEncoding>,
|
||||||
pub(crate) status_code: StatusCode,
|
|
||||||
pub(crate) flags: Flags,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NamedFile {
|
impl NamedFile {
|
||||||
@ -86,14 +88,23 @@ impl NamedFile {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let ct = guess_mime_type(&path);
|
let ct = from_path(&path).first_or_octet_stream();
|
||||||
let disposition_type = match ct.type_() {
|
let disposition_type = match ct.type_() {
|
||||||
mime::IMAGE | mime::TEXT | mime::VIDEO => DispositionType::Inline,
|
mime::IMAGE | mime::TEXT | mime::VIDEO => DispositionType::Inline,
|
||||||
_ => DispositionType::Attachment,
|
_ => DispositionType::Attachment,
|
||||||
};
|
};
|
||||||
|
let mut parameters =
|
||||||
|
vec![DispositionParam::Filename(String::from(filename.as_ref()))];
|
||||||
|
if !filename.is_ascii() {
|
||||||
|
parameters.push(DispositionParam::FilenameExt(ExtendedValue {
|
||||||
|
charset: Charset::Ext(String::from("UTF-8")),
|
||||||
|
language_tag: None,
|
||||||
|
value: filename.into_owned().into_bytes(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
let cd = ContentDisposition {
|
let cd = ContentDisposition {
|
||||||
disposition: disposition_type,
|
disposition: disposition_type,
|
||||||
parameters: vec![DispositionParam::Filename(filename.into_owned())],
|
parameters: parameters,
|
||||||
};
|
};
|
||||||
(ct, cd)
|
(ct, cd)
|
||||||
};
|
};
|
||||||
@ -171,11 +182,21 @@ impl NamedFile {
|
|||||||
/// sent to the peer. By default the disposition is `inline` for text,
|
/// sent to the peer. By default the disposition is `inline` for text,
|
||||||
/// image, and video content types, and `attachment` otherwise, and
|
/// image, and video content types, and `attachment` otherwise, and
|
||||||
/// the filename is taken from the path provided in the `open` method
|
/// 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).
|
/// [to_string_lossy](https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.to_string_lossy).
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn set_content_disposition(mut self, cd: header::ContentDisposition) -> Self {
|
pub fn set_content_disposition(mut self, cd: header::ContentDisposition) -> Self {
|
||||||
self.content_disposition = cd;
|
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
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -293,10 +314,12 @@ impl Responder for NamedFile {
|
|||||||
if self.status_code != StatusCode::OK {
|
if self.status_code != StatusCode::OK {
|
||||||
let mut resp = HttpResponse::build(self.status_code);
|
let mut resp = HttpResponse::build(self.status_code);
|
||||||
resp.set(header::ContentType(self.content_type.clone()))
|
resp.set(header::ContentType(self.content_type.clone()))
|
||||||
.header(
|
.if_true(self.flags.contains(Flags::CONTENT_DISPOSITION), |res| {
|
||||||
|
res.header(
|
||||||
header::CONTENT_DISPOSITION,
|
header::CONTENT_DISPOSITION,
|
||||||
self.content_disposition.to_string(),
|
self.content_disposition.to_string(),
|
||||||
);
|
);
|
||||||
|
});
|
||||||
if let Some(current_encoding) = self.encoding {
|
if let Some(current_encoding) = self.encoding {
|
||||||
resp.encoding(current_encoding);
|
resp.encoding(current_encoding);
|
||||||
}
|
}
|
||||||
@ -310,16 +333,6 @@ impl Responder for NamedFile {
|
|||||||
return Ok(resp.streaming(reader));
|
return Ok(resp.streaming(reader));
|
||||||
}
|
}
|
||||||
|
|
||||||
match req.method() {
|
|
||||||
&Method::HEAD | &Method::GET => (),
|
|
||||||
_ => {
|
|
||||||
return Ok(HttpResponse::MethodNotAllowed()
|
|
||||||
.header(header::CONTENT_TYPE, "text/plain")
|
|
||||||
.header(header::ALLOW, "GET, HEAD")
|
|
||||||
.body("This resource only supports GET and HEAD."));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let etag = if self.flags.contains(Flags::ETAG) {
|
let etag = if self.flags.contains(Flags::ETAG) {
|
||||||
self.etag()
|
self.etag()
|
||||||
} else {
|
} else {
|
||||||
@ -367,10 +380,12 @@ impl Responder for NamedFile {
|
|||||||
|
|
||||||
let mut resp = HttpResponse::build(self.status_code);
|
let mut resp = HttpResponse::build(self.status_code);
|
||||||
resp.set(header::ContentType(self.content_type.clone()))
|
resp.set(header::ContentType(self.content_type.clone()))
|
||||||
.header(
|
.if_true(self.flags.contains(Flags::CONTENT_DISPOSITION), |res| {
|
||||||
|
res.header(
|
||||||
header::CONTENT_DISPOSITION,
|
header::CONTENT_DISPOSITION,
|
||||||
self.content_disposition.to_string(),
|
self.content_disposition.to_string(),
|
||||||
);
|
);
|
||||||
|
});
|
||||||
// default compressing
|
// default compressing
|
||||||
if let Some(current_encoding) = self.encoding {
|
if let Some(current_encoding) = self.encoding {
|
||||||
resp.encoding(current_encoding);
|
resp.encoding(current_encoding);
|
||||||
@ -413,17 +428,12 @@ impl Responder for NamedFile {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
resp.header(header::CONTENT_LENGTH, format!("{}", length));
|
|
||||||
|
|
||||||
if precondition_failed {
|
if precondition_failed {
|
||||||
return Ok(resp.status(StatusCode::PRECONDITION_FAILED).finish());
|
return Ok(resp.status(StatusCode::PRECONDITION_FAILED).finish());
|
||||||
} else if not_modified {
|
} else if not_modified {
|
||||||
return Ok(resp.status(StatusCode::NOT_MODIFIED).finish());
|
return Ok(resp.status(StatusCode::NOT_MODIFIED).finish());
|
||||||
}
|
}
|
||||||
|
|
||||||
if *req.method() == Method::HEAD {
|
|
||||||
Ok(resp.finish())
|
|
||||||
} else {
|
|
||||||
let reader = ChunkedReadFile {
|
let reader = ChunkedReadFile {
|
||||||
offset,
|
offset,
|
||||||
size: length,
|
size: length,
|
||||||
@ -434,7 +444,6 @@ impl Responder for NamedFile {
|
|||||||
if offset != 0 || length != self.md.len() {
|
if offset != 0 || length != self.md.len() {
|
||||||
return Ok(resp.status(StatusCode::PARTIAL_CONTENT).streaming(reader));
|
return Ok(resp.status(StatusCode::PARTIAL_CONTENT).streaming(reader));
|
||||||
};
|
};
|
||||||
Ok(resp.streaming(reader))
|
Ok(resp.body(SizedStream::new(length, reader)))
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,7 +5,7 @@ pub struct HttpRange {
|
|||||||
pub length: u64,
|
pub length: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
static PREFIX: &'static str = "bytes=";
|
static PREFIX: &str = "bytes=";
|
||||||
const PREFIX_LEN: usize = 6;
|
const PREFIX_LEN: usize = 6;
|
||||||
|
|
||||||
impl HttpRange {
|
impl HttpRange {
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-framed"
|
name = "actix-framed"
|
||||||
version = "0.2.0"
|
version = "0.2.1"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix framed app server"
|
description = "Actix framed app server"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -21,18 +21,18 @@ path = "src/lib.rs"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-codec = "0.1.2"
|
actix-codec = "0.1.2"
|
||||||
actix-service = "0.4.0"
|
actix-service = "0.4.1"
|
||||||
actix-utils = "0.4.0"
|
|
||||||
actix-router = "0.1.2"
|
actix-router = "0.1.2"
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.2"
|
||||||
actix-http = "0.2.0"
|
actix-http = "0.2.7"
|
||||||
actix-server-config = "0.1.1"
|
actix-server-config = "0.1.2"
|
||||||
|
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
futures = "0.1.25"
|
futures = "0.1.25"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
|
|
||||||
[dev-dependencies]
|
[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-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
|
# Changes
|
||||||
|
|
||||||
|
## [0.2.1] - 2019-07-20
|
||||||
|
|
||||||
|
* Remove unneeded actix-utils dependency
|
||||||
|
|
||||||
|
|
||||||
## [0.2.0] - 2019-05-12
|
## [0.2.0] - 2019-05-12
|
||||||
|
|
||||||
* Update dependencies
|
* Update dependencies
|
||||||
|
@ -6,14 +6,13 @@ use actix_http::{Error, Request, Response};
|
|||||||
use actix_router::{Path, Router, Url};
|
use actix_router::{Path, Router, Url};
|
||||||
use actix_server_config::ServerConfig;
|
use actix_server_config::ServerConfig;
|
||||||
use actix_service::{IntoNewService, NewService, Service};
|
use actix_service::{IntoNewService, NewService, Service};
|
||||||
use actix_utils::cloneable::CloneableService;
|
|
||||||
use futures::{Async, Future, Poll};
|
use futures::{Async, Future, Poll};
|
||||||
|
|
||||||
use crate::helpers::{BoxedHttpNewService, BoxedHttpService, HttpNewService};
|
use crate::helpers::{BoxedHttpNewService, BoxedHttpService, HttpNewService};
|
||||||
use crate::request::FramedRequest;
|
use crate::request::FramedRequest;
|
||||||
use crate::state::State;
|
use crate::state::State;
|
||||||
|
|
||||||
type BoxedResponse = Box<Future<Item = (), Error = Error>>;
|
type BoxedResponse = Box<dyn Future<Item = (), Error = Error>>;
|
||||||
|
|
||||||
pub trait HttpServiceFactory {
|
pub trait HttpServiceFactory {
|
||||||
type Factory: NewService;
|
type Factory: NewService;
|
||||||
@ -61,7 +60,7 @@ impl<T: 'static, S: 'static> FramedApp<T, S> {
|
|||||||
Request = FramedRequest<T, S>,
|
Request = FramedRequest<T, S>,
|
||||||
Response = (),
|
Response = (),
|
||||||
Error = Error,
|
Error = Error,
|
||||||
Future = Box<Future<Item = (), Error = Error>>,
|
Future = Box<dyn Future<Item = (), Error = Error>>,
|
||||||
>,
|
>,
|
||||||
{
|
{
|
||||||
let path = factory.path().to_string();
|
let path = factory.path().to_string();
|
||||||
@ -100,7 +99,7 @@ where
|
|||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Service = CloneableService<FramedAppService<T, S>>;
|
type Service = FramedAppService<T, S>;
|
||||||
type Future = CreateService<T, S>;
|
type Future = CreateService<T, S>;
|
||||||
|
|
||||||
fn new_service(&self, _: &ServerConfig) -> Self::Future {
|
fn new_service(&self, _: &ServerConfig) -> Self::Future {
|
||||||
@ -129,7 +128,7 @@ pub struct CreateService<T, S> {
|
|||||||
enum CreateServiceItem<T, S> {
|
enum CreateServiceItem<T, S> {
|
||||||
Future(
|
Future(
|
||||||
Option<String>,
|
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>>),
|
Service(String, BoxedHttpService<FramedRequest<T, S>>),
|
||||||
}
|
}
|
||||||
@ -138,7 +137,7 @@ impl<S: 'static, T: 'static> Future for CreateService<T, S>
|
|||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
{
|
{
|
||||||
type Item = CloneableService<FramedAppService<T, S>>;
|
type Item = FramedAppService<T, S>;
|
||||||
type Error = ();
|
type Error = ();
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
@ -177,10 +176,10 @@ where
|
|||||||
}
|
}
|
||||||
router
|
router
|
||||||
});
|
});
|
||||||
Ok(Async::Ready(CloneableService::new(FramedAppService {
|
Ok(Async::Ready(FramedAppService {
|
||||||
router: router.finish(),
|
router: router.finish(),
|
||||||
state: self.state.clone(),
|
state: self.state.clone(),
|
||||||
})))
|
}))
|
||||||
} else {
|
} else {
|
||||||
Ok(Async::NotReady)
|
Ok(Async::NotReady)
|
||||||
}
|
}
|
||||||
|
@ -3,23 +3,23 @@ use actix_service::{NewService, Service};
|
|||||||
use futures::{Future, Poll};
|
use futures::{Future, Poll};
|
||||||
|
|
||||||
pub(crate) type BoxedHttpService<Req> = Box<
|
pub(crate) type BoxedHttpService<Req> = Box<
|
||||||
Service<
|
dyn Service<
|
||||||
Request = Req,
|
Request = Req,
|
||||||
Response = (),
|
Response = (),
|
||||||
Error = Error,
|
Error = Error,
|
||||||
Future = Box<Future<Item = (), Error = Error>>,
|
Future = Box<dyn Future<Item = (), Error = Error>>,
|
||||||
>,
|
>,
|
||||||
>;
|
>;
|
||||||
|
|
||||||
pub(crate) type BoxedHttpNewService<Req> = Box<
|
pub(crate) type BoxedHttpNewService<Req> = Box<
|
||||||
NewService<
|
dyn NewService<
|
||||||
Config = (),
|
Config = (),
|
||||||
Request = Req,
|
Request = Req,
|
||||||
Response = (),
|
Response = (),
|
||||||
Error = Error,
|
Error = Error,
|
||||||
InitError = (),
|
InitError = (),
|
||||||
Service = BoxedHttpService<Req>,
|
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: NewService<Response = (), Error = Error>,
|
||||||
T::Response: 'static,
|
T::Response: 'static,
|
||||||
T::Future: '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,
|
<T::Service as Service>::Future: 'static,
|
||||||
{
|
{
|
||||||
pub fn new(service: T) -> Self {
|
pub fn new(service: T) -> Self {
|
||||||
@ -43,7 +43,7 @@ where
|
|||||||
T: NewService<Config = (), Response = (), Error = Error>,
|
T: NewService<Config = (), Response = (), Error = Error>,
|
||||||
T::Request: 'static,
|
T::Request: 'static,
|
||||||
T::Future: '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,
|
<T::Service as Service>::Future: 'static,
|
||||||
{
|
{
|
||||||
type Config = ();
|
type Config = ();
|
||||||
@ -52,7 +52,7 @@ where
|
|||||||
type Error = Error;
|
type Error = Error;
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Service = BoxedHttpService<T::Request>;
|
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 {
|
fn new_service(&self, _: &()) -> Self::Future {
|
||||||
Box::new(self.0.new_service(&()).map_err(|_| ()).and_then(|service| {
|
Box::new(self.0.new_service(&()).map_err(|_| ()).and_then(|service| {
|
||||||
@ -70,7 +70,7 @@ impl<T> Service for HttpServiceWrapper<T>
|
|||||||
where
|
where
|
||||||
T: Service<
|
T: Service<
|
||||||
Response = (),
|
Response = (),
|
||||||
Future = Box<Future<Item = (), Error = Error>>,
|
Future = Box<dyn Future<Item = (), Error = Error>>,
|
||||||
Error = Error,
|
Error = Error,
|
||||||
>,
|
>,
|
||||||
T::Request: 'static,
|
T::Request: 'static,
|
||||||
@ -78,7 +78,7 @@ where
|
|||||||
type Request = T::Request;
|
type Request = T::Request;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = Error;
|
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> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
self.service.poll_ready()
|
self.service.poll_ready()
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
#![allow(clippy::type_complexity, clippy::new_without_default, dead_code)]
|
||||||
mod app;
|
mod app;
|
||||||
mod helpers;
|
mod helpers;
|
||||||
mod request;
|
mod request;
|
||||||
|
@ -140,7 +140,7 @@ where
|
|||||||
type Request = FramedRequest<Io, S>;
|
type Request = FramedRequest<Io, S>;
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = Error;
|
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> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
Ok(Async::Ready(()))
|
Ok(Async::Ready(()))
|
||||||
|
@ -1,5 +1,112 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.2.11] - 2019-11-06
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Add support for serde_json::Value to be passed as argument to ResponseBuilder.body()
|
||||||
|
|
||||||
|
* Add an additional `filename*` param in the `Content-Disposition` header of `actix_files::NamedFile` to be more compatible. (#1151)
|
||||||
|
|
||||||
|
* Allow to use `std::convert::Infallible` as `actix_http::error::Error`
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* To be compatible with non-English error responses, `ResponseError` rendered with `text/plain; charset=utf-8` header #1118
|
||||||
|
|
||||||
|
|
||||||
|
## [0.2.10] - 2019-09-11
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Add support for sending HTTP requests with `Rc<RequestHead>` in addition to sending HTTP requests with `RequestHead`
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* h2 will use error response #1080
|
||||||
|
|
||||||
|
* 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
|
||||||
|
|
||||||
|
* Add `on-connect` callback, `HttpServiceBuilder::on_connect()` #946
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Use `encoding_rs` crate instead of unmaintained `encoding` crate
|
||||||
|
|
||||||
|
* Add `Copy` and `Clone` impls for `ws::Codec`
|
||||||
|
|
||||||
|
|
||||||
|
## [0.2.4] - 2019-06-16
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Do not compress NoContent (204) responses #918
|
||||||
|
|
||||||
|
|
||||||
|
## [0.2.3] - 2019-06-02
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Debug impl for ResponseBuilder
|
||||||
|
|
||||||
|
* From SizedStream and BodyStream for Body
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* SizedStream uses u64
|
||||||
|
|
||||||
|
|
||||||
## [0.2.2] - 2019-05-29
|
## [0.2.2] - 2019-05-29
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
@ -63,7 +170,7 @@
|
|||||||
|
|
||||||
## [0.1.1] - 2019-04-19
|
## [0.1.1] - 2019-04-19
|
||||||
|
|
||||||
### Changes
|
### Changed
|
||||||
|
|
||||||
* Cookie::max_age() accepts value in seconds
|
* Cookie::max_age() accepts value in seconds
|
||||||
|
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-http"
|
name = "actix-http"
|
||||||
version = "0.2.2"
|
version = "0.2.11"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix http primitives"
|
description = "Actix http primitives"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -28,6 +28,9 @@ default = []
|
|||||||
# openssl
|
# openssl
|
||||||
ssl = ["openssl", "actix-connect/ssl"]
|
ssl = ["openssl", "actix-connect/ssl"]
|
||||||
|
|
||||||
|
# rustls support
|
||||||
|
rust-tls = ["rustls", "webpki-roots", "actix-connect/rust-tls"]
|
||||||
|
|
||||||
# brotli encoding, requires c compiler
|
# brotli encoding, requires c compiler
|
||||||
brotli = ["brotli2"]
|
brotli = ["brotli2"]
|
||||||
|
|
||||||
@ -44,44 +47,43 @@ fail = ["failure"]
|
|||||||
secure-cookies = ["ring"]
|
secure-cookies = ["ring"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "0.4.0"
|
actix-service = "0.4.1"
|
||||||
actix-codec = "0.1.2"
|
actix-codec = "0.1.2"
|
||||||
actix-connect = "0.2.0"
|
actix-connect = "0.2.4"
|
||||||
actix-utils = "0.4.1"
|
actix-utils = "0.4.4"
|
||||||
actix-server-config = "0.1.1"
|
actix-server-config = "0.1.2"
|
||||||
actix-threadpool = "0.1.0"
|
actix-threadpool = "0.1.1"
|
||||||
|
|
||||||
base64 = "0.10"
|
base64 = "0.10"
|
||||||
bitflags = "1.0"
|
bitflags = "1.0"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
byteorder = "1.2"
|
copyless = "0.1.4"
|
||||||
copyless = "0.1.2"
|
derive_more = "0.15.0"
|
||||||
derive_more = "0.14"
|
|
||||||
either = "1.5.2"
|
either = "1.5.2"
|
||||||
encoding = "0.2"
|
encoding_rs = "0.8"
|
||||||
futures = "0.1.25"
|
futures = "0.1.25"
|
||||||
hashbrown = "0.3.0"
|
hashbrown = "0.6.3"
|
||||||
h2 = "0.1.16"
|
h2 = "0.1.16"
|
||||||
http = "0.1.17"
|
http = "0.1.17"
|
||||||
httparse = "1.3"
|
httparse = "1.3"
|
||||||
indexmap = "1.0"
|
indexmap = "1.2"
|
||||||
lazy_static = "1.0"
|
lazy_static = "1.0"
|
||||||
language-tags = "0.2"
|
language-tags = "0.2"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
mime = "0.3"
|
mime = "0.3"
|
||||||
percent-encoding = "1.0"
|
percent-encoding = "2.1"
|
||||||
rand = "0.6"
|
rand = "0.7"
|
||||||
regex = "1.0"
|
regex = "1.0"
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
sha1 = "0.6"
|
sha1 = "0.6"
|
||||||
slab = "0.4"
|
slab = "0.4"
|
||||||
serde_urlencoded = "0.5.5"
|
serde_urlencoded = "0.6.1"
|
||||||
time = "0.1.42"
|
time = "0.1.42"
|
||||||
tokio-tcp = "0.1.3"
|
tokio-tcp = "0.1.3"
|
||||||
tokio-timer = "0.2.8"
|
tokio-timer = "0.2.8"
|
||||||
tokio-current-thread = "0.1"
|
tokio-current-thread = "0.1"
|
||||||
trust-dns-resolver = { version="0.11.0", default-features = false }
|
trust-dns-resolver = { version="0.11.1", default-features = false }
|
||||||
|
|
||||||
# for secure cookie
|
# for secure cookie
|
||||||
ring = { version = "0.14.6", optional = true }
|
ring = { version = "0.14.6", optional = true }
|
||||||
@ -93,13 +95,15 @@ flate2 = { version="1.0.7", optional = true, default-features = false }
|
|||||||
# optional deps
|
# optional deps
|
||||||
failure = { version = "0.1.5", optional = true }
|
failure = { version = "0.1.5", optional = true }
|
||||||
openssl = { version="0.10", 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"
|
chrono = "0.4.6"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "0.2.2"
|
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-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"
|
env_logger = "0.6"
|
||||||
serde_derive = "1.0"
|
serde_derive = "1.0"
|
||||||
openssl = { version="0.10" }
|
openssl = { version="0.10" }
|
||||||
|
@ -234,6 +234,31 @@ impl From<BytesMut> for Body {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<serde_json::Value> for Body {
|
||||||
|
fn from(v: serde_json::Value) -> Body {
|
||||||
|
Body::Bytes(v.to_string().into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S> From<SizedStream<S>> for Body
|
||||||
|
where
|
||||||
|
S: Stream<Item = Bytes, Error = Error> + 'static,
|
||||||
|
{
|
||||||
|
fn from(s: SizedStream<S>) -> Body {
|
||||||
|
Body::from_message(s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S, E> From<BodyStream<S, E>> for Body
|
||||||
|
where
|
||||||
|
S: Stream<Item = Bytes, Error = E> + 'static,
|
||||||
|
E: Into<Error> + 'static,
|
||||||
|
{
|
||||||
|
fn from(s: BodyStream<S, E>) -> Body {
|
||||||
|
Body::from_message(s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl MessageBody for Bytes {
|
impl MessageBody for Bytes {
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Sized(self.len())
|
BodySize::Sized(self.len())
|
||||||
@ -366,7 +391,7 @@ where
|
|||||||
/// Type represent streaming body. This body implementation should be used
|
/// Type represent streaming body. This body implementation should be used
|
||||||
/// if total size of stream is known. Data get sent as is without using transfer encoding.
|
/// if total size of stream is known. Data get sent as is without using transfer encoding.
|
||||||
pub struct SizedStream<S> {
|
pub struct SizedStream<S> {
|
||||||
size: usize,
|
size: u64,
|
||||||
stream: S,
|
stream: S,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -374,7 +399,7 @@ impl<S> SizedStream<S>
|
|||||||
where
|
where
|
||||||
S: Stream<Item = Bytes, Error = Error>,
|
S: Stream<Item = Bytes, Error = Error>,
|
||||||
{
|
{
|
||||||
pub fn new(size: usize, stream: S) -> Self {
|
pub fn new(size: u64, stream: S) -> Self {
|
||||||
SizedStream { size, stream }
|
SizedStream { size, stream }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -384,7 +409,7 @@ where
|
|||||||
S: Stream<Item = Bytes, Error = Error>,
|
S: Stream<Item = Bytes, Error = Error>,
|
||||||
{
|
{
|
||||||
fn size(&self) -> BodySize {
|
fn size(&self) -> BodySize {
|
||||||
BodySize::Sized(self.size)
|
BodySize::Sized64(self.size)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_next(&mut self) -> Poll<Option<Bytes>, Error> {
|
fn poll_next(&mut self) -> Poll<Option<Bytes>, Error> {
|
||||||
@ -529,4 +554,17 @@ mod tests {
|
|||||||
assert!(format!("{:?}", Body::Empty).contains("Body::Empty"));
|
assert!(format!("{:?}", Body::Empty).contains("Body::Empty"));
|
||||||
assert!(format!("{:?}", Body::Bytes(Bytes::from_static(b"1"))).contains("1"));
|
assert!(format!("{:?}", Body::Bytes(Bytes::from_static(b"1"))).contains("1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_serde_json() {
|
||||||
|
use serde_json::json;
|
||||||
|
assert_eq!(
|
||||||
|
Body::from(serde_json::Value::String("test".into())).size(),
|
||||||
|
BodySize::Sized(6)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Body::from(json!({"test-key":"test-value"})).size(),
|
||||||
|
BodySize::Sized(25)
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_codec::Framed;
|
use actix_codec::Framed;
|
||||||
use actix_server_config::ServerConfig as SrvConfig;
|
use actix_server_config::ServerConfig as SrvConfig;
|
||||||
@ -10,6 +11,7 @@ use crate::config::{KeepAlive, ServiceConfig};
|
|||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
use crate::h1::{Codec, ExpectHandler, H1Service, UpgradeHandler};
|
use crate::h1::{Codec, ExpectHandler, H1Service, UpgradeHandler};
|
||||||
use crate::h2::H2Service;
|
use crate::h2::H2Service;
|
||||||
|
use crate::helpers::{Data, DataFactory};
|
||||||
use crate::request::Request;
|
use crate::request::Request;
|
||||||
use crate::response::Response;
|
use crate::response::Response;
|
||||||
use crate::service::HttpService;
|
use crate::service::HttpService;
|
||||||
@ -24,6 +26,7 @@ pub struct HttpServiceBuilder<T, S, X = ExpectHandler, U = UpgradeHandler<T>> {
|
|||||||
client_disconnect: u64,
|
client_disconnect: u64,
|
||||||
expect: X,
|
expect: X,
|
||||||
upgrade: Option<U>,
|
upgrade: Option<U>,
|
||||||
|
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
_t: PhantomData<(T, S)>,
|
_t: PhantomData<(T, S)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -41,6 +44,7 @@ where
|
|||||||
client_disconnect: 0,
|
client_disconnect: 0,
|
||||||
expect: ExpectHandler,
|
expect: ExpectHandler,
|
||||||
upgrade: None,
|
upgrade: None,
|
||||||
|
on_connect: None,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -115,6 +119,7 @@ where
|
|||||||
client_disconnect: self.client_disconnect,
|
client_disconnect: self.client_disconnect,
|
||||||
expect: expect.into_new_service(),
|
expect: expect.into_new_service(),
|
||||||
upgrade: self.upgrade,
|
upgrade: self.upgrade,
|
||||||
|
on_connect: self.on_connect,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -140,10 +145,24 @@ where
|
|||||||
client_disconnect: self.client_disconnect,
|
client_disconnect: self.client_disconnect,
|
||||||
expect: self.expect,
|
expect: self.expect,
|
||||||
upgrade: Some(upgrade.into_new_service()),
|
upgrade: Some(upgrade.into_new_service()),
|
||||||
|
on_connect: self.on_connect,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set on-connect callback.
|
||||||
|
///
|
||||||
|
/// It get called once per connection and result of the call
|
||||||
|
/// get stored to the request's extensions.
|
||||||
|
pub fn on_connect<F, I>(mut self, f: F) -> Self
|
||||||
|
where
|
||||||
|
F: Fn(&T) -> I + 'static,
|
||||||
|
I: Clone + 'static,
|
||||||
|
{
|
||||||
|
self.on_connect = Some(Rc::new(move |io| Box::new(Data(f(io)))));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Finish service configuration and create *http service* for HTTP/1 protocol.
|
/// Finish service configuration and create *http service* for HTTP/1 protocol.
|
||||||
pub fn h1<F, P, B>(self, service: F) -> H1Service<T, P, S, B, X, U>
|
pub fn h1<F, P, B>(self, service: F) -> H1Service<T, P, S, B, X, U>
|
||||||
where
|
where
|
||||||
@ -161,6 +180,7 @@ where
|
|||||||
H1Service::with_config(cfg, service.into_new_service())
|
H1Service::with_config(cfg, service.into_new_service())
|
||||||
.expect(self.expect)
|
.expect(self.expect)
|
||||||
.upgrade(self.upgrade)
|
.upgrade(self.upgrade)
|
||||||
|
.on_connect(self.on_connect)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Finish service configuration and create *http service* for HTTP/2 protocol.
|
/// Finish service configuration and create *http service* for HTTP/2 protocol.
|
||||||
@ -179,6 +199,7 @@ where
|
|||||||
self.client_disconnect,
|
self.client_disconnect,
|
||||||
);
|
);
|
||||||
H2Service::with_config(cfg, service.into_new_service())
|
H2Service::with_config(cfg, service.into_new_service())
|
||||||
|
.on_connect(self.on_connect)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Finish service configuration and create `HttpService` instance.
|
/// Finish service configuration and create `HttpService` instance.
|
||||||
@ -199,5 +220,6 @@ where
|
|||||||
HttpService::with_config(cfg, service.into_new_service())
|
HttpService::with_config(cfg, service.into_new_service())
|
||||||
.expect(self.expect)
|
.expect(self.expect)
|
||||||
.upgrade(self.upgrade)
|
.upgrade(self.upgrade)
|
||||||
|
.on_connect(self.on_connect)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,7 +8,7 @@ use h2::client::SendRequest;
|
|||||||
|
|
||||||
use crate::body::MessageBody;
|
use crate::body::MessageBody;
|
||||||
use crate::h1::ClientCodec;
|
use crate::h1::ClientCodec;
|
||||||
use crate::message::{RequestHead, ResponseHead};
|
use crate::message::{RequestHeadType, ResponseHead};
|
||||||
use crate::payload::Payload;
|
use crate::payload::Payload;
|
||||||
|
|
||||||
use super::error::SendRequestError;
|
use super::error::SendRequestError;
|
||||||
@ -27,9 +27,9 @@ pub trait Connection {
|
|||||||
fn protocol(&self) -> Protocol;
|
fn protocol(&self) -> Protocol;
|
||||||
|
|
||||||
/// Send request and body
|
/// Send request and body
|
||||||
fn send_request<B: MessageBody + 'static>(
|
fn send_request<B: MessageBody + 'static, H: Into<RequestHeadType>>(
|
||||||
self,
|
self,
|
||||||
head: RequestHead,
|
head: H,
|
||||||
body: B,
|
body: B,
|
||||||
) -> Self::Future;
|
) -> Self::Future;
|
||||||
|
|
||||||
@ -39,7 +39,7 @@ pub trait Connection {
|
|||||||
>;
|
>;
|
||||||
|
|
||||||
/// Send request, returns Response and Framed
|
/// 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 {
|
pub(crate) trait ConnectionLifetime: AsyncRead + AsyncWrite + 'static {
|
||||||
@ -94,7 +94,8 @@ where
|
|||||||
T: AsyncRead + AsyncWrite + 'static,
|
T: AsyncRead + AsyncWrite + 'static,
|
||||||
{
|
{
|
||||||
type Io = T;
|
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 {
|
fn protocol(&self) -> Protocol {
|
||||||
match self.io {
|
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,
|
mut self,
|
||||||
head: RequestHead,
|
head: H,
|
||||||
body: B,
|
body: B,
|
||||||
) -> Self::Future {
|
) -> Self::Future {
|
||||||
match self.io.take().unwrap() {
|
match self.io.take().unwrap() {
|
||||||
ConnectionType::H1(io) => Box::new(h1proto::send_request(
|
ConnectionType::H1(io) => Box::new(h1proto::send_request(
|
||||||
io,
|
io,
|
||||||
head,
|
head.into(),
|
||||||
body,
|
body,
|
||||||
self.created,
|
self.created,
|
||||||
self.pool,
|
self.pool,
|
||||||
)),
|
)),
|
||||||
ConnectionType::H2(io) => Box::new(h2proto::send_request(
|
ConnectionType::H2(io) => Box::new(h2proto::send_request(
|
||||||
io,
|
io,
|
||||||
head,
|
head.into(),
|
||||||
body,
|
body,
|
||||||
self.created,
|
self.created,
|
||||||
self.pool,
|
self.pool,
|
||||||
@ -129,7 +130,7 @@ where
|
|||||||
|
|
||||||
type TunnelFuture = Either<
|
type TunnelFuture = Either<
|
||||||
Box<
|
Box<
|
||||||
Future<
|
dyn Future<
|
||||||
Item = (ResponseHead, Framed<Self::Io, ClientCodec>),
|
Item = (ResponseHead, Framed<Self::Io, ClientCodec>),
|
||||||
Error = SendRequestError,
|
Error = SendRequestError,
|
||||||
>,
|
>,
|
||||||
@ -138,10 +139,10 @@ where
|
|||||||
>;
|
>;
|
||||||
|
|
||||||
/// Send request, returns Response and Framed
|
/// 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() {
|
match self.io.take().unwrap() {
|
||||||
ConnectionType::H1(io) => {
|
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) => {
|
ConnectionType::H2(io) => {
|
||||||
if let Some(mut pool) = self.pool.take() {
|
if let Some(mut pool) = self.pool.take() {
|
||||||
@ -169,7 +170,8 @@ where
|
|||||||
B: AsyncRead + AsyncWrite + 'static,
|
B: AsyncRead + AsyncWrite + 'static,
|
||||||
{
|
{
|
||||||
type Io = EitherIo<A, B>;
|
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 {
|
fn protocol(&self) -> Protocol {
|
||||||
match self {
|
match self {
|
||||||
@ -178,9 +180,9 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn send_request<RB: MessageBody + 'static>(
|
fn send_request<RB: MessageBody + 'static, H: Into<RequestHeadType>>(
|
||||||
self,
|
self,
|
||||||
head: RequestHead,
|
head: H,
|
||||||
body: RB,
|
body: RB,
|
||||||
) -> Self::Future {
|
) -> Self::Future {
|
||||||
match self {
|
match self {
|
||||||
@ -190,14 +192,14 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
type TunnelFuture = Box<
|
type TunnelFuture = Box<
|
||||||
Future<
|
dyn Future<
|
||||||
Item = (ResponseHead, Framed<Self::Io, ClientCodec>),
|
Item = (ResponseHead, Framed<Self::Io, ClientCodec>),
|
||||||
Error = SendRequestError,
|
Error = SendRequestError,
|
||||||
>,
|
>,
|
||||||
>;
|
>;
|
||||||
|
|
||||||
/// Send request, returns Response and Framed
|
/// 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 {
|
match self {
|
||||||
EitherConnection::A(con) => Box::new(
|
EitherConnection::A(con) => Box::new(
|
||||||
con.open_tunnel(head)
|
con.open_tunnel(head)
|
||||||
|
@ -17,9 +17,21 @@ use super::pool::{ConnectionPool, Protocol};
|
|||||||
use super::Connect;
|
use super::Connect;
|
||||||
|
|
||||||
#[cfg(feature = "ssl")]
|
#[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 = ();
|
type SslConnector = ();
|
||||||
|
|
||||||
/// Manages http client network connectivity
|
/// Manages http client network connectivity
|
||||||
@ -46,7 +58,11 @@ pub struct Connector<T, U> {
|
|||||||
_t: PhantomData<U>,
|
_t: PhantomData<U>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
trait Io: AsyncRead + AsyncWrite {}
|
||||||
|
impl<T: AsyncRead + AsyncWrite> Io for T {}
|
||||||
|
|
||||||
impl Connector<(), ()> {
|
impl Connector<(), ()> {
|
||||||
|
#[allow(clippy::new_ret_no_self)]
|
||||||
pub fn new() -> Connector<
|
pub fn new() -> Connector<
|
||||||
impl Service<
|
impl Service<
|
||||||
Request = TcpConnect<Uri>,
|
Request = TcpConnect<Uri>,
|
||||||
@ -60,13 +76,23 @@ impl Connector<(), ()> {
|
|||||||
{
|
{
|
||||||
use openssl::ssl::SslMethod;
|
use openssl::ssl::SslMethod;
|
||||||
|
|
||||||
let mut ssl = SslConnector::builder(SslMethod::tls()).unwrap();
|
let mut ssl = OpensslConnector::builder(SslMethod::tls()).unwrap();
|
||||||
let _ = ssl
|
let _ = ssl
|
||||||
.set_alpn_protos(b"\x02h2\x08http/1.1")
|
.set_alpn_protos(b"\x02h2\x08http/1.1")
|
||||||
.map_err(|e| error!("Can not set alpn protocol: {:?}", e));
|
.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")]
|
#[cfg(feature = "ssl")]
|
||||||
/// Use custom `SslConnector` instance.
|
/// Use custom `SslConnector` instance.
|
||||||
pub fn ssl(mut self, connector: SslConnector) -> Self {
|
pub fn ssl(mut self, connector: OpensslConnector) -> Self {
|
||||||
self.ssl = connector;
|
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
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -181,7 +213,7 @@ where
|
|||||||
self,
|
self,
|
||||||
) -> impl Service<Request = Connect, Response = impl Connection, Error = ConnectError>
|
) -> impl Service<Request = Connect, Response = impl Connection, Error = ConnectError>
|
||||||
+ Clone {
|
+ Clone {
|
||||||
#[cfg(not(feature = "ssl"))]
|
#[cfg(not(any(feature = "ssl", feature = "rust-tls")))]
|
||||||
{
|
{
|
||||||
let connector = TimeoutService::new(
|
let connector = TimeoutService::new(
|
||||||
self.timeout,
|
self.timeout,
|
||||||
@ -206,10 +238,16 @@ where
|
|||||||
),
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#[cfg(feature = "ssl")]
|
#[cfg(any(feature = "ssl", feature = "rust-tls"))]
|
||||||
{
|
{
|
||||||
const H2: &[u8] = b"h2";
|
const H2: &[u8] = b"h2";
|
||||||
|
#[cfg(feature = "ssl")]
|
||||||
use actix_connect::ssl::OpensslConnector;
|
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(
|
let ssl_service = TimeoutService::new(
|
||||||
self.timeout,
|
self.timeout,
|
||||||
@ -217,8 +255,10 @@ where
|
|||||||
srv.call(TcpConnect::new(msg.uri).set_addr(msg.addr))
|
srv.call(TcpConnect::new(msg.uri).set_addr(msg.addr))
|
||||||
})
|
})
|
||||||
.map_err(ConnectError::from)
|
.map_err(ConnectError::from)
|
||||||
.and_then(
|
.and_then(match self.ssl {
|
||||||
OpensslConnector::service(self.ssl)
|
#[cfg(feature = "ssl")]
|
||||||
|
SslConnector::Openssl(ssl) => service(
|
||||||
|
OpensslConnector::service(ssl)
|
||||||
.map_err(ConnectError::from)
|
.map_err(ConnectError::from)
|
||||||
.map(|stream| {
|
.map(|stream| {
|
||||||
let sock = stream.into_parts().0;
|
let sock = stream.into_parts().0;
|
||||||
@ -229,12 +269,32 @@ where
|
|||||||
.map(|protos| protos.windows(2).any(|w| w == H2))
|
.map(|protos| protos.windows(2).any(|w| w == H2))
|
||||||
.unwrap_or(false);
|
.unwrap_or(false);
|
||||||
if h2 {
|
if h2 {
|
||||||
(sock, Protocol::Http2)
|
(Box::new(sock) as Box<dyn Io>, Protocol::Http2)
|
||||||
} else {
|
} else {
|
||||||
(sock, Protocol::Http1)
|
(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 {
|
.map_err(|e| match e {
|
||||||
TimeoutError::Service(e) => 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 {
|
mod connect_impl {
|
||||||
use futures::future::{err, Either, FutureResult};
|
use futures::future::{err, Either, FutureResult};
|
||||||
use futures::Poll;
|
use futures::Poll;
|
||||||
@ -336,7 +396,7 @@ mod connect_impl {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "ssl")]
|
#[cfg(any(feature = "ssl", feature = "rust-tls"))]
|
||||||
mod connect_impl {
|
mod connect_impl {
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
|
||||||
|
@ -128,3 +128,23 @@ impl ResponseError for SendRequestError {
|
|||||||
.into()
|
.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(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -8,8 +8,9 @@ use futures::{Async, Future, Poll, Sink, Stream};
|
|||||||
|
|
||||||
use crate::error::PayloadError;
|
use crate::error::PayloadError;
|
||||||
use crate::h1;
|
use crate::h1;
|
||||||
|
use crate::header::HeaderMap;
|
||||||
use crate::http::header::{IntoHeaderValue, HOST};
|
use crate::http::header::{IntoHeaderValue, HOST};
|
||||||
use crate::message::{RequestHead, ResponseHead};
|
use crate::message::{RequestHeadType, ResponseHead};
|
||||||
use crate::payload::{Payload, PayloadStream};
|
use crate::payload::{Payload, PayloadStream};
|
||||||
|
|
||||||
use super::connection::{ConnectionLifetime, ConnectionType, IoConnection};
|
use super::connection::{ConnectionLifetime, ConnectionType, IoConnection};
|
||||||
@ -19,7 +20,7 @@ use crate::body::{BodySize, MessageBody};
|
|||||||
|
|
||||||
pub(crate) fn send_request<T, B>(
|
pub(crate) fn send_request<T, B>(
|
||||||
io: T,
|
io: T,
|
||||||
mut head: RequestHead,
|
mut head: RequestHeadType,
|
||||||
body: B,
|
body: B,
|
||||||
created: time::Instant,
|
created: time::Instant,
|
||||||
pool: Option<Acquired<T>>,
|
pool: Option<Acquired<T>>,
|
||||||
@ -29,22 +30,28 @@ where
|
|||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
{
|
{
|
||||||
// set request host header
|
// set request host header
|
||||||
if !head.headers.contains_key(HOST) {
|
if !head.as_ref().headers.contains_key(HOST)
|
||||||
if let Some(host) = head.uri.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 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),
|
None | Some(80) | Some(443) => write!(wrt, "{}", host),
|
||||||
Some(port) => write!(wrt, "{}:{}", host, port),
|
Some(port) => write!(wrt, "{}:{}", host, port),
|
||||||
};
|
};
|
||||||
|
|
||||||
match wrt.get_mut().take().freeze().try_into() {
|
match wrt.get_mut().take().freeze().try_into() {
|
||||||
Ok(value) => {
|
Ok(value) => match head {
|
||||||
head.headers.insert(HOST, value);
|
RequestHeadType::Owned(ref mut head) => {
|
||||||
|
head.headers.insert(HOST, value)
|
||||||
}
|
}
|
||||||
Err(e) => {
|
RequestHeadType::Rc(_, ref mut extra_headers) => {
|
||||||
log::error!("Can not set HOST header {}", e);
|
let headers = extra_headers.get_or_insert(HeaderMap::new());
|
||||||
|
headers.insert(HOST, value)
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
Err(e) => log::error!("Can not set HOST header {}", e),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -57,7 +64,7 @@ where
|
|||||||
|
|
||||||
let len = body.size();
|
let len = body.size();
|
||||||
|
|
||||||
// create Framed and send reqest
|
// create Framed and send request
|
||||||
Framed::new(io, h1::ClientCodec::default())
|
Framed::new(io, h1::ClientCodec::default())
|
||||||
.send((head, len).into())
|
.send((head, len).into())
|
||||||
.from_err()
|
.from_err()
|
||||||
@ -95,12 +102,12 @@ where
|
|||||||
|
|
||||||
pub(crate) fn open_tunnel<T>(
|
pub(crate) fn open_tunnel<T>(
|
||||||
io: T,
|
io: T,
|
||||||
head: RequestHead,
|
head: RequestHeadType,
|
||||||
) -> impl Future<Item = (ResponseHead, Framed<T, h1::ClientCodec>), Error = SendRequestError>
|
) -> impl Future<Item = (ResponseHead, Framed<T, h1::ClientCodec>), Error = SendRequestError>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite + 'static,
|
T: AsyncRead + AsyncWrite + 'static,
|
||||||
{
|
{
|
||||||
// create Framed and send reqest
|
// create Framed and send request
|
||||||
Framed::new(io, h1::ClientCodec::default())
|
Framed::new(io, h1::ClientCodec::default())
|
||||||
.send((head, BodySize::None).into())
|
.send((head, BodySize::None).into())
|
||||||
.from_err()
|
.from_err()
|
||||||
|
@ -9,7 +9,8 @@ use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, TRANSFER_ENCODING};
|
|||||||
use http::{request::Request, HttpTryFrom, Method, Version};
|
use http::{request::Request, HttpTryFrom, Method, Version};
|
||||||
|
|
||||||
use crate::body::{BodySize, MessageBody};
|
use crate::body::{BodySize, MessageBody};
|
||||||
use crate::message::{RequestHead, ResponseHead};
|
use crate::header::HeaderMap;
|
||||||
|
use crate::message::{RequestHeadType, ResponseHead};
|
||||||
use crate::payload::Payload;
|
use crate::payload::Payload;
|
||||||
|
|
||||||
use super::connection::{ConnectionType, IoConnection};
|
use super::connection::{ConnectionType, IoConnection};
|
||||||
@ -18,7 +19,7 @@ use super::pool::Acquired;
|
|||||||
|
|
||||||
pub(crate) fn send_request<T, B>(
|
pub(crate) fn send_request<T, B>(
|
||||||
io: SendRequest<Bytes>,
|
io: SendRequest<Bytes>,
|
||||||
head: RequestHead,
|
head: RequestHeadType,
|
||||||
body: B,
|
body: B,
|
||||||
created: time::Instant,
|
created: time::Instant,
|
||||||
pool: Option<Acquired<T>>,
|
pool: Option<Acquired<T>>,
|
||||||
@ -28,7 +29,7 @@ where
|
|||||||
B: MessageBody,
|
B: MessageBody,
|
||||||
{
|
{
|
||||||
trace!("Sending client request: {:?} {:?}", head, body.size());
|
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 length = body.size();
|
||||||
let eof = match length {
|
let eof = match length {
|
||||||
BodySize::None | BodySize::Empty | BodySize::Sized(0) => true,
|
BodySize::None | BodySize::Empty | BodySize::Sized(0) => true,
|
||||||
@ -39,8 +40,8 @@ where
|
|||||||
.map_err(SendRequestError::from)
|
.map_err(SendRequestError::from)
|
||||||
.and_then(move |mut io| {
|
.and_then(move |mut io| {
|
||||||
let mut req = Request::new(());
|
let mut req = Request::new(());
|
||||||
*req.uri_mut() = head.uri;
|
*req.uri_mut() = head.as_ref().uri.clone();
|
||||||
*req.method_mut() = head.method;
|
*req.method_mut() = head.as_ref().method.clone();
|
||||||
*req.version_mut() = Version::HTTP_2;
|
*req.version_mut() = Version::HTTP_2;
|
||||||
|
|
||||||
let mut skip_len = true;
|
let mut skip_len = true;
|
||||||
@ -66,8 +67,27 @@ 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_else(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
|
// copy headers
|
||||||
for (key, value) in head.headers.iter() {
|
for (key, value) in headers {
|
||||||
match *key {
|
match *key {
|
||||||
CONNECTION | TRANSFER_ENCODING => continue, // http2 specific
|
CONNECTION | TRANSFER_ENCODING => continue, // http2 specific
|
||||||
CONTENT_LENGTH if skip_len => continue,
|
CONTENT_LENGTH if skip_len => continue,
|
||||||
|
@ -10,7 +10,7 @@ mod pool;
|
|||||||
|
|
||||||
pub use self::connection::Connection;
|
pub use self::connection::Connection;
|
||||||
pub use self::connector::Connector;
|
pub use self::connector::Connector;
|
||||||
pub use self::error::{ConnectError, InvalidUrl, SendRequestError};
|
pub use self::error::{ConnectError, FreezeRequestError, InvalidUrl, SendRequestError};
|
||||||
pub use self::pool::Protocol;
|
pub use self::pool::Protocol;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
|
@ -305,10 +305,12 @@ pub(crate) struct Inner<Io> {
|
|||||||
limit: usize,
|
limit: usize,
|
||||||
acquired: usize,
|
acquired: usize,
|
||||||
available: HashMap<Key, VecDeque<AvailableConnection<Io>>>,
|
available: HashMap<Key, VecDeque<AvailableConnection<Io>>>,
|
||||||
waiters: Slab<(
|
waiters: Slab<
|
||||||
|
Option<(
|
||||||
Connect,
|
Connect,
|
||||||
oneshot::Sender<Result<IoConnection<Io>, ConnectError>>,
|
oneshot::Sender<Result<IoConnection<Io>, ConnectError>>,
|
||||||
)>,
|
)>,
|
||||||
|
>,
|
||||||
waiters_queue: IndexSet<(Key, usize)>,
|
waiters_queue: IndexSet<(Key, usize)>,
|
||||||
task: Option<AtomicTask>,
|
task: Option<AtomicTask>,
|
||||||
}
|
}
|
||||||
@ -324,7 +326,7 @@ impl<Io> Inner<Io> {
|
|||||||
|
|
||||||
fn release_waiter(&mut self, key: &Key, token: usize) {
|
fn release_waiter(&mut self, key: &Key, token: usize) {
|
||||||
self.waiters.remove(token);
|
self.waiters.remove(token);
|
||||||
self.waiters_queue.remove(&(key.clone(), token));
|
let _ = self.waiters_queue.shift_remove(&(key.clone(), token));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -346,7 +348,7 @@ where
|
|||||||
let key: Key = connect.uri.authority_part().unwrap().clone().into();
|
let key: Key = connect.uri.authority_part().unwrap().clone().into();
|
||||||
let entry = self.waiters.vacant_entry();
|
let entry = self.waiters.vacant_entry();
|
||||||
let token = entry.key();
|
let token = entry.key();
|
||||||
entry.insert((connect, tx));
|
entry.insert(Some((connect, tx)));
|
||||||
assert!(self.waiters_queue.insert((key, token)));
|
assert!(self.waiters_queue.insert((key, token)));
|
||||||
|
|
||||||
(rx, token, self.task.is_some())
|
(rx, token, self.task.is_some())
|
||||||
@ -427,7 +429,9 @@ where
|
|||||||
|
|
||||||
fn check_availibility(&self) {
|
fn check_availibility(&self) {
|
||||||
if !self.waiters_queue.is_empty() && self.acquired < self.limit {
|
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;
|
break;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
if inner.waiters.get(token).unwrap().is_none() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
match inner.acquire(&key) {
|
match inner.acquire(&key) {
|
||||||
Acquire::NotAvailable => break,
|
Acquire::NotAvailable => break,
|
||||||
Acquire::Acquired(io, created) => {
|
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(
|
if let Err(conn) = tx.send(Ok(IoConnection::new(
|
||||||
io,
|
io,
|
||||||
created,
|
created,
|
||||||
@ -511,7 +519,8 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Acquire::Available => {
|
Acquire::Available => {
|
||||||
let (connect, tx) = inner.waiters.remove(token);
|
let (connect, tx) =
|
||||||
|
inner.waiters.get_mut(token).unwrap().take().unwrap();
|
||||||
OpenWaitingConnection::spawn(
|
OpenWaitingConnection::spawn(
|
||||||
key.clone(),
|
key.clone(),
|
||||||
tx,
|
tx,
|
||||||
@ -581,6 +590,29 @@ where
|
|||||||
type Error = ();
|
type Error = ();
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Self::Item, Self::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() {
|
match self.fut.poll() {
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
let _ = self.inner.take();
|
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) {
|
pub fn set_date(&self, dst: &mut BytesMut) {
|
||||||
let mut buf: [u8; 39] = [0; 39];
|
let mut buf: [u8; 39] = [0; 39];
|
||||||
buf[..6].copy_from_slice(b"date: ");
|
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");
|
buf[35..].copy_from_slice(b"\r\n\r\n");
|
||||||
dst.extend_from_slice(&buf);
|
dst.extend_from_slice(&buf);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn set_date_header(&self, dst: &mut BytesMut) {
|
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 {
|
struct Date {
|
||||||
bytes: [u8; DATE_VALUE_LENGTH],
|
bytes: [u8; DATE_VALUE_LENGTH],
|
||||||
pos: usize,
|
pos: usize,
|
||||||
@ -215,10 +220,6 @@ impl DateServiceInner {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_ref(&self) -> &Option<(Date, Instant)> {
|
|
||||||
unsafe { &*self.current.get() }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn reset(&self) {
|
fn reset(&self) {
|
||||||
unsafe { (&mut *self.current.get()).take() };
|
unsafe { (&mut *self.current.get()).take() };
|
||||||
}
|
}
|
||||||
@ -236,7 +237,7 @@ impl DateService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn check_date(&self) {
|
fn check_date(&self) {
|
||||||
if self.0.get_ref().is_none() {
|
if unsafe { (&*self.0.current.get()).is_none() } {
|
||||||
self.0.update();
|
self.0.update();
|
||||||
|
|
||||||
// periodic date update
|
// periodic date update
|
||||||
@ -252,14 +253,12 @@ impl DateService {
|
|||||||
|
|
||||||
fn now(&self) -> Instant {
|
fn now(&self) -> Instant {
|
||||||
self.check_date();
|
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();
|
self.check_date();
|
||||||
|
f(&unsafe { (&*self.0.current.get()).as_ref().unwrap().0 })
|
||||||
let item = self.0.get_ref().as_ref().unwrap();
|
|
||||||
&item.0
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -66,7 +66,7 @@ use std::fmt;
|
|||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
use chrono::Duration;
|
use chrono::Duration;
|
||||||
use percent_encoding::{percent_encode, USERINFO_ENCODE_SET};
|
use percent_encoding::{percent_encode, AsciiSet, CONTROLS};
|
||||||
use time::Tm;
|
use time::Tm;
|
||||||
|
|
||||||
pub use self::builder::CookieBuilder;
|
pub use self::builder::CookieBuilder;
|
||||||
@ -75,6 +75,25 @@ pub use self::jar::{CookieJar, Delta, Iter};
|
|||||||
use self::parse::parse_cookie;
|
use self::parse::parse_cookie;
|
||||||
pub use self::parse::ParseError;
|
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)]
|
#[derive(Debug, Clone)]
|
||||||
enum CookieStr {
|
enum CookieStr {
|
||||||
/// An string derived from indexes (start, end).
|
/// 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> {
|
fn to_raw_str<'s, 'c: 's>(&'s self, string: &'s Cow<'c, str>) -> Option<&'c str> {
|
||||||
match *self {
|
match *self {
|
||||||
CookieStr::Indexed(i, j) => match *string {
|
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> {
|
impl<'a, 'c: 'a> fmt::Display for EncodedCookie<'a, 'c> {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
// Percent-encode the name and value.
|
// Percent-encode the name and value.
|
||||||
let name = percent_encode(self.0.name().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_ENCODE_SET);
|
let value = percent_encode(self.0.value().as_bytes(), USERINFO);
|
||||||
|
|
||||||
// Write out the name/value pair and the cookie's parameters.
|
// Write out the name/value pair and the cookie's parameters.
|
||||||
write!(f, "{}={}", name, value)?;
|
write!(f, "{}={}", name, value)?;
|
||||||
|
@ -6,8 +6,8 @@ use ring::rand::{SecureRandom, SystemRandom};
|
|||||||
use super::private::KEY_LEN as PRIVATE_KEY_LEN;
|
use super::private::KEY_LEN as PRIVATE_KEY_LEN;
|
||||||
use super::signed::KEY_LEN as SIGNED_KEY_LEN;
|
use super::signed::KEY_LEN as SIGNED_KEY_LEN;
|
||||||
|
|
||||||
static HKDF_DIGEST: &'static Algorithm = &SHA256;
|
static HKDF_DIGEST: &Algorithm = &SHA256;
|
||||||
const KEYS_INFO: &'static str = "COOKIE;SIGNED:HMAC-SHA256;PRIVATE:AEAD-AES-256-GCM";
|
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.
|
/// 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
|
// Keep these in sync, and keep the key len synced with the `private` docs as
|
||||||
// well as the `KEYS_INFO` const in secure::Key.
|
// 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;
|
const NONCE_LEN: usize = 12;
|
||||||
pub const KEY_LEN: usize = 32;
|
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
|
// Keep these in sync, and keep the key len synced with the `signed` docs as
|
||||||
// well as the `KEYS_INFO` const in secure::Key.
|
// 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;
|
const BASE64_DIGEST_LEN: usize = 44;
|
||||||
pub const KEY_LEN: usize = 32;
|
pub const KEY_LEN: usize = 32;
|
||||||
|
|
||||||
|
@ -33,6 +33,7 @@ impl<B: MessageBody> Encoder<B> {
|
|||||||
) -> ResponseBody<Encoder<B>> {
|
) -> ResponseBody<Encoder<B>> {
|
||||||
let can_encode = !(head.headers().contains_key(&CONTENT_ENCODING)
|
let can_encode = !(head.headers().contains_key(&CONTENT_ENCODING)
|
||||||
|| head.status == StatusCode::SWITCHING_PROTOCOLS
|
|| head.status == StatusCode::SWITCHING_PROTOCOLS
|
||||||
|
|| head.status == StatusCode::NO_CONTENT
|
||||||
|| encoding == ContentEncoding::Identity
|
|| encoding == ContentEncoding::Identity
|
||||||
|| encoding == ContentEncoding::Auto);
|
|| encoding == ContentEncoding::Auto);
|
||||||
|
|
||||||
@ -53,15 +54,18 @@ impl<B: MessageBody> Encoder<B> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if can_encode {
|
if can_encode {
|
||||||
|
// Modify response body only if encoder is not None
|
||||||
|
if let Some(enc) = ContentEncoder::encoder(encoding) {
|
||||||
update_head(encoding, head);
|
update_head(encoding, head);
|
||||||
head.no_chunking(false);
|
head.no_chunking(false);
|
||||||
ResponseBody::Body(Encoder {
|
return ResponseBody::Body(Encoder {
|
||||||
body,
|
body,
|
||||||
eof: false,
|
eof: false,
|
||||||
fut: None,
|
fut: None,
|
||||||
encoder: ContentEncoder::encoder(encoding),
|
encoder: Some(enc),
|
||||||
})
|
});
|
||||||
} else {
|
}
|
||||||
|
}
|
||||||
ResponseBody::Body(Encoder {
|
ResponseBody::Body(Encoder {
|
||||||
body,
|
body,
|
||||||
eof: false,
|
eof: false,
|
||||||
@ -70,7 +74,6 @@ impl<B: MessageBody> Encoder<B> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
enum EncoderBody<B> {
|
enum EncoderBody<B> {
|
||||||
Bytes(Bytes),
|
Bytes(Bytes),
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
//! Error and Result module
|
//! Error and Result module
|
||||||
|
use std::any::TypeId;
|
||||||
use std::cell::RefCell;
|
use std::cell::RefCell;
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::str::Utf8Error;
|
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
|
/// if you have access to an actix `Error` you can always get a
|
||||||
/// `ResponseError` reference from it.
|
/// `ResponseError` reference from it.
|
||||||
pub struct Error {
|
pub struct Error {
|
||||||
cause: Box<ResponseError>,
|
cause: Box<dyn ResponseError>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Error {
|
impl Error {
|
||||||
/// Returns the reference to the underlying `ResponseError`.
|
/// 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()
|
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`
|
/// Error that can be converted to `Response`
|
||||||
@ -69,10 +75,29 @@ pub trait ResponseError: fmt::Debug + fmt::Display {
|
|||||||
let _ = write!(Writer(&mut buf), "{}", self);
|
let _ = write!(Writer(&mut buf), "{}", self);
|
||||||
resp.headers_mut().insert(
|
resp.headers_mut().insert(
|
||||||
header::CONTENT_TYPE,
|
header::CONTENT_TYPE,
|
||||||
header::HeaderValue::from_static("text/plain"),
|
header::HeaderValue::from_static("text/plain; charset=utf-8"),
|
||||||
);
|
);
|
||||||
resp.set_body(Body::from(buf))
|
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 {
|
impl fmt::Display for Error {
|
||||||
@ -107,6 +132,14 @@ impl std::error::Error for Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<std::convert::Infallible> for Error {
|
||||||
|
fn from(_: std::convert::Infallible) -> Self {
|
||||||
|
// `std::convert::Infallible` indicates an error
|
||||||
|
// that will never happen
|
||||||
|
unreachable!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Convert `Error` to a `Response` instance
|
/// Convert `Error` to a `Response` instance
|
||||||
impl From<Error> for Response {
|
impl From<Error> for Response {
|
||||||
fn from(err: Error) -> Self {
|
fn from(err: Error) -> Self {
|
||||||
@ -503,7 +536,7 @@ where
|
|||||||
let _ = write!(Writer(&mut buf), "{}", self);
|
let _ = write!(Writer(&mut buf), "{}", self);
|
||||||
res.headers_mut().insert(
|
res.headers_mut().insert(
|
||||||
header::CONTENT_TYPE,
|
header::CONTENT_TYPE,
|
||||||
header::HeaderValue::from_static("text/plain"),
|
header::HeaderValue::from_static("text/plain; charset=utf-8"),
|
||||||
);
|
);
|
||||||
res.set_body(Body::from(buf))
|
res.set_body(Body::from(buf))
|
||||||
}
|
}
|
||||||
@ -1044,6 +1077,16 @@ mod tests {
|
|||||||
assert_eq!(resp.status(), StatusCode::OK);
|
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]
|
#[test]
|
||||||
fn test_error_helpers() {
|
fn test_error_helpers() {
|
||||||
let r: Response = ErrorBadRequest("err").into();
|
let r: Response = ErrorBadRequest("err").into();
|
||||||
|
@ -6,7 +6,7 @@ use hashbrown::HashMap;
|
|||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
/// A type map of request extensions.
|
/// A type map of request extensions.
|
||||||
pub struct Extensions {
|
pub struct Extensions {
|
||||||
map: HashMap<TypeId, Box<Any>>,
|
map: HashMap<TypeId, Box<dyn Any>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Extensions {
|
impl Extensions {
|
||||||
@ -35,14 +35,14 @@ impl Extensions {
|
|||||||
pub fn get<T: 'static>(&self) -> Option<&T> {
|
pub fn get<T: 'static>(&self) -> Option<&T> {
|
||||||
self.map
|
self.map
|
||||||
.get(&TypeId::of::<T>())
|
.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`.
|
/// Get a mutable reference to a type previously inserted on this `Extensions`.
|
||||||
pub fn get_mut<T: 'static>(&mut self) -> Option<&mut T> {
|
pub fn get_mut<T: 'static>(&mut self) -> Option<&mut T> {
|
||||||
self.map
|
self.map
|
||||||
.get_mut(&TypeId::of::<T>())
|
.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`.
|
/// Remove a type from this `Extensions`.
|
||||||
@ -50,7 +50,7 @@ impl Extensions {
|
|||||||
/// If a extension of this type existed, it will be returned.
|
/// If a extension of this type existed, it will be returned.
|
||||||
pub fn remove<T: 'static>(&mut self) -> Option<T> {
|
pub fn remove<T: 'static>(&mut self) -> Option<T> {
|
||||||
self.map.remove(&TypeId::of::<T>()).and_then(|boxed| {
|
self.map.remove(&TypeId::of::<T>()).and_then(|boxed| {
|
||||||
(boxed as Box<Any + 'static>)
|
(boxed as Box<dyn Any + 'static>)
|
||||||
.downcast()
|
.downcast()
|
||||||
.ok()
|
.ok()
|
||||||
.map(|boxed| *boxed)
|
.map(|boxed| *boxed)
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
#![allow(unused_imports, unused_variables, dead_code)]
|
#![allow(unused_imports, unused_variables, dead_code)]
|
||||||
use std::io::{self, Write};
|
use std::io::{self, Write};
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_codec::{Decoder, Encoder};
|
use actix_codec::{Decoder, Encoder};
|
||||||
use bitflags::bitflags;
|
use bitflags::bitflags;
|
||||||
@ -15,8 +16,11 @@ use super::{Message, MessageType};
|
|||||||
use crate::body::BodySize;
|
use crate::body::BodySize;
|
||||||
use crate::config::ServiceConfig;
|
use crate::config::ServiceConfig;
|
||||||
use crate::error::{ParseError, PayloadError};
|
use crate::error::{ParseError, PayloadError};
|
||||||
|
use crate::header::HeaderMap;
|
||||||
use crate::helpers;
|
use crate::helpers;
|
||||||
use crate::message::{ConnectionType, Head, MessagePool, RequestHead, ResponseHead};
|
use crate::message::{
|
||||||
|
ConnectionType, Head, MessagePool, RequestHead, RequestHeadType, ResponseHead,
|
||||||
|
};
|
||||||
|
|
||||||
bitflags! {
|
bitflags! {
|
||||||
struct Flags: u8 {
|
struct Flags: u8 {
|
||||||
@ -48,7 +52,7 @@ struct ClientCodecInner {
|
|||||||
// encoder part
|
// encoder part
|
||||||
flags: Flags,
|
flags: Flags,
|
||||||
headers_size: u32,
|
headers_size: u32,
|
||||||
encoder: encoder::MessageEncoder<RequestHead>,
|
encoder: encoder::MessageEncoder<RequestHeadType>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for ClientCodec {
|
impl Default for ClientCodec {
|
||||||
@ -183,7 +187,7 @@ impl Decoder for ClientPayloadCodec {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Encoder for ClientCodec {
|
impl Encoder for ClientCodec {
|
||||||
type Item = Message<(RequestHead, BodySize)>;
|
type Item = Message<(RequestHeadType, BodySize)>;
|
||||||
type Error = io::Error;
|
type Error = io::Error;
|
||||||
|
|
||||||
fn encode(
|
fn encode(
|
||||||
@ -192,13 +196,15 @@ impl Encoder for ClientCodec {
|
|||||||
dst: &mut BytesMut,
|
dst: &mut BytesMut,
|
||||||
) -> Result<(), Self::Error> {
|
) -> Result<(), Self::Error> {
|
||||||
match item {
|
match item {
|
||||||
Message::Item((mut msg, length)) => {
|
Message::Item((mut head, length)) => {
|
||||||
let inner = &mut self.inner;
|
let inner = &mut self.inner;
|
||||||
inner.version = msg.version;
|
inner.version = head.as_ref().version;
|
||||||
inner.flags.set(Flags::HEAD, msg.method == Method::HEAD);
|
inner
|
||||||
|
.flags
|
||||||
|
.set(Flags::HEAD, head.as_ref().method == Method::HEAD);
|
||||||
|
|
||||||
// connection status
|
// connection status
|
||||||
inner.ctype = match msg.connection_type() {
|
inner.ctype = match head.as_ref().connection_type() {
|
||||||
ConnectionType::KeepAlive => {
|
ConnectionType::KeepAlive => {
|
||||||
if inner.flags.contains(Flags::KEEPALIVE_ENABLED) {
|
if inner.flags.contains(Flags::KEEPALIVE_ENABLED) {
|
||||||
ConnectionType::KeepAlive
|
ConnectionType::KeepAlive
|
||||||
@ -212,7 +218,7 @@ impl Encoder for ClientCodec {
|
|||||||
|
|
||||||
inner.encoder.encode(
|
inner.encoder.encode(
|
||||||
dst,
|
dst,
|
||||||
&mut msg,
|
&mut head,
|
||||||
false,
|
false,
|
||||||
false,
|
false,
|
||||||
inner.version,
|
inner.version,
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
|
use std::io;
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::{io, mem};
|
use std::mem::MaybeUninit;
|
||||||
|
|
||||||
use actix_codec::Decoder;
|
use actix_codec::Decoder;
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
@ -186,11 +187,12 @@ impl MessageType for Request {
|
|||||||
fn decode(src: &mut BytesMut) -> Result<Option<(Self, PayloadType)>, ParseError> {
|
fn decode(src: &mut BytesMut) -> Result<Option<(Self, PayloadType)>, ParseError> {
|
||||||
// Unsafe: we read only this data only after httparse parses headers into.
|
// Unsafe: we read only this data only after httparse parses headers into.
|
||||||
// performance bump for pipeline benchmarks.
|
// performance bump for pipeline benchmarks.
|
||||||
let mut headers: [HeaderIndex; MAX_HEADERS] = unsafe { mem::uninitialized() };
|
let mut headers: [HeaderIndex; MAX_HEADERS] =
|
||||||
|
unsafe { MaybeUninit::uninit().assume_init() };
|
||||||
|
|
||||||
let (len, method, uri, ver, h_len) = {
|
let (len, method, uri, ver, h_len) = {
|
||||||
let mut parsed: [httparse::Header; MAX_HEADERS] =
|
let mut parsed: [httparse::Header; MAX_HEADERS] =
|
||||||
unsafe { mem::uninitialized() };
|
unsafe { MaybeUninit::uninit().assume_init() };
|
||||||
|
|
||||||
let mut req = httparse::Request::new(&mut parsed);
|
let mut req = httparse::Request::new(&mut parsed);
|
||||||
match req.parse(src)? {
|
match req.parse(src)? {
|
||||||
@ -260,11 +262,12 @@ impl MessageType for ResponseHead {
|
|||||||
fn decode(src: &mut BytesMut) -> Result<Option<(Self, PayloadType)>, ParseError> {
|
fn decode(src: &mut BytesMut) -> Result<Option<(Self, PayloadType)>, ParseError> {
|
||||||
// Unsafe: we read only this data only after httparse parses headers into.
|
// Unsafe: we read only this data only after httparse parses headers into.
|
||||||
// performance bump for pipeline benchmarks.
|
// performance bump for pipeline benchmarks.
|
||||||
let mut headers: [HeaderIndex; MAX_HEADERS] = unsafe { mem::uninitialized() };
|
let mut headers: [HeaderIndex; MAX_HEADERS] =
|
||||||
|
unsafe { MaybeUninit::uninit().assume_init() };
|
||||||
|
|
||||||
let (len, ver, status, h_len) = {
|
let (len, ver, status, h_len) = {
|
||||||
let mut parsed: [httparse::Header; MAX_HEADERS] =
|
let mut parsed: [httparse::Header; MAX_HEADERS] =
|
||||||
unsafe { mem::uninitialized() };
|
unsafe { MaybeUninit::uninit().assume_init() };
|
||||||
|
|
||||||
let mut res = httparse::Response::new(&mut parsed);
|
let mut res = httparse::Response::new(&mut parsed);
|
||||||
match res.parse(src)? {
|
match res.parse(src)? {
|
||||||
@ -502,15 +505,15 @@ impl ChunkedState {
|
|||||||
fn read_size(rdr: &mut BytesMut, size: &mut u64) -> Poll<ChunkedState, io::Error> {
|
fn read_size(rdr: &mut BytesMut, size: &mut u64) -> Poll<ChunkedState, io::Error> {
|
||||||
let radix = 16;
|
let radix = 16;
|
||||||
match byte!(rdr) {
|
match byte!(rdr) {
|
||||||
b @ b'0'...b'9' => {
|
b @ b'0'..=b'9' => {
|
||||||
*size *= radix;
|
*size *= radix;
|
||||||
*size += u64::from(b - b'0');
|
*size += u64::from(b - b'0');
|
||||||
}
|
}
|
||||||
b @ b'a'...b'f' => {
|
b @ b'a'..=b'f' => {
|
||||||
*size *= radix;
|
*size *= radix;
|
||||||
*size += u64::from(b + 10 - b'a');
|
*size += u64::from(b + 10 - b'a');
|
||||||
}
|
}
|
||||||
b @ b'A'...b'F' => {
|
b @ b'A'..=b'F' => {
|
||||||
*size *= radix;
|
*size *= radix;
|
||||||
*size += u64::from(b + 10 - b'A');
|
*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_codec::{Decoder, Encoder, Framed, FramedParts};
|
||||||
use actix_server_config::IoStream;
|
use actix_server_config::IoStream;
|
||||||
use actix_service::Service;
|
use actix_service::Service;
|
||||||
use actix_utils::cloneable::CloneableService;
|
|
||||||
use bitflags::bitflags;
|
use bitflags::bitflags;
|
||||||
use bytes::{BufMut, BytesMut};
|
use bytes::{BufMut, BytesMut};
|
||||||
use futures::{Async, Future, Poll};
|
use futures::{Async, Future, Poll};
|
||||||
@ -13,9 +12,12 @@ use log::{error, trace};
|
|||||||
use tokio_timer::Delay;
|
use tokio_timer::Delay;
|
||||||
|
|
||||||
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
|
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
|
||||||
|
use crate::cloneable::CloneableService;
|
||||||
use crate::config::ServiceConfig;
|
use crate::config::ServiceConfig;
|
||||||
use crate::error::{DispatchError, Error};
|
use crate::error::{DispatchError, Error};
|
||||||
use crate::error::{ParseError, PayloadError};
|
use crate::error::{ParseError, PayloadError};
|
||||||
|
use crate::helpers::DataFactory;
|
||||||
|
use crate::httpmessage::HttpMessage;
|
||||||
use crate::request::Request;
|
use crate::request::Request;
|
||||||
use crate::response::Response;
|
use crate::response::Response;
|
||||||
|
|
||||||
@ -81,6 +83,7 @@ where
|
|||||||
service: CloneableService<S>,
|
service: CloneableService<S>,
|
||||||
expect: CloneableService<X>,
|
expect: CloneableService<X>,
|
||||||
upgrade: Option<CloneableService<U>>,
|
upgrade: Option<CloneableService<U>>,
|
||||||
|
on_connect: Option<Box<dyn DataFactory>>,
|
||||||
flags: Flags,
|
flags: Flags,
|
||||||
peer_addr: Option<net::SocketAddr>,
|
peer_addr: Option<net::SocketAddr>,
|
||||||
error: Option<DispatchError>,
|
error: Option<DispatchError>,
|
||||||
@ -174,12 +177,13 @@ where
|
|||||||
U::Error: fmt::Display,
|
U::Error: fmt::Display,
|
||||||
{
|
{
|
||||||
/// Create http/1 dispatcher.
|
/// Create http/1 dispatcher.
|
||||||
pub fn new(
|
pub(crate) fn new(
|
||||||
stream: T,
|
stream: T,
|
||||||
config: ServiceConfig,
|
config: ServiceConfig,
|
||||||
service: CloneableService<S>,
|
service: CloneableService<S>,
|
||||||
expect: CloneableService<X>,
|
expect: CloneableService<X>,
|
||||||
upgrade: Option<CloneableService<U>>,
|
upgrade: Option<CloneableService<U>>,
|
||||||
|
on_connect: Option<Box<dyn DataFactory>>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Dispatcher::with_timeout(
|
Dispatcher::with_timeout(
|
||||||
stream,
|
stream,
|
||||||
@ -190,11 +194,12 @@ where
|
|||||||
service,
|
service,
|
||||||
expect,
|
expect,
|
||||||
upgrade,
|
upgrade,
|
||||||
|
on_connect,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create http/1 dispatcher with slow request timeout.
|
/// Create http/1 dispatcher with slow request timeout.
|
||||||
pub fn with_timeout(
|
pub(crate) fn with_timeout(
|
||||||
io: T,
|
io: T,
|
||||||
codec: Codec,
|
codec: Codec,
|
||||||
config: ServiceConfig,
|
config: ServiceConfig,
|
||||||
@ -203,6 +208,7 @@ where
|
|||||||
service: CloneableService<S>,
|
service: CloneableService<S>,
|
||||||
expect: CloneableService<X>,
|
expect: CloneableService<X>,
|
||||||
upgrade: Option<CloneableService<U>>,
|
upgrade: Option<CloneableService<U>>,
|
||||||
|
on_connect: Option<Box<dyn DataFactory>>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let keepalive = config.keep_alive_enabled();
|
let keepalive = config.keep_alive_enabled();
|
||||||
let flags = if keepalive {
|
let flags = if keepalive {
|
||||||
@ -234,6 +240,7 @@ where
|
|||||||
service,
|
service,
|
||||||
expect,
|
expect,
|
||||||
upgrade,
|
upgrade,
|
||||||
|
on_connect,
|
||||||
flags,
|
flags,
|
||||||
ka_expire,
|
ka_expire,
|
||||||
ka_timer,
|
ka_timer,
|
||||||
@ -495,6 +502,11 @@ where
|
|||||||
let pl = self.codec.message_type();
|
let pl = self.codec.message_type();
|
||||||
req.head_mut().peer_addr = self.peer_addr;
|
req.head_mut().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());
|
||||||
|
}
|
||||||
|
|
||||||
if pl == MessageType::Stream && self.upgrade.is_some() {
|
if pl == MessageType::Stream && self.upgrade.is_some() {
|
||||||
self.messages.push_back(DispatcherMessage::Upgrade(req));
|
self.messages.push_back(DispatcherMessage::Upgrade(req));
|
||||||
break;
|
break;
|
||||||
@ -693,7 +705,8 @@ where
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// read socket into a buf
|
// read socket into a buf
|
||||||
let should_disconnect = if !inner.flags.contains(Flags::READ_DISCONNECT) {
|
let should_disconnect =
|
||||||
|
if !inner.flags.contains(Flags::READ_DISCONNECT) {
|
||||||
read_available(&mut inner.io, &mut inner.read_buf)?
|
read_available(&mut inner.io, &mut inner.read_buf)?
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
@ -850,6 +863,7 @@ mod tests {
|
|||||||
),
|
),
|
||||||
CloneableService::new(ExpectHandler),
|
CloneableService::new(ExpectHandler),
|
||||||
None,
|
None,
|
||||||
|
None,
|
||||||
);
|
);
|
||||||
assert!(h1.poll().is_err());
|
assert!(h1.poll().is_err());
|
||||||
|
|
||||||
|
@ -2,6 +2,7 @@
|
|||||||
use std::fmt::Write as FmtWrite;
|
use std::fmt::Write as FmtWrite;
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
use std::rc::Rc;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use std::{cmp, fmt, io, mem};
|
use std::{cmp, fmt, io, mem};
|
||||||
|
|
||||||
@ -15,7 +16,7 @@ use crate::http::header::{
|
|||||||
HeaderValue, ACCEPT_ENCODING, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING,
|
HeaderValue, ACCEPT_ENCODING, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING,
|
||||||
};
|
};
|
||||||
use crate::http::{HeaderMap, Method, StatusCode, Version};
|
use crate::http::{HeaderMap, Method, StatusCode, Version};
|
||||||
use crate::message::{ConnectionType, Head, RequestHead, ResponseHead};
|
use crate::message::{ConnectionType, Head, RequestHead, RequestHeadType, ResponseHead};
|
||||||
use crate::request::Request;
|
use crate::request::Request;
|
||||||
use crate::response::Response;
|
use crate::response::Response;
|
||||||
|
|
||||||
@ -43,6 +44,8 @@ pub(crate) trait MessageType: Sized {
|
|||||||
|
|
||||||
fn headers(&self) -> &HeaderMap;
|
fn headers(&self) -> &HeaderMap;
|
||||||
|
|
||||||
|
fn extra_headers(&self) -> Option<&HeaderMap>;
|
||||||
|
|
||||||
fn camel_case(&self) -> bool {
|
fn camel_case(&self) -> bool {
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
@ -128,12 +131,22 @@ 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
|
// write headers
|
||||||
let mut pos = 0;
|
let mut pos = 0;
|
||||||
let mut has_date = false;
|
let mut has_date = false;
|
||||||
let mut remaining = dst.remaining_mut();
|
let mut remaining = dst.remaining_mut();
|
||||||
let mut buf = unsafe { &mut *(dst.bytes_mut() as *mut [u8]) };
|
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 {
|
match *key {
|
||||||
CONNECTION => continue,
|
CONNECTION => continue,
|
||||||
TRANSFER_ENCODING | CONTENT_LENGTH if skip_len => continue,
|
TRANSFER_ENCODING | CONTENT_LENGTH if skip_len => continue,
|
||||||
@ -235,6 +248,10 @@ impl MessageType for Response<()> {
|
|||||||
&self.head().headers
|
&self.head().headers
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn extra_headers(&self) -> Option<&HeaderMap> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
fn encode_status(&mut self, dst: &mut BytesMut) -> io::Result<()> {
|
fn encode_status(&mut self, dst: &mut BytesMut) -> io::Result<()> {
|
||||||
let head = self.head();
|
let head = self.head();
|
||||||
let reason = head.reason().as_bytes();
|
let reason = head.reason().as_bytes();
|
||||||
@ -247,31 +264,36 @@ impl MessageType for Response<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MessageType for RequestHead {
|
impl MessageType for RequestHeadType {
|
||||||
fn status(&self) -> Option<StatusCode> {
|
fn status(&self) -> Option<StatusCode> {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
fn chunked(&self) -> bool {
|
fn chunked(&self) -> bool {
|
||||||
self.chunked()
|
self.as_ref().chunked()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn camel_case(&self) -> bool {
|
fn camel_case(&self) -> bool {
|
||||||
RequestHead::camel_case_headers(self)
|
self.as_ref().camel_case_headers()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn headers(&self) -> &HeaderMap {
|
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<()> {
|
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!(
|
write!(
|
||||||
Writer(dst),
|
Writer(dst),
|
||||||
"{} {} {}",
|
"{} {} {}",
|
||||||
self.method,
|
head.method,
|
||||||
self.uri.path_and_query().map(|u| u.as_str()).unwrap_or("/"),
|
head.uri.path_and_query().map(|u| u.as_str()).unwrap_or("/"),
|
||||||
match self.version {
|
match head.version {
|
||||||
Version::HTTP_09 => "HTTP/0.9",
|
Version::HTTP_09 => "HTTP/0.9",
|
||||||
Version::HTTP_10 => "HTTP/1.0",
|
Version::HTTP_10 => "HTTP/1.0",
|
||||||
Version::HTTP_11 => "HTTP/1.1",
|
Version::HTTP_11 => "HTTP/1.1",
|
||||||
@ -488,9 +510,11 @@ fn write_camel_case(value: &[u8], buffer: &mut [u8]) {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
|
//use std::rc::Rc;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::http::header::{HeaderValue, CONTENT_TYPE};
|
use crate::http::header::{HeaderValue, CONTENT_TYPE};
|
||||||
|
use http::header::AUTHORIZATION;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_chunked_te() {
|
fn test_chunked_te() {
|
||||||
@ -515,6 +539,8 @@ mod tests {
|
|||||||
head.headers
|
head.headers
|
||||||
.insert(CONTENT_TYPE, HeaderValue::from_static("plain/text"));
|
.insert(CONTENT_TYPE, HeaderValue::from_static("plain/text"));
|
||||||
|
|
||||||
|
let mut head = RequestHeadType::Owned(head);
|
||||||
|
|
||||||
let _ = head.encode_headers(
|
let _ = head.encode_headers(
|
||||||
&mut bytes,
|
&mut bytes,
|
||||||
Version::HTTP_11,
|
Version::HTTP_11,
|
||||||
@ -522,10 +548,11 @@ mod tests {
|
|||||||
ConnectionType::Close,
|
ConnectionType::Close,
|
||||||
&ServiceConfig::default(),
|
&ServiceConfig::default(),
|
||||||
);
|
);
|
||||||
assert_eq!(
|
let data = String::from_utf8(Vec::from(bytes.take().freeze().as_ref())).unwrap();
|
||||||
bytes.take().freeze(),
|
assert!(data.contains("Content-Length: 0\r\n"));
|
||||||
Bytes::from_static(b"\r\nContent-Length: 0\r\nConnection: close\r\nDate: date\r\nContent-Type: plain/text\r\n\r\n")
|
assert!(data.contains("Connection: close\r\n"));
|
||||||
);
|
assert!(data.contains("Content-Type: plain/text\r\n"));
|
||||||
|
assert!(data.contains("Date: date\r\n"));
|
||||||
|
|
||||||
let _ = head.encode_headers(
|
let _ = head.encode_headers(
|
||||||
&mut bytes,
|
&mut bytes,
|
||||||
@ -534,10 +561,10 @@ mod tests {
|
|||||||
ConnectionType::KeepAlive,
|
ConnectionType::KeepAlive,
|
||||||
&ServiceConfig::default(),
|
&ServiceConfig::default(),
|
||||||
);
|
);
|
||||||
assert_eq!(
|
let data = String::from_utf8(Vec::from(bytes.take().freeze().as_ref())).unwrap();
|
||||||
bytes.take().freeze(),
|
assert!(data.contains("Transfer-Encoding: chunked\r\n"));
|
||||||
Bytes::from_static(b"\r\nTransfer-Encoding: chunked\r\nDate: date\r\nContent-Type: plain/text\r\n\r\n")
|
assert!(data.contains("Content-Type: plain/text\r\n"));
|
||||||
);
|
assert!(data.contains("Date: date\r\n"));
|
||||||
|
|
||||||
let _ = head.encode_headers(
|
let _ = head.encode_headers(
|
||||||
&mut bytes,
|
&mut bytes,
|
||||||
@ -546,13 +573,20 @@ mod tests {
|
|||||||
ConnectionType::KeepAlive,
|
ConnectionType::KeepAlive,
|
||||||
&ServiceConfig::default(),
|
&ServiceConfig::default(),
|
||||||
);
|
);
|
||||||
assert_eq!(
|
let data = String::from_utf8(Vec::from(bytes.take().freeze().as_ref())).unwrap();
|
||||||
bytes.take().freeze(),
|
assert!(data.contains("Content-Length: 100\r\n"));
|
||||||
Bytes::from_static(b"\r\nContent-Length: 100\r\nDate: date\r\nContent-Type: plain/text\r\n\r\n")
|
assert!(data.contains("Content-Type: plain/text\r\n"));
|
||||||
);
|
assert!(data.contains("Date: date\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
|
head.headers
|
||||||
.append(CONTENT_TYPE, HeaderValue::from_static("xml"));
|
.append(CONTENT_TYPE, HeaderValue::from_static("xml"));
|
||||||
|
|
||||||
|
let mut head = RequestHeadType::Owned(head);
|
||||||
let _ = head.encode_headers(
|
let _ = head.encode_headers(
|
||||||
&mut bytes,
|
&mut bytes,
|
||||||
Version::HTTP_11,
|
Version::HTTP_11,
|
||||||
@ -560,22 +594,43 @@ mod tests {
|
|||||||
ConnectionType::KeepAlive,
|
ConnectionType::KeepAlive,
|
||||||
&ServiceConfig::default(),
|
&ServiceConfig::default(),
|
||||||
);
|
);
|
||||||
assert_eq!(
|
let data = String::from_utf8(Vec::from(bytes.take().freeze().as_ref())).unwrap();
|
||||||
bytes.take().freeze(),
|
assert!(data.contains("transfer-encoding: chunked\r\n"));
|
||||||
Bytes::from_static(b"\r\nTransfer-Encoding: chunked\r\nDate: date\r\nContent-Type: xml\r\nContent-Type: plain/text\r\n\r\n")
|
assert!(data.contains("content-type: xml\r\n"));
|
||||||
|
assert!(data.contains("content-type: plain/text\r\n"));
|
||||||
|
assert!(data.contains("date: date\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"),
|
||||||
);
|
);
|
||||||
|
|
||||||
head.set_camel_case_headers(false);
|
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(
|
let _ = head.encode_headers(
|
||||||
&mut bytes,
|
&mut bytes,
|
||||||
Version::HTTP_11,
|
Version::HTTP_11,
|
||||||
BodySize::Stream,
|
BodySize::Empty,
|
||||||
ConnectionType::KeepAlive,
|
ConnectionType::Close,
|
||||||
&ServiceConfig::default(),
|
&ServiceConfig::default(),
|
||||||
);
|
);
|
||||||
assert_eq!(
|
let data = String::from_utf8(Vec::from(bytes.take().freeze().as_ref())).unwrap();
|
||||||
bytes.take().freeze(),
|
assert!(data.contains("content-length: 0\r\n"));
|
||||||
Bytes::from_static(b"\r\ntransfer-encoding: chunked\r\ndate: date\r\ncontent-type: xml\r\ncontent-type: plain/text\r\n\r\n")
|
assert!(data.contains("connection: close\r\n"));
|
||||||
);
|
assert!(data.contains("authorization: another authorization\r\n"));
|
||||||
|
assert!(data.contains("date: date\r\n"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,16 +1,18 @@
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_codec::Framed;
|
use actix_codec::Framed;
|
||||||
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
|
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
|
||||||
use actix_service::{IntoNewService, NewService, Service};
|
use actix_service::{IntoNewService, NewService, Service};
|
||||||
use actix_utils::cloneable::CloneableService;
|
|
||||||
use futures::future::{ok, FutureResult};
|
use futures::future::{ok, FutureResult};
|
||||||
use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream};
|
use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream};
|
||||||
|
|
||||||
use crate::body::MessageBody;
|
use crate::body::MessageBody;
|
||||||
|
use crate::cloneable::CloneableService;
|
||||||
use crate::config::{KeepAlive, ServiceConfig};
|
use crate::config::{KeepAlive, ServiceConfig};
|
||||||
use crate::error::{DispatchError, Error, ParseError};
|
use crate::error::{DispatchError, Error, ParseError};
|
||||||
|
use crate::helpers::DataFactory;
|
||||||
use crate::request::Request;
|
use crate::request::Request;
|
||||||
use crate::response::Response;
|
use crate::response::Response;
|
||||||
|
|
||||||
@ -24,6 +26,7 @@ pub struct H1Service<T, P, S, B, X = ExpectHandler, U = UpgradeHandler<T>> {
|
|||||||
cfg: ServiceConfig,
|
cfg: ServiceConfig,
|
||||||
expect: X,
|
expect: X,
|
||||||
upgrade: Option<U>,
|
upgrade: Option<U>,
|
||||||
|
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
_t: PhantomData<(T, P, B)>,
|
_t: PhantomData<(T, P, B)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -44,6 +47,7 @@ where
|
|||||||
srv: service.into_new_service(),
|
srv: service.into_new_service(),
|
||||||
expect: ExpectHandler,
|
expect: ExpectHandler,
|
||||||
upgrade: None,
|
upgrade: None,
|
||||||
|
on_connect: None,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -55,6 +59,7 @@ where
|
|||||||
srv: service.into_new_service(),
|
srv: service.into_new_service(),
|
||||||
expect: ExpectHandler,
|
expect: ExpectHandler,
|
||||||
upgrade: None,
|
upgrade: None,
|
||||||
|
on_connect: None,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -79,6 +84,7 @@ where
|
|||||||
cfg: self.cfg,
|
cfg: self.cfg,
|
||||||
srv: self.srv,
|
srv: self.srv,
|
||||||
upgrade: self.upgrade,
|
upgrade: self.upgrade,
|
||||||
|
on_connect: self.on_connect,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -94,9 +100,19 @@ where
|
|||||||
cfg: self.cfg,
|
cfg: self.cfg,
|
||||||
srv: self.srv,
|
srv: self.srv,
|
||||||
expect: self.expect,
|
expect: self.expect,
|
||||||
|
on_connect: self.on_connect,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set on connect callback.
|
||||||
|
pub(crate) fn on_connect(
|
||||||
|
mut self,
|
||||||
|
f: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
|
) -> Self {
|
||||||
|
self.on_connect = f;
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, P, S, B, X, U> NewService for H1Service<T, P, S, B, X, U>
|
impl<T, P, S, B, X, U> NewService for H1Service<T, P, S, B, X, U>
|
||||||
@ -133,6 +149,7 @@ where
|
|||||||
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(cfg)),
|
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(cfg)),
|
||||||
expect: None,
|
expect: None,
|
||||||
upgrade: None,
|
upgrade: None,
|
||||||
|
on_connect: self.on_connect.clone(),
|
||||||
cfg: Some(self.cfg.clone()),
|
cfg: Some(self.cfg.clone()),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
@ -157,6 +174,7 @@ where
|
|||||||
fut_upg: Option<U::Future>,
|
fut_upg: Option<U::Future>,
|
||||||
expect: Option<X::Service>,
|
expect: Option<X::Service>,
|
||||||
upgrade: Option<U::Service>,
|
upgrade: Option<U::Service>,
|
||||||
|
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
cfg: Option<ServiceConfig>,
|
cfg: Option<ServiceConfig>,
|
||||||
_t: PhantomData<(T, P, B)>,
|
_t: PhantomData<(T, P, B)>,
|
||||||
}
|
}
|
||||||
@ -205,6 +223,7 @@ where
|
|||||||
service,
|
service,
|
||||||
self.expect.take().unwrap(),
|
self.expect.take().unwrap(),
|
||||||
self.upgrade.take(),
|
self.upgrade.take(),
|
||||||
|
self.on_connect.clone(),
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -214,6 +233,7 @@ pub struct H1ServiceHandler<T, P, S, B, X, U> {
|
|||||||
srv: CloneableService<S>,
|
srv: CloneableService<S>,
|
||||||
expect: CloneableService<X>,
|
expect: CloneableService<X>,
|
||||||
upgrade: Option<CloneableService<U>>,
|
upgrade: Option<CloneableService<U>>,
|
||||||
|
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
cfg: ServiceConfig,
|
cfg: ServiceConfig,
|
||||||
_t: PhantomData<(T, P, B)>,
|
_t: PhantomData<(T, P, B)>,
|
||||||
}
|
}
|
||||||
@ -234,12 +254,14 @@ where
|
|||||||
srv: S,
|
srv: S,
|
||||||
expect: X,
|
expect: X,
|
||||||
upgrade: Option<U>,
|
upgrade: Option<U>,
|
||||||
|
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
) -> H1ServiceHandler<T, P, S, B, X, U> {
|
) -> H1ServiceHandler<T, P, S, B, X, U> {
|
||||||
H1ServiceHandler {
|
H1ServiceHandler {
|
||||||
srv: CloneableService::new(srv),
|
srv: CloneableService::new(srv),
|
||||||
expect: CloneableService::new(expect),
|
expect: CloneableService::new(expect),
|
||||||
upgrade: upgrade.map(|s| CloneableService::new(s)),
|
upgrade: upgrade.map(CloneableService::new),
|
||||||
cfg,
|
cfg,
|
||||||
|
on_connect,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -292,12 +314,21 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||||
|
let io = req.into_parts().0;
|
||||||
|
|
||||||
|
let on_connect = if let Some(ref on_connect) = self.on_connect {
|
||||||
|
Some(on_connect(&io))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
Dispatcher::new(
|
Dispatcher::new(
|
||||||
req.into_parts().0,
|
io,
|
||||||
self.cfg.clone(),
|
self.cfg.clone(),
|
||||||
self.srv.clone(),
|
self.srv.clone(),
|
||||||
self.expect.clone(),
|
self.expect.clone(),
|
||||||
self.upgrade.clone(),
|
self.upgrade.clone(),
|
||||||
|
on_connect,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,7 +6,6 @@ use std::{fmt, mem, net};
|
|||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
use actix_codec::{AsyncRead, AsyncWrite};
|
||||||
use actix_server_config::IoStream;
|
use actix_server_config::IoStream;
|
||||||
use actix_service::Service;
|
use actix_service::Service;
|
||||||
use actix_utils::cloneable::CloneableService;
|
|
||||||
use bitflags::bitflags;
|
use bitflags::bitflags;
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
use futures::{try_ready, Async, Future, Poll, Sink, Stream};
|
use futures::{try_ready, Async, Future, Poll, Sink, Stream};
|
||||||
@ -20,8 +19,11 @@ use log::{debug, error, trace};
|
|||||||
use tokio_timer::Delay;
|
use tokio_timer::Delay;
|
||||||
|
|
||||||
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
|
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
|
||||||
|
use crate::cloneable::CloneableService;
|
||||||
use crate::config::ServiceConfig;
|
use crate::config::ServiceConfig;
|
||||||
use crate::error::{DispatchError, Error, ParseError, PayloadError, ResponseError};
|
use crate::error::{DispatchError, Error, ParseError, PayloadError, ResponseError};
|
||||||
|
use crate::helpers::DataFactory;
|
||||||
|
use crate::httpmessage::HttpMessage;
|
||||||
use crate::message::ResponseHead;
|
use crate::message::ResponseHead;
|
||||||
use crate::payload::Payload;
|
use crate::payload::Payload;
|
||||||
use crate::request::Request;
|
use crate::request::Request;
|
||||||
@ -33,6 +35,7 @@ const CHUNK_SIZE: usize = 16_384;
|
|||||||
pub struct Dispatcher<T: IoStream, S: Service<Request = Request>, B: MessageBody> {
|
pub struct Dispatcher<T: IoStream, S: Service<Request = Request>, B: MessageBody> {
|
||||||
service: CloneableService<S>,
|
service: CloneableService<S>,
|
||||||
connection: Connection<T, Bytes>,
|
connection: Connection<T, Bytes>,
|
||||||
|
on_connect: Option<Box<dyn DataFactory>>,
|
||||||
config: ServiceConfig,
|
config: ServiceConfig,
|
||||||
peer_addr: Option<net::SocketAddr>,
|
peer_addr: Option<net::SocketAddr>,
|
||||||
ka_expire: Instant,
|
ka_expire: Instant,
|
||||||
@ -49,9 +52,10 @@ where
|
|||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
{
|
{
|
||||||
pub fn new(
|
pub(crate) fn new(
|
||||||
service: CloneableService<S>,
|
service: CloneableService<S>,
|
||||||
connection: Connection<T, Bytes>,
|
connection: Connection<T, Bytes>,
|
||||||
|
on_connect: Option<Box<dyn DataFactory>>,
|
||||||
config: ServiceConfig,
|
config: ServiceConfig,
|
||||||
timeout: Option<Delay>,
|
timeout: Option<Delay>,
|
||||||
peer_addr: Option<net::SocketAddr>,
|
peer_addr: Option<net::SocketAddr>,
|
||||||
@ -77,6 +81,7 @@ where
|
|||||||
config,
|
config,
|
||||||
peer_addr,
|
peer_addr,
|
||||||
connection,
|
connection,
|
||||||
|
on_connect,
|
||||||
ka_expire,
|
ka_expire,
|
||||||
ka_timer,
|
ka_timer,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
@ -118,6 +123,12 @@ where
|
|||||||
head.version = parts.version;
|
head.version = parts.version;
|
||||||
head.headers = parts.headers.into();
|
head.headers = parts.headers.into();
|
||||||
head.peer_addr = self.peer_addr;
|
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> {
|
tokio_current_thread::spawn(ServiceResponse::<S::Future, B> {
|
||||||
state: ServiceResponseState::ServiceCall(
|
state: ServiceResponseState::ServiceCall(
|
||||||
self.service.call(req),
|
self.service.call(req),
|
||||||
@ -246,8 +257,8 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||||
Err(_e) => {
|
Err(e) => {
|
||||||
let res: Response = Response::InternalServerError().finish();
|
let res: Response = e.into().into();
|
||||||
let (res, body) = res.replace_body(());
|
let (res, body) = res.replace_body(());
|
||||||
|
|
||||||
let mut send = send.take().unwrap();
|
let mut send = send.take().unwrap();
|
||||||
|
@ -1,11 +1,10 @@
|
|||||||
use std::fmt::Debug;
|
use std::fmt::Debug;
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::{io, net};
|
use std::{io, net, rc};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||||
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
|
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
|
||||||
use actix_service::{IntoNewService, NewService, Service};
|
use actix_service::{IntoNewService, NewService, Service};
|
||||||
use actix_utils::cloneable::CloneableService;
|
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use futures::future::{ok, FutureResult};
|
use futures::future::{ok, FutureResult};
|
||||||
use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream};
|
use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream};
|
||||||
@ -14,8 +13,10 @@ use h2::RecvStream;
|
|||||||
use log::error;
|
use log::error;
|
||||||
|
|
||||||
use crate::body::MessageBody;
|
use crate::body::MessageBody;
|
||||||
|
use crate::cloneable::CloneableService;
|
||||||
use crate::config::{KeepAlive, ServiceConfig};
|
use crate::config::{KeepAlive, ServiceConfig};
|
||||||
use crate::error::{DispatchError, Error, ParseError, ResponseError};
|
use crate::error::{DispatchError, Error, ParseError, ResponseError};
|
||||||
|
use crate::helpers::DataFactory;
|
||||||
use crate::payload::Payload;
|
use crate::payload::Payload;
|
||||||
use crate::request::Request;
|
use crate::request::Request;
|
||||||
use crate::response::Response;
|
use crate::response::Response;
|
||||||
@ -26,6 +27,7 @@ use super::dispatcher::Dispatcher;
|
|||||||
pub struct H2Service<T, P, S, B> {
|
pub struct H2Service<T, P, S, B> {
|
||||||
srv: S,
|
srv: S,
|
||||||
cfg: ServiceConfig,
|
cfg: ServiceConfig,
|
||||||
|
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
_t: PhantomData<(T, P, B)>,
|
_t: PhantomData<(T, P, B)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -43,6 +45,7 @@ where
|
|||||||
|
|
||||||
H2Service {
|
H2Service {
|
||||||
cfg,
|
cfg,
|
||||||
|
on_connect: None,
|
||||||
srv: service.into_new_service(),
|
srv: service.into_new_service(),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
@ -52,10 +55,20 @@ where
|
|||||||
pub fn with_config<F: IntoNewService<S>>(cfg: ServiceConfig, service: F) -> Self {
|
pub fn with_config<F: IntoNewService<S>>(cfg: ServiceConfig, service: F) -> Self {
|
||||||
H2Service {
|
H2Service {
|
||||||
cfg,
|
cfg,
|
||||||
|
on_connect: None,
|
||||||
srv: service.into_new_service(),
|
srv: service.into_new_service(),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set on connect callback.
|
||||||
|
pub(crate) fn on_connect(
|
||||||
|
mut self,
|
||||||
|
f: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
|
) -> Self {
|
||||||
|
self.on_connect = f;
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, P, S, B> NewService for H2Service<T, P, S, B>
|
impl<T, P, S, B> NewService for H2Service<T, P, S, B>
|
||||||
@ -79,6 +92,7 @@ where
|
|||||||
H2ServiceResponse {
|
H2ServiceResponse {
|
||||||
fut: self.srv.new_service(cfg).into_future(),
|
fut: self.srv.new_service(cfg).into_future(),
|
||||||
cfg: Some(self.cfg.clone()),
|
cfg: Some(self.cfg.clone()),
|
||||||
|
on_connect: self.on_connect.clone(),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -88,6 +102,7 @@ where
|
|||||||
pub struct H2ServiceResponse<T, P, S: NewService, B> {
|
pub struct H2ServiceResponse<T, P, S: NewService, B> {
|
||||||
fut: <S::Future as IntoFuture>::Future,
|
fut: <S::Future as IntoFuture>::Future,
|
||||||
cfg: Option<ServiceConfig>,
|
cfg: Option<ServiceConfig>,
|
||||||
|
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
_t: PhantomData<(T, P, B)>,
|
_t: PhantomData<(T, P, B)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -107,6 +122,7 @@ where
|
|||||||
let service = try_ready!(self.fut.poll());
|
let service = try_ready!(self.fut.poll());
|
||||||
Ok(Async::Ready(H2ServiceHandler::new(
|
Ok(Async::Ready(H2ServiceHandler::new(
|
||||||
self.cfg.take().unwrap(),
|
self.cfg.take().unwrap(),
|
||||||
|
self.on_connect.clone(),
|
||||||
service,
|
service,
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
@ -116,6 +132,7 @@ where
|
|||||||
pub struct H2ServiceHandler<T, P, S, B> {
|
pub struct H2ServiceHandler<T, P, S, B> {
|
||||||
srv: CloneableService<S>,
|
srv: CloneableService<S>,
|
||||||
cfg: ServiceConfig,
|
cfg: ServiceConfig,
|
||||||
|
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
_t: PhantomData<(T, P, B)>,
|
_t: PhantomData<(T, P, B)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -127,9 +144,14 @@ where
|
|||||||
S::Response: Into<Response<B>>,
|
S::Response: Into<Response<B>>,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
{
|
{
|
||||||
fn new(cfg: ServiceConfig, srv: S) -> H2ServiceHandler<T, P, S, B> {
|
fn new(
|
||||||
|
cfg: ServiceConfig,
|
||||||
|
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
|
srv: S,
|
||||||
|
) -> H2ServiceHandler<T, P, S, B> {
|
||||||
H2ServiceHandler {
|
H2ServiceHandler {
|
||||||
cfg,
|
cfg,
|
||||||
|
on_connect,
|
||||||
srv: CloneableService::new(srv),
|
srv: CloneableService::new(srv),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
@ -161,11 +183,18 @@ where
|
|||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||||
let io = req.into_parts().0;
|
let io = req.into_parts().0;
|
||||||
let peer_addr = io.peer_addr();
|
let peer_addr = io.peer_addr();
|
||||||
|
let on_connect = if let Some(ref on_connect) = self.on_connect {
|
||||||
|
Some(on_connect(&io))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
H2ServiceHandlerResponse {
|
H2ServiceHandlerResponse {
|
||||||
state: State::Handshake(
|
state: State::Handshake(
|
||||||
Some(self.srv.clone()),
|
Some(self.srv.clone()),
|
||||||
Some(self.cfg.clone()),
|
Some(self.cfg.clone()),
|
||||||
peer_addr,
|
peer_addr,
|
||||||
|
on_connect,
|
||||||
server::handshake(io),
|
server::handshake(io),
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
@ -181,6 +210,7 @@ where
|
|||||||
Option<CloneableService<S>>,
|
Option<CloneableService<S>>,
|
||||||
Option<ServiceConfig>,
|
Option<ServiceConfig>,
|
||||||
Option<net::SocketAddr>,
|
Option<net::SocketAddr>,
|
||||||
|
Option<Box<dyn DataFactory>>,
|
||||||
Handshake<T, Bytes>,
|
Handshake<T, Bytes>,
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
@ -216,15 +246,17 @@ where
|
|||||||
ref mut srv,
|
ref mut srv,
|
||||||
ref mut config,
|
ref mut config,
|
||||||
ref peer_addr,
|
ref peer_addr,
|
||||||
|
ref mut on_connect,
|
||||||
ref mut handshake,
|
ref mut handshake,
|
||||||
) => match handshake.poll() {
|
) => match handshake.poll() {
|
||||||
Ok(Async::Ready(conn)) => {
|
Ok(Async::Ready(conn)) => {
|
||||||
self.state = State::Incoming(Dispatcher::new(
|
self.state = State::Incoming(Dispatcher::new(
|
||||||
srv.take().unwrap(),
|
srv.take().unwrap(),
|
||||||
conn,
|
conn,
|
||||||
|
on_connect.take(),
|
||||||
config.take().unwrap(),
|
config.take().unwrap(),
|
||||||
None,
|
None,
|
||||||
peer_addr.clone(),
|
*peer_addr,
|
||||||
));
|
));
|
||||||
self.poll()
|
self.poll()
|
||||||
}
|
}
|
||||||
|
@ -70,11 +70,17 @@ impl<'a> From<&'a str> for DispositionType {
|
|||||||
/// assert_eq!(param.as_filename().unwrap(), "sample.txt");
|
/// assert_eq!(param.as_filename().unwrap(), "sample.txt");
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
#[allow(clippy::large_enum_variant)]
|
||||||
pub enum DispositionParam {
|
pub enum DispositionParam {
|
||||||
/// For [`DispositionType::FormData`] (i.e. *multipart/form-data*), the name of an field from
|
/// For [`DispositionType::FormData`] (i.e. *multipart/form-data*), the name of an field from
|
||||||
/// the form.
|
/// the form.
|
||||||
Name(String),
|
Name(String),
|
||||||
/// A plain file name.
|
/// A plain file name.
|
||||||
|
///
|
||||||
|
/// It is [not supposed](https://tools.ietf.org/html/rfc6266#appendix-D) to contain any
|
||||||
|
/// non-ASCII characters when used in a *Content-Disposition* HTTP response header, where
|
||||||
|
/// [`FilenameExt`](DispositionParam::FilenameExt) with charset UTF-8 may be used instead
|
||||||
|
/// in case there are Unicode characters in file names.
|
||||||
Filename(String),
|
Filename(String),
|
||||||
/// An extended file name. It must not exist for `ContentType::Formdata` according to
|
/// An extended file name. It must not exist for `ContentType::Formdata` according to
|
||||||
/// [RFC7578 Section 4.2](https://tools.ietf.org/html/rfc7578#section-4.2).
|
/// [RFC7578 Section 4.2](https://tools.ietf.org/html/rfc7578#section-4.2).
|
||||||
@ -219,7 +225,16 @@ impl DispositionParam {
|
|||||||
/// ext-token = <the characters in token, followed by "*">
|
/// ext-token = <the characters in token, followed by "*">
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// **Note**: filename* [must not](https://tools.ietf.org/html/rfc7578#section-4.2) be used within
|
/// # Note
|
||||||
|
///
|
||||||
|
/// filename is [not supposed](https://tools.ietf.org/html/rfc6266#appendix-D) to contain any
|
||||||
|
/// non-ASCII characters when used in a *Content-Disposition* HTTP response header, where
|
||||||
|
/// filename* with charset UTF-8 may be used instead in case there are Unicode characters in file
|
||||||
|
/// names.
|
||||||
|
/// filename is [acceptable](https://tools.ietf.org/html/rfc7578#section-4.2) to be UTF-8 encoded
|
||||||
|
/// directly in a *Content-Disposition* header for *multipart/form-data*, though.
|
||||||
|
///
|
||||||
|
/// filename* [must not](https://tools.ietf.org/html/rfc7578#section-4.2) be used within
|
||||||
/// *multipart/form-data*.
|
/// *multipart/form-data*.
|
||||||
///
|
///
|
||||||
/// # Example
|
/// # Example
|
||||||
@ -250,6 +265,22 @@ impl DispositionParam {
|
|||||||
/// };
|
/// };
|
||||||
/// assert_eq!(cd2.get_name(), Some("file")); // field name
|
/// assert_eq!(cd2.get_name(), Some("file")); // field name
|
||||||
/// assert_eq!(cd2.get_filename(), Some("bill.odt"));
|
/// assert_eq!(cd2.get_filename(), Some("bill.odt"));
|
||||||
|
///
|
||||||
|
/// // HTTP response header with Unicode characters in file names
|
||||||
|
/// let cd3 = ContentDisposition {
|
||||||
|
/// disposition: DispositionType::Attachment,
|
||||||
|
/// parameters: vec![
|
||||||
|
/// DispositionParam::FilenameExt(ExtendedValue {
|
||||||
|
/// charset: Charset::Ext(String::from("UTF-8")),
|
||||||
|
/// language_tag: None,
|
||||||
|
/// value: String::from("\u{1f600}.svg").into_bytes(),
|
||||||
|
/// }),
|
||||||
|
/// // fallback for better compatibility
|
||||||
|
/// DispositionParam::Filename(String::from("Grinning-Face-Emoji.svg"))
|
||||||
|
/// ],
|
||||||
|
/// };
|
||||||
|
/// assert_eq!(cd3.get_filename_ext().map(|ev| ev.value.as_ref()),
|
||||||
|
/// Some("\u{1f600}.svg".as_bytes()));
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// # WARN
|
/// # WARN
|
||||||
@ -332,15 +363,17 @@ impl ContentDisposition {
|
|||||||
// token: won't contains semicolon according to RFC 2616 Section 2.2
|
// token: won't contains semicolon according to RFC 2616 Section 2.2
|
||||||
let (token, new_left) = split_once_and_trim(left, ';');
|
let (token, new_left) = split_once_and_trim(left, ';');
|
||||||
left = new_left;
|
left = new_left;
|
||||||
token.to_owned()
|
if token.is_empty() {
|
||||||
};
|
// quoted-string can be empty, but token cannot be empty
|
||||||
if value.is_empty() {
|
|
||||||
return Err(crate::error::ParseError::Header);
|
return Err(crate::error::ParseError::Header);
|
||||||
}
|
}
|
||||||
|
token.to_owned()
|
||||||
|
};
|
||||||
|
|
||||||
let param = if param_name.eq_ignore_ascii_case("name") {
|
let param = if param_name.eq_ignore_ascii_case("name") {
|
||||||
DispositionParam::Name(value)
|
DispositionParam::Name(value)
|
||||||
} else if param_name.eq_ignore_ascii_case("filename") {
|
} else if param_name.eq_ignore_ascii_case("filename") {
|
||||||
|
// See also comments in test_from_raw_uncessary_percent_decode.
|
||||||
DispositionParam::Filename(value)
|
DispositionParam::Filename(value)
|
||||||
} else {
|
} else {
|
||||||
DispositionParam::Unknown(param_name.to_owned(), value)
|
DispositionParam::Unknown(param_name.to_owned(), value)
|
||||||
@ -465,11 +498,40 @@ impl fmt::Display for DispositionType {
|
|||||||
|
|
||||||
impl fmt::Display for DispositionParam {
|
impl fmt::Display for DispositionParam {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
// All ASCII control charaters (0-30, 127) excepting horizontal tab, double quote, and
|
// All ASCII control characters (0-30, 127) including horizontal tab, double quote, and
|
||||||
// backslash should be escaped in quoted-string (i.e. "foobar").
|
// backslash should be escaped in quoted-string (i.e. "foobar").
|
||||||
// Ref: RFC6266 S4.1 -> RFC2616 S2.2; RFC 7578 S4.2 -> RFC2183 S2 -> ... .
|
// Ref: RFC6266 S4.1 -> RFC2616 S3.6
|
||||||
|
// filename-parm = "filename" "=" value
|
||||||
|
// value = token | quoted-string
|
||||||
|
// quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
|
||||||
|
// qdtext = <any TEXT except <">>
|
||||||
|
// quoted-pair = "\" CHAR
|
||||||
|
// TEXT = <any OCTET except CTLs,
|
||||||
|
// but including LWS>
|
||||||
|
// LWS = [CRLF] 1*( SP | HT )
|
||||||
|
// OCTET = <any 8-bit sequence of data>
|
||||||
|
// CHAR = <any US-ASCII character (octets 0 - 127)>
|
||||||
|
// CTL = <any US-ASCII control character
|
||||||
|
// (octets 0 - 31) and DEL (127)>
|
||||||
|
//
|
||||||
|
// Ref: RFC7578 S4.2 -> RFC2183 S2 -> RFC2045 S5.1
|
||||||
|
// parameter := attribute "=" value
|
||||||
|
// attribute := token
|
||||||
|
// ; Matching of attributes
|
||||||
|
// ; is ALWAYS case-insensitive.
|
||||||
|
// value := token / quoted-string
|
||||||
|
// token := 1*<any (US-ASCII) CHAR except SPACE, CTLs,
|
||||||
|
// or tspecials>
|
||||||
|
// tspecials := "(" / ")" / "<" / ">" / "@" /
|
||||||
|
// "," / ";" / ":" / "\" / <">
|
||||||
|
// "/" / "[" / "]" / "?" / "="
|
||||||
|
// ; Must be in quoted-string,
|
||||||
|
// ; to use within parameter values
|
||||||
|
//
|
||||||
|
//
|
||||||
|
// See also comments in test_from_raw_uncessary_percent_decode.
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
static ref RE: Regex = Regex::new("[\x01-\x08\x10\x1F\x7F\"\\\\]").unwrap();
|
static ref RE: Regex = Regex::new("[\x00-\x08\x10-\x1F\x7F\"\\\\]").unwrap();
|
||||||
}
|
}
|
||||||
match self {
|
match self {
|
||||||
DispositionParam::Name(ref value) => write!(f, "name={}", value),
|
DispositionParam::Name(ref value) => write!(f, "name={}", value),
|
||||||
@ -719,8 +781,10 @@ mod tests {
|
|||||||
};
|
};
|
||||||
assert_eq!(a, b);
|
assert_eq!(a, b);
|
||||||
|
|
||||||
let a =
|
let a = HeaderValue::from_str(
|
||||||
HeaderValue::from_str("form-data; name=upload; filename=\"余固知謇謇之為患兮,忍而不能舍也.pptx\"").unwrap();
|
"form-data; name=upload; filename=\"余固知謇謇之為患兮,忍而不能舍也.pptx\"",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
||||||
let b = ContentDisposition {
|
let b = ContentDisposition {
|
||||||
disposition: DispositionType::FormData,
|
disposition: DispositionType::FormData,
|
||||||
@ -771,8 +835,18 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_from_raw_uncessary_percent_decode() {
|
fn test_from_raw_uncessary_percent_decode() {
|
||||||
|
// In fact, RFC7578 (multipart/form-data) Section 2 and 4.2 suggests that filename with
|
||||||
|
// non-ASCII characters MAY be percent-encoded.
|
||||||
|
// On the contrary, RFC6266 or other RFCs related to Content-Disposition response header
|
||||||
|
// do not mention such percent-encoding.
|
||||||
|
// So, it appears to be undecidable whether to percent-decode or not without
|
||||||
|
// knowing the usage scenario (multipart/form-data v.s. HTTP response header) and
|
||||||
|
// inevitable to unnecessarily percent-decode filename with %XX in the former scenario.
|
||||||
|
// Fortunately, it seems that almost all mainstream browsers just send UTF-8 encoded file
|
||||||
|
// names in quoted-string format (tested on Edge, IE11, Chrome and Firefox) without
|
||||||
|
// percent-encoding. So we do not bother to attempt to percent-decode.
|
||||||
let a = HeaderValue::from_static(
|
let a = HeaderValue::from_static(
|
||||||
"form-data; name=photo; filename=\"%74%65%73%74%2e%70%6e%67\"", // Should not be decoded!
|
"form-data; name=photo; filename=\"%74%65%73%74%2e%70%6e%67\"",
|
||||||
);
|
);
|
||||||
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
||||||
let b = ContentDisposition {
|
let b = ContentDisposition {
|
||||||
@ -808,6 +882,9 @@ mod tests {
|
|||||||
|
|
||||||
let a = HeaderValue::from_static("inline; filename= ");
|
let a = HeaderValue::from_static("inline; filename= ");
|
||||||
assert!(ContentDisposition::from_raw(&a).is_err());
|
assert!(ContentDisposition::from_raw(&a).is_err());
|
||||||
|
|
||||||
|
let a = HeaderValue::from_static("inline; filename=\"\"");
|
||||||
|
assert!(ContentDisposition::from_raw(&a).expect("parse cd").get_filename().expect("filename").is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -9,12 +9,12 @@ use http::HttpTryFrom;
|
|||||||
/// `HeaderMap` is an multimap of [`HeaderName`] to values.
|
/// `HeaderMap` is an multimap of [`HeaderName`] to values.
|
||||||
///
|
///
|
||||||
/// [`HeaderName`]: struct.HeaderName.html
|
/// [`HeaderName`]: struct.HeaderName.html
|
||||||
#[derive(Debug)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct HeaderMap {
|
pub struct HeaderMap {
|
||||||
pub(crate) inner: HashMap<HeaderName, Value>,
|
pub(crate) inner: HashMap<HeaderName, Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug, Clone)]
|
||||||
pub(crate) enum Value {
|
pub(crate) enum Value {
|
||||||
One(HeaderValue),
|
One(HeaderValue),
|
||||||
Multi(Vec<HeaderValue>),
|
Multi(Vec<HeaderValue>),
|
||||||
|
@ -6,6 +6,7 @@ use std::{fmt, str::FromStr};
|
|||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
use http::Error as HttpError;
|
use http::Error as HttpError;
|
||||||
use mime::Mime;
|
use mime::Mime;
|
||||||
|
use percent_encoding::{AsciiSet, CONTROLS};
|
||||||
|
|
||||||
pub use http::header::*;
|
pub use http::header::*;
|
||||||
|
|
||||||
@ -15,7 +16,6 @@ use crate::httpmessage::HttpMessage;
|
|||||||
mod common;
|
mod common;
|
||||||
pub(crate) mod map;
|
pub(crate) mod map;
|
||||||
mod shared;
|
mod shared;
|
||||||
#[doc(hidden)]
|
|
||||||
pub use self::common::*;
|
pub use self::common::*;
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub use self::shared::*;
|
pub use self::shared::*;
|
||||||
@ -361,10 +361,8 @@ pub fn parse_extended_value(
|
|||||||
|
|
||||||
impl fmt::Display for ExtendedValue {
|
impl fmt::Display for ExtendedValue {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
let encoded_value = percent_encoding::percent_encode(
|
let encoded_value =
|
||||||
&self.value[..],
|
percent_encoding::percent_encode(&self.value[..], HTTP_VALUE);
|
||||||
self::percent_encoding_http::HTTP_VALUE,
|
|
||||||
);
|
|
||||||
if let Some(ref lang) = self.language_tag {
|
if let Some(ref lang) = self.language_tag {
|
||||||
write!(f, "{}'{}'{}", self.charset, lang, encoded_value)
|
write!(f, "{}'{}'{}", self.charset, lang, encoded_value)
|
||||||
} else {
|
} else {
|
||||||
@ -378,8 +376,7 @@ impl fmt::Display for ExtendedValue {
|
|||||||
///
|
///
|
||||||
/// [url]: https://tools.ietf.org/html/rfc5987#section-3.2
|
/// [url]: https://tools.ietf.org/html/rfc5987#section-3.2
|
||||||
pub fn http_percent_encode(f: &mut fmt::Formatter, bytes: &[u8]) -> fmt::Result {
|
pub fn http_percent_encode(f: &mut fmt::Formatter, bytes: &[u8]) -> fmt::Result {
|
||||||
let encoded =
|
let encoded = percent_encoding::percent_encode(bytes, HTTP_VALUE);
|
||||||
percent_encoding::percent_encode(bytes, self::percent_encoding_http::HTTP_VALUE);
|
|
||||||
fmt::Display::fmt(&encoded, f)
|
fmt::Display::fmt(&encoded, f)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -394,20 +391,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
|
// This encode set is used for HTTP header values and is defined at
|
||||||
// https://tools.ietf.org/html/rfc5987#section-3.2
|
// https://tools.ietf.org/html/rfc5987#section-3.2
|
||||||
pub HTTP_VALUE = [percent_encoding::SIMPLE_ENCODE_SET] | {
|
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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
@ -3,6 +3,8 @@ use std::{io, mem, ptr, slice};
|
|||||||
use bytes::{BufMut, BytesMut};
|
use bytes::{BufMut, BytesMut};
|
||||||
use http::Version;
|
use http::Version;
|
||||||
|
|
||||||
|
use crate::extensions::Extensions;
|
||||||
|
|
||||||
const DEC_DIGITS_LUT: &[u8] = b"0001020304050607080910111213141516171819\
|
const DEC_DIGITS_LUT: &[u8] = b"0001020304050607080910111213141516171819\
|
||||||
2021222324252627282930313233343536373839\
|
2021222324252627282930313233343536373839\
|
||||||
4041424344454647484950515253545556575859\
|
4041424344454647484950515253545556575859\
|
||||||
@ -113,7 +115,7 @@ pub fn write_content_length(mut n: usize, bytes: &mut BytesMut) {
|
|||||||
|
|
||||||
pub(crate) fn convert_usize(mut n: usize, bytes: &mut BytesMut) {
|
pub(crate) fn convert_usize(mut n: usize, bytes: &mut BytesMut) {
|
||||||
let mut curr: isize = 39;
|
let mut curr: isize = 39;
|
||||||
let mut buf: [u8; 41] = unsafe { mem::uninitialized() };
|
let mut buf: [u8; 41] = unsafe { mem::MaybeUninit::uninit().assume_init() };
|
||||||
buf[39] = b'\r';
|
buf[39] = b'\r';
|
||||||
buf[40] = b'\n';
|
buf[40] = b'\n';
|
||||||
let buf_ptr = buf.as_mut_ptr();
|
let buf_ptr = buf.as_mut_ptr();
|
||||||
@ -180,6 +182,18 @@ impl<'a> io::Write for Writer<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) trait DataFactory {
|
||||||
|
fn set(&self, ext: &mut Extensions);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct Data<T>(pub(crate) T);
|
||||||
|
|
||||||
|
impl<T: Clone + 'static> DataFactory for Data<T> {
|
||||||
|
fn set(&self, ext: &mut Extensions) {
|
||||||
|
ext.insert(self.0.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
@ -29,7 +29,6 @@ impl Response {
|
|||||||
STATIC_RESP!(AlreadyReported, StatusCode::ALREADY_REPORTED);
|
STATIC_RESP!(AlreadyReported, StatusCode::ALREADY_REPORTED);
|
||||||
|
|
||||||
STATIC_RESP!(MultipleChoices, StatusCode::MULTIPLE_CHOICES);
|
STATIC_RESP!(MultipleChoices, StatusCode::MULTIPLE_CHOICES);
|
||||||
STATIC_RESP!(MovedPermanenty, StatusCode::MOVED_PERMANENTLY);
|
|
||||||
STATIC_RESP!(MovedPermanently, StatusCode::MOVED_PERMANENTLY);
|
STATIC_RESP!(MovedPermanently, StatusCode::MOVED_PERMANENTLY);
|
||||||
STATIC_RESP!(Found, StatusCode::FOUND);
|
STATIC_RESP!(Found, StatusCode::FOUND);
|
||||||
STATIC_RESP!(SeeOther, StatusCode::SEE_OTHER);
|
STATIC_RESP!(SeeOther, StatusCode::SEE_OTHER);
|
||||||
@ -61,6 +60,7 @@ impl Response {
|
|||||||
STATIC_RESP!(RangeNotSatisfiable, StatusCode::RANGE_NOT_SATISFIABLE);
|
STATIC_RESP!(RangeNotSatisfiable, StatusCode::RANGE_NOT_SATISFIABLE);
|
||||||
STATIC_RESP!(ExpectationFailed, StatusCode::EXPECTATION_FAILED);
|
STATIC_RESP!(ExpectationFailed, StatusCode::EXPECTATION_FAILED);
|
||||||
STATIC_RESP!(UnprocessableEntity, StatusCode::UNPROCESSABLE_ENTITY);
|
STATIC_RESP!(UnprocessableEntity, StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
STATIC_RESP!(TooManyRequests, StatusCode::TOO_MANY_REQUESTS);
|
||||||
|
|
||||||
STATIC_RESP!(InternalServerError, StatusCode::INTERNAL_SERVER_ERROR);
|
STATIC_RESP!(InternalServerError, StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
STATIC_RESP!(NotImplemented, StatusCode::NOT_IMPLEMENTED);
|
STATIC_RESP!(NotImplemented, StatusCode::NOT_IMPLEMENTED);
|
||||||
|
@ -1,9 +1,7 @@
|
|||||||
use std::cell::{Ref, RefMut};
|
use std::cell::{Ref, RefMut};
|
||||||
use std::str;
|
use std::str;
|
||||||
|
|
||||||
use encoding::all::UTF_8;
|
use encoding_rs::{Encoding, UTF_8};
|
||||||
use encoding::label::encoding_from_whatwg_label;
|
|
||||||
use encoding::EncodingRef;
|
|
||||||
use http::header;
|
use http::header;
|
||||||
use mime::Mime;
|
use mime::Mime;
|
||||||
|
|
||||||
@ -59,10 +57,12 @@ pub trait HttpMessage: Sized {
|
|||||||
/// Get content type encoding
|
/// Get content type encoding
|
||||||
///
|
///
|
||||||
/// UTF-8 is used by default, If request charset is not set.
|
/// UTF-8 is used by default, If request charset is not set.
|
||||||
fn encoding(&self) -> Result<EncodingRef, ContentTypeError> {
|
fn encoding(&self) -> Result<&'static Encoding, ContentTypeError> {
|
||||||
if let Some(mime_type) = self.mime_type()? {
|
if let Some(mime_type) = self.mime_type()? {
|
||||||
if let Some(charset) = mime_type.get_param("charset") {
|
if let Some(charset) = mime_type.get_param("charset") {
|
||||||
if let Some(enc) = encoding_from_whatwg_label(charset.as_str()) {
|
if let Some(enc) =
|
||||||
|
Encoding::for_label_no_replacement(charset.as_str().as_bytes())
|
||||||
|
{
|
||||||
Ok(enc)
|
Ok(enc)
|
||||||
} else {
|
} else {
|
||||||
Err(ContentTypeError::UnknownEncoding)
|
Err(ContentTypeError::UnknownEncoding)
|
||||||
@ -166,8 +166,7 @@ where
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use encoding::all::ISO_8859_2;
|
use encoding_rs::ISO_8859_2;
|
||||||
use encoding::Encoding;
|
|
||||||
use mime;
|
use mime;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
@ -223,7 +222,7 @@ mod tests {
|
|||||||
"application/json; charset=ISO-8859-2",
|
"application/json; charset=ISO-8859-2",
|
||||||
)
|
)
|
||||||
.finish();
|
.finish();
|
||||||
assert_eq!(ISO_8859_2.name(), req.encoding().unwrap().name());
|
assert_eq!(ISO_8859_2, req.encoding().unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -1,8 +1,10 @@
|
|||||||
//! Basic http primitives for actix-net framework.
|
//! Basic http primitives for actix-net framework.
|
||||||
#![allow(
|
#![allow(
|
||||||
clippy::type_complexity,
|
clippy::type_complexity,
|
||||||
|
clippy::too_many_arguments,
|
||||||
clippy::new_without_default,
|
clippy::new_without_default,
|
||||||
clippy::borrow_interior_mutable_const
|
clippy::borrow_interior_mutable_const,
|
||||||
|
clippy::write_with_newline
|
||||||
)]
|
)]
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
@ -11,6 +13,7 @@ extern crate log;
|
|||||||
pub mod body;
|
pub mod body;
|
||||||
mod builder;
|
mod builder;
|
||||||
pub mod client;
|
pub mod client;
|
||||||
|
mod cloneable;
|
||||||
mod config;
|
mod config;
|
||||||
pub mod encoding;
|
pub mod encoding;
|
||||||
mod extensions;
|
mod extensions;
|
||||||
@ -36,7 +39,7 @@ pub use self::config::{KeepAlive, ServiceConfig};
|
|||||||
pub use self::error::{Error, ResponseError, Result};
|
pub use self::error::{Error, ResponseError, Result};
|
||||||
pub use self::extensions::Extensions;
|
pub use self::extensions::Extensions;
|
||||||
pub use self::httpmessage::HttpMessage;
|
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::payload::{Payload, PayloadStream};
|
||||||
pub use self::request::Request;
|
pub use self::request::Request;
|
||||||
pub use self::response::{Response, ResponseBuilder};
|
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)]
|
#[derive(Debug)]
|
||||||
pub struct ResponseHead {
|
pub struct ResponseHead {
|
||||||
pub version: Version,
|
pub version: Version,
|
||||||
@ -385,6 +415,7 @@ impl Drop for BoxedResponseHead {
|
|||||||
pub struct MessagePool<T: Head>(RefCell<Vec<Rc<T>>>);
|
pub struct MessagePool<T: Head>(RefCell<Vec<Rc<T>>>);
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
|
#[allow(clippy::vec_box)]
|
||||||
/// Request's objects pool
|
/// Request's objects pool
|
||||||
pub struct BoxedResponsePool(RefCell<Vec<Box<ResponseHead>>>);
|
pub struct BoxedResponsePool(RefCell<Vec<Box<ResponseHead>>>);
|
||||||
|
|
||||||
|
@ -52,6 +52,9 @@ impl Response<Body> {
|
|||||||
#[inline]
|
#[inline]
|
||||||
pub fn from_error(error: Error) -> Response {
|
pub fn from_error(error: Error) -> Response {
|
||||||
let mut resp = error.as_response_error().render_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.error = Some(error);
|
||||||
resp
|
resp
|
||||||
}
|
}
|
||||||
@ -191,7 +194,7 @@ impl<B> Response<B> {
|
|||||||
self.head.extensions.borrow_mut()
|
self.head.extensions.borrow_mut()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get body os this response
|
/// Get body of this response
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn body(&self) -> &ResponseBody<B> {
|
pub fn body(&self) -> &ResponseBody<B> {
|
||||||
&self.body
|
&self.body
|
||||||
@ -764,6 +767,25 @@ impl IntoFuture for ResponseBuilder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for ResponseBuilder {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
let head = self.head.as_ref().unwrap();
|
||||||
|
|
||||||
|
let res = writeln!(
|
||||||
|
f,
|
||||||
|
"\nResponseBuilder {:?} {}{}",
|
||||||
|
head.version,
|
||||||
|
head.status,
|
||||||
|
head.reason.unwrap_or(""),
|
||||||
|
);
|
||||||
|
let _ = writeln!(f, " headers:");
|
||||||
|
for (key, val) in head.headers.iter() {
|
||||||
|
let _ = writeln!(f, " {:?}: {:?}", key, val);
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Helper converters
|
/// Helper converters
|
||||||
impl<I: Into<Response>, E: Into<Error>> From<Result<I, E>> for Response {
|
impl<I: Into<Response>, E: Into<Error>> From<Result<I, E>> for Response {
|
||||||
fn from(res: Result<I, E>) -> Self {
|
fn from(res: Result<I, E>) -> Self {
|
||||||
@ -970,6 +992,14 @@ mod tests {
|
|||||||
assert_eq!(resp.body().get_ref(), b"[\"v1\",\"v2\",\"v3\"]");
|
assert_eq!(resp.body().get_ref(), b"[\"v1\",\"v2\",\"v3\"]");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_serde_json_in_body() {
|
||||||
|
use serde_json::json;
|
||||||
|
let resp =
|
||||||
|
Response::build(StatusCode::OK).body(json!({"test-key":"test-value"}));
|
||||||
|
assert_eq!(resp.body().get_ref(), br#"{"test-key":"test-value"}"#);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_into_response() {
|
fn test_into_response() {
|
||||||
let resp: Response = "test".into();
|
let resp: Response = "test".into();
|
||||||
|
@ -1,20 +1,21 @@
|
|||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::{fmt, io, net};
|
use std::{fmt, io, net, rc};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||||
use actix_server_config::{
|
use actix_server_config::{
|
||||||
Io as ServerIo, IoStream, Protocol, ServerConfig as SrvConfig,
|
Io as ServerIo, IoStream, Protocol, ServerConfig as SrvConfig,
|
||||||
};
|
};
|
||||||
use actix_service::{IntoNewService, NewService, Service};
|
use actix_service::{IntoNewService, NewService, Service};
|
||||||
use actix_utils::cloneable::CloneableService;
|
|
||||||
use bytes::{Buf, BufMut, Bytes, BytesMut};
|
use bytes::{Buf, BufMut, Bytes, BytesMut};
|
||||||
use futures::{try_ready, Async, Future, IntoFuture, Poll};
|
use futures::{try_ready, Async, Future, IntoFuture, Poll};
|
||||||
use h2::server::{self, Handshake};
|
use h2::server::{self, Handshake};
|
||||||
|
|
||||||
use crate::body::MessageBody;
|
use crate::body::MessageBody;
|
||||||
use crate::builder::HttpServiceBuilder;
|
use crate::builder::HttpServiceBuilder;
|
||||||
|
use crate::cloneable::CloneableService;
|
||||||
use crate::config::{KeepAlive, ServiceConfig};
|
use crate::config::{KeepAlive, ServiceConfig};
|
||||||
use crate::error::{DispatchError, Error};
|
use crate::error::{DispatchError, Error};
|
||||||
|
use crate::helpers::DataFactory;
|
||||||
use crate::request::Request;
|
use crate::request::Request;
|
||||||
use crate::response::Response;
|
use crate::response::Response;
|
||||||
use crate::{h1, h2::Dispatcher};
|
use crate::{h1, h2::Dispatcher};
|
||||||
@ -25,6 +26,7 @@ pub struct HttpService<T, P, S, B, X = h1::ExpectHandler, U = h1::UpgradeHandler
|
|||||||
cfg: ServiceConfig,
|
cfg: ServiceConfig,
|
||||||
expect: X,
|
expect: X,
|
||||||
upgrade: Option<U>,
|
upgrade: Option<U>,
|
||||||
|
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
_t: PhantomData<(T, P, B)>,
|
_t: PhantomData<(T, P, B)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -61,6 +63,7 @@ where
|
|||||||
srv: service.into_new_service(),
|
srv: service.into_new_service(),
|
||||||
expect: h1::ExpectHandler,
|
expect: h1::ExpectHandler,
|
||||||
upgrade: None,
|
upgrade: None,
|
||||||
|
on_connect: None,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -75,6 +78,7 @@ where
|
|||||||
srv: service.into_new_service(),
|
srv: service.into_new_service(),
|
||||||
expect: h1::ExpectHandler,
|
expect: h1::ExpectHandler,
|
||||||
upgrade: None,
|
upgrade: None,
|
||||||
|
on_connect: None,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -104,6 +108,7 @@ where
|
|||||||
cfg: self.cfg,
|
cfg: self.cfg,
|
||||||
srv: self.srv,
|
srv: self.srv,
|
||||||
upgrade: self.upgrade,
|
upgrade: self.upgrade,
|
||||||
|
on_connect: self.on_connect,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -127,9 +132,19 @@ where
|
|||||||
cfg: self.cfg,
|
cfg: self.cfg,
|
||||||
srv: self.srv,
|
srv: self.srv,
|
||||||
expect: self.expect,
|
expect: self.expect,
|
||||||
|
on_connect: self.on_connect,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set on connect callback.
|
||||||
|
pub(crate) fn on_connect(
|
||||||
|
mut self,
|
||||||
|
f: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
|
) -> Self {
|
||||||
|
self.on_connect = f;
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, P, S, B, X, U> NewService for HttpService<T, P, S, B, X, U>
|
impl<T, P, S, B, X, U> NewService for HttpService<T, P, S, B, X, U>
|
||||||
@ -167,6 +182,7 @@ where
|
|||||||
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(cfg)),
|
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(cfg)),
|
||||||
expect: None,
|
expect: None,
|
||||||
upgrade: None,
|
upgrade: None,
|
||||||
|
on_connect: self.on_connect.clone(),
|
||||||
cfg: Some(self.cfg.clone()),
|
cfg: Some(self.cfg.clone()),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
@ -180,6 +196,7 @@ pub struct HttpServiceResponse<T, P, S: NewService, B, X: NewService, U: NewServ
|
|||||||
fut_upg: Option<U::Future>,
|
fut_upg: Option<U::Future>,
|
||||||
expect: Option<X::Service>,
|
expect: Option<X::Service>,
|
||||||
upgrade: Option<U::Service>,
|
upgrade: Option<U::Service>,
|
||||||
|
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
cfg: Option<ServiceConfig>,
|
cfg: Option<ServiceConfig>,
|
||||||
_t: PhantomData<(T, P, B)>,
|
_t: PhantomData<(T, P, B)>,
|
||||||
}
|
}
|
||||||
@ -229,6 +246,7 @@ where
|
|||||||
service,
|
service,
|
||||||
self.expect.take().unwrap(),
|
self.expect.take().unwrap(),
|
||||||
self.upgrade.take(),
|
self.upgrade.take(),
|
||||||
|
self.on_connect.clone(),
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -239,6 +257,7 @@ pub struct HttpServiceHandler<T, P, S, B, X, U> {
|
|||||||
expect: CloneableService<X>,
|
expect: CloneableService<X>,
|
||||||
upgrade: Option<CloneableService<U>>,
|
upgrade: Option<CloneableService<U>>,
|
||||||
cfg: ServiceConfig,
|
cfg: ServiceConfig,
|
||||||
|
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
_t: PhantomData<(T, P, B, X)>,
|
_t: PhantomData<(T, P, B, X)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -259,12 +278,14 @@ where
|
|||||||
srv: S,
|
srv: S,
|
||||||
expect: X,
|
expect: X,
|
||||||
upgrade: Option<U>,
|
upgrade: Option<U>,
|
||||||
|
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||||
) -> HttpServiceHandler<T, P, S, B, X, U> {
|
) -> HttpServiceHandler<T, P, S, B, X, U> {
|
||||||
HttpServiceHandler {
|
HttpServiceHandler {
|
||||||
cfg,
|
cfg,
|
||||||
|
on_connect,
|
||||||
srv: CloneableService::new(srv),
|
srv: CloneableService::new(srv),
|
||||||
expect: CloneableService::new(expect),
|
expect: CloneableService::new(expect),
|
||||||
upgrade: upgrade.map(|s| CloneableService::new(s)),
|
upgrade: upgrade.map(CloneableService::new),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -319,6 +340,13 @@ where
|
|||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||||
let (io, _, proto) = req.into_parts();
|
let (io, _, proto) = req.into_parts();
|
||||||
|
|
||||||
|
let on_connect = if let Some(ref on_connect) = self.on_connect {
|
||||||
|
Some(on_connect(&io))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
match proto {
|
match proto {
|
||||||
Protocol::Http2 => {
|
Protocol::Http2 => {
|
||||||
let peer_addr = io.peer_addr();
|
let peer_addr = io.peer_addr();
|
||||||
@ -332,6 +360,7 @@ where
|
|||||||
self.cfg.clone(),
|
self.cfg.clone(),
|
||||||
self.srv.clone(),
|
self.srv.clone(),
|
||||||
peer_addr,
|
peer_addr,
|
||||||
|
on_connect,
|
||||||
))),
|
))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -342,6 +371,7 @@ where
|
|||||||
self.srv.clone(),
|
self.srv.clone(),
|
||||||
self.expect.clone(),
|
self.expect.clone(),
|
||||||
self.upgrade.clone(),
|
self.upgrade.clone(),
|
||||||
|
on_connect,
|
||||||
)),
|
)),
|
||||||
},
|
},
|
||||||
_ => HttpServiceHandlerResponse {
|
_ => HttpServiceHandlerResponse {
|
||||||
@ -352,6 +382,7 @@ where
|
|||||||
self.srv.clone(),
|
self.srv.clone(),
|
||||||
self.expect.clone(),
|
self.expect.clone(),
|
||||||
self.upgrade.clone(),
|
self.upgrade.clone(),
|
||||||
|
on_connect,
|
||||||
))),
|
))),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@ -380,6 +411,7 @@ where
|
|||||||
CloneableService<S>,
|
CloneableService<S>,
|
||||||
CloneableService<X>,
|
CloneableService<X>,
|
||||||
Option<CloneableService<U>>,
|
Option<CloneableService<U>>,
|
||||||
|
Option<Box<dyn DataFactory>>,
|
||||||
)>,
|
)>,
|
||||||
),
|
),
|
||||||
Handshake(
|
Handshake(
|
||||||
@ -388,6 +420,7 @@ where
|
|||||||
ServiceConfig,
|
ServiceConfig,
|
||||||
CloneableService<S>,
|
CloneableService<S>,
|
||||||
Option<net::SocketAddr>,
|
Option<net::SocketAddr>,
|
||||||
|
Option<Box<dyn DataFactory>>,
|
||||||
)>,
|
)>,
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
@ -433,22 +466,25 @@ where
|
|||||||
State::Unknown(ref mut data) => {
|
State::Unknown(ref mut data) => {
|
||||||
if let Some(ref mut item) = data {
|
if let Some(ref mut item) = data {
|
||||||
loop {
|
loop {
|
||||||
unsafe {
|
// Safety - we only write to the returned slice.
|
||||||
let b = item.1.bytes_mut();
|
let b = unsafe { item.1.bytes_mut() };
|
||||||
let n = try_ready!(item.0.poll_read(b));
|
let n = try_ready!(item.0.poll_read(b));
|
||||||
if n == 0 {
|
if n == 0 {
|
||||||
return Ok(Async::Ready(()));
|
return Ok(Async::Ready(()));
|
||||||
}
|
}
|
||||||
item.1.advance_mut(n);
|
// 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() {
|
if item.1.len() >= HTTP2_PREFACE.len() {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
panic!()
|
panic!()
|
||||||
}
|
}
|
||||||
let (io, buf, cfg, srv, expect, upgrade) = data.take().unwrap();
|
let (io, buf, cfg, srv, expect, upgrade, on_connect) =
|
||||||
|
data.take().unwrap();
|
||||||
if buf[..14] == HTTP2_PREFACE[..] {
|
if buf[..14] == HTTP2_PREFACE[..] {
|
||||||
let peer_addr = io.peer_addr();
|
let peer_addr = io.peer_addr();
|
||||||
let io = Io {
|
let io = Io {
|
||||||
@ -460,6 +496,7 @@ where
|
|||||||
cfg,
|
cfg,
|
||||||
srv,
|
srv,
|
||||||
peer_addr,
|
peer_addr,
|
||||||
|
on_connect,
|
||||||
)));
|
)));
|
||||||
} else {
|
} else {
|
||||||
self.state = State::H1(h1::Dispatcher::with_timeout(
|
self.state = State::H1(h1::Dispatcher::with_timeout(
|
||||||
@ -471,6 +508,7 @@ where
|
|||||||
srv,
|
srv,
|
||||||
expect,
|
expect,
|
||||||
upgrade,
|
upgrade,
|
||||||
|
on_connect,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
self.poll()
|
self.poll()
|
||||||
@ -488,8 +526,10 @@ where
|
|||||||
} else {
|
} else {
|
||||||
panic!()
|
panic!()
|
||||||
};
|
};
|
||||||
let (_, cfg, srv, peer_addr) = data.take().unwrap();
|
let (_, cfg, srv, peer_addr, on_connect) = data.take().unwrap();
|
||||||
self.state = State::H2(Dispatcher::new(srv, conn, cfg, None, peer_addr));
|
self.state = State::H2(Dispatcher::new(
|
||||||
|
srv, conn, on_connect, cfg, None, peer_addr,
|
||||||
|
));
|
||||||
self.poll()
|
self.poll()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,9 +9,9 @@ use bytes::{Buf, Bytes, BytesMut};
|
|||||||
use futures::{Async, Poll};
|
use futures::{Async, Poll};
|
||||||
use http::header::{self, HeaderName, HeaderValue};
|
use http::header::{self, HeaderName, HeaderValue};
|
||||||
use http::{HttpTryFrom, Method, Uri, Version};
|
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::HeaderMap;
|
||||||
use crate::header::{Header, IntoHeaderValue};
|
use crate::header::{Header, IntoHeaderValue};
|
||||||
use crate::payload::Payload;
|
use crate::payload::Payload;
|
||||||
@ -150,7 +150,7 @@ impl TestRequest {
|
|||||||
|
|
||||||
/// Complete request creation and generate `Request` instance
|
/// Complete request creation and generate `Request` instance
|
||||||
pub fn finish(&mut self) -> Request {
|
pub fn finish(&mut self) -> Request {
|
||||||
let inner = self.0.take().expect("cannot reuse test request builder");;
|
let inner = self.0.take().expect("cannot reuse test request builder");
|
||||||
|
|
||||||
let mut req = if let Some(pl) = inner.payload {
|
let mut req = if let Some(pl) = inner.payload {
|
||||||
Request::with_payload(pl)
|
Request::with_payload(pl)
|
||||||
@ -166,8 +166,8 @@ impl TestRequest {
|
|||||||
|
|
||||||
let mut cookie = String::new();
|
let mut cookie = String::new();
|
||||||
for c in inner.cookies.delta() {
|
for c in inner.cookies.delta() {
|
||||||
let name = percent_encode(c.name().as_bytes(), USERINFO_ENCODE_SET);
|
let name = percent_encode(c.name().as_bytes(), USERINFO);
|
||||||
let value = percent_encode(c.value().as_bytes(), USERINFO_ENCODE_SET);
|
let value = percent_encode(c.value().as_bytes(), USERINFO);
|
||||||
let _ = write!(&mut cookie, "; {}={}", name, value);
|
let _ = write!(&mut cookie, "; {}={}", name, value);
|
||||||
}
|
}
|
||||||
if !cookie.is_empty() {
|
if !cookie.is_empty() {
|
||||||
|
@ -37,7 +37,7 @@ pub enum Frame {
|
|||||||
Close(Option<CloseReason>),
|
Close(Option<CloseReason>),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug, Copy, Clone)]
|
||||||
/// WebSockets protocol codec
|
/// WebSockets protocol codec
|
||||||
pub struct Codec {
|
pub struct Codec {
|
||||||
max_size: usize,
|
max_size: usize,
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
use byteorder::{ByteOrder, LittleEndian, NetworkEndian};
|
use std::convert::TryFrom;
|
||||||
|
|
||||||
use bytes::{BufMut, Bytes, BytesMut};
|
use bytes::{BufMut, Bytes, BytesMut};
|
||||||
use log::debug;
|
use log::debug;
|
||||||
use rand;
|
use rand;
|
||||||
@ -48,14 +49,16 @@ impl Parser {
|
|||||||
if chunk_len < 4 {
|
if chunk_len < 4 {
|
||||||
return Ok(None);
|
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;
|
idx += 2;
|
||||||
len
|
len
|
||||||
} else if len == 127 {
|
} else if len == 127 {
|
||||||
if chunk_len < 10 {
|
if chunk_len < 10 {
|
||||||
return Ok(None);
|
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 {
|
if len > max_size as u64 {
|
||||||
return Err(ProtocolError::Overflow);
|
return Err(ProtocolError::Overflow);
|
||||||
}
|
}
|
||||||
@ -75,10 +78,10 @@ impl Parser {
|
|||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mask: &[u8] = &src[idx..idx + 4];
|
let mask =
|
||||||
let mask_u32 = LittleEndian::read_u32(mask);
|
u32::from_le_bytes(TryFrom::try_from(&src[idx..idx + 4]).unwrap());
|
||||||
idx += 4;
|
idx += 4;
|
||||||
Some(mask_u32)
|
Some(mask)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
@ -137,7 +140,7 @@ impl Parser {
|
|||||||
/// Parse the payload of a close frame.
|
/// Parse the payload of a close frame.
|
||||||
pub fn parse_close_payload(payload: &[u8]) -> Option<CloseReason> {
|
pub fn parse_close_payload(payload: &[u8]) -> Option<CloseReason> {
|
||||||
if payload.len() >= 2 {
|
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 code = CloseCode::from(raw_code);
|
||||||
let description = if payload.len() > 2 {
|
let description = if payload.len() > 2 {
|
||||||
Some(String::from_utf8_lossy(&payload[2..]).into())
|
Some(String::from_utf8_lossy(&payload[2..]).into())
|
||||||
@ -201,10 +204,7 @@ impl Parser {
|
|||||||
let payload = match reason {
|
let payload = match reason {
|
||||||
None => Vec::new(),
|
None => Vec::new(),
|
||||||
Some(reason) => {
|
Some(reason) => {
|
||||||
let mut code_bytes = [0; 2];
|
let mut payload = Into::<u16>::into(reason.code).to_be_bytes().to_vec();
|
||||||
NetworkEndian::write_u16(&mut code_bytes, reason.code.into());
|
|
||||||
|
|
||||||
let mut payload = Vec::from(&code_bytes[..]);
|
|
||||||
if let Some(description) = reason.description {
|
if let Some(description) = reason.description {
|
||||||
payload.extend(description.as_bytes());
|
payload.extend(description.as_bytes());
|
||||||
}
|
}
|
||||||
|
@ -105,7 +105,6 @@ fn align_buf(buf: &mut [u8]) -> (ShortSlice, &mut [u64], ShortSlice) {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::apply_mask;
|
use super::apply_mask;
|
||||||
use byteorder::{ByteOrder, LittleEndian};
|
|
||||||
|
|
||||||
/// A safe unoptimized mask application.
|
/// A safe unoptimized mask application.
|
||||||
fn apply_mask_fallback(buf: &mut [u8], mask: &[u8; 4]) {
|
fn apply_mask_fallback(buf: &mut [u8], mask: &[u8; 4]) {
|
||||||
@ -117,7 +116,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_apply_mask() {
|
fn test_apply_mask() {
|
||||||
let mask = [0x6d, 0xb6, 0xb2, 0x80];
|
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![
|
let unmasked = vec![
|
||||||
0xf3, 0x00, 0x01, 0x02, 0x03, 0x80, 0x81, 0x82, 0xff, 0xfe, 0x00, 0x17,
|
0xf3, 0x00, 0x01, 0x02, 0x03, 0x80, 0x81, 0x82, 0xff, 0xfe, 0x00, 0x17,
|
||||||
|
@ -47,10 +47,7 @@ impl Into<u8> for OpCode {
|
|||||||
Ping => 9,
|
Ping => 9,
|
||||||
Pong => 10,
|
Pong => 10,
|
||||||
Bad => {
|
Bad => {
|
||||||
debug_assert!(
|
log::error!("Attempted to convert invalid opcode to u8. This is a bug.");
|
||||||
false,
|
|
||||||
"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
|
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
|
// TODO: hash is always same size, we dont need String
|
||||||
pub fn hash_key(key: &[u8]) -> 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,33 +2,20 @@ use std::io::{Read, Write};
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use std::{net, thread};
|
use std::{net, thread};
|
||||||
|
|
||||||
use actix_codec::{AsyncRead, AsyncWrite};
|
|
||||||
use actix_http_test::TestServer;
|
use actix_http_test::TestServer;
|
||||||
use actix_server_config::ServerConfig;
|
use actix_server_config::ServerConfig;
|
||||||
use actix_service::{new_service_cfg, service_fn, NewService};
|
use actix_service::{new_service_cfg, service_fn, NewService};
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::Bytes;
|
||||||
use futures::future::{self, ok, Future};
|
use futures::future::{self, ok, Future};
|
||||||
use futures::stream::{once, Stream};
|
use futures::stream::{once, Stream};
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
use tokio_timer::sleep;
|
use tokio_timer::sleep;
|
||||||
|
|
||||||
use actix_http::body::Body;
|
use actix_http::httpmessage::HttpMessage;
|
||||||
use actix_http::error::PayloadError;
|
|
||||||
use actix_http::{
|
use actix_http::{
|
||||||
body, error, http, http::header, Error, HttpService, KeepAlive, Request, Response,
|
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]
|
#[test]
|
||||||
fn test_h1() {
|
fn test_h1() {
|
||||||
let mut srv = TestServer::new(|| {
|
let mut srv = TestServer::new(|| {
|
||||||
@ -65,101 +52,6 @@ fn test_h1_2() {
|
|||||||
assert!(response.status().is_success());
|
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]
|
#[test]
|
||||||
fn test_expect_continue() {
|
fn test_expect_continue() {
|
||||||
let srv = TestServer::new(|| {
|
let srv = TestServer::new(|| {
|
||||||
@ -222,26 +114,24 @@ fn test_chunked_payload() {
|
|||||||
let total_size: usize = chunk_sizes.iter().sum();
|
let total_size: usize = chunk_sizes.iter().sum();
|
||||||
|
|
||||||
let srv = TestServer::new(|| {
|
let srv = TestServer::new(|| {
|
||||||
HttpService::build()
|
HttpService::build().h1(|mut request: Request| {
|
||||||
.h1(|mut request: Request| {
|
request
|
||||||
request.take_payload()
|
.take_payload()
|
||||||
.map_err(|e| panic!(format!("Error reading payload: {}", e)))
|
.map_err(|e| panic!(format!("Error reading payload: {}", e)))
|
||||||
.fold(0usize, |acc, chunk| {
|
.fold(0usize, |acc, chunk| future::ok::<_, ()>(acc + chunk.len()))
|
||||||
future::ok::<_, ()>(acc + chunk.len())
|
.map(|req_size| Response::Ok().body(format!("size={}", req_size)))
|
||||||
})
|
|
||||||
.map(|req_size| {
|
|
||||||
Response::Ok().body(format!("size={}", req_size))
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
let returned_size = {
|
let returned_size = {
|
||||||
let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
|
let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
|
||||||
let _ = stream.write_all(b"POST /test HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n");
|
let _ = stream
|
||||||
|
.write_all(b"POST /test HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n");
|
||||||
|
|
||||||
for chunk_size in chunk_sizes.iter() {
|
for chunk_size in chunk_sizes.iter() {
|
||||||
let mut bytes = Vec::new();
|
let mut bytes = Vec::new();
|
||||||
let random_bytes: Vec<u8> = (0..*chunk_size).map(|_| rand::random::<u8>()).collect();
|
let random_bytes: Vec<u8> =
|
||||||
|
(0..*chunk_size).map(|_| rand::random::<u8>()).collect();
|
||||||
|
|
||||||
bytes.extend(format!("{:X}\r\n", chunk_size).as_bytes());
|
bytes.extend(format!("{:X}\r\n", chunk_size).as_bytes());
|
||||||
bytes.extend(&random_bytes[..]);
|
bytes.extend(&random_bytes[..]);
|
||||||
@ -460,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]
|
#[test]
|
||||||
fn test_h1_headers() {
|
fn test_h1_headers() {
|
||||||
let data = STR.repeat(10);
|
let data = STR.repeat(10);
|
||||||
@ -558,51 +389,6 @@ fn test_h1_headers() {
|
|||||||
assert_eq!(bytes, Bytes::from(data2));
|
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 \
|
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 \
|
||||||
@ -639,29 +425,6 @@ fn test_h1_body() {
|
|||||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
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]
|
#[test]
|
||||||
fn test_h1_head_empty() {
|
fn test_h1_head_empty() {
|
||||||
let mut srv = TestServer::new(|| {
|
let mut srv = TestServer::new(|| {
|
||||||
@ -684,38 +447,6 @@ fn test_h1_head_empty() {
|
|||||||
assert!(bytes.is_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]
|
#[test]
|
||||||
fn test_h1_head_binary() {
|
fn test_h1_head_binary() {
|
||||||
let mut srv = TestServer::new(|| {
|
let mut srv = TestServer::new(|| {
|
||||||
@ -740,41 +471,6 @@ fn test_h1_head_binary() {
|
|||||||
assert!(bytes.is_empty());
|
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]
|
#[test]
|
||||||
fn test_h1_head_binary2() {
|
fn test_h1_head_binary2() {
|
||||||
let mut srv = TestServer::new(|| {
|
let mut srv = TestServer::new(|| {
|
||||||
@ -793,41 +489,13 @@ 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]
|
#[test]
|
||||||
fn test_h1_body_length() {
|
fn test_h1_body_length() {
|
||||||
let mut srv = TestServer::new(|| {
|
let mut srv = TestServer::new(|| {
|
||||||
HttpService::build().h1(|_| {
|
HttpService::build().h1(|_| {
|
||||||
let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
||||||
ok::<_, ()>(
|
ok::<_, ()>(
|
||||||
Response::Ok()
|
Response::Ok().body(body::SizedStream::new(STR.len() as u64, body)),
|
||||||
.body(Body::from_message(body::SizedStream::new(STR.len(), body))),
|
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
@ -840,34 +508,6 @@ fn test_h1_body_length() {
|
|||||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
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::from_message(
|
|
||||||
body::SizedStream::new(STR.len(), 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]
|
#[test]
|
||||||
fn test_h1_body_chunked_explicit() {
|
fn test_h1_body_chunked_explicit() {
|
||||||
let mut srv = TestServer::new(|| {
|
let mut srv = TestServer::new(|| {
|
||||||
@ -900,40 +540,6 @@ fn test_h1_body_chunked_explicit() {
|
|||||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
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]
|
#[test]
|
||||||
fn test_h1_body_chunked_implicit() {
|
fn test_h1_body_chunked_implicit() {
|
||||||
let mut srv = TestServer::new(|| {
|
let mut srv = TestServer::new(|| {
|
||||||
@ -983,39 +589,6 @@ fn test_h1_response_http_error_handling() {
|
|||||||
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
|
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]
|
#[test]
|
||||||
fn test_h1_service_error() {
|
fn test_h1_service_error() {
|
||||||
let mut srv = TestServer::new(|| {
|
let mut srv = TestServer::new(|| {
|
||||||
@ -1031,26 +604,17 @@ fn test_h1_service_error() {
|
|||||||
assert_eq!(bytes, Bytes::from_static(b"error"));
|
assert_eq!(bytes, Bytes::from_static(b"error"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "ssl")]
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_h2_service_error() {
|
fn test_h1_on_connect() {
|
||||||
let openssl = ssl_acceptor().unwrap();
|
let mut srv = TestServer::new(|| {
|
||||||
|
|
||||||
let mut srv = TestServer::new(move || {
|
|
||||||
openssl
|
|
||||||
.clone()
|
|
||||||
.map_err(|e| println!("Openssl error: {}", e))
|
|
||||||
.and_then(
|
|
||||||
HttpService::build()
|
HttpService::build()
|
||||||
.h2(|_| Err::<Response, Error>(error::ErrorBadRequest("error")))
|
.on_connect(|_| 10usize)
|
||||||
.map_err(|_| ()),
|
.h1(|req: Request| {
|
||||||
)
|
assert!(req.extensions().contains::<usize>());
|
||||||
|
future::ok::<_, ()>(Response::Ok().finish())
|
||||||
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
let response = srv.block_on(srv.get("/").send()).unwrap();
|
||||||
assert_eq!(response.status(), http::StatusCode::INTERNAL_SERVER_ERROR);
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
// read response
|
|
||||||
let bytes = srv.load_body(response).unwrap();
|
|
||||||
assert!(bytes.is_empty());
|
|
||||||
}
|
}
|
||||||
|
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());
|
||||||
|
}
|
5
actix-identity/CHANGES.md
Normal file
5
actix-identity/CHANGES.md
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
# Changes
|
||||||
|
|
||||||
|
## [0.1.0] - 2019-06-xx
|
||||||
|
|
||||||
|
* Move identity middleware to separate crate
|
30
actix-identity/Cargo.toml
Normal file
30
actix-identity/Cargo.toml
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
[package]
|
||||||
|
name = "actix-identity"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
|
description = "Identity service for actix web framework."
|
||||||
|
readme = "README.md"
|
||||||
|
keywords = ["http", "web", "framework", "async", "futures"]
|
||||||
|
homepage = "https://actix.rs"
|
||||||
|
repository = "https://github.com/actix/actix-web.git"
|
||||||
|
documentation = "https://docs.rs/actix-identity/"
|
||||||
|
license = "MIT/Apache-2.0"
|
||||||
|
edition = "2018"
|
||||||
|
workspace = ".."
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "actix_identity"
|
||||||
|
path = "src/lib.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
actix-web = { version = "1.0.0", default-features = false, features = ["secure-cookies"] }
|
||||||
|
actix-service = "0.4.0"
|
||||||
|
futures = "0.1.25"
|
||||||
|
serde = "1.0"
|
||||||
|
serde_json = "1.0"
|
||||||
|
time = "0.1.42"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
actix-rt = "0.2.2"
|
||||||
|
actix-http = "0.2.3"
|
||||||
|
bytes = "0.4"
|
1
actix-identity/LICENSE-APACHE
Symbolic link
1
actix-identity/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-APACHE
|
1
actix-identity/LICENSE-MIT
Symbolic link
1
actix-identity/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-MIT
|
9
actix-identity/README.md
Normal file
9
actix-identity/README.md
Normal file
@ -0,0 +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)
|
||||||
|
|
||||||
|
## Documentation & community resources
|
||||||
|
|
||||||
|
* [User Guide](https://actix.rs/docs/)
|
||||||
|
* [API Documentation](https://docs.rs/actix-identity/)
|
||||||
|
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||||
|
* Cargo package: [actix-session](https://crates.io/crates/actix-identity)
|
||||||
|
* Minimum supported Rust version: 1.34 or later
|
@ -10,12 +10,11 @@
|
|||||||
//! uses cookies as identity storage.
|
//! uses cookies as identity storage.
|
||||||
//!
|
//!
|
||||||
//! To access current request identity
|
//! To access current request identity
|
||||||
//! [**Identity**](trait.Identity.html) extractor should be used.
|
//! [**Identity**](struct.Identity.html) extractor should be used.
|
||||||
//!
|
//!
|
||||||
//! ```rust
|
//! ```rust
|
||||||
//! use actix_web::middleware::identity::Identity;
|
|
||||||
//! use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
|
|
||||||
//! use actix_web::*;
|
//! use actix_web::*;
|
||||||
|
//! use actix_identity::{Identity, CookieIdentityPolicy, IdentityService};
|
||||||
//!
|
//!
|
||||||
//! fn index(id: Identity) -> String {
|
//! fn index(id: Identity) -> String {
|
||||||
//! // access request identity
|
//! // access request identity
|
||||||
@ -39,7 +38,7 @@
|
|||||||
//! fn main() {
|
//! fn main() {
|
||||||
//! let app = App::new().wrap(IdentityService::new(
|
//! let app = App::new().wrap(IdentityService::new(
|
||||||
//! // <- create identity middleware
|
//! // <- create identity middleware
|
||||||
//! CookieIdentityPolicy::new(&[0; 32]) // <- create cookie session backend
|
//! CookieIdentityPolicy::new(&[0; 32]) // <- create cookie identity policy
|
||||||
//! .name("auth-cookie")
|
//! .name("auth-cookie")
|
||||||
//! .secure(false)))
|
//! .secure(false)))
|
||||||
//! .service(web::resource("/index.html").to(index))
|
//! .service(web::resource("/index.html").to(index))
|
||||||
@ -57,17 +56,17 @@ use futures::{Future, IntoFuture, Poll};
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use time::Duration;
|
use time::Duration;
|
||||||
|
|
||||||
use crate::cookie::{Cookie, CookieJar, Key, SameSite};
|
use actix_web::cookie::{Cookie, CookieJar, Key, SameSite};
|
||||||
use crate::error::{Error, Result};
|
use actix_web::dev::{Extensions, Payload, ServiceRequest, ServiceResponse};
|
||||||
use crate::http::header::{self, HeaderValue};
|
use actix_web::error::{Error, Result};
|
||||||
use crate::service::{ServiceRequest, ServiceResponse};
|
use actix_web::http::header::{self, HeaderValue};
|
||||||
use crate::{dev::Payload, FromRequest, HttpMessage, HttpRequest};
|
use actix_web::{FromRequest, HttpMessage, HttpRequest};
|
||||||
|
|
||||||
/// The extractor type to obtain your identity from a request.
|
/// The extractor type to obtain your identity from a request.
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use actix_web::*;
|
/// use actix_web::*;
|
||||||
/// use actix_web::middleware::identity::Identity;
|
/// use actix_identity::Identity;
|
||||||
///
|
///
|
||||||
/// fn index(id: Identity) -> Result<String> {
|
/// fn index(id: Identity) -> Result<String> {
|
||||||
/// // access request identity
|
/// // access request identity
|
||||||
@ -96,11 +95,7 @@ impl Identity {
|
|||||||
/// Return the claimed identity of the user associated request or
|
/// Return the claimed identity of the user associated request or
|
||||||
/// ``None`` if no identity can be found associated with the request.
|
/// ``None`` if no identity can be found associated with the request.
|
||||||
pub fn identity(&self) -> Option<String> {
|
pub fn identity(&self) -> Option<String> {
|
||||||
if let Some(id) = self.0.extensions().get::<IdentityItem>() {
|
Identity::get_identity(&self.0.extensions())
|
||||||
id.id.clone()
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Remember identity.
|
/// Remember identity.
|
||||||
@ -119,6 +114,14 @@ impl Identity {
|
|||||||
id.changed = true;
|
id.changed = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn get_identity(extensions: &Extensions) -> Option<String> {
|
||||||
|
if let Some(id) = extensions.get::<IdentityItem>() {
|
||||||
|
id.id.clone()
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct IdentityItem {
|
struct IdentityItem {
|
||||||
@ -126,11 +129,28 @@ struct IdentityItem {
|
|||||||
changed: bool,
|
changed: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Helper trait that allows to get Identity.
|
||||||
|
///
|
||||||
|
/// It could be used in middleware but identity policy must be set before any other middleware that needs identity
|
||||||
|
/// RequestIdentity is implemented both for `ServiceRequest` and `HttpRequest`.
|
||||||
|
pub trait RequestIdentity {
|
||||||
|
fn get_identity(&self) -> Option<String>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> RequestIdentity for T
|
||||||
|
where
|
||||||
|
T: HttpMessage,
|
||||||
|
{
|
||||||
|
fn get_identity(&self) -> Option<String> {
|
||||||
|
Identity::get_identity(&self.extensions())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Extractor implementation for Identity type.
|
/// Extractor implementation for Identity type.
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// # use actix_web::*;
|
/// # use actix_web::*;
|
||||||
/// use actix_web::middleware::identity::Identity;
|
/// use actix_identity::Identity;
|
||||||
///
|
///
|
||||||
/// fn index(id: Identity) -> String {
|
/// fn index(id: Identity) -> String {
|
||||||
/// // access request identity
|
/// // access request identity
|
||||||
@ -177,7 +197,7 @@ pub trait IdentityPolicy: Sized + 'static {
|
|||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// use actix_web::App;
|
/// use actix_web::App;
|
||||||
/// use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
|
/// use actix_identity::{CookieIdentityPolicy, IdentityService};
|
||||||
///
|
///
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = App::new().wrap(IdentityService::new(
|
/// let app = App::new().wrap(IdentityService::new(
|
||||||
@ -241,7 +261,7 @@ where
|
|||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse<B>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = Error;
|
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> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
self.service.borrow_mut().poll_ready()
|
self.service.borrow_mut().poll_ready()
|
||||||
@ -263,7 +283,7 @@ where
|
|||||||
res.request().extensions_mut().remove::<IdentityItem>();
|
res.request().extensions_mut().remove::<IdentityItem>();
|
||||||
|
|
||||||
if let Some(id) = id {
|
if let Some(id) = id {
|
||||||
return Either::A(
|
Either::A(
|
||||||
backend
|
backend
|
||||||
.to_response(id.id, id.changed, &mut res)
|
.to_response(id.id, id.changed, &mut res)
|
||||||
.into_future()
|
.into_future()
|
||||||
@ -271,7 +291,7 @@ where
|
|||||||
Ok(_) => Ok(res),
|
Ok(_) => Ok(res),
|
||||||
Err(e) => Ok(res.error_response(e)),
|
Err(e) => Ok(res.error_response(e)),
|
||||||
}),
|
}),
|
||||||
);
|
)
|
||||||
} else {
|
} else {
|
||||||
Either::B(ok(res))
|
Either::B(ok(res))
|
||||||
}
|
}
|
||||||
@ -313,8 +333,7 @@ struct CookieIdentityExtention {
|
|||||||
|
|
||||||
impl CookieIdentityInner {
|
impl CookieIdentityInner {
|
||||||
fn new(key: &[u8]) -> CookieIdentityInner {
|
fn new(key: &[u8]) -> CookieIdentityInner {
|
||||||
let key_v2: Vec<u8> =
|
let key_v2: Vec<u8> = key.iter().chain([1, 0, 0, 0].iter()).cloned().collect();
|
||||||
key.iter().chain([1, 0, 0, 0].iter()).map(|e| *e).collect();
|
|
||||||
CookieIdentityInner {
|
CookieIdentityInner {
|
||||||
key: Key::from_master(key),
|
key: Key::from_master(key),
|
||||||
key_v2: Key::from_master(&key_v2),
|
key_v2: Key::from_master(&key_v2),
|
||||||
@ -442,9 +461,8 @@ impl CookieIdentityInner {
|
|||||||
/// # Example
|
/// # Example
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// # extern crate actix_web;
|
|
||||||
/// use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
|
|
||||||
/// use actix_web::App;
|
/// use actix_web::App;
|
||||||
|
/// use actix_identity::{CookieIdentityPolicy, IdentityService};
|
||||||
///
|
///
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = App::new().wrap(IdentityService::new(
|
/// let app = App::new().wrap(IdentityService::new(
|
||||||
@ -566,13 +584,14 @@ impl IdentityPolicy for CookieIdentityPolicy {
|
|||||||
)
|
)
|
||||||
} else if self.0.always_update_cookie() && id.is_some() {
|
} else if self.0.always_update_cookie() && id.is_some() {
|
||||||
let visit_timestamp = SystemTime::now();
|
let visit_timestamp = SystemTime::now();
|
||||||
let mut login_timestamp = None;
|
let login_timestamp = if self.0.requires_oob_data() {
|
||||||
if self.0.requires_oob_data() {
|
|
||||||
let CookieIdentityExtention {
|
let CookieIdentityExtention {
|
||||||
login_timestamp: lt,
|
login_timestamp: lt,
|
||||||
} = res.request().extensions_mut().remove().unwrap();
|
} = res.request().extensions_mut().remove().unwrap();
|
||||||
login_timestamp = lt;
|
lt
|
||||||
}
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
self.0.set_cookie(
|
self.0.set_cookie(
|
||||||
res,
|
res,
|
||||||
Some(CookieValue {
|
Some(CookieValue {
|
||||||
@ -590,13 +609,13 @@ impl IdentityPolicy for CookieIdentityPolicy {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
|
||||||
use crate::http::StatusCode;
|
|
||||||
use crate::test::{self, TestRequest};
|
|
||||||
use crate::{web, App, HttpResponse};
|
|
||||||
|
|
||||||
use std::borrow::Borrow;
|
use std::borrow::Borrow;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use actix_web::http::StatusCode;
|
||||||
|
use actix_web::test::{self, TestRequest};
|
||||||
|
use actix_web::{web, App, Error, HttpResponse};
|
||||||
|
|
||||||
const COOKIE_KEY_MASTER: [u8; 32] = [0; 32];
|
const COOKIE_KEY_MASTER: [u8; 32] = [0; 32];
|
||||||
const COOKIE_NAME: &'static str = "actix_auth";
|
const COOKIE_NAME: &'static str = "actix_auth";
|
||||||
const COOKIE_LOGIN: &'static str = "test";
|
const COOKIE_LOGIN: &'static str = "test";
|
||||||
@ -717,8 +736,8 @@ mod tests {
|
|||||||
f: F,
|
f: F,
|
||||||
) -> impl actix_service::Service<
|
) -> impl actix_service::Service<
|
||||||
Request = actix_http::Request,
|
Request = actix_http::Request,
|
||||||
Response = ServiceResponse<actix_http::body::Body>,
|
Response = ServiceResponse<actix_web::body::Body>,
|
||||||
Error = actix_http::Error,
|
Error = Error,
|
||||||
> {
|
> {
|
||||||
test::init_service(
|
test::init_service(
|
||||||
App::new()
|
App::new()
|
@ -1,5 +1,21 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.1.5] - 2019-12-07
|
||||||
|
|
||||||
|
* Multipart handling now handles NotReady during read of boundary #1189
|
||||||
|
|
||||||
|
## [0.1.4] - 2019-09-12
|
||||||
|
|
||||||
|
* 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.
|
||||||
|
|
||||||
|
## [0.1.2] - 2019-06-02
|
||||||
|
|
||||||
|
* Fix boundary parsing #876
|
||||||
|
|
||||||
## [0.1.1] - 2019-05-25
|
## [0.1.1] - 2019-05-25
|
||||||
|
|
||||||
* Fix disconnect handling #834
|
* Fix disconnect handling #834
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-multipart"
|
name = "actix-multipart"
|
||||||
version = "0.1.1"
|
version = "0.1.5"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Multipart support for actix web framework."
|
description = "Multipart support for actix web framework."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -18,10 +18,10 @@ name = "actix_multipart"
|
|||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = "1.0.0-rc"
|
actix-web = { version = "1.0.0", default-features = false }
|
||||||
actix-service = "0.4.0"
|
actix-service = "0.4.1"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
derive_more = "0.14"
|
derive_more = "0.15.0"
|
||||||
httparse = "1.3"
|
httparse = "1.3"
|
||||||
futures = "0.1.25"
|
futures = "0.1.25"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
@ -31,4 +31,4 @@ twoway = "0.2"
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.2"
|
||||||
actix-http = "0.2.0"
|
actix-http = "0.2.4"
|
1
actix-multipart/LICENSE-APACHE
Symbolic link
1
actix-multipart/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-APACHE
|
1
actix-multipart/LICENSE-MIT
Symbolic link
1
actix-multipart/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-MIT
|
@ -1,3 +1,5 @@
|
|||||||
|
#![allow(clippy::borrow_interior_mutable_const)]
|
||||||
|
|
||||||
mod error;
|
mod error;
|
||||||
mod extractor;
|
mod extractor;
|
||||||
mod server;
|
mod server;
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
//! Multipart payload support
|
//! Multipart payload support
|
||||||
use std::cell::{Cell, RefCell, UnsafeCell};
|
use std::cell::{Cell, RefCell, RefMut};
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::{cmp, fmt};
|
use std::{cmp, fmt};
|
||||||
@ -112,7 +112,7 @@ impl Stream for Multipart {
|
|||||||
Err(err)
|
Err(err)
|
||||||
} else if self.safety.current() {
|
} else if self.safety.current() {
|
||||||
let mut inner = self.inner.as_mut().unwrap().borrow_mut();
|
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()?;
|
payload.poll_stream()?;
|
||||||
}
|
}
|
||||||
inner.poll(&self.safety)
|
inner.poll(&self.safety)
|
||||||
@ -167,7 +167,7 @@ impl InnerMultipart {
|
|||||||
boundary: &str,
|
boundary: &str,
|
||||||
) -> Result<Option<bool>, MultipartError> {
|
) -> Result<Option<bool>, MultipartError> {
|
||||||
// TODO: need to read epilogue
|
// TODO: need to read epilogue
|
||||||
match payload.readline()? {
|
match payload.readline_or_eof()? {
|
||||||
None => {
|
None => {
|
||||||
if payload.eof {
|
if payload.eof {
|
||||||
Ok(Some(true))
|
Ok(Some(true))
|
||||||
@ -176,15 +176,16 @@ impl InnerMultipart {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(chunk) => {
|
Some(chunk) => {
|
||||||
if chunk.len() == boundary.len() + 4
|
if chunk.len() < boundary.len() + 4
|
||||||
&& &chunk[..2] == b"--"
|
|| &chunk[..2] != b"--"
|
||||||
&& &chunk[2..boundary.len() + 2] == boundary.as_bytes()
|
|| &chunk[2..boundary.len() + 2] != boundary.as_bytes()
|
||||||
{
|
{
|
||||||
|
Err(MultipartError::Boundary)
|
||||||
|
} else if &chunk[boundary.len() + 2..] == b"\r\n" {
|
||||||
Ok(Some(false))
|
Ok(Some(false))
|
||||||
} else if chunk.len() == boundary.len() + 6
|
} else if &chunk[boundary.len() + 2..boundary.len() + 4] == b"--"
|
||||||
&& &chunk[..2] == b"--"
|
&& (chunk.len() == boundary.len() + 4
|
||||||
&& &chunk[2..boundary.len() + 2] == boundary.as_bytes()
|
|| &chunk[boundary.len() + 4..] == b"\r\n")
|
||||||
&& &chunk[boundary.len() + 2..boundary.len() + 4] == b"--"
|
|
||||||
{
|
{
|
||||||
Ok(Some(true))
|
Ok(Some(true))
|
||||||
} else {
|
} else {
|
||||||
@ -265,12 +266,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 {
|
match self.state {
|
||||||
// read until first boundary
|
// read until first boundary
|
||||||
InnerState::FirstBoundary => {
|
InnerState::FirstBoundary => {
|
||||||
match InnerMultipart::skip_until_boundary(
|
match InnerMultipart::skip_until_boundary(
|
||||||
payload,
|
&mut *payload,
|
||||||
&self.boundary,
|
&self.boundary,
|
||||||
)? {
|
)? {
|
||||||
Some(eof) => {
|
Some(eof) => {
|
||||||
@ -286,7 +287,10 @@ impl InnerMultipart {
|
|||||||
}
|
}
|
||||||
// read boundary
|
// read boundary
|
||||||
InnerState::Boundary => {
|
InnerState::Boundary => {
|
||||||
match InnerMultipart::read_boundary(payload, &self.boundary)? {
|
match InnerMultipart::read_boundary(
|
||||||
|
&mut *payload,
|
||||||
|
&self.boundary,
|
||||||
|
)? {
|
||||||
None => return Ok(Async::NotReady),
|
None => return Ok(Async::NotReady),
|
||||||
Some(eof) => {
|
Some(eof) => {
|
||||||
if eof {
|
if eof {
|
||||||
@ -303,7 +307,7 @@ impl InnerMultipart {
|
|||||||
|
|
||||||
// read field headers for next field
|
// read field headers for next field
|
||||||
if self.state == InnerState::Headers {
|
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;
|
self.state = InnerState::Boundary;
|
||||||
headers
|
headers
|
||||||
} else {
|
} else {
|
||||||
@ -411,14 +415,15 @@ impl Stream for Field {
|
|||||||
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
|
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
|
||||||
if self.safety.current() {
|
if self.safety.current() {
|
||||||
let mut inner = self.inner.borrow_mut();
|
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()?;
|
payload.poll_stream()?;
|
||||||
}
|
}
|
||||||
|
|
||||||
inner.poll(&self.safety)
|
inner.poll(&self.safety)
|
||||||
} else if !self.safety.is_clean() {
|
} else if !self.safety.is_clean() {
|
||||||
return Err(MultipartError::NotConsumed);
|
Err(MultipartError::NotConsumed)
|
||||||
} else {
|
} else {
|
||||||
Ok(Async::NotReady)
|
Ok(Async::NotReady)
|
||||||
}
|
}
|
||||||
@ -533,13 +538,9 @@ impl InnerField {
|
|||||||
let b_size = boundary.len() + b_len;
|
let b_size = boundary.len() + b_len;
|
||||||
if len < b_size {
|
if len < b_size {
|
||||||
return Ok(Async::NotReady);
|
return Ok(Async::NotReady);
|
||||||
} else {
|
} else if &payload.buf[b_len..b_size] == boundary.as_bytes() {
|
||||||
if &payload.buf[b_len..b_size] == boundary.as_bytes() {
|
|
||||||
// found boundary
|
// found boundary
|
||||||
return Ok(Async::Ready(None));
|
return Ok(Async::Ready(None));
|
||||||
} else {
|
|
||||||
pos = b_size;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -559,7 +560,7 @@ impl InnerField {
|
|||||||
// check boundary
|
// check boundary
|
||||||
if (&payload.buf[cur..cur + 2] == b"\r\n"
|
if (&payload.buf[cur..cur + 2] == b"\r\n"
|
||||||
&& &payload.buf[cur + 2..cur + 4] == b"--")
|
&& &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"--")
|
&& &payload.buf[cur + 1..cur + 3] == b"--")
|
||||||
{
|
{
|
||||||
if cur != 0 {
|
if cur != 0 {
|
||||||
@ -576,7 +577,7 @@ impl InnerField {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return Ok(Async::Ready(Some(payload.buf.take().freeze())));
|
Ok(Async::Ready(Some(payload.buf.take().freeze())))
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -586,12 +587,13 @@ impl InnerField {
|
|||||||
return Ok(Async::Ready(None));
|
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 {
|
if !self.eof {
|
||||||
let res = if let Some(ref mut len) = self.length {
|
let res = if let Some(ref mut len) = self.length {
|
||||||
InnerField::read_len(payload, len)?
|
InnerField::read_len(&mut *payload, len)?
|
||||||
} else {
|
} else {
|
||||||
InnerField::read_stream(payload, &self.boundary)?
|
InnerField::read_stream(&mut *payload, &self.boundary)?
|
||||||
};
|
};
|
||||||
|
|
||||||
match res {
|
match res {
|
||||||
@ -602,7 +604,7 @@ impl InnerField {
|
|||||||
}
|
}
|
||||||
|
|
||||||
match payload.readline()? {
|
match payload.readline()? {
|
||||||
None => Async::Ready(None),
|
None => Async::NotReady,
|
||||||
Some(line) => {
|
Some(line) => {
|
||||||
if line.as_ref() != b"\r\n" {
|
if line.as_ref() != b"\r\n" {
|
||||||
log::warn!("multipart field did not read all the data or it is malformed");
|
log::warn!("multipart field did not read all the data or it is malformed");
|
||||||
@ -622,7 +624,7 @@ impl InnerField {
|
|||||||
}
|
}
|
||||||
|
|
||||||
struct PayloadRef {
|
struct PayloadRef {
|
||||||
payload: Rc<UnsafeCell<PayloadBuffer>>,
|
payload: Rc<RefCell<PayloadBuffer>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PayloadRef {
|
impl PayloadRef {
|
||||||
@ -632,15 +634,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
|
where
|
||||||
'a: 'b,
|
'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() {
|
if s.current() {
|
||||||
let payload: &mut PayloadBuffer = unsafe { &mut *self.payload.get() };
|
Some(self.payload.borrow_mut())
|
||||||
Some(payload)
|
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
@ -781,6 +780,16 @@ impl PayloadBuffer {
|
|||||||
self.read_until(b"\n")
|
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
|
/// Put unprocessed data back to the buffer
|
||||||
pub fn unprocessed(&mut self, data: Bytes) {
|
pub fn unprocessed(&mut self, data: Bytes) {
|
||||||
let buf = BytesMut::from(data);
|
let buf = BytesMut::from(data);
|
||||||
@ -851,11 +860,43 @@ mod tests {
|
|||||||
(tx, rx.map_err(|_| panic!()).and_then(|res| res))
|
(tx, rx.map_err(|_| panic!()).and_then(|res| res))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
// Stream that returns from a Bytes, one char at a time and NotReady every other poll()
|
||||||
fn test_multipart() {
|
struct SlowStream {
|
||||||
run_on(|| {
|
bytes: Bytes,
|
||||||
let (sender, payload) = create_stream();
|
pos: usize,
|
||||||
|
ready: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SlowStream {
|
||||||
|
fn new(bytes: Bytes) -> SlowStream {
|
||||||
|
return SlowStream {
|
||||||
|
bytes: bytes,
|
||||||
|
pos: 0,
|
||||||
|
ready: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Stream for SlowStream {
|
||||||
|
type Item = Bytes;
|
||||||
|
type Error = PayloadError;
|
||||||
|
|
||||||
|
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
|
||||||
|
if !self.ready {
|
||||||
|
self.ready = true;
|
||||||
|
return Ok(Async::NotReady);
|
||||||
|
}
|
||||||
|
if self.pos == self.bytes.len() {
|
||||||
|
return Ok(Async::Ready(None));
|
||||||
|
}
|
||||||
|
let res = Ok(Async::Ready(Some(self.bytes.slice(self.pos, self.pos + 1))));
|
||||||
|
self.pos += 1;
|
||||||
|
self.ready = false;
|
||||||
|
res
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_simple_request_with_header() -> (Bytes, HeaderMap) {
|
||||||
let bytes = Bytes::from(
|
let bytes = Bytes::from(
|
||||||
"testasdadsad\r\n\
|
"testasdadsad\r\n\
|
||||||
--abbc761f78ff4d7cb7573b5a23f96ef0\r\n\
|
--abbc761f78ff4d7cb7573b5a23f96ef0\r\n\
|
||||||
@ -867,8 +908,6 @@ mod tests {
|
|||||||
data\r\n\
|
data\r\n\
|
||||||
--abbc761f78ff4d7cb7573b5a23f96ef0--\r\n",
|
--abbc761f78ff4d7cb7573b5a23f96ef0--\r\n",
|
||||||
);
|
);
|
||||||
sender.unbounded_send(Ok(bytes)).unwrap();
|
|
||||||
|
|
||||||
let mut headers = HeaderMap::new();
|
let mut headers = HeaderMap::new();
|
||||||
headers.insert(
|
headers.insert(
|
||||||
header::CONTENT_TYPE,
|
header::CONTENT_TYPE,
|
||||||
@ -876,6 +915,45 @@ mod tests {
|
|||||||
"multipart/mixed; boundary=\"abbc761f78ff4d7cb7573b5a23f96ef0\"",
|
"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();
|
||||||
|
|
||||||
|
sender.unbounded_send(Ok(bytes)).unwrap();
|
||||||
|
|
||||||
let mut multipart = Multipart::new(&headers, payload);
|
let mut multipart = Multipart::new(&headers, payload);
|
||||||
match multipart.poll().unwrap() {
|
match multipart.poll().unwrap() {
|
||||||
@ -923,34 +1001,38 @@ mod tests {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Retries on NotReady
|
||||||
|
fn loop_poll<T>(stream: &mut T) -> Poll<Option<T::Item>, T::Error>
|
||||||
|
where T: Stream {
|
||||||
|
loop {
|
||||||
|
let r = stream.poll();
|
||||||
|
match r {
|
||||||
|
Ok(Async::NotReady) => continue,
|
||||||
|
_ => return r,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Loops polling, collecting all bytes until end-of-field
|
||||||
|
fn get_whole_field(field: &mut Field) -> BytesMut {
|
||||||
|
let mut b = BytesMut::new();
|
||||||
|
loop {
|
||||||
|
match loop_poll(field) {
|
||||||
|
Ok(Async::Ready(Some(chunk))) => b.extend_from_slice(&chunk),
|
||||||
|
Ok(Async::Ready(None)) => return b,
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_stream() {
|
fn test_stream() {
|
||||||
run_on(|| {
|
run_on(|| {
|
||||||
let (sender, payload) = create_stream();
|
let (bytes, headers) = create_simple_request_with_header();
|
||||||
|
let payload = SlowStream::new(bytes);
|
||||||
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);
|
let mut multipart = Multipart::new(&headers, payload);
|
||||||
match multipart.poll().unwrap() {
|
match loop_poll(&mut multipart).unwrap() {
|
||||||
Async::Ready(Some(mut field)) => {
|
Async::Ready(Some(mut field)) => {
|
||||||
let cd = field.content_disposition().unwrap();
|
let cd = field.content_disposition().unwrap();
|
||||||
assert_eq!(cd.disposition, DispositionType::FormData);
|
assert_eq!(cd.disposition, DispositionType::FormData);
|
||||||
@ -959,37 +1041,18 @@ mod tests {
|
|||||||
assert_eq!(field.content_type().type_(), mime::TEXT);
|
assert_eq!(field.content_type().type_(), mime::TEXT);
|
||||||
assert_eq!(field.content_type().subtype(), mime::PLAIN);
|
assert_eq!(field.content_type().subtype(), mime::PLAIN);
|
||||||
|
|
||||||
match field.poll().unwrap() {
|
assert_eq!(get_whole_field(&mut field), "test");
|
||||||
Async::Ready(Some(chunk)) => assert_eq!(chunk, "test"),
|
|
||||||
_ => unreachable!(),
|
|
||||||
}
|
|
||||||
match field.poll().unwrap() {
|
|
||||||
Async::Ready(None) => (),
|
|
||||||
_ => unreachable!(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
}
|
}
|
||||||
|
|
||||||
match multipart.poll().unwrap() {
|
match loop_poll(&mut multipart).unwrap() {
|
||||||
Async::Ready(Some(mut field)) => {
|
Async::Ready(Some(mut field)) => {
|
||||||
assert_eq!(field.content_type().type_(), mime::TEXT);
|
assert_eq!(field.content_type().type_(), mime::TEXT);
|
||||||
assert_eq!(field.content_type().subtype(), mime::PLAIN);
|
assert_eq!(field.content_type().subtype(), mime::PLAIN);
|
||||||
|
|
||||||
match field.poll() {
|
assert_eq!(get_whole_field(&mut field), "data");
|
||||||
Ok(Async::Ready(Some(chunk))) => assert_eq!(chunk, "data"),
|
|
||||||
_ => unreachable!(),
|
|
||||||
}
|
}
|
||||||
match field.poll() {
|
|
||||||
Ok(Async::Ready(None)) => (),
|
|
||||||
_ => unreachable!(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => unreachable!(),
|
|
||||||
}
|
|
||||||
|
|
||||||
match multipart.poll().unwrap() {
|
|
||||||
Async::Ready(None) => (),
|
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
@ -1,5 +1,16 @@
|
|||||||
# Changes
|
# 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
|
||||||
|
|
||||||
## [0.1.0] - 2019-05-18
|
## [0.1.0] - 2019-05-18
|
||||||
|
|
||||||
* Use actix-web 1.0.0-rc
|
* Use actix-web 1.0.0-rc
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-session"
|
name = "actix-session"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Session for actix web framework."
|
description = "Session for actix web framework."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -24,12 +24,12 @@ default = ["cookie-session"]
|
|||||||
cookie-session = ["actix-web/secure-cookies"]
|
cookie-session = ["actix-web/secure-cookies"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = "1.0.0-rc"
|
actix-web = "1.0.0"
|
||||||
actix-service = "0.4.0"
|
actix-service = "0.4.1"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
derive_more = "0.14"
|
derive_more = "0.15.0"
|
||||||
futures = "0.1.25"
|
futures = "0.1.25"
|
||||||
hashbrown = "0.3.0"
|
hashbrown = "0.5.0"
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
time = "0.1.42"
|
time = "0.1.42"
|
||||||
|
1
actix-session/LICENSE-APACHE
Symbolic link
1
actix-session/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-APACHE
|
1
actix-session/LICENSE-MIT
Symbolic link
1
actix-session/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-MIT
|
@ -6,4 +6,4 @@
|
|||||||
* [API Documentation](https://docs.rs/actix-session/)
|
* [API Documentation](https://docs.rs/actix-session/)
|
||||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||||
* Cargo package: [actix-session](https://crates.io/crates/actix-session)
|
* 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 futures::Poll;
|
||||||
use serde_json::error::Error as JsonError;
|
use serde_json::error::Error as JsonError;
|
||||||
|
|
||||||
use crate::Session;
|
use crate::{Session, SessionStatus};
|
||||||
|
|
||||||
/// Errors that can occur during handling cookie session
|
/// Errors that can occur during handling cookie session
|
||||||
#[derive(Debug, From, Display)]
|
#[derive(Debug, From, Display)]
|
||||||
@ -119,7 +119,20 @@ impl CookieSessionInner {
|
|||||||
Ok(())
|
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() {
|
if let Ok(cookies) = req.cookies() {
|
||||||
for cookie in cookies.iter() {
|
for cookie in cookies.iter() {
|
||||||
if cookie.name() == self.name {
|
if cookie.name() == self.name {
|
||||||
@ -134,13 +147,13 @@ impl CookieSessionInner {
|
|||||||
};
|
};
|
||||||
if let Some(cookie) = cookie_opt {
|
if let Some(cookie) = cookie_opt {
|
||||||
if let Ok(val) = serde_json::from_str(cookie.value()) {
|
if let Ok(val) = serde_json::from_str(cookie.value()) {
|
||||||
return val;
|
return (false, val);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
HashMap::new()
|
(true, HashMap::new())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -296,23 +309,44 @@ where
|
|||||||
type Request = ServiceRequest;
|
type Request = ServiceRequest;
|
||||||
type Response = ServiceResponse<B>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = S::Error;
|
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> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
self.service.poll_ready()
|
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 {
|
fn call(&mut self, mut req: ServiceRequest) -> Self::Future {
|
||||||
let inner = self.inner.clone();
|
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);
|
Session::set_session(state.into_iter(), &mut req);
|
||||||
|
|
||||||
Box::new(self.service.call(req).map(move |mut res| {
|
Box::new(self.service.call(req).map(move |mut res| {
|
||||||
if let Some(state) = Session::get_changes(&mut res) {
|
match Session::get_changes(&mut res) {
|
||||||
|
(SessionStatus::Changed, Some(state))
|
||||||
|
| (SessionStatus::Renewed, Some(state)) => {
|
||||||
res.checked_expr(|res| inner.set_cookie(res, 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 {
|
} else {
|
||||||
res
|
res
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
(SessionStatus::Purged, _) => {
|
||||||
|
let _ = inner.remove_cookie(&mut res);
|
||||||
|
res
|
||||||
|
}
|
||||||
|
_ => res,
|
||||||
|
}
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -52,7 +52,9 @@ use serde::de::DeserializeOwned;
|
|||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use serde_json;
|
use serde_json;
|
||||||
|
|
||||||
|
#[cfg(feature = "cookie-session")]
|
||||||
mod cookie;
|
mod cookie;
|
||||||
|
#[cfg(feature = "cookie-session")]
|
||||||
pub use crate::cookie::CookieSession;
|
pub use crate::cookie::CookieSession;
|
||||||
|
|
||||||
/// The high-level interface you use to modify session data.
|
/// The high-level interface you use to modify session data.
|
||||||
@ -96,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)]
|
#[derive(Default)]
|
||||||
struct SessionInner {
|
struct SessionInner {
|
||||||
state: HashMap<String, String>,
|
state: HashMap<String, String>,
|
||||||
changed: bool,
|
pub status: SessionStatus,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Session {
|
impl Session {
|
||||||
@ -115,26 +130,47 @@ impl Session {
|
|||||||
/// Set a `value` from the session.
|
/// Set a `value` from the session.
|
||||||
pub fn set<T: Serialize>(&self, key: &str, value: T) -> Result<(), Error> {
|
pub fn set<T: Serialize>(&self, key: &str, value: T) -> Result<(), Error> {
|
||||||
let mut inner = self.0.borrow_mut();
|
let mut inner = self.0.borrow_mut();
|
||||||
inner.changed = true;
|
if inner.status != SessionStatus::Purged {
|
||||||
|
inner.status = SessionStatus::Changed;
|
||||||
inner
|
inner
|
||||||
.state
|
.state
|
||||||
.insert(key.to_owned(), serde_json::to_string(&value)?);
|
.insert(key.to_owned(), serde_json::to_string(&value)?);
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Remove value from the session.
|
/// Remove value from the session.
|
||||||
pub fn remove(&self, key: &str) {
|
pub fn remove(&self, key: &str) {
|
||||||
let mut inner = self.0.borrow_mut();
|
let mut inner = self.0.borrow_mut();
|
||||||
inner.changed = true;
|
if inner.status != SessionStatus::Purged {
|
||||||
|
inner.status = SessionStatus::Changed;
|
||||||
inner.state.remove(key);
|
inner.state.remove(key);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Clear the session.
|
/// Clear the session.
|
||||||
pub fn clear(&self) {
|
pub fn clear(&self) {
|
||||||
let mut inner = self.0.borrow_mut();
|
let mut inner = self.0.borrow_mut();
|
||||||
inner.changed = true;
|
if inner.status != SessionStatus::Purged {
|
||||||
|
inner.status = SessionStatus::Changed;
|
||||||
inner.state.clear()
|
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(
|
pub fn set_session(
|
||||||
data: impl Iterator<Item = (String, String)>,
|
data: impl Iterator<Item = (String, String)>,
|
||||||
@ -147,7 +183,10 @@ impl Session {
|
|||||||
|
|
||||||
pub fn get_changes<B>(
|
pub fn get_changes<B>(
|
||||||
res: &mut ServiceResponse<B>,
|
res: &mut ServiceResponse<B>,
|
||||||
) -> Option<impl Iterator<Item = (String, String)>> {
|
) -> (
|
||||||
|
SessionStatus,
|
||||||
|
Option<impl Iterator<Item = (String, String)>>,
|
||||||
|
) {
|
||||||
if let Some(s_impl) = res
|
if let Some(s_impl) = res
|
||||||
.request()
|
.request()
|
||||||
.extensions()
|
.extensions()
|
||||||
@ -155,9 +194,9 @@ impl Session {
|
|||||||
{
|
{
|
||||||
let state =
|
let state =
|
||||||
std::mem::replace(&mut s_impl.borrow_mut().state, HashMap::new());
|
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 {
|
} else {
|
||||||
None
|
(SessionStatus::Unchanged, None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -222,7 +261,8 @@ mod tests {
|
|||||||
session.remove("key");
|
session.remove("key");
|
||||||
|
|
||||||
let mut res = req.into_response(HttpResponse::Ok().finish());
|
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())]);
|
assert_eq!(changes, [("key2".to_string(), "\"value2\"".to_string())]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -239,4 +279,22 @@ mod tests {
|
|||||||
let res = session.get::<String>("key").unwrap();
|
let res = session.get::<String>("key").unwrap();
|
||||||
assert_eq!(res, Some("value".to_string()));
|
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,24 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [1.0.3] - 2019-11-14
|
||||||
|
|
||||||
|
* Update actix-web and actix-http dependencies
|
||||||
|
|
||||||
|
## [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.0.0] - 2019-05-29
|
||||||
|
|
||||||
|
* Update actix-http and actix-web
|
||||||
|
|
||||||
## [0.1.0-alpha.3] - 2019-04-02
|
## [0.1.0-alpha.3] - 2019-04-02
|
||||||
|
|
||||||
* Update actix-http and actix-web
|
* Update actix-http and actix-web
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-web-actors"
|
name = "actix-web-actors"
|
||||||
version = "1.0.0-beta.4"
|
version = "1.0.3"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix actors support for actix web framework."
|
description = "Actix actors support for actix web framework."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -18,13 +18,13 @@ name = "actix_web_actors"
|
|||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix = "0.8.2"
|
actix = "0.8.3"
|
||||||
actix-web = "1.0.0-beta.5"
|
actix-web = "1.0.9"
|
||||||
actix-http = "0.2.0"
|
actix-http = "0.2.11"
|
||||||
actix-codec = "0.1.2"
|
actix-codec = "0.1.2"
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
futures = "0.1.25"
|
futures = "0.1.25"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
env_logger = "0.6"
|
env_logger = "0.6"
|
||||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
actix-http-test = { version = "0.2.4", features=["ssl"] }
|
||||||
|
1
actix-web-actors/LICENSE-APACHE
Symbolic link
1
actix-web-actors/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-APACHE
|
1
actix-web-actors/LICENSE-MIT
Symbolic link
1
actix-web-actors/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-MIT
|
@ -1,3 +1,4 @@
|
|||||||
|
#![allow(clippy::borrow_interior_mutable_const)]
|
||||||
//! Actix actors integration for Actix web framework
|
//! Actix actors integration for Actix web framework
|
||||||
mod context;
|
mod context;
|
||||||
pub mod ws;
|
pub mod ws;
|
||||||
|
@ -35,15 +35,68 @@ where
|
|||||||
Ok(res.streaming(WebsocketContext::create(actor, stream)))
|
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.
|
/// Prepare `WebSocket` handshake response.
|
||||||
///
|
///
|
||||||
/// This function returns handshake `HttpResponse`, ready to send to peer.
|
/// This function returns handshake `HttpResponse`, ready to send to peer.
|
||||||
/// It does not perform any IO.
|
/// It does not perform any IO.
|
||||||
///
|
///
|
||||||
// /// `protocols` is a sequence of known protocols. On successful handshake,
|
/// `protocols` is a sequence of known protocols. On successful handshake,
|
||||||
// /// the returned response headers contain the first protocol in this list
|
/// the returned response headers contain the first protocol in this list
|
||||||
// /// which the server also knows.
|
/// which the server also knows.
|
||||||
pub fn handshake(req: &HttpRequest) -> Result<HttpResponseBuilder, HandshakeError> {
|
pub fn handshake_with_protocols(
|
||||||
|
req: &HttpRequest,
|
||||||
|
protocols: &[&str],
|
||||||
|
) -> Result<HttpResponseBuilder, HandshakeError> {
|
||||||
// WebSocket accepts only GET
|
// WebSocket accepts only GET
|
||||||
if *req.method() != Method::GET {
|
if *req.method() != Method::GET {
|
||||||
return Err(HandshakeError::GetMethodRequired);
|
return Err(HandshakeError::GetMethodRequired);
|
||||||
@ -92,11 +145,28 @@ pub fn handshake(req: &HttpRequest) -> Result<HttpResponseBuilder, HandshakeErro
|
|||||||
hash_key(key.as_ref())
|
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")
|
.upgrade("websocket")
|
||||||
.header(header::TRANSFER_ENCODING, "chunked")
|
.header(header::TRANSFER_ENCODING, "chunked")
|
||||||
.header(header::SEC_WEBSOCKET_ACCEPT, key.as_str())
|
.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
|
/// Execution context for `WebSockets` actors
|
||||||
@ -168,6 +238,24 @@ where
|
|||||||
#[inline]
|
#[inline]
|
||||||
/// Create a new Websocket context from a request and an actor
|
/// 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>
|
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
|
where
|
||||||
A: StreamHandler<Message, ProtocolError>,
|
A: StreamHandler<Message, ProtocolError>,
|
||||||
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
||||||
@ -177,9 +265,32 @@ where
|
|||||||
inner: ContextParts::new(mb.sender_producer()),
|
inner: ContextParts::new(mb.sender_producer()),
|
||||||
messages: VecDeque::new(),
|
messages: VecDeque::new(),
|
||||||
};
|
};
|
||||||
ctx.add_stream(WsStream::new(stream));
|
ctx.add_stream(WsStream::new(stream, Codec::new()));
|
||||||
|
|
||||||
WebsocketContextFut::new(ctx, actor, mb)
|
let addr = ctx.address();
|
||||||
|
|
||||||
|
(addr, WebsocketContextFut::new(ctx, actor, mb, Codec::new()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
/// Create a new Websocket context from a request, an actor, and a codec
|
||||||
|
pub fn with_codec<S>(
|
||||||
|
actor: A,
|
||||||
|
stream: S,
|
||||||
|
codec: Codec,
|
||||||
|
) -> impl Stream<Item = Bytes, Error = Error>
|
||||||
|
where
|
||||||
|
A: StreamHandler<Message, ProtocolError>,
|
||||||
|
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
||||||
|
{
|
||||||
|
let mb = Mailbox::default();
|
||||||
|
let mut ctx = WebsocketContext {
|
||||||
|
inner: ContextParts::new(mb.sender_producer()),
|
||||||
|
messages: VecDeque::new(),
|
||||||
|
};
|
||||||
|
ctx.add_stream(WsStream::new(stream, codec));
|
||||||
|
|
||||||
|
WebsocketContextFut::new(ctx, actor, mb, codec)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create a new Websocket context
|
/// Create a new Websocket context
|
||||||
@ -197,11 +308,11 @@ where
|
|||||||
inner: ContextParts::new(mb.sender_producer()),
|
inner: ContextParts::new(mb.sender_producer()),
|
||||||
messages: VecDeque::new(),
|
messages: VecDeque::new(),
|
||||||
};
|
};
|
||||||
ctx.add_stream(WsStream::new(stream));
|
ctx.add_stream(WsStream::new(stream, Codec::new()));
|
||||||
|
|
||||||
let act = f(&mut ctx);
|
let act = f(&mut ctx);
|
||||||
|
|
||||||
WebsocketContextFut::new(ctx, act, mb)
|
WebsocketContextFut::new(ctx, act, mb, Codec::new())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -288,11 +399,11 @@ impl<A> WebsocketContextFut<A>
|
|||||||
where
|
where
|
||||||
A: Actor<Context = WebsocketContext<A>>,
|
A: Actor<Context = WebsocketContext<A>>,
|
||||||
{
|
{
|
||||||
fn new(ctx: WebsocketContext<A>, act: A, mailbox: Mailbox<A>) -> Self {
|
fn new(ctx: WebsocketContext<A>, act: A, mailbox: Mailbox<A>, codec: Codec) -> Self {
|
||||||
let fut = ContextFut::new(ctx, act, mailbox);
|
let fut = ContextFut::new(ctx, act, mailbox);
|
||||||
WebsocketContextFut {
|
WebsocketContextFut {
|
||||||
fut,
|
fut,
|
||||||
encoder: Codec::new(),
|
encoder: codec,
|
||||||
buf: BytesMut::new(),
|
buf: BytesMut::new(),
|
||||||
closed: false,
|
closed: false,
|
||||||
}
|
}
|
||||||
@ -353,10 +464,10 @@ impl<S> WsStream<S>
|
|||||||
where
|
where
|
||||||
S: Stream<Item = Bytes, Error = PayloadError>,
|
S: Stream<Item = Bytes, Error = PayloadError>,
|
||||||
{
|
{
|
||||||
fn new(stream: S) -> Self {
|
fn new(stream: S, codec: Codec) -> Self {
|
||||||
Self {
|
Self {
|
||||||
stream,
|
stream,
|
||||||
decoder: Codec::new(),
|
decoder: codec,
|
||||||
buf: BytesMut::new(),
|
buf: BytesMut::new(),
|
||||||
closed: false,
|
closed: false,
|
||||||
}
|
}
|
||||||
@ -414,7 +525,7 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Frame::Binary(data) => Message::Binary(
|
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::Ping(s) => Message::Ping(s),
|
||||||
Frame::Pong(s) => Message::Pong(s),
|
Frame::Pong(s) => Message::Pong(s),
|
||||||
@ -543,5 +654,87 @@ mod tests {
|
|||||||
StatusCode::SWITCHING_PROTOCOLS,
|
StatusCode::SWITCHING_PROTOCOLS,
|
||||||
handshake(&req).unwrap().finish().status()
|
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)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,19 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.1.3] - 2019-10-14
|
||||||
|
|
||||||
|
* Bump up `syn` & `quote` to 1.0
|
||||||
|
|
||||||
|
* Provide better error message
|
||||||
|
|
||||||
|
## [0.1.2] - 2019-06-04
|
||||||
|
|
||||||
|
* Add macros for head, options, trace, connect and patch http methods
|
||||||
|
|
||||||
|
## [0.1.1] - 2019-06-01
|
||||||
|
|
||||||
|
* Add syn "extra-traits" feature
|
||||||
|
|
||||||
## [0.1.0] - 2019-05-18
|
## [0.1.0] - 2019-05-18
|
||||||
|
|
||||||
* Release
|
* Release
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-web-codegen"
|
name = "actix-web-codegen"
|
||||||
version = "0.1.0"
|
version = "0.1.3"
|
||||||
description = "Actix web proc macros"
|
description = "Actix web proc macros"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
@ -12,11 +12,12 @@ workspace = ".."
|
|||||||
proc-macro = true
|
proc-macro = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
quote = "0.6"
|
quote = "1"
|
||||||
syn = { version = "0.15", features = ["full", "parsing"] }
|
syn = { version = "1", features = ["full", "parsing"] }
|
||||||
|
proc-macro2 = "1"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-web = { version = "1.0.0-beta.5" }
|
actix-web = { version = "1.0.0" }
|
||||||
actix-http = { version = "0.2.0", features=["ssl"] }
|
actix-http = { version = "0.2.4", features=["ssl"] }
|
||||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||||
futures = { version = "0.1" }
|
futures = { version = "0.1" }
|
||||||
|
1
actix-web-codegen/LICENSE-APACHE
Symbolic link
1
actix-web-codegen/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-APACHE
|
1
actix-web-codegen/LICENSE-MIT
Symbolic link
1
actix-web-codegen/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../LICENSE-MIT
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user