mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-03 09:36:36 +02:00
Compare commits
149 Commits
web-v1.0.0
...
http-v0.2.
Author | SHA1 | Date | |
---|---|---|---|
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 | |||
21418c7414 | |||
fe781345d5 | |||
a614be7cb5 | |||
1eb89b8375 | |||
aa626a1e72 | |||
7f12b754e9 | |||
3f196f469d | |||
35eb378585 | |||
6db625f55b | |||
801cc2ed5d | |||
ded1e86e7e | |||
babf48c550 | |||
d3e807f6e9 | |||
7746e785c1 | |||
4e141d7f5d | |||
12842871fe | |||
fc85ae4014 | |||
5826f39dbe | |||
8ff56d7cd5 | |||
0843bce7ba |
@ -3,7 +3,7 @@ sudo: required
|
||||
dist: trusty
|
||||
|
||||
cache:
|
||||
cargo: true
|
||||
# cargo: true
|
||||
apt: true
|
||||
|
||||
matrix:
|
||||
@ -26,7 +26,7 @@ before_install:
|
||||
|
||||
before_cache: |
|
||||
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-04-02" ]]; then
|
||||
RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install cargo-tarpaulin
|
||||
RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install --version 0.6.11 cargo-tarpaulin
|
||||
fi
|
||||
|
||||
# Add clippy
|
||||
|
114
CHANGES.md
114
CHANGES.md
@ -1,5 +1,115 @@
|
||||
# Changes
|
||||
|
||||
## [1.0.6] - 2019-xx-xx
|
||||
|
||||
### Added
|
||||
|
||||
* Re-implement Host predicate (#989)
|
||||
|
||||
* Form immplements Responder, returning a `application/x-www-form-urlencoded` response
|
||||
|
||||
### Changed
|
||||
|
||||
* `Query` payload made `pub`. Allows user to pattern-match the payload.
|
||||
|
||||
|
||||
## [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 `test::TestRequest::set_json()` convenience method to automatically
|
||||
serialize data and set header in test requests.
|
||||
|
||||
* Add macros for head, options, trace, connect and patch http methods
|
||||
|
||||
### Changed
|
||||
|
||||
* Drop an unnecessary `Option<_>` indirection around `ServerBuilder` from `HttpServer`. #863
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fix Logger request time format, and use rfc3339. #867
|
||||
|
||||
* Clear http requests pool on app service drop #860
|
||||
|
||||
|
||||
## [1.0.0-rc] - 2019-05-18
|
||||
|
||||
### Add
|
||||
@ -7,7 +117,7 @@
|
||||
* Add `Query<T>::from_query()` to extract parameters from a query string. #846
|
||||
* `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.
|
||||
|
||||
@ -22,7 +132,7 @@
|
||||
|
||||
* Allow to set/override app data on scope level
|
||||
|
||||
### Changes
|
||||
### Changed
|
||||
|
||||
* `App::configure` take an `FnOnce` instead of `Fn`
|
||||
* Upgrade actix-net crates
|
||||
|
45
Cargo.toml
45
Cargo.toml
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web"
|
||||
version = "1.0.0-rc"
|
||||
version = "1.0.5"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
|
||||
readme = "README.md"
|
||||
@ -16,7 +16,7 @@ exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["ssl", "brotli", "flate2-zlib", "secure-cookies", "client", "rust-tls"]
|
||||
features = ["ssl", "brotli", "flate2-zlib", "secure-cookies", "client", "rust-tls", "uds"]
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "actix/actix-web", branch = "master" }
|
||||
@ -31,9 +31,11 @@ members = [
|
||||
".",
|
||||
"awc",
|
||||
"actix-http",
|
||||
"actix-cors",
|
||||
"actix-files",
|
||||
"actix-framed",
|
||||
"actix-session",
|
||||
"actix-identity",
|
||||
"actix-multipart",
|
||||
"actix-web-actors",
|
||||
"actix-web-codegen",
|
||||
@ -41,7 +43,7 @@ members = [
|
||||
]
|
||||
|
||||
[features]
|
||||
default = ["brotli", "flate2-zlib", "secure-cookies", "client", "fail"]
|
||||
default = ["brotli", "flate2-zlib", "client", "fail"]
|
||||
|
||||
# http client
|
||||
client = ["awc"]
|
||||
@ -66,28 +68,31 @@ ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
|
||||
# rustls
|
||||
rust-tls = ["rustls", "actix-server/rust-tls"]
|
||||
|
||||
# unix domain sockets support
|
||||
uds = ["actix-server/uds"]
|
||||
|
||||
[dependencies]
|
||||
actix-codec = "0.1.2"
|
||||
actix-service = "0.4.0"
|
||||
actix-utils = "0.4.1"
|
||||
actix-service = "0.4.1"
|
||||
actix-utils = "0.4.4"
|
||||
actix-router = "0.1.5"
|
||||
actix-rt = "0.2.2"
|
||||
actix-web-codegen = "0.1.0"
|
||||
actix-http = "0.2.0"
|
||||
actix-server = "0.5.1"
|
||||
actix-server-config = "0.1.1"
|
||||
actix-threadpool = "0.1.0"
|
||||
awc = { version = "0.2.0", optional = true }
|
||||
actix-rt = "0.2.4"
|
||||
actix-web-codegen = "0.1.2"
|
||||
actix-http = "0.2.7"
|
||||
actix-server = "0.6.0"
|
||||
actix-server-config = "0.1.2"
|
||||
actix-threadpool = "0.1.1"
|
||||
awc = { version = "0.2.2", optional = true }
|
||||
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
encoding = "0.2"
|
||||
derive_more = "0.15.0"
|
||||
encoding_rs = "0.8"
|
||||
futures = "0.1.25"
|
||||
hashbrown = "0.3.0"
|
||||
hashbrown = "0.5.0"
|
||||
log = "0.4"
|
||||
mime = "0.3"
|
||||
net2 = "0.2.33"
|
||||
parking_lot = "0.8"
|
||||
parking_lot = "0.9"
|
||||
regex = "1.0"
|
||||
serde = { version = "1.0", features=["derive"] }
|
||||
serde_json = "1.0"
|
||||
@ -100,10 +105,10 @@ openssl = { version="0.10", optional = true }
|
||||
rustls = { version = "0.15", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-http = { version = "0.2.0", features=["ssl", "brotli", "flate2-zlib"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
actix-files = { version = "0.1.0-beta.4" }
|
||||
rand = "0.6"
|
||||
actix = "0.8.3"
|
||||
actix-connect = "0.2.2"
|
||||
actix-http-test = "0.2.4"
|
||||
rand = "0.7"
|
||||
env_logger = "0.6"
|
||||
serde_derive = "1.0"
|
||||
tokio-timer = "0.2.8"
|
||||
|
102
MIGRATION.md
102
MIGRATION.md
@ -1,5 +1,94 @@
|
||||
## 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
|
||||
registration via `.service()` method.
|
||||
|
||||
@ -238,6 +327,17 @@
|
||||
|
||||
* Actors support have been moved to `actix-web-actors` crate
|
||||
|
||||
* Custom Error
|
||||
|
||||
Instead of error_response method alone, ResponseError now provides two methods: error_response and render_response respectively. Where, error_response creates the error response and render_response returns the error response to the caller.
|
||||
|
||||
Simplest migration from 0.7 to 1.0 shall include below method to the custom implementation of ResponseError:
|
||||
|
||||
```rust
|
||||
fn render_response(&self) -> HttpResponse {
|
||||
self.error_response()
|
||||
}
|
||||
```
|
||||
|
||||
## 0.7.15
|
||||
|
||||
|
@ -11,7 +11,7 @@ Actix web is a simple, pragmatic and extremely fast web framework for Rust.
|
||||
* Multipart streams
|
||||
* Static assets
|
||||
* 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)
|
||||
* 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/)
|
||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||
* 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
|
||||
|
||||
@ -61,7 +61,7 @@ You may consider checking out
|
||||
|
||||
## Benchmarks
|
||||
|
||||
* [TechEmpower Framework Benchmark](https://www.techempower.com/benchmarks/#section=data-r16&hw=ph&test=plaintext)
|
||||
* [TechEmpower Framework Benchmark](https://www.techempower.com/benchmarks/#section=data-r18)
|
||||
|
||||
## License
|
||||
|
||||
|
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 @@
|
||||
# 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-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
|
||||
//!
|
||||
//! CORS middleware could be used with application and with resource.
|
||||
@ -7,7 +8,7 @@
|
||||
//! # Example
|
||||
//!
|
||||
//! ```rust
|
||||
//! use actix_web::middleware::cors::Cors;
|
||||
//! use actix_cors::Cors;
|
||||
//! use actix_web::{http, web, App, HttpRequest, HttpResponse, HttpServer};
|
||||
//!
|
||||
//! fn index(req: HttpRequest) -> &'static str {
|
||||
@ -42,17 +43,15 @@ use std::iter::FromIterator;
|
||||
use std::rc::Rc;
|
||||
|
||||
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 futures::future::{ok, Either, Future, FutureResult};
|
||||
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
|
||||
#[derive(Debug, Display)]
|
||||
pub enum CorsError {
|
||||
@ -152,11 +151,11 @@ impl<T> AllOrSome<T> {
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_cors::Cors;
|
||||
/// use actix_web::http::header;
|
||||
/// use actix_web::middleware::cors;
|
||||
///
|
||||
/// # fn main() {
|
||||
/// let cors = cors::Cors::new()
|
||||
/// let cors = Cors::new()
|
||||
/// .allowed_origin("https://www.rust-lang.org/")
|
||||
/// .allowed_methods(vec!["GET", "POST"])
|
||||
/// .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
|
||||
@ -164,6 +163,7 @@ impl<T> AllOrSome<T> {
|
||||
/// .max_age(3600);
|
||||
/// # }
|
||||
/// ```
|
||||
#[derive(Default)]
|
||||
pub struct Cors {
|
||||
cors: Option<Inner>,
|
||||
methods: bool,
|
||||
@ -587,10 +587,10 @@ impl Inner {
|
||||
}
|
||||
Err(CorsError::BadOrigin)
|
||||
} else {
|
||||
return match self.origins {
|
||||
match self.origins {
|
||||
AllOrSome::All => Ok(()),
|
||||
_ => Err(CorsError::MissingOrigin),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -665,7 +665,7 @@ impl Inner {
|
||||
}
|
||||
Err(CorsError::BadRequestHeaders)
|
||||
} else {
|
||||
return Ok(());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -683,7 +683,7 @@ where
|
||||
type Error = Error;
|
||||
type Future = Either<
|
||||
FutureResult<Self::Response, Error>,
|
||||
Either<S::Future, Box<Future<Item = Self::Response, Error = Error>>>,
|
||||
Either<S::Future, Box<dyn Future<Item = Self::Response, Error = Error>>>,
|
||||
>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
@ -806,9 +806,9 @@ where
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_service::{IntoService, Transform};
|
||||
use actix_web::test::{self, block_on, TestRequest};
|
||||
|
||||
use super::*;
|
||||
use crate::test::{self, block_on, TestRequest};
|
||||
|
||||
impl Cors {
|
||||
fn finish<F, S, B>(self, srv: F) -> CorsMiddleware<S>
|
@ -1,5 +1,30 @@
|
||||
# Changes
|
||||
|
||||
## [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
|
||||
|
||||
* NamedFile last-modified check always fails due to nano-seconds
|
||||
in file modified date #820
|
||||
|
||||
## [0.1.0-beta.4] - 2019-05-12
|
||||
|
||||
* Update actix-web to beta.4
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-files"
|
||||
version = "0.1.0-beta.4"
|
||||
version = "0.1.4"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Static files support for actix web."
|
||||
readme = "README.md"
|
||||
@ -18,12 +18,13 @@ name = "actix_files"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "1.0.0-beta.5"
|
||||
actix-service = "0.4.0"
|
||||
actix-web = { version = "1.0.2", default-features = false }
|
||||
actix-http = "0.2.4"
|
||||
actix-service = "0.4.1"
|
||||
bitflags = "1"
|
||||
bytes = "0.4"
|
||||
futures = "0.1.25"
|
||||
derive_more = "0.14"
|
||||
derive_more = "0.15.0"
|
||||
log = "0.4"
|
||||
mime = "0.3"
|
||||
mime_guess = "2.0.0-alpha"
|
||||
@ -31,4 +32,4 @@ percent-encoding = "1.0"
|
||||
v_htmlescape = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = { version = "1.0.0-beta.5", features=["ssl"] }
|
||||
actix-web = { version = "1.0.2", 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
|
||||
use std::cell::RefCell;
|
||||
use std::fmt::Write;
|
||||
@ -50,14 +52,14 @@ pub struct ChunkedReadFile {
|
||||
size: u64,
|
||||
offset: u64,
|
||||
file: Option<File>,
|
||||
fut: Option<Box<Future<Item = (File, Bytes), Error = BlockingError<io::Error>>>>,
|
||||
fut: Option<Box<dyn Future<Item = (File, Bytes), Error = BlockingError<io::Error>>>>,
|
||||
counter: u64,
|
||||
}
|
||||
|
||||
fn handle_error(err: BlockingError<io::Error>) -> Error {
|
||||
match err {
|
||||
BlockingError::Error(err) => err.into(),
|
||||
BlockingError::Canceled => ErrorInternalServerError("Unexpected error").into(),
|
||||
BlockingError::Canceled => ErrorInternalServerError("Unexpected error"),
|
||||
}
|
||||
}
|
||||
|
||||
@ -105,7 +107,7 @@ impl Stream for ChunkedReadFile {
|
||||
}
|
||||
|
||||
type DirectoryRenderer =
|
||||
Fn(&Directory, &HttpRequest) -> Result<ServiceResponse, io::Error>;
|
||||
dyn Fn(&Directory, &HttpRequest) -> Result<ServiceResponse, io::Error>;
|
||||
|
||||
/// A directory; responds with the generated directory listing.
|
||||
#[derive(Debug)]
|
||||
@ -209,7 +211,7 @@ fn directory_listing(
|
||||
))
|
||||
}
|
||||
|
||||
type MimeOverride = Fn(&mime::Name) -> DispositionType;
|
||||
type MimeOverride = dyn Fn(&mime::Name) -> DispositionType;
|
||||
|
||||
/// Static files handling
|
||||
///
|
||||
@ -259,7 +261,7 @@ impl Files {
|
||||
pub fn new<T: Into<PathBuf>>(path: &str, dir: T) -> Files {
|
||||
let dir = dir.into().canonicalize().unwrap_or_else(|_| PathBuf::new());
|
||||
if !dir.is_dir() {
|
||||
log::error!("Specified path is not a directory");
|
||||
log::error!("Specified path is not a directory: {:?}", dir);
|
||||
}
|
||||
|
||||
Files {
|
||||
@ -312,23 +314,32 @@ impl Files {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
///Specifies whether to use ETag or not.
|
||||
/// Specifies whether to use ETag or not.
|
||||
///
|
||||
///Default is true.
|
||||
/// Default is true.
|
||||
pub fn use_etag(mut self, value: bool) -> Self {
|
||||
self.file_flags.set(named::Flags::ETAG, value);
|
||||
self
|
||||
}
|
||||
|
||||
#[inline]
|
||||
///Specifies whether to use Last-Modified or not.
|
||||
/// Specifies whether to use Last-Modified or not.
|
||||
///
|
||||
///Default is true.
|
||||
/// Default is true.
|
||||
pub fn use_last_modified(mut self, value: bool) -> Self {
|
||||
self.file_flags.set(named::Flags::LAST_MD, value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Disable `Content-Disposition` header.
|
||||
///
|
||||
/// By default Content-Disposition` header is enabled.
|
||||
#[inline]
|
||||
pub fn disable_content_disposition(mut self) -> Self {
|
||||
self.file_flags.remove(named::Flags::CONTENT_DISPOSITION);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets default handler which is used when no matched file could be found.
|
||||
pub fn default_handler<F, U>(mut self, f: F) -> Self
|
||||
where
|
||||
@ -370,7 +381,7 @@ impl NewService for Files {
|
||||
type Error = Error;
|
||||
type Service = FilesService;
|
||||
type InitError = ();
|
||||
type Future = Box<Future<Item = Self::Service, Error = Self::InitError>>;
|
||||
type Future = Box<dyn Future<Item = Self::Service, Error = Self::InitError>>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
let mut srv = FilesService {
|
||||
@ -416,7 +427,7 @@ impl FilesService {
|
||||
req: ServiceRequest,
|
||||
) -> Either<
|
||||
FutureResult<ServiceResponse, Error>,
|
||||
Box<Future<Item = ServiceResponse, Error = Error>>,
|
||||
Box<dyn Future<Item = ServiceResponse, Error = Error>>,
|
||||
> {
|
||||
log::debug!("Files: Failed to handle {}: {}", req.path(), e);
|
||||
if let Some(ref mut default) = self.default {
|
||||
@ -433,7 +444,7 @@ impl Service for FilesService {
|
||||
type Error = Error;
|
||||
type Future = Either<
|
||||
FutureResult<Self::Response, Self::Error>,
|
||||
Box<Future<Item = Self::Response, Error = Self::Error>>,
|
||||
Box<dyn Future<Item = Self::Response, Error = Self::Error>>,
|
||||
>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
@ -473,7 +484,7 @@ impl Service for FilesService {
|
||||
Err(e) => ServiceResponse::from_err(e, req),
|
||||
}))
|
||||
}
|
||||
Err(e) => return self.handle_err(e, req),
|
||||
Err(e) => self.handle_err(e, req),
|
||||
}
|
||||
} else if self.show_index {
|
||||
let dir = Directory::new(self.directory.clone(), path);
|
||||
@ -481,7 +492,7 @@ impl Service for FilesService {
|
||||
let x = (self.renderer)(&dir, &req);
|
||||
match x {
|
||||
Ok(resp) => Either::A(ok(resp)),
|
||||
Err(e) => return Either::A(ok(ServiceResponse::from_err(e, req))),
|
||||
Err(e) => Either::A(ok(ServiceResponse::from_err(e, req))),
|
||||
}
|
||||
} else {
|
||||
Either::A(ok(ServiceResponse::from_err(
|
||||
@ -636,6 +647,33 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_named_file_content_disposition() {
|
||||
assert!(NamedFile::open("test--").is_err());
|
||||
let mut file = NamedFile::open("Cargo.toml").unwrap();
|
||||
{
|
||||
file.file();
|
||||
let _f: &File = &file;
|
||||
}
|
||||
{
|
||||
let _f: &mut File = &mut file;
|
||||
}
|
||||
|
||||
let req = TestRequest::default().to_http_request();
|
||||
let resp = file.respond_to(&req).unwrap();
|
||||
assert_eq!(
|
||||
resp.headers().get(header::CONTENT_DISPOSITION).unwrap(),
|
||||
"inline; filename=\"Cargo.toml\""
|
||||
);
|
||||
|
||||
let file = NamedFile::open("Cargo.toml")
|
||||
.unwrap()
|
||||
.disable_content_disposition();
|
||||
let req = TestRequest::default().to_http_request();
|
||||
let resp = file.respond_to(&req).unwrap();
|
||||
assert!(resp.headers().get(header::CONTENT_DISPOSITION).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_named_file_set_content_type() {
|
||||
let mut file = NamedFile::open("Cargo.toml")
|
||||
@ -855,6 +893,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_named_file_content_length_headers() {
|
||||
// use actix_web::body::{MessageBody, ResponseBody};
|
||||
|
||||
let mut srv = test::init_service(
|
||||
App::new().service(Files::new("test", ".").index_file("tests/test.binary")),
|
||||
);
|
||||
@ -864,16 +904,15 @@ mod tests {
|
||||
.uri("/t%65st/tests/test.binary")
|
||||
.header(header::RANGE, "bytes=10-20")
|
||||
.to_request();
|
||||
let response = test::call_service(&mut srv, request);
|
||||
let _response = test::call_service(&mut srv, request);
|
||||
|
||||
let contentlength = response
|
||||
.headers()
|
||||
.get(header::CONTENT_LENGTH)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(contentlength, "11");
|
||||
// let contentlength = response
|
||||
// .headers()
|
||||
// .get(header::CONTENT_LENGTH)
|
||||
// .unwrap()
|
||||
// .to_str()
|
||||
// .unwrap();
|
||||
// assert_eq!(contentlength, "11");
|
||||
|
||||
// Invalid range header
|
||||
let request = TestRequest::get()
|
||||
@ -888,16 +927,15 @@ mod tests {
|
||||
.uri("/t%65st/tests/test.binary")
|
||||
// .no_default_headers()
|
||||
.to_request();
|
||||
let response = test::call_service(&mut srv, request);
|
||||
let _response = test::call_service(&mut srv, request);
|
||||
|
||||
let contentlength = response
|
||||
.headers()
|
||||
.get(header::CONTENT_LENGTH)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(contentlength, "100");
|
||||
// let contentlength = response
|
||||
// .headers()
|
||||
// .get(header::CONTENT_LENGTH)
|
||||
// .unwrap()
|
||||
// .to_str()
|
||||
// .unwrap();
|
||||
// assert_eq!(contentlength, "100");
|
||||
|
||||
// chunked
|
||||
let request = TestRequest::get()
|
||||
@ -926,6 +964,29 @@ mod tests {
|
||||
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]
|
||||
fn test_static_files_with_spaces() {
|
||||
let mut srv = test::init_service(
|
||||
|
@ -11,6 +11,7 @@ use bitflags::bitflags;
|
||||
use mime;
|
||||
use mime_guess::guess_mime_type;
|
||||
|
||||
use actix_http::body::SizedStream;
|
||||
use actix_web::http::header::{
|
||||
self, ContentDisposition, DispositionParam, DispositionType,
|
||||
};
|
||||
@ -22,9 +23,10 @@ use crate::range::HttpRange;
|
||||
use crate::ChunkedReadFile;
|
||||
|
||||
bitflags! {
|
||||
pub(crate) struct Flags: u32 {
|
||||
const ETAG = 0b00000001;
|
||||
const LAST_MD = 0b00000010;
|
||||
pub(crate) struct Flags: u8 {
|
||||
const ETAG = 0b0000_0001;
|
||||
const LAST_MD = 0b0000_0010;
|
||||
const CONTENT_DISPOSITION = 0b0000_0100;
|
||||
}
|
||||
}
|
||||
|
||||
@ -39,13 +41,13 @@ impl Default for Flags {
|
||||
pub struct NamedFile {
|
||||
path: PathBuf,
|
||||
file: File,
|
||||
modified: Option<SystemTime>,
|
||||
pub(crate) md: Metadata,
|
||||
pub(crate) flags: Flags,
|
||||
pub(crate) status_code: StatusCode,
|
||||
pub(crate) content_type: mime::Mime,
|
||||
pub(crate) content_disposition: header::ContentDisposition,
|
||||
pub(crate) md: Metadata,
|
||||
modified: Option<SystemTime>,
|
||||
pub(crate) encoding: Option<ContentEncoding>,
|
||||
pub(crate) status_code: StatusCode,
|
||||
pub(crate) flags: Flags,
|
||||
}
|
||||
|
||||
impl NamedFile {
|
||||
@ -171,11 +173,21 @@ impl NamedFile {
|
||||
/// sent to the peer. By default the disposition is `inline` for text,
|
||||
/// image, and video content types, and `attachment` otherwise, and
|
||||
/// the filename is taken from the path provided in the `open` method
|
||||
/// after converting it to UTF-8 using
|
||||
/// after converting it to UTF-8 using.
|
||||
/// [to_string_lossy](https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.to_string_lossy).
|
||||
#[inline]
|
||||
pub fn set_content_disposition(mut self, cd: header::ContentDisposition) -> Self {
|
||||
self.content_disposition = cd;
|
||||
self.flags.insert(Flags::CONTENT_DISPOSITION);
|
||||
self
|
||||
}
|
||||
|
||||
/// Disable `Content-Disposition` header.
|
||||
///
|
||||
/// By default Content-Disposition` header is enabled.
|
||||
#[inline]
|
||||
pub fn disable_content_disposition(mut self) -> Self {
|
||||
self.flags.remove(Flags::CONTENT_DISPOSITION);
|
||||
self
|
||||
}
|
||||
|
||||
@ -293,10 +305,12 @@ impl Responder for NamedFile {
|
||||
if self.status_code != StatusCode::OK {
|
||||
let mut resp = HttpResponse::build(self.status_code);
|
||||
resp.set(header::ContentType(self.content_type.clone()))
|
||||
.header(
|
||||
header::CONTENT_DISPOSITION,
|
||||
self.content_disposition.to_string(),
|
||||
);
|
||||
.if_true(self.flags.contains(Flags::CONTENT_DISPOSITION), |res| {
|
||||
res.header(
|
||||
header::CONTENT_DISPOSITION,
|
||||
self.content_disposition.to_string(),
|
||||
);
|
||||
});
|
||||
if let Some(current_encoding) = self.encoding {
|
||||
resp.encoding(current_encoding);
|
||||
}
|
||||
@ -310,8 +324,8 @@ impl Responder for NamedFile {
|
||||
return Ok(resp.streaming(reader));
|
||||
}
|
||||
|
||||
match req.method() {
|
||||
&Method::HEAD | &Method::GET => (),
|
||||
match *req.method() {
|
||||
Method::HEAD | Method::GET => (),
|
||||
_ => {
|
||||
return Ok(HttpResponse::MethodNotAllowed()
|
||||
.header(header::CONTENT_TYPE, "text/plain")
|
||||
@ -337,7 +351,12 @@ impl Responder for NamedFile {
|
||||
} else if let (Some(ref m), Some(header::IfUnmodifiedSince(ref since))) =
|
||||
(last_modified, req.get_header())
|
||||
{
|
||||
m > since
|
||||
let t1: SystemTime = m.clone().into();
|
||||
let t2: SystemTime = since.clone().into();
|
||||
match (t1.duration_since(UNIX_EPOCH), t2.duration_since(UNIX_EPOCH)) {
|
||||
(Ok(t1), Ok(t2)) => t1 > t2,
|
||||
_ => false,
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
@ -350,17 +369,24 @@ impl Responder for NamedFile {
|
||||
} else if let (Some(ref m), Some(header::IfModifiedSince(ref since))) =
|
||||
(last_modified, req.get_header())
|
||||
{
|
||||
m <= since
|
||||
let t1: SystemTime = m.clone().into();
|
||||
let t2: SystemTime = since.clone().into();
|
||||
match (t1.duration_since(UNIX_EPOCH), t2.duration_since(UNIX_EPOCH)) {
|
||||
(Ok(t1), Ok(t2)) => t1 <= t2,
|
||||
_ => false,
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
let mut resp = HttpResponse::build(self.status_code);
|
||||
resp.set(header::ContentType(self.content_type.clone()))
|
||||
.header(
|
||||
header::CONTENT_DISPOSITION,
|
||||
self.content_disposition.to_string(),
|
||||
);
|
||||
.if_true(self.flags.contains(Flags::CONTENT_DISPOSITION), |res| {
|
||||
res.header(
|
||||
header::CONTENT_DISPOSITION,
|
||||
self.content_disposition.to_string(),
|
||||
);
|
||||
});
|
||||
// default compressing
|
||||
if let Some(current_encoding) = self.encoding {
|
||||
resp.encoding(current_encoding);
|
||||
@ -403,28 +429,22 @@ impl Responder for NamedFile {
|
||||
};
|
||||
};
|
||||
|
||||
resp.header(header::CONTENT_LENGTH, format!("{}", length));
|
||||
|
||||
if precondition_failed {
|
||||
return Ok(resp.status(StatusCode::PRECONDITION_FAILED).finish());
|
||||
} else if not_modified {
|
||||
return Ok(resp.status(StatusCode::NOT_MODIFIED).finish());
|
||||
}
|
||||
|
||||
if *req.method() == Method::HEAD {
|
||||
Ok(resp.finish())
|
||||
} else {
|
||||
let reader = ChunkedReadFile {
|
||||
offset,
|
||||
size: length,
|
||||
file: Some(self.file),
|
||||
fut: None,
|
||||
counter: 0,
|
||||
};
|
||||
if offset != 0 || length != self.md.len() {
|
||||
return Ok(resp.status(StatusCode::PARTIAL_CONTENT).streaming(reader));
|
||||
};
|
||||
Ok(resp.streaming(reader))
|
||||
}
|
||||
let reader = ChunkedReadFile {
|
||||
offset,
|
||||
size: length,
|
||||
file: Some(self.file),
|
||||
fut: None,
|
||||
counter: 0,
|
||||
};
|
||||
if offset != 0 || length != self.md.len() {
|
||||
return Ok(resp.status(StatusCode::PARTIAL_CONTENT).streaming(reader));
|
||||
};
|
||||
Ok(resp.body(SizedStream::new(length, reader)))
|
||||
}
|
||||
}
|
||||
|
@ -5,7 +5,7 @@ pub struct HttpRange {
|
||||
pub length: u64,
|
||||
}
|
||||
|
||||
static PREFIX: &'static str = "bytes=";
|
||||
static PREFIX: &str = "bytes=";
|
||||
const PREFIX_LEN: usize = 6;
|
||||
|
||||
impl HttpRange {
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-framed"
|
||||
version = "0.2.0"
|
||||
version = "0.2.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix framed app server"
|
||||
readme = "README.md"
|
||||
@ -21,18 +21,18 @@ path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-codec = "0.1.2"
|
||||
actix-service = "0.4.0"
|
||||
actix-utils = "0.4.0"
|
||||
actix-service = "0.4.1"
|
||||
actix-router = "0.1.2"
|
||||
actix-rt = "0.2.2"
|
||||
actix-http = "0.2.0"
|
||||
actix-server-config = "0.1.1"
|
||||
actix-http = "0.2.7"
|
||||
actix-server-config = "0.1.2"
|
||||
|
||||
bytes = "0.4"
|
||||
futures = "0.1.25"
|
||||
log = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-server = { version = "0.5.0", features=["ssl"] }
|
||||
actix-server = { version = "0.6.0", features=["ssl"] }
|
||||
actix-connect = { version = "0.2.0", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.4", features=["ssl"] }
|
||||
actix-utils = "0.4.4"
|
||||
|
@ -1,5 +1,10 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.1] - 2019-07-20
|
||||
|
||||
* Remove unneeded actix-utils dependency
|
||||
|
||||
|
||||
## [0.2.0] - 2019-05-12
|
||||
|
||||
* Update dependencies
|
||||
|
@ -6,14 +6,13 @@ use actix_http::{Error, Request, Response};
|
||||
use actix_router::{Path, Router, Url};
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{IntoNewService, NewService, Service};
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use crate::helpers::{BoxedHttpNewService, BoxedHttpService, HttpNewService};
|
||||
use crate::request::FramedRequest;
|
||||
use crate::state::State;
|
||||
|
||||
type BoxedResponse = Box<Future<Item = (), Error = Error>>;
|
||||
type BoxedResponse = Box<dyn Future<Item = (), Error = Error>>;
|
||||
|
||||
pub trait HttpServiceFactory {
|
||||
type Factory: NewService;
|
||||
@ -61,7 +60,7 @@ impl<T: 'static, S: 'static> FramedApp<T, S> {
|
||||
Request = FramedRequest<T, S>,
|
||||
Response = (),
|
||||
Error = Error,
|
||||
Future = Box<Future<Item = (), Error = Error>>,
|
||||
Future = Box<dyn Future<Item = (), Error = Error>>,
|
||||
>,
|
||||
{
|
||||
let path = factory.path().to_string();
|
||||
@ -100,7 +99,7 @@ where
|
||||
type Response = ();
|
||||
type Error = Error;
|
||||
type InitError = ();
|
||||
type Service = CloneableService<FramedAppService<T, S>>;
|
||||
type Service = FramedAppService<T, S>;
|
||||
type Future = CreateService<T, S>;
|
||||
|
||||
fn new_service(&self, _: &ServerConfig) -> Self::Future {
|
||||
@ -129,7 +128,7 @@ pub struct CreateService<T, S> {
|
||||
enum CreateServiceItem<T, S> {
|
||||
Future(
|
||||
Option<String>,
|
||||
Box<Future<Item = BoxedHttpService<FramedRequest<T, S>>, Error = ()>>,
|
||||
Box<dyn Future<Item = BoxedHttpService<FramedRequest<T, S>>, Error = ()>>,
|
||||
),
|
||||
Service(String, BoxedHttpService<FramedRequest<T, S>>),
|
||||
}
|
||||
@ -138,7 +137,7 @@ impl<S: 'static, T: 'static> Future for CreateService<T, S>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
{
|
||||
type Item = CloneableService<FramedAppService<T, S>>;
|
||||
type Item = FramedAppService<T, S>;
|
||||
type Error = ();
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
@ -177,10 +176,10 @@ where
|
||||
}
|
||||
router
|
||||
});
|
||||
Ok(Async::Ready(CloneableService::new(FramedAppService {
|
||||
Ok(Async::Ready(FramedAppService {
|
||||
router: router.finish(),
|
||||
state: self.state.clone(),
|
||||
})))
|
||||
}))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
|
@ -3,23 +3,23 @@ use actix_service::{NewService, Service};
|
||||
use futures::{Future, Poll};
|
||||
|
||||
pub(crate) type BoxedHttpService<Req> = Box<
|
||||
Service<
|
||||
dyn Service<
|
||||
Request = Req,
|
||||
Response = (),
|
||||
Error = Error,
|
||||
Future = Box<Future<Item = (), Error = Error>>,
|
||||
Future = Box<dyn Future<Item = (), Error = Error>>,
|
||||
>,
|
||||
>;
|
||||
|
||||
pub(crate) type BoxedHttpNewService<Req> = Box<
|
||||
NewService<
|
||||
dyn NewService<
|
||||
Config = (),
|
||||
Request = Req,
|
||||
Response = (),
|
||||
Error = Error,
|
||||
InitError = (),
|
||||
Service = BoxedHttpService<Req>,
|
||||
Future = Box<Future<Item = BoxedHttpService<Req>, Error = ()>>,
|
||||
Future = Box<dyn Future<Item = BoxedHttpService<Req>, Error = ()>>,
|
||||
>,
|
||||
>;
|
||||
|
||||
@ -30,7 +30,7 @@ where
|
||||
T: NewService<Response = (), Error = Error>,
|
||||
T::Response: 'static,
|
||||
T::Future: 'static,
|
||||
T::Service: Service<Future = Box<Future<Item = (), Error = Error>>> + 'static,
|
||||
T::Service: Service<Future = Box<dyn Future<Item = (), Error = Error>>> + 'static,
|
||||
<T::Service as Service>::Future: 'static,
|
||||
{
|
||||
pub fn new(service: T) -> Self {
|
||||
@ -43,7 +43,7 @@ where
|
||||
T: NewService<Config = (), Response = (), Error = Error>,
|
||||
T::Request: 'static,
|
||||
T::Future: 'static,
|
||||
T::Service: Service<Future = Box<Future<Item = (), Error = Error>>> + 'static,
|
||||
T::Service: Service<Future = Box<dyn Future<Item = (), Error = Error>>> + 'static,
|
||||
<T::Service as Service>::Future: 'static,
|
||||
{
|
||||
type Config = ();
|
||||
@ -52,7 +52,7 @@ where
|
||||
type Error = Error;
|
||||
type InitError = ();
|
||||
type Service = BoxedHttpService<T::Request>;
|
||||
type Future = Box<Future<Item = Self::Service, Error = ()>>;
|
||||
type Future = Box<dyn Future<Item = Self::Service, Error = ()>>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
Box::new(self.0.new_service(&()).map_err(|_| ()).and_then(|service| {
|
||||
@ -70,7 +70,7 @@ impl<T> Service for HttpServiceWrapper<T>
|
||||
where
|
||||
T: Service<
|
||||
Response = (),
|
||||
Future = Box<Future<Item = (), Error = Error>>,
|
||||
Future = Box<dyn Future<Item = (), Error = Error>>,
|
||||
Error = Error,
|
||||
>,
|
||||
T::Request: 'static,
|
||||
@ -78,7 +78,7 @@ where
|
||||
type Request = T::Request;
|
||||
type Response = ();
|
||||
type Error = Error;
|
||||
type Future = Box<Future<Item = (), Error = Error>>;
|
||||
type Future = Box<dyn Future<Item = (), Error = Error>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.service.poll_ready()
|
||||
|
@ -1,3 +1,4 @@
|
||||
#![allow(clippy::type_complexity, clippy::new_without_default, dead_code)]
|
||||
mod app;
|
||||
mod helpers;
|
||||
mod request;
|
||||
|
@ -140,7 +140,7 @@ where
|
||||
type Request = FramedRequest<Io, S>;
|
||||
type Response = ();
|
||||
type Error = Error;
|
||||
type Future = Box<Future<Item = (), Error = Error>>;
|
||||
type Future = Box<dyn Future<Item = (), Error = Error>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
|
@ -1,5 +1,83 @@
|
||||
# Changes
|
||||
|
||||
## [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
|
||||
|
||||
### Fixed
|
||||
|
||||
* Parse incoming stream before closing stream on disconnect #868
|
||||
|
||||
|
||||
## [0.2.1] - 2019-05-25
|
||||
|
||||
### Fixed
|
||||
|
||||
* Handle socket read disconnect
|
||||
|
||||
|
||||
## [0.2.0] - 2019-05-12
|
||||
|
||||
### Changed
|
||||
@ -49,7 +127,7 @@
|
||||
|
||||
## [0.1.1] - 2019-04-19
|
||||
|
||||
### Changes
|
||||
### Changed
|
||||
|
||||
* Cookie::max_age() accepts value in seconds
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-http"
|
||||
version = "0.2.0"
|
||||
version = "0.2.8"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix http primitives"
|
||||
readme = "README.md"
|
||||
@ -28,6 +28,9 @@ default = []
|
||||
# openssl
|
||||
ssl = ["openssl", "actix-connect/ssl"]
|
||||
|
||||
# rustls support
|
||||
rust-tls = ["rustls", "webpki-roots", "actix-connect/rust-tls"]
|
||||
|
||||
# brotli encoding, requires c compiler
|
||||
brotli = ["brotli2"]
|
||||
|
||||
@ -44,23 +47,23 @@ fail = ["failure"]
|
||||
secure-cookies = ["ring"]
|
||||
|
||||
[dependencies]
|
||||
actix-service = "0.4.0"
|
||||
actix-service = "0.4.1"
|
||||
actix-codec = "0.1.2"
|
||||
actix-connect = "0.2.0"
|
||||
actix-utils = "0.4.0"
|
||||
actix-server-config = "0.1.1"
|
||||
actix-threadpool = "0.1.0"
|
||||
actix-connect = "0.2.2"
|
||||
actix-utils = "0.4.4"
|
||||
actix-server-config = "0.1.2"
|
||||
actix-threadpool = "0.1.1"
|
||||
|
||||
base64 = "0.10"
|
||||
bitflags = "1.0"
|
||||
bytes = "0.4"
|
||||
byteorder = "1.2"
|
||||
copyless = "0.1.2"
|
||||
derive_more = "0.14"
|
||||
copyless = "0.1.4"
|
||||
derive_more = "0.15.0"
|
||||
either = "1.5.2"
|
||||
encoding = "0.2"
|
||||
encoding_rs = "0.8"
|
||||
futures = "0.1.25"
|
||||
hashbrown = "0.3.0"
|
||||
hashbrown = "0.5.0"
|
||||
h2 = "0.1.16"
|
||||
http = "0.1.17"
|
||||
httparse = "1.3"
|
||||
@ -70,7 +73,7 @@ language-tags = "0.2"
|
||||
log = "0.4"
|
||||
mime = "0.3"
|
||||
percent-encoding = "1.0"
|
||||
rand = "0.6"
|
||||
rand = "0.7"
|
||||
regex = "1.0"
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
@ -81,7 +84,7 @@ time = "0.1.42"
|
||||
tokio-tcp = "0.1.3"
|
||||
tokio-timer = "0.2.8"
|
||||
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
|
||||
ring = { version = "0.14.6", optional = true }
|
||||
@ -93,13 +96,15 @@ flate2 = { version="1.0.7", optional = true, default-features = false }
|
||||
# optional deps
|
||||
failure = { version = "0.1.5", optional = true }
|
||||
openssl = { version="0.10", optional = true }
|
||||
rustls = { version = "0.15.2", optional = true }
|
||||
webpki-roots = { version = "0.16", optional = true }
|
||||
chrono = "0.4.6"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.2"
|
||||
actix-server = { version = "0.5.0", features=["ssl"] }
|
||||
actix-server = { version = "0.6.0", features=["ssl"] }
|
||||
actix-connect = { version = "0.2.0", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.4", features=["ssl"] }
|
||||
env_logger = "0.6"
|
||||
serde_derive = "1.0"
|
||||
openssl = { version="0.10" }
|
||||
|
@ -234,6 +234,25 @@ impl From<BytesMut> for Body {
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
fn size(&self) -> BodySize {
|
||||
BodySize::Sized(self.len())
|
||||
@ -366,7 +385,7 @@ where
|
||||
/// 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.
|
||||
pub struct SizedStream<S> {
|
||||
size: usize,
|
||||
size: u64,
|
||||
stream: S,
|
||||
}
|
||||
|
||||
@ -374,7 +393,7 @@ impl<S> SizedStream<S>
|
||||
where
|
||||
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 }
|
||||
}
|
||||
}
|
||||
@ -384,7 +403,7 @@ where
|
||||
S: Stream<Item = Bytes, Error = Error>,
|
||||
{
|
||||
fn size(&self) -> BodySize {
|
||||
BodySize::Sized(self.size)
|
||||
BodySize::Sized64(self.size)
|
||||
}
|
||||
|
||||
fn poll_next(&mut self) -> Poll<Option<Bytes>, Error> {
|
||||
|
@ -1,5 +1,6 @@
|
||||
use std::fmt;
|
||||
use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_codec::Framed;
|
||||
use actix_server_config::ServerConfig as SrvConfig;
|
||||
@ -10,6 +11,7 @@ use crate::config::{KeepAlive, ServiceConfig};
|
||||
use crate::error::Error;
|
||||
use crate::h1::{Codec, ExpectHandler, H1Service, UpgradeHandler};
|
||||
use crate::h2::H2Service;
|
||||
use crate::helpers::{Data, DataFactory};
|
||||
use crate::request::Request;
|
||||
use crate::response::Response;
|
||||
use crate::service::HttpService;
|
||||
@ -24,6 +26,7 @@ pub struct HttpServiceBuilder<T, S, X = ExpectHandler, U = UpgradeHandler<T>> {
|
||||
client_disconnect: u64,
|
||||
expect: X,
|
||||
upgrade: Option<U>,
|
||||
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
_t: PhantomData<(T, S)>,
|
||||
}
|
||||
|
||||
@ -41,6 +44,7 @@ where
|
||||
client_disconnect: 0,
|
||||
expect: ExpectHandler,
|
||||
upgrade: None,
|
||||
on_connect: None,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@ -115,6 +119,7 @@ where
|
||||
client_disconnect: self.client_disconnect,
|
||||
expect: expect.into_new_service(),
|
||||
upgrade: self.upgrade,
|
||||
on_connect: self.on_connect,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@ -140,10 +145,24 @@ where
|
||||
client_disconnect: self.client_disconnect,
|
||||
expect: self.expect,
|
||||
upgrade: Some(upgrade.into_new_service()),
|
||||
on_connect: self.on_connect,
|
||||
_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.
|
||||
pub fn h1<F, P, B>(self, service: F) -> H1Service<T, P, S, B, X, U>
|
||||
where
|
||||
@ -161,6 +180,7 @@ where
|
||||
H1Service::with_config(cfg, service.into_new_service())
|
||||
.expect(self.expect)
|
||||
.upgrade(self.upgrade)
|
||||
.on_connect(self.on_connect)
|
||||
}
|
||||
|
||||
/// Finish service configuration and create *http service* for HTTP/2 protocol.
|
||||
@ -199,5 +219,6 @@ where
|
||||
HttpService::with_config(cfg, service.into_new_service())
|
||||
.expect(self.expect)
|
||||
.upgrade(self.upgrade)
|
||||
.on_connect(self.on_connect)
|
||||
}
|
||||
}
|
||||
|
@ -94,7 +94,8 @@ where
|
||||
T: AsyncRead + AsyncWrite + 'static,
|
||||
{
|
||||
type Io = T;
|
||||
type Future = Box<Future<Item = (ResponseHead, Payload), Error = SendRequestError>>;
|
||||
type Future =
|
||||
Box<dyn Future<Item = (ResponseHead, Payload), Error = SendRequestError>>;
|
||||
|
||||
fn protocol(&self) -> Protocol {
|
||||
match self.io {
|
||||
@ -129,7 +130,7 @@ where
|
||||
|
||||
type TunnelFuture = Either<
|
||||
Box<
|
||||
Future<
|
||||
dyn Future<
|
||||
Item = (ResponseHead, Framed<Self::Io, ClientCodec>),
|
||||
Error = SendRequestError,
|
||||
>,
|
||||
@ -169,7 +170,8 @@ where
|
||||
B: AsyncRead + AsyncWrite + 'static,
|
||||
{
|
||||
type Io = EitherIo<A, B>;
|
||||
type Future = Box<Future<Item = (ResponseHead, Payload), Error = SendRequestError>>;
|
||||
type Future =
|
||||
Box<dyn Future<Item = (ResponseHead, Payload), Error = SendRequestError>>;
|
||||
|
||||
fn protocol(&self) -> Protocol {
|
||||
match self {
|
||||
@ -190,7 +192,7 @@ where
|
||||
}
|
||||
|
||||
type TunnelFuture = Box<
|
||||
Future<
|
||||
dyn Future<
|
||||
Item = (ResponseHead, Framed<Self::Io, ClientCodec>),
|
||||
Error = SendRequestError,
|
||||
>,
|
||||
|
@ -17,9 +17,21 @@ use super::pool::{ConnectionPool, Protocol};
|
||||
use super::Connect;
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
use openssl::ssl::SslConnector;
|
||||
use openssl::ssl::SslConnector as OpensslConnector;
|
||||
|
||||
#[cfg(not(feature = "ssl"))]
|
||||
#[cfg(feature = "rust-tls")]
|
||||
use rustls::ClientConfig;
|
||||
#[cfg(feature = "rust-tls")]
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(any(feature = "ssl", feature = "rust-tls"))]
|
||||
enum SslConnector {
|
||||
#[cfg(feature = "ssl")]
|
||||
Openssl(OpensslConnector),
|
||||
#[cfg(feature = "rust-tls")]
|
||||
Rustls(Arc<ClientConfig>),
|
||||
}
|
||||
#[cfg(not(any(feature = "ssl", feature = "rust-tls")))]
|
||||
type SslConnector = ();
|
||||
|
||||
/// Manages http client network connectivity
|
||||
@ -46,7 +58,11 @@ pub struct Connector<T, U> {
|
||||
_t: PhantomData<U>,
|
||||
}
|
||||
|
||||
trait Io: AsyncRead + AsyncWrite {}
|
||||
impl<T: AsyncRead + AsyncWrite> Io for T {}
|
||||
|
||||
impl Connector<(), ()> {
|
||||
#[allow(clippy::new_ret_no_self)]
|
||||
pub fn new() -> Connector<
|
||||
impl Service<
|
||||
Request = TcpConnect<Uri>,
|
||||
@ -60,13 +76,23 @@ impl Connector<(), ()> {
|
||||
{
|
||||
use openssl::ssl::SslMethod;
|
||||
|
||||
let mut ssl = SslConnector::builder(SslMethod::tls()).unwrap();
|
||||
let mut ssl = OpensslConnector::builder(SslMethod::tls()).unwrap();
|
||||
let _ = ssl
|
||||
.set_alpn_protos(b"\x02h2\x08http/1.1")
|
||||
.map_err(|e| error!("Can not set alpn protocol: {:?}", e));
|
||||
ssl.build()
|
||||
SslConnector::Openssl(ssl.build())
|
||||
}
|
||||
#[cfg(not(feature = "ssl"))]
|
||||
#[cfg(all(not(feature = "ssl"), feature = "rust-tls"))]
|
||||
{
|
||||
let protos = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
|
||||
let mut config = ClientConfig::new();
|
||||
config.set_protocols(&protos);
|
||||
config
|
||||
.root_store
|
||||
.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
|
||||
SslConnector::Rustls(Arc::new(config))
|
||||
}
|
||||
#[cfg(not(any(feature = "ssl", feature = "rust-tls")))]
|
||||
{}
|
||||
};
|
||||
|
||||
@ -126,8 +152,14 @@ where
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
/// Use custom `SslConnector` instance.
|
||||
pub fn ssl(mut self, connector: SslConnector) -> Self {
|
||||
self.ssl = connector;
|
||||
pub fn ssl(mut self, connector: OpensslConnector) -> Self {
|
||||
self.ssl = SslConnector::Openssl(connector);
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-tls")]
|
||||
pub fn rustls(mut self, connector: Arc<ClientConfig>) -> Self {
|
||||
self.ssl = SslConnector::Rustls(connector);
|
||||
self
|
||||
}
|
||||
|
||||
@ -181,7 +213,7 @@ where
|
||||
self,
|
||||
) -> impl Service<Request = Connect, Response = impl Connection, Error = ConnectError>
|
||||
+ Clone {
|
||||
#[cfg(not(feature = "ssl"))]
|
||||
#[cfg(not(any(feature = "ssl", feature = "rust-tls")))]
|
||||
{
|
||||
let connector = TimeoutService::new(
|
||||
self.timeout,
|
||||
@ -206,10 +238,16 @@ where
|
||||
),
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "ssl")]
|
||||
#[cfg(any(feature = "ssl", feature = "rust-tls"))]
|
||||
{
|
||||
const H2: &[u8] = b"h2";
|
||||
#[cfg(feature = "ssl")]
|
||||
use actix_connect::ssl::OpensslConnector;
|
||||
#[cfg(feature = "rust-tls")]
|
||||
use actix_connect::ssl::RustlsConnector;
|
||||
use actix_service::boxed::service;
|
||||
#[cfg(feature = "rust-tls")]
|
||||
use rustls::Session;
|
||||
|
||||
let ssl_service = TimeoutService::new(
|
||||
self.timeout,
|
||||
@ -217,24 +255,46 @@ where
|
||||
srv.call(TcpConnect::new(msg.uri).set_addr(msg.addr))
|
||||
})
|
||||
.map_err(ConnectError::from)
|
||||
.and_then(
|
||||
OpensslConnector::service(self.ssl)
|
||||
.map_err(ConnectError::from)
|
||||
.map(|stream| {
|
||||
let sock = stream.into_parts().0;
|
||||
let h2 = sock
|
||||
.get_ref()
|
||||
.ssl()
|
||||
.selected_alpn_protocol()
|
||||
.map(|protos| protos.windows(2).any(|w| w == H2))
|
||||
.unwrap_or(false);
|
||||
if h2 {
|
||||
(sock, Protocol::Http2)
|
||||
} else {
|
||||
(sock, Protocol::Http1)
|
||||
}
|
||||
}),
|
||||
),
|
||||
.and_then(match self.ssl {
|
||||
#[cfg(feature = "ssl")]
|
||||
SslConnector::Openssl(ssl) => service(
|
||||
OpensslConnector::service(ssl)
|
||||
.map_err(ConnectError::from)
|
||||
.map(|stream| {
|
||||
let sock = stream.into_parts().0;
|
||||
let h2 = sock
|
||||
.get_ref()
|
||||
.ssl()
|
||||
.selected_alpn_protocol()
|
||||
.map(|protos| protos.windows(2).any(|w| w == H2))
|
||||
.unwrap_or(false);
|
||||
if h2 {
|
||||
(Box::new(sock) as Box<Io>, Protocol::Http2)
|
||||
} else {
|
||||
(Box::new(sock) as Box<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<Io>, Protocol::Http2)
|
||||
} else {
|
||||
(Box::new(sock) as Box<Io>, Protocol::Http1)
|
||||
}
|
||||
}),
|
||||
),
|
||||
}),
|
||||
)
|
||||
.map_err(|e| match e {
|
||||
TimeoutError::Service(e) => e,
|
||||
@ -274,7 +334,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "ssl"))]
|
||||
#[cfg(not(any(feature = "ssl", feature = "rust-tls")))]
|
||||
mod connect_impl {
|
||||
use futures::future::{err, Either, FutureResult};
|
||||
use futures::Poll;
|
||||
@ -336,7 +396,7 @@ mod connect_impl {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[cfg(any(feature = "ssl", feature = "rust-tls"))]
|
||||
mod connect_impl {
|
||||
use std::marker::PhantomData;
|
||||
|
||||
|
@ -305,10 +305,12 @@ pub(crate) struct Inner<Io> {
|
||||
limit: usize,
|
||||
acquired: usize,
|
||||
available: HashMap<Key, VecDeque<AvailableConnection<Io>>>,
|
||||
waiters: Slab<(
|
||||
Connect,
|
||||
oneshot::Sender<Result<IoConnection<Io>, ConnectError>>,
|
||||
)>,
|
||||
waiters: Slab<
|
||||
Option<(
|
||||
Connect,
|
||||
oneshot::Sender<Result<IoConnection<Io>, ConnectError>>,
|
||||
)>,
|
||||
>,
|
||||
waiters_queue: IndexSet<(Key, usize)>,
|
||||
task: Option<AtomicTask>,
|
||||
}
|
||||
@ -346,7 +348,7 @@ where
|
||||
let key: Key = connect.uri.authority_part().unwrap().clone().into();
|
||||
let entry = self.waiters.vacant_entry();
|
||||
let token = entry.key();
|
||||
entry.insert((connect, tx));
|
||||
entry.insert(Some((connect, tx)));
|
||||
assert!(self.waiters_queue.insert((key, token)));
|
||||
|
||||
(rx, token, self.task.is_some())
|
||||
@ -427,7 +429,9 @@ where
|
||||
|
||||
fn check_availibility(&self) {
|
||||
if !self.waiters_queue.is_empty() && self.acquired < self.limit {
|
||||
self.task.as_ref().map(|t| t.notify());
|
||||
if let Some(t) = self.task.as_ref() {
|
||||
t.notify()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -497,10 +501,14 @@ where
|
||||
break;
|
||||
}
|
||||
};
|
||||
if inner.waiters.get(token).unwrap().is_none() {
|
||||
continue;
|
||||
}
|
||||
|
||||
match inner.acquire(&key) {
|
||||
Acquire::NotAvailable => break,
|
||||
Acquire::Acquired(io, created) => {
|
||||
let (_, tx) = inner.waiters.remove(token);
|
||||
let tx = inner.waiters.get_mut(token).unwrap().take().unwrap().1;
|
||||
if let Err(conn) = tx.send(Ok(IoConnection::new(
|
||||
io,
|
||||
created,
|
||||
@ -511,7 +519,8 @@ where
|
||||
}
|
||||
}
|
||||
Acquire::Available => {
|
||||
let (connect, tx) = inner.waiters.remove(token);
|
||||
let (connect, tx) =
|
||||
inner.waiters.get_mut(token).unwrap().take().unwrap();
|
||||
OpenWaitingConnection::spawn(
|
||||
key.clone(),
|
||||
tx,
|
||||
|
42
actix-http/src/cloneable.rs
Normal file
42
actix-http/src/cloneable.rs
Normal file
@ -0,0 +1,42 @@
|
||||
use std::cell::UnsafeCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_service::Service;
|
||||
use futures::Poll;
|
||||
|
||||
#[doc(hidden)]
|
||||
/// Service that allows to turn non-clone service to a service with `Clone` impl
|
||||
pub(crate) struct CloneableService<T>(Rc<UnsafeCell<T>>);
|
||||
|
||||
impl<T> CloneableService<T> {
|
||||
pub(crate) fn new(service: T) -> Self
|
||||
where
|
||||
T: Service,
|
||||
{
|
||||
Self(Rc::new(UnsafeCell::new(service)))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for CloneableService<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Service for CloneableService<T>
|
||||
where
|
||||
T: Service,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Future = T::Future;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
unsafe { &mut *self.0.as_ref().get() }.poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: T::Request) -> Self::Future {
|
||||
unsafe { &mut *self.0.as_ref().get() }.call(req)
|
||||
}
|
||||
}
|
@ -162,16 +162,21 @@ impl ServiceConfig {
|
||||
pub fn set_date(&self, dst: &mut BytesMut) {
|
||||
let mut buf: [u8; 39] = [0; 39];
|
||||
buf[..6].copy_from_slice(b"date: ");
|
||||
buf[6..35].copy_from_slice(&self.0.timer.date().bytes);
|
||||
self.0
|
||||
.timer
|
||||
.set_date(|date| buf[6..35].copy_from_slice(&date.bytes));
|
||||
buf[35..].copy_from_slice(b"\r\n\r\n");
|
||||
dst.extend_from_slice(&buf);
|
||||
}
|
||||
|
||||
pub(crate) fn set_date_header(&self, dst: &mut BytesMut) {
|
||||
dst.extend_from_slice(&self.0.timer.date().bytes);
|
||||
self.0
|
||||
.timer
|
||||
.set_date(|date| dst.extend_from_slice(&date.bytes));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
struct Date {
|
||||
bytes: [u8; DATE_VALUE_LENGTH],
|
||||
pos: usize,
|
||||
@ -215,10 +220,6 @@ impl DateServiceInner {
|
||||
}
|
||||
}
|
||||
|
||||
fn get_ref(&self) -> &Option<(Date, Instant)> {
|
||||
unsafe { &*self.current.get() }
|
||||
}
|
||||
|
||||
fn reset(&self) {
|
||||
unsafe { (&mut *self.current.get()).take() };
|
||||
}
|
||||
@ -236,7 +237,7 @@ impl DateService {
|
||||
}
|
||||
|
||||
fn check_date(&self) {
|
||||
if self.0.get_ref().is_none() {
|
||||
if unsafe { (&*self.0.current.get()).is_none() } {
|
||||
self.0.update();
|
||||
|
||||
// periodic date update
|
||||
@ -252,14 +253,12 @@ impl DateService {
|
||||
|
||||
fn now(&self) -> Instant {
|
||||
self.check_date();
|
||||
self.0.get_ref().as_ref().unwrap().1
|
||||
unsafe { (&*self.0.current.get()).as_ref().unwrap().1 }
|
||||
}
|
||||
|
||||
fn date(&self) -> &Date {
|
||||
fn set_date<F: FnMut(&Date)>(&self, mut f: F) {
|
||||
self.check_date();
|
||||
|
||||
let item = self.0.get_ref().as_ref().unwrap();
|
||||
&item.0
|
||||
f(&unsafe { (&*self.0.current.get()).as_ref().unwrap().0 })
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -104,6 +104,7 @@ impl CookieStr {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::ptr_arg)]
|
||||
fn to_raw_str<'s, 'c: 's>(&'s self, string: &'s Cow<'c, str>) -> Option<&'c str> {
|
||||
match *self {
|
||||
CookieStr::Indexed(i, j) => match *string {
|
||||
|
@ -6,8 +6,8 @@ use ring::rand::{SecureRandom, SystemRandom};
|
||||
use super::private::KEY_LEN as PRIVATE_KEY_LEN;
|
||||
use super::signed::KEY_LEN as SIGNED_KEY_LEN;
|
||||
|
||||
static HKDF_DIGEST: &'static Algorithm = &SHA256;
|
||||
const KEYS_INFO: &'static str = "COOKIE;SIGNED:HMAC-SHA256;PRIVATE:AEAD-AES-256-GCM";
|
||||
static HKDF_DIGEST: &Algorithm = &SHA256;
|
||||
const KEYS_INFO: &str = "COOKIE;SIGNED:HMAC-SHA256;PRIVATE:AEAD-AES-256-GCM";
|
||||
|
||||
/// A cryptographic master key for use with `Signed` and/or `Private` jars.
|
||||
///
|
||||
|
@ -10,7 +10,7 @@ use crate::cookie::{Cookie, CookieJar};
|
||||
|
||||
// Keep these in sync, and keep the key len synced with the `private` docs as
|
||||
// well as the `KEYS_INFO` const in secure::Key.
|
||||
static ALGO: &'static Algorithm = &AES_256_GCM;
|
||||
static ALGO: &Algorithm = &AES_256_GCM;
|
||||
const NONCE_LEN: usize = 12;
|
||||
pub const KEY_LEN: usize = 32;
|
||||
|
||||
|
@ -6,7 +6,7 @@ use crate::cookie::{Cookie, CookieJar};
|
||||
|
||||
// Keep these in sync, and keep the key len synced with the `signed` docs as
|
||||
// well as the `KEYS_INFO` const in secure::Key.
|
||||
static HMAC_DIGEST: &'static Algorithm = &SHA256;
|
||||
static HMAC_DIGEST: &Algorithm = &SHA256;
|
||||
const BASE64_DIGEST_LEN: usize = 44;
|
||||
pub const KEY_LEN: usize = 32;
|
||||
|
||||
|
@ -33,6 +33,7 @@ impl<B: MessageBody> Encoder<B> {
|
||||
) -> ResponseBody<Encoder<B>> {
|
||||
let can_encode = !(head.headers().contains_key(&CONTENT_ENCODING)
|
||||
|| head.status == StatusCode::SWITCHING_PROTOCOLS
|
||||
|| head.status == StatusCode::NO_CONTENT
|
||||
|| encoding == ContentEncoding::Identity
|
||||
|| encoding == ContentEncoding::Auto);
|
||||
|
||||
@ -53,22 +54,24 @@ impl<B: MessageBody> Encoder<B> {
|
||||
};
|
||||
|
||||
if can_encode {
|
||||
update_head(encoding, head);
|
||||
head.no_chunking(false);
|
||||
ResponseBody::Body(Encoder {
|
||||
body,
|
||||
eof: false,
|
||||
fut: None,
|
||||
encoder: ContentEncoder::encoder(encoding),
|
||||
})
|
||||
} else {
|
||||
ResponseBody::Body(Encoder {
|
||||
body,
|
||||
eof: false,
|
||||
fut: None,
|
||||
encoder: None,
|
||||
})
|
||||
// Modify response body only if encoder is not None
|
||||
if let Some(enc) = ContentEncoder::encoder(encoding) {
|
||||
update_head(encoding, head);
|
||||
head.no_chunking(false);
|
||||
return ResponseBody::Body(Encoder {
|
||||
body,
|
||||
eof: false,
|
||||
fut: None,
|
||||
encoder: Some(enc),
|
||||
});
|
||||
}
|
||||
}
|
||||
ResponseBody::Body(Encoder {
|
||||
body,
|
||||
eof: false,
|
||||
fut: None,
|
||||
encoder: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,4 +1,5 @@
|
||||
//! Error and Result module
|
||||
use std::any::TypeId;
|
||||
use std::cell::RefCell;
|
||||
use std::io::Write;
|
||||
use std::str::Utf8Error;
|
||||
@ -43,14 +44,19 @@ pub type Result<T, E = Error> = result::Result<T, E>;
|
||||
/// if you have access to an actix `Error` you can always get a
|
||||
/// `ResponseError` reference from it.
|
||||
pub struct Error {
|
||||
cause: Box<ResponseError>,
|
||||
cause: Box<dyn ResponseError>,
|
||||
}
|
||||
|
||||
impl Error {
|
||||
/// Returns the reference to the underlying `ResponseError`.
|
||||
pub fn as_response_error(&self) -> &ResponseError {
|
||||
pub fn as_response_error(&self) -> &dyn ResponseError {
|
||||
self.cause.as_ref()
|
||||
}
|
||||
|
||||
/// Similar to `as_response_error` but downcasts.
|
||||
pub fn as_error<T: ResponseError + 'static>(&self) -> Option<&T> {
|
||||
ResponseError::downcast_ref(self.cause.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
/// Error that can be converted to `Response`
|
||||
@ -73,6 +79,25 @@ pub trait ResponseError: fmt::Debug + fmt::Display {
|
||||
);
|
||||
resp.set_body(Body::from(buf))
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
fn __private_get_type_id__(&self) -> TypeId
|
||||
where
|
||||
Self: 'static,
|
||||
{
|
||||
TypeId::of::<Self>()
|
||||
}
|
||||
}
|
||||
|
||||
impl dyn ResponseError + 'static {
|
||||
/// Downcasts a response error to a specific type.
|
||||
pub fn downcast_ref<T: ResponseError + 'static>(&self) -> Option<&T> {
|
||||
if self.__private_get_type_id__() == TypeId::of::<T>() {
|
||||
unsafe { Some(&*(self as *const dyn ResponseError as *const T)) }
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
@ -1044,6 +1069,16 @@ mod tests {
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_casting() {
|
||||
let err = PayloadError::Overflow;
|
||||
let resp_err: &ResponseError = &err;
|
||||
let err = resp_err.downcast_ref::<PayloadError>().unwrap();
|
||||
assert_eq!(err.to_string(), "A payload reached size limit.");
|
||||
let not_err = resp_err.downcast_ref::<ContentTypeError>();
|
||||
assert!(not_err.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_helpers() {
|
||||
let r: Response = ErrorBadRequest("err").into();
|
||||
|
@ -6,7 +6,7 @@ use hashbrown::HashMap;
|
||||
#[derive(Default)]
|
||||
/// A type map of request extensions.
|
||||
pub struct Extensions {
|
||||
map: HashMap<TypeId, Box<Any>>,
|
||||
map: HashMap<TypeId, Box<dyn Any>>,
|
||||
}
|
||||
|
||||
impl Extensions {
|
||||
@ -35,14 +35,14 @@ impl Extensions {
|
||||
pub fn get<T: 'static>(&self) -> Option<&T> {
|
||||
self.map
|
||||
.get(&TypeId::of::<T>())
|
||||
.and_then(|boxed| (&**boxed as &(Any + 'static)).downcast_ref())
|
||||
.and_then(|boxed| (&**boxed as &(dyn Any + 'static)).downcast_ref())
|
||||
}
|
||||
|
||||
/// Get a mutable reference to a type previously inserted on this `Extensions`.
|
||||
pub fn get_mut<T: 'static>(&mut self) -> Option<&mut T> {
|
||||
self.map
|
||||
.get_mut(&TypeId::of::<T>())
|
||||
.and_then(|boxed| (&mut **boxed as &mut (Any + 'static)).downcast_mut())
|
||||
.and_then(|boxed| (&mut **boxed as &mut (dyn Any + 'static)).downcast_mut())
|
||||
}
|
||||
|
||||
/// Remove a type from this `Extensions`.
|
||||
@ -50,7 +50,7 @@ impl Extensions {
|
||||
/// If a extension of this type existed, it will be returned.
|
||||
pub fn remove<T: 'static>(&mut self) -> Option<T> {
|
||||
self.map.remove(&TypeId::of::<T>()).and_then(|boxed| {
|
||||
(boxed as Box<Any + 'static>)
|
||||
(boxed as Box<dyn Any + 'static>)
|
||||
.downcast()
|
||||
.ok()
|
||||
.map(|boxed| *boxed)
|
||||
|
@ -502,15 +502,15 @@ impl ChunkedState {
|
||||
fn read_size(rdr: &mut BytesMut, size: &mut u64) -> Poll<ChunkedState, io::Error> {
|
||||
let radix = 16;
|
||||
match byte!(rdr) {
|
||||
b @ b'0'...b'9' => {
|
||||
b @ b'0'..=b'9' => {
|
||||
*size *= radix;
|
||||
*size += u64::from(b - b'0');
|
||||
}
|
||||
b @ b'a'...b'f' => {
|
||||
b @ b'a'..=b'f' => {
|
||||
*size *= radix;
|
||||
*size += u64::from(b + 10 - b'a');
|
||||
}
|
||||
b @ b'A'...b'F' => {
|
||||
b @ b'A'..=b'F' => {
|
||||
*size *= radix;
|
||||
*size += u64::from(b + 10 - b'A');
|
||||
}
|
||||
|
@ -5,7 +5,6 @@ use std::{fmt, io, net};
|
||||
use actix_codec::{Decoder, Encoder, Framed, FramedParts};
|
||||
use actix_server_config::IoStream;
|
||||
use actix_service::Service;
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use bitflags::bitflags;
|
||||
use bytes::{BufMut, BytesMut};
|
||||
use futures::{Async, Future, Poll};
|
||||
@ -13,9 +12,12 @@ use log::{error, trace};
|
||||
use tokio_timer::Delay;
|
||||
|
||||
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
|
||||
use crate::cloneable::CloneableService;
|
||||
use crate::config::ServiceConfig;
|
||||
use crate::error::{DispatchError, Error};
|
||||
use crate::error::{ParseError, PayloadError};
|
||||
use crate::helpers::DataFactory;
|
||||
use crate::httpmessage::HttpMessage;
|
||||
use crate::request::Request;
|
||||
use crate::response::Response;
|
||||
|
||||
@ -81,6 +83,7 @@ where
|
||||
service: CloneableService<S>,
|
||||
expect: CloneableService<X>,
|
||||
upgrade: Option<CloneableService<U>>,
|
||||
on_connect: Option<Box<dyn DataFactory>>,
|
||||
flags: Flags,
|
||||
peer_addr: Option<net::SocketAddr>,
|
||||
error: Option<DispatchError>,
|
||||
@ -174,12 +177,13 @@ where
|
||||
U::Error: fmt::Display,
|
||||
{
|
||||
/// Create http/1 dispatcher.
|
||||
pub fn new(
|
||||
pub(crate) fn new(
|
||||
stream: T,
|
||||
config: ServiceConfig,
|
||||
service: CloneableService<S>,
|
||||
expect: CloneableService<X>,
|
||||
upgrade: Option<CloneableService<U>>,
|
||||
on_connect: Option<Box<dyn DataFactory>>,
|
||||
) -> Self {
|
||||
Dispatcher::with_timeout(
|
||||
stream,
|
||||
@ -190,11 +194,12 @@ where
|
||||
service,
|
||||
expect,
|
||||
upgrade,
|
||||
on_connect,
|
||||
)
|
||||
}
|
||||
|
||||
/// Create http/1 dispatcher with slow request timeout.
|
||||
pub fn with_timeout(
|
||||
pub(crate) fn with_timeout(
|
||||
io: T,
|
||||
codec: Codec,
|
||||
config: ServiceConfig,
|
||||
@ -203,6 +208,7 @@ where
|
||||
service: CloneableService<S>,
|
||||
expect: CloneableService<X>,
|
||||
upgrade: Option<CloneableService<U>>,
|
||||
on_connect: Option<Box<dyn DataFactory>>,
|
||||
) -> Self {
|
||||
let keepalive = config.keep_alive_enabled();
|
||||
let flags = if keepalive {
|
||||
@ -234,6 +240,7 @@ where
|
||||
service,
|
||||
expect,
|
||||
upgrade,
|
||||
on_connect,
|
||||
flags,
|
||||
ka_expire,
|
||||
ka_timer,
|
||||
@ -495,6 +502,11 @@ where
|
||||
let pl = self.codec.message_type();
|
||||
req.head_mut().peer_addr = self.peer_addr;
|
||||
|
||||
// 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() {
|
||||
self.messages.push_back(DispatcherMessage::Upgrade(req));
|
||||
break;
|
||||
@ -583,6 +595,9 @@ where
|
||||
self.ka_timer = Some(Delay::new(interval));
|
||||
} else {
|
||||
self.flags.insert(Flags::READ_DISCONNECT);
|
||||
if let Some(mut payload) = self.payload.take() {
|
||||
payload.set_error(PayloadError::Incomplete(None));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
} else {
|
||||
@ -690,15 +705,21 @@ where
|
||||
}
|
||||
} else {
|
||||
// read socket into a buf
|
||||
if !inner.flags.contains(Flags::READ_DISCONNECT) {
|
||||
if let Some(true) =
|
||||
let should_disconnect =
|
||||
if !inner.flags.contains(Flags::READ_DISCONNECT) {
|
||||
read_available(&mut inner.io, &mut inner.read_buf)?
|
||||
{
|
||||
inner.flags.insert(Flags::READ_DISCONNECT)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
inner.poll_request()?;
|
||||
if let Some(true) = should_disconnect {
|
||||
inner.flags.insert(Flags::READ_DISCONNECT);
|
||||
if let Some(mut payload) = inner.payload.take() {
|
||||
payload.feed_eof();
|
||||
}
|
||||
};
|
||||
|
||||
loop {
|
||||
if inner.write_buf.remaining_mut() < LW_BUFFER_SIZE {
|
||||
inner.write_buf.reserve(HW_BUFFER_SIZE);
|
||||
@ -842,6 +863,7 @@ mod tests {
|
||||
),
|
||||
CloneableService::new(ExpectHandler),
|
||||
None,
|
||||
None,
|
||||
);
|
||||
assert!(h1.poll().is_err());
|
||||
|
||||
|
@ -1,16 +1,18 @@
|
||||
use std::fmt;
|
||||
use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_codec::Framed;
|
||||
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
|
||||
use actix_service::{IntoNewService, NewService, Service};
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream};
|
||||
|
||||
use crate::body::MessageBody;
|
||||
use crate::cloneable::CloneableService;
|
||||
use crate::config::{KeepAlive, ServiceConfig};
|
||||
use crate::error::{DispatchError, Error, ParseError};
|
||||
use crate::helpers::DataFactory;
|
||||
use crate::request::Request;
|
||||
use crate::response::Response;
|
||||
|
||||
@ -24,6 +26,7 @@ pub struct H1Service<T, P, S, B, X = ExpectHandler, U = UpgradeHandler<T>> {
|
||||
cfg: ServiceConfig,
|
||||
expect: X,
|
||||
upgrade: Option<U>,
|
||||
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
_t: PhantomData<(T, P, B)>,
|
||||
}
|
||||
|
||||
@ -44,6 +47,7 @@ where
|
||||
srv: service.into_new_service(),
|
||||
expect: ExpectHandler,
|
||||
upgrade: None,
|
||||
on_connect: None,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@ -55,6 +59,7 @@ where
|
||||
srv: service.into_new_service(),
|
||||
expect: ExpectHandler,
|
||||
upgrade: None,
|
||||
on_connect: None,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@ -79,6 +84,7 @@ where
|
||||
cfg: self.cfg,
|
||||
srv: self.srv,
|
||||
upgrade: self.upgrade,
|
||||
on_connect: self.on_connect,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@ -94,9 +100,19 @@ where
|
||||
cfg: self.cfg,
|
||||
srv: self.srv,
|
||||
expect: self.expect,
|
||||
on_connect: self.on_connect,
|
||||
_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>
|
||||
@ -133,6 +149,7 @@ where
|
||||
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(cfg)),
|
||||
expect: None,
|
||||
upgrade: None,
|
||||
on_connect: self.on_connect.clone(),
|
||||
cfg: Some(self.cfg.clone()),
|
||||
_t: PhantomData,
|
||||
}
|
||||
@ -157,6 +174,7 @@ where
|
||||
fut_upg: Option<U::Future>,
|
||||
expect: Option<X::Service>,
|
||||
upgrade: Option<U::Service>,
|
||||
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
cfg: Option<ServiceConfig>,
|
||||
_t: PhantomData<(T, P, B)>,
|
||||
}
|
||||
@ -205,6 +223,7 @@ where
|
||||
service,
|
||||
self.expect.take().unwrap(),
|
||||
self.upgrade.take(),
|
||||
self.on_connect.clone(),
|
||||
)))
|
||||
}
|
||||
}
|
||||
@ -214,6 +233,7 @@ pub struct H1ServiceHandler<T, P, S, B, X, U> {
|
||||
srv: CloneableService<S>,
|
||||
expect: CloneableService<X>,
|
||||
upgrade: Option<CloneableService<U>>,
|
||||
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
cfg: ServiceConfig,
|
||||
_t: PhantomData<(T, P, B)>,
|
||||
}
|
||||
@ -234,12 +254,14 @@ where
|
||||
srv: S,
|
||||
expect: X,
|
||||
upgrade: Option<U>,
|
||||
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
) -> H1ServiceHandler<T, P, S, B, X, U> {
|
||||
H1ServiceHandler {
|
||||
srv: CloneableService::new(srv),
|
||||
expect: CloneableService::new(expect),
|
||||
upgrade: upgrade.map(|s| CloneableService::new(s)),
|
||||
upgrade: upgrade.map(CloneableService::new),
|
||||
cfg,
|
||||
on_connect,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@ -292,12 +314,21 @@ where
|
||||
}
|
||||
|
||||
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(
|
||||
req.into_parts().0,
|
||||
io,
|
||||
self.cfg.clone(),
|
||||
self.srv.clone(),
|
||||
self.expect.clone(),
|
||||
self.upgrade.clone(),
|
||||
on_connect,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
@ -6,7 +6,6 @@ use std::{fmt, mem, net};
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_server_config::IoStream;
|
||||
use actix_service::Service;
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use bitflags::bitflags;
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures::{try_ready, Async, Future, Poll, Sink, Stream};
|
||||
@ -20,8 +19,10 @@ use log::{debug, error, trace};
|
||||
use tokio_timer::Delay;
|
||||
|
||||
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
|
||||
use crate::cloneable::CloneableService;
|
||||
use crate::config::ServiceConfig;
|
||||
use crate::error::{DispatchError, Error, ParseError, PayloadError, ResponseError};
|
||||
use crate::helpers::DataFactory;
|
||||
use crate::message::ResponseHead;
|
||||
use crate::payload::Payload;
|
||||
use crate::request::Request;
|
||||
@ -33,6 +34,7 @@ const CHUNK_SIZE: usize = 16_384;
|
||||
pub struct Dispatcher<T: IoStream, S: Service<Request = Request>, B: MessageBody> {
|
||||
service: CloneableService<S>,
|
||||
connection: Connection<T, Bytes>,
|
||||
on_connect: Option<Box<dyn DataFactory>>,
|
||||
config: ServiceConfig,
|
||||
peer_addr: Option<net::SocketAddr>,
|
||||
ka_expire: Instant,
|
||||
@ -49,9 +51,10 @@ where
|
||||
S::Response: Into<Response<B>>,
|
||||
B: MessageBody + 'static,
|
||||
{
|
||||
pub fn new(
|
||||
pub(crate) fn new(
|
||||
service: CloneableService<S>,
|
||||
connection: Connection<T, Bytes>,
|
||||
on_connect: Option<Box<dyn DataFactory>>,
|
||||
config: ServiceConfig,
|
||||
timeout: Option<Delay>,
|
||||
peer_addr: Option<net::SocketAddr>,
|
||||
@ -77,6 +80,7 @@ where
|
||||
config,
|
||||
peer_addr,
|
||||
connection,
|
||||
on_connect,
|
||||
ka_expire,
|
||||
ka_timer,
|
||||
_t: PhantomData,
|
||||
|
@ -1,11 +1,10 @@
|
||||
use std::fmt::Debug;
|
||||
use std::marker::PhantomData;
|
||||
use std::{io, net};
|
||||
use std::{io, net, rc};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
|
||||
use actix_service::{IntoNewService, NewService, Service};
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use bytes::Bytes;
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream};
|
||||
@ -14,8 +13,10 @@ use h2::RecvStream;
|
||||
use log::error;
|
||||
|
||||
use crate::body::MessageBody;
|
||||
use crate::cloneable::CloneableService;
|
||||
use crate::config::{KeepAlive, ServiceConfig};
|
||||
use crate::error::{DispatchError, Error, ParseError, ResponseError};
|
||||
use crate::helpers::DataFactory;
|
||||
use crate::payload::Payload;
|
||||
use crate::request::Request;
|
||||
use crate::response::Response;
|
||||
@ -26,6 +27,7 @@ use super::dispatcher::Dispatcher;
|
||||
pub struct H2Service<T, P, S, B> {
|
||||
srv: S,
|
||||
cfg: ServiceConfig,
|
||||
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
_t: PhantomData<(T, P, B)>,
|
||||
}
|
||||
|
||||
@ -43,6 +45,7 @@ where
|
||||
|
||||
H2Service {
|
||||
cfg,
|
||||
on_connect: None,
|
||||
srv: service.into_new_service(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
@ -52,10 +55,20 @@ where
|
||||
pub fn with_config<F: IntoNewService<S>>(cfg: ServiceConfig, service: F) -> Self {
|
||||
H2Service {
|
||||
cfg,
|
||||
on_connect: None,
|
||||
srv: service.into_new_service(),
|
||||
_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>
|
||||
@ -79,6 +92,7 @@ where
|
||||
H2ServiceResponse {
|
||||
fut: self.srv.new_service(cfg).into_future(),
|
||||
cfg: Some(self.cfg.clone()),
|
||||
on_connect: self.on_connect.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@ -88,6 +102,7 @@ where
|
||||
pub struct H2ServiceResponse<T, P, S: NewService, B> {
|
||||
fut: <S::Future as IntoFuture>::Future,
|
||||
cfg: Option<ServiceConfig>,
|
||||
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
_t: PhantomData<(T, P, B)>,
|
||||
}
|
||||
|
||||
@ -107,6 +122,7 @@ where
|
||||
let service = try_ready!(self.fut.poll());
|
||||
Ok(Async::Ready(H2ServiceHandler::new(
|
||||
self.cfg.take().unwrap(),
|
||||
self.on_connect.clone(),
|
||||
service,
|
||||
)))
|
||||
}
|
||||
@ -116,6 +132,7 @@ where
|
||||
pub struct H2ServiceHandler<T, P, S, B> {
|
||||
srv: CloneableService<S>,
|
||||
cfg: ServiceConfig,
|
||||
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
_t: PhantomData<(T, P, B)>,
|
||||
}
|
||||
|
||||
@ -127,9 +144,14 @@ where
|
||||
S::Response: Into<Response<B>>,
|
||||
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 {
|
||||
cfg,
|
||||
on_connect,
|
||||
srv: CloneableService::new(srv),
|
||||
_t: PhantomData,
|
||||
}
|
||||
@ -161,11 +183,18 @@ where
|
||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||
let io = req.into_parts().0;
|
||||
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 {
|
||||
state: State::Handshake(
|
||||
Some(self.srv.clone()),
|
||||
Some(self.cfg.clone()),
|
||||
peer_addr,
|
||||
on_connect,
|
||||
server::handshake(io),
|
||||
),
|
||||
}
|
||||
@ -181,6 +210,7 @@ where
|
||||
Option<CloneableService<S>>,
|
||||
Option<ServiceConfig>,
|
||||
Option<net::SocketAddr>,
|
||||
Option<Box<dyn DataFactory>>,
|
||||
Handshake<T, Bytes>,
|
||||
),
|
||||
}
|
||||
@ -216,15 +246,17 @@ where
|
||||
ref mut srv,
|
||||
ref mut config,
|
||||
ref peer_addr,
|
||||
ref mut on_connect,
|
||||
ref mut handshake,
|
||||
) => match handshake.poll() {
|
||||
Ok(Async::Ready(conn)) => {
|
||||
self.state = State::Incoming(Dispatcher::new(
|
||||
srv.take().unwrap(),
|
||||
conn,
|
||||
on_connect.take(),
|
||||
config.take().unwrap(),
|
||||
None,
|
||||
peer_addr.clone(),
|
||||
*peer_addr,
|
||||
));
|
||||
self.poll()
|
||||
}
|
||||
|
@ -70,6 +70,7 @@ impl<'a> From<&'a str> for DispositionType {
|
||||
/// assert_eq!(param.as_filename().unwrap(), "sample.txt");
|
||||
/// ```
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum DispositionParam {
|
||||
/// For [`DispositionType::FormData`] (i.e. *multipart/form-data*), the name of an field from
|
||||
/// the form.
|
||||
@ -719,8 +720,10 @@ mod tests {
|
||||
};
|
||||
assert_eq!(a, b);
|
||||
|
||||
let a =
|
||||
HeaderValue::from_str("form-data; name=upload; filename=\"余固知謇謇之為患兮,忍而不能舍也.pptx\"").unwrap();
|
||||
let a = HeaderValue::from_str(
|
||||
"form-data; name=upload; filename=\"余固知謇謇之為患兮,忍而不能舍也.pptx\"",
|
||||
)
|
||||
.unwrap();
|
||||
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
|
||||
let b = ContentDisposition {
|
||||
disposition: DispositionType::FormData,
|
||||
|
@ -9,12 +9,12 @@ use http::HttpTryFrom;
|
||||
/// `HeaderMap` is an multimap of [`HeaderName`] to values.
|
||||
///
|
||||
/// [`HeaderName`]: struct.HeaderName.html
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct HeaderMap {
|
||||
pub(crate) inner: HashMap<HeaderName, Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) enum Value {
|
||||
One(HeaderValue),
|
||||
Multi(Vec<HeaderValue>),
|
||||
|
@ -3,6 +3,8 @@ use std::{io, mem, ptr, slice};
|
||||
use bytes::{BufMut, BytesMut};
|
||||
use http::Version;
|
||||
|
||||
use crate::extensions::Extensions;
|
||||
|
||||
const DEC_DIGITS_LUT: &[u8] = b"0001020304050607080910111213141516171819\
|
||||
2021222324252627282930313233343536373839\
|
||||
4041424344454647484950515253545556575859\
|
||||
@ -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)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
@ -61,6 +61,7 @@ impl Response {
|
||||
STATIC_RESP!(RangeNotSatisfiable, StatusCode::RANGE_NOT_SATISFIABLE);
|
||||
STATIC_RESP!(ExpectationFailed, StatusCode::EXPECTATION_FAILED);
|
||||
STATIC_RESP!(UnprocessableEntity, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
STATIC_RESP!(TooManyRequests, StatusCode::TOO_MANY_REQUESTS);
|
||||
|
||||
STATIC_RESP!(InternalServerError, StatusCode::INTERNAL_SERVER_ERROR);
|
||||
STATIC_RESP!(NotImplemented, StatusCode::NOT_IMPLEMENTED);
|
||||
|
@ -1,9 +1,7 @@
|
||||
use std::cell::{Ref, RefMut};
|
||||
use std::str;
|
||||
|
||||
use encoding::all::UTF_8;
|
||||
use encoding::label::encoding_from_whatwg_label;
|
||||
use encoding::EncodingRef;
|
||||
use encoding_rs::{Encoding, UTF_8};
|
||||
use http::header;
|
||||
use mime::Mime;
|
||||
|
||||
@ -59,10 +57,12 @@ pub trait HttpMessage: Sized {
|
||||
/// Get content type encoding
|
||||
///
|
||||
/// 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(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)
|
||||
} else {
|
||||
Err(ContentTypeError::UnknownEncoding)
|
||||
@ -166,8 +166,7 @@ where
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use bytes::Bytes;
|
||||
use encoding::all::ISO_8859_2;
|
||||
use encoding::Encoding;
|
||||
use encoding_rs::ISO_8859_2;
|
||||
use mime;
|
||||
|
||||
use super::*;
|
||||
@ -223,7 +222,7 @@ mod tests {
|
||||
"application/json; charset=ISO-8859-2",
|
||||
)
|
||||
.finish();
|
||||
assert_eq!(ISO_8859_2.name(), req.encoding().unwrap().name());
|
||||
assert_eq!(ISO_8859_2, req.encoding().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
@ -1,8 +1,10 @@
|
||||
//! Basic http primitives for actix-net framework.
|
||||
#![allow(
|
||||
clippy::type_complexity,
|
||||
clippy::too_many_arguments,
|
||||
clippy::new_without_default,
|
||||
clippy::borrow_interior_mutable_const
|
||||
clippy::borrow_interior_mutable_const,
|
||||
clippy::write_with_newline
|
||||
)]
|
||||
|
||||
#[macro_use]
|
||||
@ -11,6 +13,7 @@ extern crate log;
|
||||
pub mod body;
|
||||
mod builder;
|
||||
pub mod client;
|
||||
mod cloneable;
|
||||
mod config;
|
||||
pub mod encoding;
|
||||
mod extensions;
|
||||
|
@ -385,6 +385,7 @@ impl Drop for BoxedResponseHead {
|
||||
pub struct MessagePool<T: Head>(RefCell<Vec<Rc<T>>>);
|
||||
|
||||
#[doc(hidden)]
|
||||
#[allow(clippy::vec_box)]
|
||||
/// Request's objects pool
|
||||
pub struct BoxedResponsePool(RefCell<Vec<Box<ResponseHead>>>);
|
||||
|
||||
|
@ -52,6 +52,9 @@ impl Response<Body> {
|
||||
#[inline]
|
||||
pub fn from_error(error: Error) -> Response {
|
||||
let mut resp = error.as_response_error().render_response();
|
||||
if resp.head.status == StatusCode::INTERNAL_SERVER_ERROR {
|
||||
error!("Internal Server Error: {:?}", error);
|
||||
}
|
||||
resp.error = Some(error);
|
||||
resp
|
||||
}
|
||||
@ -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
|
||||
impl<I: Into<Response>, E: Into<Error>> From<Result<I, E>> for Response {
|
||||
fn from(res: Result<I, E>) -> Self {
|
||||
|
@ -1,20 +1,21 @@
|
||||
use std::marker::PhantomData;
|
||||
use std::{fmt, io, net};
|
||||
use std::{fmt, io, net, rc};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||
use actix_server_config::{
|
||||
Io as ServerIo, IoStream, Protocol, ServerConfig as SrvConfig,
|
||||
};
|
||||
use actix_service::{IntoNewService, NewService, Service};
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use bytes::{Buf, BufMut, Bytes, BytesMut};
|
||||
use futures::{try_ready, Async, Future, IntoFuture, Poll};
|
||||
use h2::server::{self, Handshake};
|
||||
|
||||
use crate::body::MessageBody;
|
||||
use crate::builder::HttpServiceBuilder;
|
||||
use crate::cloneable::CloneableService;
|
||||
use crate::config::{KeepAlive, ServiceConfig};
|
||||
use crate::error::{DispatchError, Error};
|
||||
use crate::helpers::DataFactory;
|
||||
use crate::request::Request;
|
||||
use crate::response::Response;
|
||||
use crate::{h1, h2::Dispatcher};
|
||||
@ -25,6 +26,7 @@ pub struct HttpService<T, P, S, B, X = h1::ExpectHandler, U = h1::UpgradeHandler
|
||||
cfg: ServiceConfig,
|
||||
expect: X,
|
||||
upgrade: Option<U>,
|
||||
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
_t: PhantomData<(T, P, B)>,
|
||||
}
|
||||
|
||||
@ -61,6 +63,7 @@ where
|
||||
srv: service.into_new_service(),
|
||||
expect: h1::ExpectHandler,
|
||||
upgrade: None,
|
||||
on_connect: None,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@ -75,6 +78,7 @@ where
|
||||
srv: service.into_new_service(),
|
||||
expect: h1::ExpectHandler,
|
||||
upgrade: None,
|
||||
on_connect: None,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@ -104,6 +108,7 @@ where
|
||||
cfg: self.cfg,
|
||||
srv: self.srv,
|
||||
upgrade: self.upgrade,
|
||||
on_connect: self.on_connect,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@ -127,9 +132,19 @@ where
|
||||
cfg: self.cfg,
|
||||
srv: self.srv,
|
||||
expect: self.expect,
|
||||
on_connect: self.on_connect,
|
||||
_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>
|
||||
@ -167,6 +182,7 @@ where
|
||||
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(cfg)),
|
||||
expect: None,
|
||||
upgrade: None,
|
||||
on_connect: self.on_connect.clone(),
|
||||
cfg: Some(self.cfg.clone()),
|
||||
_t: PhantomData,
|
||||
}
|
||||
@ -180,6 +196,7 @@ pub struct HttpServiceResponse<T, P, S: NewService, B, X: NewService, U: NewServ
|
||||
fut_upg: Option<U::Future>,
|
||||
expect: Option<X::Service>,
|
||||
upgrade: Option<U::Service>,
|
||||
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
cfg: Option<ServiceConfig>,
|
||||
_t: PhantomData<(T, P, B)>,
|
||||
}
|
||||
@ -229,6 +246,7 @@ where
|
||||
service,
|
||||
self.expect.take().unwrap(),
|
||||
self.upgrade.take(),
|
||||
self.on_connect.clone(),
|
||||
)))
|
||||
}
|
||||
}
|
||||
@ -239,6 +257,7 @@ pub struct HttpServiceHandler<T, P, S, B, X, U> {
|
||||
expect: CloneableService<X>,
|
||||
upgrade: Option<CloneableService<U>>,
|
||||
cfg: ServiceConfig,
|
||||
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
_t: PhantomData<(T, P, B, X)>,
|
||||
}
|
||||
|
||||
@ -259,12 +278,14 @@ where
|
||||
srv: S,
|
||||
expect: X,
|
||||
upgrade: Option<U>,
|
||||
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
|
||||
) -> HttpServiceHandler<T, P, S, B, X, U> {
|
||||
HttpServiceHandler {
|
||||
cfg,
|
||||
on_connect,
|
||||
srv: CloneableService::new(srv),
|
||||
expect: CloneableService::new(expect),
|
||||
upgrade: upgrade.map(|s| CloneableService::new(s)),
|
||||
upgrade: upgrade.map(CloneableService::new),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@ -319,6 +340,13 @@ where
|
||||
|
||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||
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 {
|
||||
Protocol::Http2 => {
|
||||
let peer_addr = io.peer_addr();
|
||||
@ -332,6 +360,7 @@ where
|
||||
self.cfg.clone(),
|
||||
self.srv.clone(),
|
||||
peer_addr,
|
||||
on_connect,
|
||||
))),
|
||||
}
|
||||
}
|
||||
@ -342,6 +371,7 @@ where
|
||||
self.srv.clone(),
|
||||
self.expect.clone(),
|
||||
self.upgrade.clone(),
|
||||
on_connect,
|
||||
)),
|
||||
},
|
||||
_ => HttpServiceHandlerResponse {
|
||||
@ -352,6 +382,7 @@ where
|
||||
self.srv.clone(),
|
||||
self.expect.clone(),
|
||||
self.upgrade.clone(),
|
||||
on_connect,
|
||||
))),
|
||||
},
|
||||
}
|
||||
@ -380,6 +411,7 @@ where
|
||||
CloneableService<S>,
|
||||
CloneableService<X>,
|
||||
Option<CloneableService<U>>,
|
||||
Option<Box<dyn DataFactory>>,
|
||||
)>,
|
||||
),
|
||||
Handshake(
|
||||
@ -388,6 +420,7 @@ where
|
||||
ServiceConfig,
|
||||
CloneableService<S>,
|
||||
Option<net::SocketAddr>,
|
||||
Option<Box<dyn DataFactory>>,
|
||||
)>,
|
||||
),
|
||||
}
|
||||
@ -433,22 +466,25 @@ where
|
||||
State::Unknown(ref mut data) => {
|
||||
if let Some(ref mut item) = data {
|
||||
loop {
|
||||
unsafe {
|
||||
let b = item.1.bytes_mut();
|
||||
let n = try_ready!(item.0.poll_read(b));
|
||||
if n == 0 {
|
||||
return Ok(Async::Ready(()));
|
||||
}
|
||||
item.1.advance_mut(n);
|
||||
if item.1.len() >= HTTP2_PREFACE.len() {
|
||||
break;
|
||||
}
|
||||
// Safety - we only write to the returned slice.
|
||||
let b = unsafe { item.1.bytes_mut() };
|
||||
let n = try_ready!(item.0.poll_read(b));
|
||||
if n == 0 {
|
||||
return Ok(Async::Ready(()));
|
||||
}
|
||||
// Safety - we know that 'n' bytes have
|
||||
// been initialized via the contract of
|
||||
// 'poll_read'
|
||||
unsafe { item.1.advance_mut(n) };
|
||||
if item.1.len() >= HTTP2_PREFACE.len() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
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[..] {
|
||||
let peer_addr = io.peer_addr();
|
||||
let io = Io {
|
||||
@ -460,6 +496,7 @@ where
|
||||
cfg,
|
||||
srv,
|
||||
peer_addr,
|
||||
on_connect,
|
||||
)));
|
||||
} else {
|
||||
self.state = State::H1(h1::Dispatcher::with_timeout(
|
||||
@ -471,6 +508,7 @@ where
|
||||
srv,
|
||||
expect,
|
||||
upgrade,
|
||||
on_connect,
|
||||
))
|
||||
}
|
||||
self.poll()
|
||||
@ -488,8 +526,10 @@ where
|
||||
} else {
|
||||
panic!()
|
||||
};
|
||||
let (_, cfg, srv, peer_addr) = data.take().unwrap();
|
||||
self.state = State::H2(Dispatcher::new(srv, conn, cfg, None, peer_addr));
|
||||
let (_, cfg, srv, peer_addr, on_connect) = data.take().unwrap();
|
||||
self.state = State::H2(Dispatcher::new(
|
||||
srv, conn, on_connect, cfg, None, peer_addr,
|
||||
));
|
||||
self.poll()
|
||||
}
|
||||
}
|
||||
|
@ -37,7 +37,7 @@ pub enum Frame {
|
||||
Close(Option<CloseReason>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
/// WebSockets protocol codec
|
||||
pub struct Codec {
|
||||
max_size: usize,
|
||||
|
@ -47,10 +47,7 @@ impl Into<u8> for OpCode {
|
||||
Ping => 9,
|
||||
Pong => 10,
|
||||
Bad => {
|
||||
debug_assert!(
|
||||
false,
|
||||
"Attempted to convert invalid opcode to u8. This is a bug."
|
||||
);
|
||||
log::error!("Attempted to convert invalid opcode to u8. This is a bug.");
|
||||
8 // if this somehow happens, a close frame will help us tear down quickly
|
||||
}
|
||||
}
|
||||
@ -206,7 +203,7 @@ impl<T: Into<String>> From<(CloseCode, T)> for CloseReason {
|
||||
}
|
||||
}
|
||||
|
||||
static WS_GUID: &'static str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
||||
static WS_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
||||
|
||||
// TODO: hash is always same size, we dont need String
|
||||
pub fn hash_key(key: &[u8]) -> String {
|
||||
|
@ -1,20 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDPjCCAiYCCQCmkoCBehOyYTANBgkqhkiG9w0BAQsFADBhMQswCQYDVQQGEwJV
|
||||
UzELMAkGA1UECAwCQ0ExCzAJBgNVBAcMAlNGMRAwDgYDVQQKDAdDb21wYW55MQww
|
||||
CgYDVQQLDANPcmcxGDAWBgNVBAMMD3d3dy5leGFtcGxlLmNvbTAeFw0xOTAzMjky
|
||||
MzE5MDlaFw0yMDAzMjgyMzE5MDlaMGExCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJD
|
||||
QTELMAkGA1UEBwwCU0YxEDAOBgNVBAoMB0NvbXBhbnkxDDAKBgNVBAsMA09yZzEY
|
||||
MBYGA1UEAwwPd3d3LmV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
|
||||
MIIBCgKCAQEA2uFoWm74qumqIIsBBf/rgP3ZtZw6dRQhVoYjIwYk00T1RLmmbt8r
|
||||
YNh3lehmnrQlM/YC3dzcspucGqIfvs5FEReh/vgvsqY3lfy47Q1zzdtBrKq2ZBro
|
||||
AuJUe4ayMYz/L/2jAtPtGDQqWyzhKv6x/oz6N/tKqlzoGbjSGSJUqKAV+Tuo4YI4
|
||||
xw3r/RJg3I3+ruXOgM65GBdja7usI/BhseEOp9VXotoTEItGmvG2RFZ4A7cN124x
|
||||
giFl2IeYuC60jteZ+bnhPiqxcdzf3K4dnZlzrYma+FxwWbaow4wlpQcZVFdZ+K/Y
|
||||
p/Bbm/FDKoUHnEdn/QAanTruRxSGdai0owIDAQABMA0GCSqGSIb3DQEBCwUAA4IB
|
||||
AQAEWn3WAwAbd64f5jo2w4076s2qFiCJjPWoxO6bO75FgFFtw/NNev8pxGVw1ehg
|
||||
HiTO6VRYolL5S/RKOchjA83AcDEBjgf8fKtvTmE9kxZSUIo4kIvv8V9ZM72gJhDN
|
||||
8D/lXduTZ9JMwLOa1NUB8/I6CbaU3VzWkfodArKKpQF3M+LLgK03i12PD0KPQ5zv
|
||||
bwaNoQo6cTmPNIdsVZETRvPqONiCUaQV57G74dGtjeirCh/DO5EYRtb1thgS7TGm
|
||||
+Xg8OC5vZ6g0+xsrSqDBmWNtlI7S3bsL5C3LIEOOAL1ZJHRy2KvIGQ9ipb3XjnKS
|
||||
N7/wlQduRyPH7oaD/o4xf5Gt
|
||||
-----END CERTIFICATE-----
|
@ -1,27 +0,0 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEpQIBAAKCAQEA2uFoWm74qumqIIsBBf/rgP3ZtZw6dRQhVoYjIwYk00T1RLmm
|
||||
bt8rYNh3lehmnrQlM/YC3dzcspucGqIfvs5FEReh/vgvsqY3lfy47Q1zzdtBrKq2
|
||||
ZBroAuJUe4ayMYz/L/2jAtPtGDQqWyzhKv6x/oz6N/tKqlzoGbjSGSJUqKAV+Tuo
|
||||
4YI4xw3r/RJg3I3+ruXOgM65GBdja7usI/BhseEOp9VXotoTEItGmvG2RFZ4A7cN
|
||||
124xgiFl2IeYuC60jteZ+bnhPiqxcdzf3K4dnZlzrYma+FxwWbaow4wlpQcZVFdZ
|
||||
+K/Yp/Bbm/FDKoUHnEdn/QAanTruRxSGdai0owIDAQABAoIBAQC4lzyQd+ITEbi+
|
||||
dTxJuQj94hgHB1htgKqU888SLI5F9nP6n67y9hb5N9WygSp6UWbGqYTFYwxlPMKr
|
||||
22p2WjL5NTsTcm+XdIKQZW/3y06Mn4qFefsT9XURaZriCjihfU2BRaCCNARSUzwd
|
||||
ZH4I6n9mM7KaH71aa7v6ZVoahE9tXPR6hM+SHQEySW4pWkEu98VpNNeIt6vP7WF9
|
||||
ONGbRa+0En4xgkuaxem2ZYa/GZFFtdQRkroNMhIRlfcPpkjy8DCc8E5RAkOzKC3O
|
||||
lnxQwt+tdNNkGZz02ed2hx/YHPwFYy76y6hK5dxq74iKIaOc8U5t0HjB1zVfwiR0
|
||||
5mcxMncxAoGBAP+RivwXZ4FcxDY1uyziF+rwlC/1RujQFEWXIxsXCnba5DH3yKul
|
||||
iKEIZPZtGhpsnQe367lcXcn7tztuoVjpAnk5L+hQY64tLwYbHeRcOMJ75C2y8FFC
|
||||
NeG5sQsrk3IU1+jhGvrbE7UgOeAuWJmv0M1vPNB/+hGoZBW5W5uU1x89AoGBANtA
|
||||
AhLtAcqQ/Qh2SpVhLljh7U85Be9tbCGua09clkYFzh3bcoBolXKH18Veww0TP0yF
|
||||
0748CKw1A+ITbTVFV+vKvi4jzIxS7mr4wYtVCMssbttQN7y3l30IDxJwa9j3zTJx
|
||||
IUn5OMMLv1JyitLId8HdOy1AdU3MkpJzdLyi1mFfAoGBAL3kL4fGABM/kU7SN6RO
|
||||
zgS0AvdrYOeljBp1BRGg2hab58g02vamxVEZgqMTR7zwjPDqOIz+03U7wda4Ccyd
|
||||
PUhDNJSB/r6xNepshZZi642eLlnCRguqjYyNw72QADtYv2B6uehAlXEUY8xtw0lW
|
||||
OGgcSeyF2pH6M3tswWNlgT3lAoGAQ/BttBelOnP7NKgTLH7Usc4wjyAIaszpePZn
|
||||
Ykw6dLBP0oixzoCZ7seRYSOgJWkVcEz39Db+KP60mVWTvbIjMHm+vOVy+Pip0JQM
|
||||
xXQwKWU3ZNZSrzPkyWW55ejYQn9nIn5T5mxH3ojBXHcJ9Y8RLQ20zKzwrI77zE3i
|
||||
mqGK9NkCgYEAq3dzHI0DGAJrR19sWl2LcqI19sj5a91tHx4cl1dJXS/iApOLLieU
|
||||
zyUGkwfsqjHPAZ7GacICeBojIn/7KdPdlSKAbGVAU3d4qzvFS0qmWzObplBz3niT
|
||||
Xnep2XLaVXqwlFJZZ6AHeKzYmMH0d0raiou2bpEUBqYizy2fi3NI4mA=
|
||||
-----END RSA PRIVATE KEY-----
|
462
actix-http/tests/test_rustls_server.rs
Normal file
462
actix-http/tests/test_rustls_server.rs
Normal file
@ -0,0 +1,462 @@
|
||||
#![cfg(feature = "rust-tls")]
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_http::error::PayloadError;
|
||||
use actix_http::http::header::{self, HeaderName, HeaderValue};
|
||||
use actix_http::http::{Method, StatusCode, Version};
|
||||
use actix_http::{body, error, Error, HttpService, Request, Response};
|
||||
use actix_http_test::TestServer;
|
||||
use actix_server::ssl::RustlsAcceptor;
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{new_service_cfg, NewService};
|
||||
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures::future::{self, ok, Future};
|
||||
use futures::stream::{once, Stream};
|
||||
use rustls::{
|
||||
internal::pemfile::{certs, pkcs8_private_keys},
|
||||
NoClientAuth, ServerConfig as RustlsServerConfig,
|
||||
};
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{BufReader, Result};
|
||||
|
||||
fn load_body<S>(stream: S) -> impl Future<Item = BytesMut, Error = PayloadError>
|
||||
where
|
||||
S: Stream<Item = Bytes, Error = PayloadError>,
|
||||
{
|
||||
stream.fold(BytesMut::new(), move |mut body, chunk| {
|
||||
body.extend_from_slice(&chunk);
|
||||
Ok::<_, PayloadError>(body)
|
||||
})
|
||||
}
|
||||
|
||||
fn ssl_acceptor<T: AsyncRead + AsyncWrite>() -> Result<RustlsAcceptor<T, ()>> {
|
||||
// load ssl keys
|
||||
let mut config = RustlsServerConfig::new(NoClientAuth::new());
|
||||
let cert_file = &mut BufReader::new(File::open("../tests/cert.pem").unwrap());
|
||||
let key_file = &mut BufReader::new(File::open("../tests/key.pem").unwrap());
|
||||
let cert_chain = certs(cert_file).unwrap();
|
||||
let mut keys = pkcs8_private_keys(key_file).unwrap();
|
||||
config.set_single_cert(cert_chain, keys.remove(0)).unwrap();
|
||||
|
||||
let protos = vec![b"h2".to_vec()];
|
||||
config.set_protocols(&protos);
|
||||
Ok(RustlsAcceptor::new(config))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2() -> Result<()> {
|
||||
let rustls = ssl_acceptor()?;
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| future::ok::<_, Error>(Response::Ok().finish()))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_1() -> Result<()> {
|
||||
let rustls = ssl_acceptor()?;
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.finish(|req: Request| {
|
||||
assert!(req.peer_addr().is_some());
|
||||
assert_eq!(req.version(), Version::HTTP_2);
|
||||
future::ok::<_, Error>(Response::Ok().finish())
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_body() -> Result<()> {
|
||||
let data = "HELLOWORLD".to_owned().repeat(64 * 1024);
|
||||
let rustls = ssl_acceptor()?;
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|mut req: Request<_>| {
|
||||
load_body(req.take_payload())
|
||||
.and_then(|body| Ok(Response::Ok().body(body)))
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send_body(data.clone())).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let body = srv.load_body(response).unwrap();
|
||||
assert_eq!(&body, data.as_bytes());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_content_length() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|req: Request| {
|
||||
let indx: usize = req.uri().path()[1..].parse().unwrap();
|
||||
let statuses = [
|
||||
StatusCode::NO_CONTENT,
|
||||
StatusCode::CONTINUE,
|
||||
StatusCode::SWITCHING_PROTOCOLS,
|
||||
StatusCode::PROCESSING,
|
||||
StatusCode::OK,
|
||||
StatusCode::NOT_FOUND,
|
||||
];
|
||||
future::ok::<_, ()>(Response::new(statuses[indx]))
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let header = HeaderName::from_static("content-length");
|
||||
let value = HeaderValue::from_static("0");
|
||||
|
||||
{
|
||||
for i in 0..4 {
|
||||
let req = srv
|
||||
.request(Method::GET, srv.surl(&format!("/{}", i)))
|
||||
.send();
|
||||
let response = srv.block_on(req).unwrap();
|
||||
assert_eq!(response.headers().get(&header), None);
|
||||
|
||||
let req = srv
|
||||
.request(Method::HEAD, srv.surl(&format!("/{}", i)))
|
||||
.send();
|
||||
let response = srv.block_on(req).unwrap();
|
||||
assert_eq!(response.headers().get(&header), None);
|
||||
}
|
||||
|
||||
for i in 4..6 {
|
||||
let req = srv
|
||||
.request(Method::GET, srv.surl(&format!("/{}", i)))
|
||||
.send();
|
||||
let response = srv.block_on(req).unwrap();
|
||||
assert_eq!(response.headers().get(&header), Some(&value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_headers() {
|
||||
let data = STR.repeat(10);
|
||||
let data2 = data.clone();
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let data = data.clone();
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build().h2(move |_| {
|
||||
let mut config = Response::Ok();
|
||||
for idx in 0..90 {
|
||||
config.header(
|
||||
format!("X-TEST-{}", idx).as_str(),
|
||||
"TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST ",
|
||||
);
|
||||
}
|
||||
future::ok::<_, ()>(config.body(data.clone()))
|
||||
}).map_err(|_| ()))
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from(data2));
|
||||
}
|
||||
|
||||
const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World";
|
||||
|
||||
#[test]
|
||||
fn test_h2_body2() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| future::ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_head_empty() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.shead("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
assert_eq!(response.version(), Version::HTTP_2);
|
||||
|
||||
{
|
||||
let len = response
|
||||
.headers()
|
||||
.get(http::header::CONTENT_LENGTH)
|
||||
.unwrap();
|
||||
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
|
||||
}
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert!(bytes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_head_binary() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| {
|
||||
ok::<_, ()>(
|
||||
Response::Ok().content_length(STR.len() as u64).body(STR),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.shead("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
{
|
||||
let len = response
|
||||
.headers()
|
||||
.get(http::header::CONTENT_LENGTH)
|
||||
.unwrap();
|
||||
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
|
||||
}
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert!(bytes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_head_binary2() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.shead("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
{
|
||||
let len = response
|
||||
.headers()
|
||||
.get(http::header::CONTENT_LENGTH)
|
||||
.unwrap();
|
||||
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_body_length() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| {
|
||||
let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.body(body::SizedStream::new(STR.len() as u64, body)),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_body_chunked_explicit() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| {
|
||||
let body =
|
||||
once::<_, Error>(Ok(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.header(header::TRANSFER_ENCODING, "chunked")
|
||||
.streaming(body),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
assert!(!response.headers().contains_key(header::TRANSFER_ENCODING));
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
|
||||
// decode
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_response_http_error_handling() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(new_service_cfg(|_: &ServerConfig| {
|
||||
Ok::<_, ()>(|_| {
|
||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.header(http::header::CONTENT_TYPE, broken_header)
|
||||
.body(STR),
|
||||
)
|
||||
})
|
||||
}))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert_eq!(response.status(), http::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h2_service_error() {
|
||||
let rustls = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
rustls
|
||||
.clone()
|
||||
.map_err(|e| println!("Rustls error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| Err::<Response, Error>(error::ErrorBadRequest("error")))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert_eq!(response.status(), http::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert!(bytes.is_empty());
|
||||
}
|
@ -2,32 +2,19 @@ use std::io::{Read, Write};
|
||||
use std::time::Duration;
|
||||
use std::{net, thread};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_http_test::TestServer;
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{new_service_cfg, service_fn, NewService};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use bytes::Bytes;
|
||||
use futures::future::{self, ok, Future};
|
||||
use futures::stream::{once, Stream};
|
||||
use regex::Regex;
|
||||
use tokio_timer::sleep;
|
||||
|
||||
use actix_http::body::Body;
|
||||
use actix_http::error::PayloadError;
|
||||
use actix_http::{
|
||||
body, error, http, http::header, Error, HttpService, KeepAlive, Request, Response,
|
||||
};
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
fn load_body<S>(stream: S) -> impl Future<Item = BytesMut, Error = PayloadError>
|
||||
where
|
||||
S: Stream<Item = Bytes, Error = PayloadError>,
|
||||
{
|
||||
stream.fold(BytesMut::new(), move |mut body, chunk| {
|
||||
body.extend_from_slice(&chunk);
|
||||
Ok::<_, PayloadError>(body)
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h1() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
@ -64,101 +51,6 @@ fn test_h1_2() {
|
||||
assert!(response.status().is_success());
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
fn ssl_acceptor<T: AsyncRead + AsyncWrite>(
|
||||
) -> std::io::Result<actix_server::ssl::OpensslAcceptor<T, ()>> {
|
||||
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
|
||||
// load ssl keys
|
||||
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
|
||||
builder
|
||||
.set_private_key_file("tests/key.pem", SslFiletype::PEM)
|
||||
.unwrap();
|
||||
builder
|
||||
.set_certificate_chain_file("tests/cert.pem")
|
||||
.unwrap();
|
||||
builder.set_alpn_select_callback(|_, protos| {
|
||||
const H2: &[u8] = b"\x02h2";
|
||||
if protos.windows(3).any(|window| window == H2) {
|
||||
Ok(b"h2")
|
||||
} else {
|
||||
Err(openssl::ssl::AlpnError::NOACK)
|
||||
}
|
||||
});
|
||||
builder.set_alpn_protos(b"\x02h2")?;
|
||||
Ok(actix_server::ssl::OpensslAcceptor::new(builder.build()))
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2() -> std::io::Result<()> {
|
||||
let openssl = ssl_acceptor()?;
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| future::ok::<_, Error>(Response::Ok().finish()))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_1() -> std::io::Result<()> {
|
||||
let openssl = ssl_acceptor()?;
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.finish(|req: Request| {
|
||||
assert!(req.peer_addr().is_some());
|
||||
assert_eq!(req.version(), http::Version::HTTP_2);
|
||||
future::ok::<_, Error>(Response::Ok().finish())
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_body() -> std::io::Result<()> {
|
||||
let data = "HELLOWORLD".to_owned().repeat(64 * 1024);
|
||||
let openssl = ssl_acceptor()?;
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|mut req: Request<_>| {
|
||||
load_body(req.take_payload())
|
||||
.and_then(|body| Ok(Response::Ok().body(body)))
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send_body(data.clone())).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let body = srv.load_body(response).unwrap();
|
||||
assert_eq!(&body, data.as_bytes());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expect_continue() {
|
||||
let srv = TestServer::new(|| {
|
||||
@ -215,6 +107,54 @@ fn test_expect_continue_h1() {
|
||||
assert!(data.starts_with("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_chunked_payload() {
|
||||
let chunk_sizes = vec![32768, 32, 32768];
|
||||
let total_size: usize = chunk_sizes.iter().sum();
|
||||
|
||||
let srv = TestServer::new(|| {
|
||||
HttpService::build().h1(|mut request: Request| {
|
||||
request
|
||||
.take_payload()
|
||||
.map_err(|e| panic!(format!("Error reading payload: {}", e)))
|
||||
.fold(0usize, |acc, chunk| future::ok::<_, ()>(acc + chunk.len()))
|
||||
.map(|req_size| Response::Ok().body(format!("size={}", req_size)))
|
||||
})
|
||||
});
|
||||
|
||||
let returned_size = {
|
||||
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");
|
||||
|
||||
for chunk_size in chunk_sizes.iter() {
|
||||
let mut bytes = Vec::new();
|
||||
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(&random_bytes[..]);
|
||||
bytes.extend(b"\r\n");
|
||||
let _ = stream.write_all(&bytes);
|
||||
}
|
||||
|
||||
let _ = stream.write_all(b"0\r\n\r\n");
|
||||
stream.shutdown(net::Shutdown::Write).unwrap();
|
||||
|
||||
let mut data = String::new();
|
||||
let _ = stream.read_to_string(&mut data);
|
||||
|
||||
let re = Regex::new(r"size=(\d+)").unwrap();
|
||||
let size: usize = match re.captures(&data) {
|
||||
Some(caps) => caps.get(1).unwrap().as_str().parse().unwrap(),
|
||||
None => panic!(format!("Failed to find size in HTTP Response: {}", data)),
|
||||
};
|
||||
size
|
||||
};
|
||||
|
||||
assert_eq!(returned_size, total_size);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_slow_request() {
|
||||
let srv = TestServer::new(|| {
|
||||
@ -409,65 +349,6 @@ fn test_content_length() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_content_length() {
|
||||
use actix_http::http::{
|
||||
header::{HeaderName, HeaderValue},
|
||||
StatusCode,
|
||||
};
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|req: Request| {
|
||||
let indx: usize = req.uri().path()[1..].parse().unwrap();
|
||||
let statuses = [
|
||||
StatusCode::NO_CONTENT,
|
||||
StatusCode::CONTINUE,
|
||||
StatusCode::SWITCHING_PROTOCOLS,
|
||||
StatusCode::PROCESSING,
|
||||
StatusCode::OK,
|
||||
StatusCode::NOT_FOUND,
|
||||
];
|
||||
future::ok::<_, ()>(Response::new(statuses[indx]))
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let header = HeaderName::from_static("content-length");
|
||||
let value = HeaderValue::from_static("0");
|
||||
|
||||
{
|
||||
for i in 0..4 {
|
||||
let req = srv
|
||||
.request(http::Method::GET, srv.surl(&format!("/{}", i)))
|
||||
.send();
|
||||
let response = srv.block_on(req).unwrap();
|
||||
assert_eq!(response.headers().get(&header), None);
|
||||
|
||||
let req = srv
|
||||
.request(http::Method::HEAD, srv.surl(&format!("/{}", i)))
|
||||
.send();
|
||||
let response = srv.block_on(req).unwrap();
|
||||
assert_eq!(response.headers().get(&header), None);
|
||||
}
|
||||
|
||||
for i in 4..6 {
|
||||
let req = srv
|
||||
.request(http::Method::GET, srv.surl(&format!("/{}", i)))
|
||||
.send();
|
||||
let response = srv.block_on(req).unwrap();
|
||||
assert_eq!(response.headers().get(&header), Some(&value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h1_headers() {
|
||||
let data = STR.repeat(10);
|
||||
@ -507,51 +388,6 @@ fn test_h1_headers() {
|
||||
assert_eq!(bytes, Bytes::from(data2));
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_headers() {
|
||||
let data = STR.repeat(10);
|
||||
let data2 = data.clone();
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let data = data.clone();
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build().h2(move |_| {
|
||||
let mut builder = Response::Ok();
|
||||
for idx in 0..90 {
|
||||
builder.header(
|
||||
format!("X-TEST-{}", idx).as_str(),
|
||||
"TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
|
||||
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST ",
|
||||
);
|
||||
}
|
||||
future::ok::<_, ()>(builder.body(data.clone()))
|
||||
}).map_err(|_| ()))
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from(data2));
|
||||
}
|
||||
|
||||
const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World \
|
||||
@ -588,29 +424,6 @@ fn test_h1_body() {
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_body2() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| future::ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h1_head_empty() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
@ -633,38 +446,6 @@ fn test_h1_head_empty() {
|
||||
assert!(bytes.is_empty());
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_head_empty() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.finish(|_| ok::<_, ()>(Response::Ok().body(STR)))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.shead("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
assert_eq!(response.version(), http::Version::HTTP_2);
|
||||
|
||||
{
|
||||
let len = response
|
||||
.headers()
|
||||
.get(http::header::CONTENT_LENGTH)
|
||||
.unwrap();
|
||||
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
|
||||
}
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert!(bytes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h1_head_binary() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
@ -689,41 +470,6 @@ fn test_h1_head_binary() {
|
||||
assert!(bytes.is_empty());
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_head_binary() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| {
|
||||
ok::<_, ()>(
|
||||
Response::Ok().content_length(STR.len() as u64).body(STR),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.shead("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
{
|
||||
let len = response
|
||||
.headers()
|
||||
.get(http::header::CONTENT_LENGTH)
|
||||
.unwrap();
|
||||
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
|
||||
}
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert!(bytes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h1_head_binary2() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
@ -742,41 +488,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]
|
||||
fn test_h1_body_length() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
HttpService::build().h1(|_| {
|
||||
let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.body(Body::from_message(body::SizedStream::new(STR.len(), body))),
|
||||
Response::Ok().body(body::SizedStream::new(STR.len() as u64, body)),
|
||||
)
|
||||
})
|
||||
});
|
||||
@ -789,34 +507,6 @@ fn test_h1_body_length() {
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_body_length() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| {
|
||||
let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(Response::Ok().body(Body::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]
|
||||
fn test_h1_body_chunked_explicit() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
@ -849,40 +539,6 @@ fn test_h1_body_chunked_explicit() {
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_body_chunked_explicit() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| {
|
||||
let body =
|
||||
once::<_, Error>(Ok(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.header(header::TRANSFER_ENCODING, "chunked")
|
||||
.streaming(body),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
assert!(!response.headers().contains_key(header::TRANSFER_ENCODING));
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
|
||||
// decode
|
||||
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h1_body_chunked_implicit() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
@ -932,39 +588,6 @@ fn test_h1_response_http_error_handling() {
|
||||
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_response_http_error_handling() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(new_service_cfg(|_: &ServerConfig| {
|
||||
Ok::<_, ()>(|_| {
|
||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.header(http::header::CONTENT_TYPE, broken_header)
|
||||
.body(STR),
|
||||
)
|
||||
})
|
||||
}))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert_eq!(response.status(), http::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(b"failed to parse header value"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h1_service_error() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
@ -979,27 +602,3 @@ fn test_h1_service_error() {
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(b"error"));
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_h2_service_error() {
|
||||
let openssl = ssl_acceptor().unwrap();
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
openssl
|
||||
.clone()
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(|_| Err::<Response, Error>(error::ErrorBadRequest("error")))
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
});
|
||||
|
||||
let response = srv.block_on(srv.sget("/").send()).unwrap();
|
||||
assert_eq!(response.status(), http::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert!(bytes.is_empty());
|
||||
}
|
||||
|
455
actix-http/tests/test_ssl_server.rs
Normal file
455
actix-http/tests/test_ssl_server.rs
Normal file
@ -0,0 +1,455 @@
|
||||
#![cfg(feature = "ssl")]
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_http::error::{ErrorBadRequest, PayloadError};
|
||||
use actix_http::http::header::{self, HeaderName, HeaderValue};
|
||||
use actix_http::http::{Method, StatusCode, Version};
|
||||
use actix_http::{body, Error, HttpService, Request, Response};
|
||||
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;
|
||||
|
||||
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::INTERNAL_SERVER_ERROR);
|
||||
|
||||
// read response
|
||||
let bytes = srv.load_body(response).unwrap();
|
||||
assert!(bytes.is_empty());
|
||||
}
|
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.
|
||||
//!
|
||||
//! To access current request identity
|
||||
//! [**Identity**](trait.Identity.html) extractor should be used.
|
||||
//! [**Identity**](struct.Identity.html) extractor should be used.
|
||||
//!
|
||||
//! ```rust
|
||||
//! use actix_web::middleware::identity::Identity;
|
||||
//! use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
|
||||
//! use actix_web::*;
|
||||
//! use actix_identity::{Identity, CookieIdentityPolicy, IdentityService};
|
||||
//!
|
||||
//! fn index(id: Identity) -> String {
|
||||
//! // access request identity
|
||||
@ -39,7 +38,7 @@
|
||||
//! fn main() {
|
||||
//! let app = App::new().wrap(IdentityService::new(
|
||||
//! // <- create identity middleware
|
||||
//! CookieIdentityPolicy::new(&[0; 32]) // <- create cookie session backend
|
||||
//! CookieIdentityPolicy::new(&[0; 32]) // <- create cookie identity policy
|
||||
//! .name("auth-cookie")
|
||||
//! .secure(false)))
|
||||
//! .service(web::resource("/index.html").to(index))
|
||||
@ -57,17 +56,17 @@ use futures::{Future, IntoFuture, Poll};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use time::Duration;
|
||||
|
||||
use crate::cookie::{Cookie, CookieJar, Key, SameSite};
|
||||
use crate::error::{Error, Result};
|
||||
use crate::http::header::{self, HeaderValue};
|
||||
use crate::service::{ServiceRequest, ServiceResponse};
|
||||
use crate::{dev::Payload, FromRequest, HttpMessage, HttpRequest};
|
||||
use actix_web::cookie::{Cookie, CookieJar, Key, SameSite};
|
||||
use actix_web::dev::{Extensions, Payload, ServiceRequest, ServiceResponse};
|
||||
use actix_web::error::{Error, Result};
|
||||
use actix_web::http::header::{self, HeaderValue};
|
||||
use actix_web::{FromRequest, HttpMessage, HttpRequest};
|
||||
|
||||
/// The extractor type to obtain your identity from a request.
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_web::*;
|
||||
/// use actix_web::middleware::identity::Identity;
|
||||
/// use actix_identity::Identity;
|
||||
///
|
||||
/// fn index(id: Identity) -> Result<String> {
|
||||
/// // access request identity
|
||||
@ -96,11 +95,7 @@ impl Identity {
|
||||
/// Return the claimed identity of the user associated request or
|
||||
/// ``None`` if no identity can be found associated with the request.
|
||||
pub fn identity(&self) -> Option<String> {
|
||||
if let Some(id) = self.0.extensions().get::<IdentityItem>() {
|
||||
id.id.clone()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
Identity::get_identity(&self.0.extensions())
|
||||
}
|
||||
|
||||
/// Remember identity.
|
||||
@ -119,6 +114,14 @@ impl Identity {
|
||||
id.changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn get_identity(extensions: &Extensions) -> Option<String> {
|
||||
if let Some(id) = extensions.get::<IdentityItem>() {
|
||||
id.id.clone()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct IdentityItem {
|
||||
@ -126,11 +129,28 @@ struct IdentityItem {
|
||||
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.
|
||||
///
|
||||
/// ```rust
|
||||
/// # use actix_web::*;
|
||||
/// use actix_web::middleware::identity::Identity;
|
||||
/// use actix_identity::Identity;
|
||||
///
|
||||
/// fn index(id: Identity) -> String {
|
||||
/// // access request identity
|
||||
@ -177,7 +197,7 @@ pub trait IdentityPolicy: Sized + 'static {
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_web::App;
|
||||
/// use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
|
||||
/// use actix_identity::{CookieIdentityPolicy, IdentityService};
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new().wrap(IdentityService::new(
|
||||
@ -241,7 +261,7 @@ where
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = Error;
|
||||
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
|
||||
type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.service.borrow_mut().poll_ready()
|
||||
@ -263,7 +283,7 @@ where
|
||||
res.request().extensions_mut().remove::<IdentityItem>();
|
||||
|
||||
if let Some(id) = id {
|
||||
return Either::A(
|
||||
Either::A(
|
||||
backend
|
||||
.to_response(id.id, id.changed, &mut res)
|
||||
.into_future()
|
||||
@ -271,7 +291,7 @@ where
|
||||
Ok(_) => Ok(res),
|
||||
Err(e) => Ok(res.error_response(e)),
|
||||
}),
|
||||
);
|
||||
)
|
||||
} else {
|
||||
Either::B(ok(res))
|
||||
}
|
||||
@ -313,8 +333,7 @@ struct CookieIdentityExtention {
|
||||
|
||||
impl CookieIdentityInner {
|
||||
fn new(key: &[u8]) -> CookieIdentityInner {
|
||||
let key_v2: Vec<u8> =
|
||||
key.iter().chain([1, 0, 0, 0].iter()).map(|e| *e).collect();
|
||||
let key_v2: Vec<u8> = key.iter().chain([1, 0, 0, 0].iter()).cloned().collect();
|
||||
CookieIdentityInner {
|
||||
key: Key::from_master(key),
|
||||
key_v2: Key::from_master(&key_v2),
|
||||
@ -442,9 +461,8 @@ impl CookieIdentityInner {
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// # extern crate actix_web;
|
||||
/// use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
|
||||
/// use actix_web::App;
|
||||
/// use actix_identity::{CookieIdentityPolicy, IdentityService};
|
||||
///
|
||||
/// fn main() {
|
||||
/// 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() {
|
||||
let visit_timestamp = SystemTime::now();
|
||||
let mut login_timestamp = None;
|
||||
if self.0.requires_oob_data() {
|
||||
let login_timestamp = if self.0.requires_oob_data() {
|
||||
let CookieIdentityExtention {
|
||||
login_timestamp: lt,
|
||||
} = res.request().extensions_mut().remove().unwrap();
|
||||
login_timestamp = lt;
|
||||
}
|
||||
lt
|
||||
} else {
|
||||
None
|
||||
};
|
||||
self.0.set_cookie(
|
||||
res,
|
||||
Some(CookieValue {
|
||||
@ -590,13 +609,13 @@ impl IdentityPolicy for CookieIdentityPolicy {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::http::StatusCode;
|
||||
use crate::test::{self, TestRequest};
|
||||
use crate::{web, App, HttpResponse};
|
||||
|
||||
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_NAME: &'static str = "actix_auth";
|
||||
const COOKIE_LOGIN: &'static str = "test";
|
||||
@ -717,8 +736,8 @@ mod tests {
|
||||
f: F,
|
||||
) -> impl actix_service::Service<
|
||||
Request = actix_http::Request,
|
||||
Response = ServiceResponse<actix_http::body::Body>,
|
||||
Error = actix_http::Error,
|
||||
Response = ServiceResponse<actix_web::body::Body>,
|
||||
Error = Error,
|
||||
> {
|
||||
test::init_service(
|
||||
App::new()
|
@ -1,8 +1,24 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.3] - 2019-06-06
|
||||
|
||||
* 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
|
||||
|
||||
* Fix disconnect handling #834
|
||||
|
||||
## [0.1.0] - 2019-05-18
|
||||
|
||||
* Release
|
||||
|
||||
## [0.1.0-beta.4] - 2019-05-12
|
||||
|
||||
* Handle cancellation of uploads #834 #736
|
||||
* Handle cancellation of uploads #736
|
||||
|
||||
* Upgrade to actix-web 1.0.0-beta.4
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-multipart"
|
||||
version = "0.1.0-beta.4"
|
||||
version = "0.1.3"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Multipart support for actix web framework."
|
||||
readme = "README.md"
|
||||
@ -18,10 +18,10 @@ name = "actix_multipart"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "1.0.0-beta.5"
|
||||
actix-service = "0.4.0"
|
||||
actix-web = { version = "1.0.0", default-features = false }
|
||||
actix-service = "0.4.1"
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
derive_more = "0.15.0"
|
||||
httparse = "1.3"
|
||||
futures = "0.1.25"
|
||||
log = "0.4"
|
||||
@ -31,4 +31,4 @@ twoway = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
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 extractor;
|
||||
mod server;
|
||||
|
@ -1,5 +1,5 @@
|
||||
//! Multipart payload support
|
||||
use std::cell::{Cell, RefCell, UnsafeCell};
|
||||
use std::cell::{Cell, RefCell, RefMut};
|
||||
use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
use std::{cmp, fmt};
|
||||
@ -112,7 +112,7 @@ impl Stream for Multipart {
|
||||
Err(err)
|
||||
} else if self.safety.current() {
|
||||
let mut inner = self.inner.as_mut().unwrap().borrow_mut();
|
||||
if let Some(payload) = inner.payload.get_mut(&self.safety) {
|
||||
if let Some(mut payload) = inner.payload.get_mut(&self.safety) {
|
||||
payload.poll_stream()?;
|
||||
}
|
||||
inner.poll(&self.safety)
|
||||
@ -128,7 +128,7 @@ impl InnerMultipart {
|
||||
fn read_headers(
|
||||
payload: &mut PayloadBuffer,
|
||||
) -> Result<Option<HeaderMap>, MultipartError> {
|
||||
match payload.read_until(b"\r\n\r\n") {
|
||||
match payload.read_until(b"\r\n\r\n")? {
|
||||
None => {
|
||||
if payload.eof {
|
||||
Err(MultipartError::Incomplete)
|
||||
@ -167,7 +167,7 @@ impl InnerMultipart {
|
||||
boundary: &str,
|
||||
) -> Result<Option<bool>, MultipartError> {
|
||||
// TODO: need to read epilogue
|
||||
match payload.readline() {
|
||||
match payload.readline()? {
|
||||
None => {
|
||||
if payload.eof {
|
||||
Ok(Some(true))
|
||||
@ -200,7 +200,7 @@ impl InnerMultipart {
|
||||
) -> Result<Option<bool>, MultipartError> {
|
||||
let mut eof = false;
|
||||
loop {
|
||||
match payload.readline() {
|
||||
match payload.readline()? {
|
||||
Some(chunk) => {
|
||||
if chunk.is_empty() {
|
||||
return Err(MultipartError::Boundary);
|
||||
@ -265,12 +265,12 @@ impl InnerMultipart {
|
||||
}
|
||||
}
|
||||
|
||||
let headers = if let Some(payload) = self.payload.get_mut(safety) {
|
||||
let headers = if let Some(mut payload) = self.payload.get_mut(safety) {
|
||||
match self.state {
|
||||
// read until first boundary
|
||||
InnerState::FirstBoundary => {
|
||||
match InnerMultipart::skip_until_boundary(
|
||||
payload,
|
||||
&mut *payload,
|
||||
&self.boundary,
|
||||
)? {
|
||||
Some(eof) => {
|
||||
@ -286,7 +286,10 @@ impl InnerMultipart {
|
||||
}
|
||||
// read boundary
|
||||
InnerState::Boundary => {
|
||||
match InnerMultipart::read_boundary(payload, &self.boundary)? {
|
||||
match InnerMultipart::read_boundary(
|
||||
&mut *payload,
|
||||
&self.boundary,
|
||||
)? {
|
||||
None => return Ok(Async::NotReady),
|
||||
Some(eof) => {
|
||||
if eof {
|
||||
@ -303,7 +306,7 @@ impl InnerMultipart {
|
||||
|
||||
// read field headers for next field
|
||||
if self.state == InnerState::Headers {
|
||||
if let Some(headers) = InnerMultipart::read_headers(payload)? {
|
||||
if let Some(headers) = InnerMultipart::read_headers(&mut *payload)? {
|
||||
self.state = InnerState::Boundary;
|
||||
headers
|
||||
} else {
|
||||
@ -411,14 +414,15 @@ impl Stream for Field {
|
||||
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
|
||||
if self.safety.current() {
|
||||
let mut inner = self.inner.borrow_mut();
|
||||
if let Some(payload) = inner.payload.as_ref().unwrap().get_mut(&self.safety)
|
||||
if let Some(mut payload) =
|
||||
inner.payload.as_ref().unwrap().get_mut(&self.safety)
|
||||
{
|
||||
payload.poll_stream()?;
|
||||
}
|
||||
|
||||
inner.poll(&self.safety)
|
||||
} else if !self.safety.is_clean() {
|
||||
return Err(MultipartError::NotConsumed);
|
||||
Err(MultipartError::NotConsumed)
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
@ -481,7 +485,7 @@ impl InnerField {
|
||||
if *size == 0 {
|
||||
Ok(Async::Ready(None))
|
||||
} else {
|
||||
match payload.read_max(*size) {
|
||||
match payload.read_max(*size)? {
|
||||
Some(mut chunk) => {
|
||||
let len = cmp::min(chunk.len() as u64, *size);
|
||||
*size -= len;
|
||||
@ -512,7 +516,11 @@ impl InnerField {
|
||||
|
||||
let len = payload.buf.len();
|
||||
if len == 0 {
|
||||
return Ok(Async::NotReady);
|
||||
return if payload.eof {
|
||||
Err(MultipartError::Incomplete)
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
};
|
||||
}
|
||||
|
||||
// check boundary
|
||||
@ -529,13 +537,9 @@ impl InnerField {
|
||||
let b_size = boundary.len() + b_len;
|
||||
if len < b_size {
|
||||
return Ok(Async::NotReady);
|
||||
} else {
|
||||
if &payload.buf[b_len..b_size] == boundary.as_bytes() {
|
||||
// found boundary
|
||||
return Ok(Async::Ready(None));
|
||||
} else {
|
||||
pos = b_size;
|
||||
}
|
||||
} else if &payload.buf[b_len..b_size] == boundary.as_bytes() {
|
||||
// found boundary
|
||||
return Ok(Async::Ready(None));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -555,7 +559,7 @@ impl InnerField {
|
||||
// check boundary
|
||||
if (&payload.buf[cur..cur + 2] == b"\r\n"
|
||||
&& &payload.buf[cur + 2..cur + 4] == b"--")
|
||||
|| (&payload.buf[cur..cur + 1] == b"\r"
|
||||
|| (&payload.buf[cur..=cur] == b"\r"
|
||||
&& &payload.buf[cur + 1..cur + 3] == b"--")
|
||||
{
|
||||
if cur != 0 {
|
||||
@ -572,7 +576,7 @@ impl InnerField {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Ok(Async::Ready(Some(payload.buf.take().freeze())));
|
||||
Ok(Async::Ready(Some(payload.buf.take().freeze())))
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -582,12 +586,13 @@ impl InnerField {
|
||||
return Ok(Async::Ready(None));
|
||||
}
|
||||
|
||||
let result = if let Some(payload) = self.payload.as_ref().unwrap().get_mut(s) {
|
||||
let result = if let Some(mut payload) = self.payload.as_ref().unwrap().get_mut(s)
|
||||
{
|
||||
if !self.eof {
|
||||
let res = if let Some(ref mut len) = self.length {
|
||||
InnerField::read_len(payload, len)?
|
||||
InnerField::read_len(&mut *payload, len)?
|
||||
} else {
|
||||
InnerField::read_stream(payload, &self.boundary)?
|
||||
InnerField::read_stream(&mut *payload, &self.boundary)?
|
||||
};
|
||||
|
||||
match res {
|
||||
@ -597,7 +602,7 @@ impl InnerField {
|
||||
}
|
||||
}
|
||||
|
||||
match payload.readline() {
|
||||
match payload.readline()? {
|
||||
None => Async::Ready(None),
|
||||
Some(line) => {
|
||||
if line.as_ref() != b"\r\n" {
|
||||
@ -618,7 +623,7 @@ impl InnerField {
|
||||
}
|
||||
|
||||
struct PayloadRef {
|
||||
payload: Rc<UnsafeCell<PayloadBuffer>>,
|
||||
payload: Rc<RefCell<PayloadBuffer>>,
|
||||
}
|
||||
|
||||
impl PayloadRef {
|
||||
@ -628,15 +633,12 @@ impl PayloadRef {
|
||||
}
|
||||
}
|
||||
|
||||
fn get_mut<'a, 'b>(&'a self, s: &'b Safety) -> Option<&'a mut PayloadBuffer>
|
||||
fn get_mut<'a, 'b>(&'a self, s: &'b Safety) -> Option<RefMut<'a, PayloadBuffer>>
|
||||
where
|
||||
'a: 'b,
|
||||
{
|
||||
// Unsafe: Invariant is inforced by Safety Safety is used as ref counter,
|
||||
// only top most ref can have mutable access to payload.
|
||||
if s.current() {
|
||||
let payload: &mut PayloadBuffer = unsafe { &mut *self.payload.get() };
|
||||
Some(payload)
|
||||
Some(self.payload.borrow_mut())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@ -749,23 +751,31 @@ impl PayloadBuffer {
|
||||
}
|
||||
}
|
||||
|
||||
fn read_max(&mut self, size: u64) -> Option<Bytes> {
|
||||
fn read_max(&mut self, size: u64) -> Result<Option<Bytes>, MultipartError> {
|
||||
if !self.buf.is_empty() {
|
||||
let size = std::cmp::min(self.buf.len() as u64, size) as usize;
|
||||
Some(self.buf.split_to(size).freeze())
|
||||
Ok(Some(self.buf.split_to(size).freeze()))
|
||||
} else if self.eof {
|
||||
Err(MultipartError::Incomplete)
|
||||
} else {
|
||||
None
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// Read until specified ending
|
||||
pub fn read_until(&mut self, line: &[u8]) -> Option<Bytes> {
|
||||
twoway::find_bytes(&self.buf, line)
|
||||
.map(|idx| self.buf.split_to(idx + line.len()).freeze())
|
||||
pub fn read_until(&mut self, line: &[u8]) -> Result<Option<Bytes>, MultipartError> {
|
||||
let res = twoway::find_bytes(&self.buf, line)
|
||||
.map(|idx| self.buf.split_to(idx + line.len()).freeze());
|
||||
|
||||
if res.is_none() && self.eof {
|
||||
Err(MultipartError::Incomplete)
|
||||
} else {
|
||||
Ok(res)
|
||||
}
|
||||
}
|
||||
|
||||
/// Read bytes until new line delimiter
|
||||
pub fn readline(&mut self) -> Option<Bytes> {
|
||||
pub fn readline(&mut self) -> Result<Option<Bytes>, MultipartError> {
|
||||
self.read_until(b"\n")
|
||||
}
|
||||
|
||||
@ -991,7 +1001,7 @@ mod tests {
|
||||
|
||||
assert_eq!(payload.buf.len(), 0);
|
||||
payload.poll_stream().unwrap();
|
||||
assert_eq!(None, payload.read_max(1));
|
||||
assert_eq!(None, payload.read_max(1).unwrap());
|
||||
})
|
||||
}
|
||||
|
||||
@ -1001,14 +1011,14 @@ mod tests {
|
||||
let (mut sender, payload) = Payload::create(false);
|
||||
let mut payload = PayloadBuffer::new(payload);
|
||||
|
||||
assert_eq!(None, payload.read_max(4));
|
||||
assert_eq!(None, payload.read_max(4).unwrap());
|
||||
sender.feed_data(Bytes::from("data"));
|
||||
sender.feed_eof();
|
||||
payload.poll_stream().unwrap();
|
||||
|
||||
assert_eq!(Some(Bytes::from("data")), payload.read_max(4));
|
||||
assert_eq!(Some(Bytes::from("data")), payload.read_max(4).unwrap());
|
||||
assert_eq!(payload.buf.len(), 0);
|
||||
assert_eq!(None, payload.read_max(1));
|
||||
assert!(payload.read_max(1).is_err());
|
||||
assert!(payload.eof);
|
||||
})
|
||||
}
|
||||
@ -1018,7 +1028,7 @@ mod tests {
|
||||
run_on(|| {
|
||||
let (mut sender, payload) = Payload::create(false);
|
||||
let mut payload = PayloadBuffer::new(payload);
|
||||
assert_eq!(None, payload.read_max(1));
|
||||
assert_eq!(None, payload.read_max(1).unwrap());
|
||||
sender.set_error(PayloadError::Incomplete(None));
|
||||
payload.poll_stream().err().unwrap();
|
||||
})
|
||||
@ -1035,10 +1045,10 @@ mod tests {
|
||||
payload.poll_stream().unwrap();
|
||||
assert_eq!(payload.buf.len(), 10);
|
||||
|
||||
assert_eq!(Some(Bytes::from("line1")), payload.read_max(5));
|
||||
assert_eq!(Some(Bytes::from("line1")), payload.read_max(5).unwrap());
|
||||
assert_eq!(payload.buf.len(), 5);
|
||||
|
||||
assert_eq!(Some(Bytes::from("line2")), payload.read_max(5));
|
||||
assert_eq!(Some(Bytes::from("line2")), payload.read_max(5).unwrap());
|
||||
assert_eq!(payload.buf.len(), 0);
|
||||
})
|
||||
}
|
||||
@ -1069,16 +1079,22 @@ mod tests {
|
||||
let (mut sender, payload) = Payload::create(false);
|
||||
let mut payload = PayloadBuffer::new(payload);
|
||||
|
||||
assert_eq!(None, payload.read_until(b"ne"));
|
||||
assert_eq!(None, payload.read_until(b"ne").unwrap());
|
||||
|
||||
sender.feed_data(Bytes::from("line1"));
|
||||
sender.feed_data(Bytes::from("line2"));
|
||||
payload.poll_stream().unwrap();
|
||||
|
||||
assert_eq!(Some(Bytes::from("line")), payload.read_until(b"ne"));
|
||||
assert_eq!(
|
||||
Some(Bytes::from("line")),
|
||||
payload.read_until(b"ne").unwrap()
|
||||
);
|
||||
assert_eq!(payload.buf.len(), 6);
|
||||
|
||||
assert_eq!(Some(Bytes::from("1line2")), payload.read_until(b"2"));
|
||||
assert_eq!(
|
||||
Some(Bytes::from("1line2")),
|
||||
payload.read_until(b"2").unwrap()
|
||||
);
|
||||
assert_eq!(payload.buf.len(), 0);
|
||||
})
|
||||
}
|
||||
|
@ -1,5 +1,20 @@
|
||||
# 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
|
||||
|
||||
* Use actix-web 1.0.0-rc
|
||||
|
||||
## [0.1.0-beta.4] - 2019-05-12
|
||||
|
||||
* Use actix-web 1.0.0-beta.4
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-session"
|
||||
version = "0.1.0-beta.4"
|
||||
version = "0.2.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Session for actix web framework."
|
||||
readme = "README.md"
|
||||
@ -24,12 +24,12 @@ default = ["cookie-session"]
|
||||
cookie-session = ["actix-web/secure-cookies"]
|
||||
|
||||
[dependencies]
|
||||
actix-web = "1.0.0-beta.5"
|
||||
actix-service = "0.4.0"
|
||||
actix-web = "1.0.0"
|
||||
actix-service = "0.4.1"
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
derive_more = "0.15.0"
|
||||
futures = "0.1.25"
|
||||
hashbrown = "0.3.0"
|
||||
hashbrown = "0.5.0"
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
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/)
|
||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||
* Cargo package: [actix-session](https://crates.io/crates/actix-session)
|
||||
* Minimum supported Rust version: 1.33 or later
|
||||
* Minimum supported Rust version: 1.34 or later
|
||||
|
@ -28,7 +28,7 @@ use futures::future::{ok, Future, FutureResult};
|
||||
use futures::Poll;
|
||||
use serde_json::error::Error as JsonError;
|
||||
|
||||
use crate::Session;
|
||||
use crate::{Session, SessionStatus};
|
||||
|
||||
/// Errors that can occur during handling cookie session
|
||||
#[derive(Debug, From, Display)]
|
||||
@ -119,7 +119,20 @@ impl CookieSessionInner {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load(&self, req: &ServiceRequest) -> HashMap<String, String> {
|
||||
/// invalidates session cookie
|
||||
fn remove_cookie<B>(&self, res: &mut ServiceResponse<B>) -> Result<(), Error> {
|
||||
let mut cookie = Cookie::named(self.name.clone());
|
||||
cookie.set_value("");
|
||||
cookie.set_max_age(time::Duration::seconds(0));
|
||||
cookie.set_expires(time::now() - time::Duration::days(365));
|
||||
|
||||
let val = HeaderValue::from_str(&cookie.to_string())?;
|
||||
res.headers_mut().append(SET_COOKIE, val);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load(&self, req: &ServiceRequest) -> (bool, HashMap<String, String>) {
|
||||
if let Ok(cookies) = req.cookies() {
|
||||
for cookie in cookies.iter() {
|
||||
if cookie.name() == self.name {
|
||||
@ -134,13 +147,13 @@ impl CookieSessionInner {
|
||||
};
|
||||
if let Some(cookie) = cookie_opt {
|
||||
if let Ok(val) = serde_json::from_str(cookie.value()) {
|
||||
return val;
|
||||
return (false, val);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
HashMap::new()
|
||||
(true, HashMap::new())
|
||||
}
|
||||
}
|
||||
|
||||
@ -296,22 +309,43 @@ where
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = S::Error;
|
||||
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
|
||||
type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.service.poll_ready()
|
||||
}
|
||||
|
||||
/// On first request, a new session cookie is returned in response, regardless
|
||||
/// of whether any session state is set. With subsequent requests, if the
|
||||
/// session state changes, then set-cookie is returned in response. As
|
||||
/// a user logs out, call session.purge() to set SessionStatus accordingly
|
||||
/// and this will trigger removal of the session cookie in the response.
|
||||
fn call(&mut self, mut req: ServiceRequest) -> Self::Future {
|
||||
let inner = self.inner.clone();
|
||||
let state = self.inner.load(&req);
|
||||
let (is_new, state) = self.inner.load(&req);
|
||||
Session::set_session(state.into_iter(), &mut req);
|
||||
|
||||
Box::new(self.service.call(req).map(move |mut res| {
|
||||
if let Some(state) = Session::get_changes(&mut res) {
|
||||
res.checked_expr(|res| inner.set_cookie(res, state))
|
||||
} else {
|
||||
res
|
||||
match Session::get_changes(&mut res) {
|
||||
(SessionStatus::Changed, Some(state))
|
||||
| (SessionStatus::Renewed, Some(state)) => {
|
||||
res.checked_expr(|res| inner.set_cookie(res, state))
|
||||
}
|
||||
(SessionStatus::Unchanged, _) =>
|
||||
// set a new session cookie upon first request (new client)
|
||||
{
|
||||
if is_new {
|
||||
let state: HashMap<String, String> = HashMap::new();
|
||||
res.checked_expr(|res| inner.set_cookie(res, state.into_iter()))
|
||||
} else {
|
||||
res
|
||||
}
|
||||
}
|
||||
(SessionStatus::Purged, _) => {
|
||||
let _ = inner.remove_cookie(&mut res);
|
||||
res
|
||||
}
|
||||
_ => res,
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
@ -52,7 +52,9 @@ use serde::de::DeserializeOwned;
|
||||
use serde::Serialize;
|
||||
use serde_json;
|
||||
|
||||
#[cfg(feature = "cookie-session")]
|
||||
mod cookie;
|
||||
#[cfg(feature = "cookie-session")]
|
||||
pub use crate::cookie::CookieSession;
|
||||
|
||||
/// 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)]
|
||||
struct SessionInner {
|
||||
state: HashMap<String, String>,
|
||||
changed: bool,
|
||||
pub status: SessionStatus,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@ -115,25 +130,46 @@ impl Session {
|
||||
/// Set a `value` from the session.
|
||||
pub fn set<T: Serialize>(&self, key: &str, value: T) -> Result<(), Error> {
|
||||
let mut inner = self.0.borrow_mut();
|
||||
inner.changed = true;
|
||||
inner
|
||||
.state
|
||||
.insert(key.to_owned(), serde_json::to_string(&value)?);
|
||||
if inner.status != SessionStatus::Purged {
|
||||
inner.status = SessionStatus::Changed;
|
||||
inner
|
||||
.state
|
||||
.insert(key.to_owned(), serde_json::to_string(&value)?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove value from the session.
|
||||
pub fn remove(&self, key: &str) {
|
||||
let mut inner = self.0.borrow_mut();
|
||||
inner.changed = true;
|
||||
inner.state.remove(key);
|
||||
if inner.status != SessionStatus::Purged {
|
||||
inner.status = SessionStatus::Changed;
|
||||
inner.state.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear the session.
|
||||
pub fn clear(&self) {
|
||||
let mut inner = self.0.borrow_mut();
|
||||
inner.changed = true;
|
||||
inner.state.clear()
|
||||
if inner.status != SessionStatus::Purged {
|
||||
inner.status = SessionStatus::Changed;
|
||||
inner.state.clear()
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes session, both client and server side.
|
||||
pub fn purge(&self) {
|
||||
let mut inner = self.0.borrow_mut();
|
||||
inner.status = SessionStatus::Purged;
|
||||
inner.state.clear();
|
||||
}
|
||||
|
||||
/// Renews the session key, assigning existing session state to new key.
|
||||
pub fn renew(&self) {
|
||||
let mut inner = self.0.borrow_mut();
|
||||
if inner.status != SessionStatus::Purged {
|
||||
inner.status = SessionStatus::Renewed;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_session(
|
||||
@ -147,7 +183,10 @@ impl Session {
|
||||
|
||||
pub fn get_changes<B>(
|
||||
res: &mut ServiceResponse<B>,
|
||||
) -> Option<impl Iterator<Item = (String, String)>> {
|
||||
) -> (
|
||||
SessionStatus,
|
||||
Option<impl Iterator<Item = (String, String)>>,
|
||||
) {
|
||||
if let Some(s_impl) = res
|
||||
.request()
|
||||
.extensions()
|
||||
@ -155,9 +194,9 @@ impl Session {
|
||||
{
|
||||
let state =
|
||||
std::mem::replace(&mut s_impl.borrow_mut().state, HashMap::new());
|
||||
Some(state.into_iter())
|
||||
(s_impl.borrow().status.clone(), Some(state.into_iter()))
|
||||
} else {
|
||||
None
|
||||
(SessionStatus::Unchanged, None)
|
||||
}
|
||||
}
|
||||
|
||||
@ -222,7 +261,8 @@ mod tests {
|
||||
session.remove("key");
|
||||
|
||||
let mut res = req.into_response(HttpResponse::Ok().finish());
|
||||
let changes: Vec<_> = Session::get_changes(&mut res).unwrap().collect();
|
||||
let (_status, state) = Session::get_changes(&mut res);
|
||||
let changes: Vec<_> = state.unwrap().collect();
|
||||
assert_eq!(changes, [("key2".to_string(), "\"value2\"".to_string())]);
|
||||
}
|
||||
|
||||
@ -239,4 +279,22 @@ mod tests {
|
||||
let res = session.get::<String>("key").unwrap();
|
||||
assert_eq!(res, Some("value".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn purge_session() {
|
||||
let req = test::TestRequest::default().to_srv_request();
|
||||
let session = Session::get_session(&mut *req.extensions_mut());
|
||||
assert_eq!(session.0.borrow().status, SessionStatus::Unchanged);
|
||||
session.purge();
|
||||
assert_eq!(session.0.borrow().status, SessionStatus::Purged);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renew_session() {
|
||||
let req = test::TestRequest::default().to_srv_request();
|
||||
let session = Session::get_session(&mut *req.extensions_mut());
|
||||
assert_eq!(session.0.borrow().status, SessionStatus::Unchanged);
|
||||
session.renew();
|
||||
assert_eq!(session.0.borrow().status, SessionStatus::Renewed);
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,20 @@
|
||||
# Changes
|
||||
|
||||
## [1.0.2] - 2019-07-20
|
||||
|
||||
* Add `ws::start_with_addr()`, returning the address of the created actor, along
|
||||
with the `HttpResponse`.
|
||||
|
||||
* Add support for specifying protocols on websocket handshake #835
|
||||
|
||||
## [1.0.1] - 2019-06-28
|
||||
|
||||
* Allow to use custom ws codec with `WebsocketContext` #925
|
||||
|
||||
## [1.0.0] - 2019-05-29
|
||||
|
||||
* Update actix-http and actix-web
|
||||
|
||||
## [0.1.0-alpha.3] - 2019-04-02
|
||||
|
||||
* Update actix-http and actix-web
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web-actors"
|
||||
version = "1.0.0-beta.4"
|
||||
version = "1.0.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix actors support for actix web framework."
|
||||
readme = "README.md"
|
||||
@ -18,13 +18,13 @@ name = "actix_web_actors"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix = "0.8.2"
|
||||
actix-web = "1.0.0-beta.5"
|
||||
actix-http = "0.2.0"
|
||||
actix = "0.8.3"
|
||||
actix-web = "1.0.3"
|
||||
actix-http = "0.2.5"
|
||||
actix-codec = "0.1.2"
|
||||
bytes = "0.4"
|
||||
futures = "0.1.25"
|
||||
|
||||
[dev-dependencies]
|
||||
env_logger = "0.6"
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.4", features=["ssl"] }
|
||||
|
1
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
|
||||
mod context;
|
||||
pub mod ws;
|
||||
|
@ -35,15 +35,68 @@ where
|
||||
Ok(res.streaming(WebsocketContext::create(actor, stream)))
|
||||
}
|
||||
|
||||
/// Do websocket handshake and start ws actor.
|
||||
///
|
||||
/// `req` is an HTTP Request that should be requesting a websocket protocol
|
||||
/// change. `stream` should be a `Bytes` stream (such as
|
||||
/// `actix_web::web::Payload`) that contains a stream of the body request.
|
||||
///
|
||||
/// If there is a problem with the handshake, an error is returned.
|
||||
///
|
||||
/// If successful, returns a pair where the first item is an address for the
|
||||
/// created actor and the second item is the response that should be returned
|
||||
/// from the websocket request.
|
||||
pub fn start_with_addr<A, T>(
|
||||
actor: A,
|
||||
req: &HttpRequest,
|
||||
stream: T,
|
||||
) -> Result<(Addr<A>, HttpResponse), Error>
|
||||
where
|
||||
A: Actor<Context = WebsocketContext<A>> + StreamHandler<Message, ProtocolError>,
|
||||
T: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
||||
{
|
||||
let mut res = handshake(req)?;
|
||||
let (addr, out_stream) = WebsocketContext::create_with_addr(actor, stream);
|
||||
Ok((addr, res.streaming(out_stream)))
|
||||
}
|
||||
|
||||
/// Do websocket handshake and start ws actor.
|
||||
///
|
||||
/// `protocols` is a sequence of known protocols.
|
||||
pub fn start_with_protocols<A, T>(
|
||||
actor: A,
|
||||
protocols: &[&str],
|
||||
req: &HttpRequest,
|
||||
stream: T,
|
||||
) -> Result<HttpResponse, Error>
|
||||
where
|
||||
A: Actor<Context = WebsocketContext<A>> + StreamHandler<Message, ProtocolError>,
|
||||
T: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
||||
{
|
||||
let mut res = handshake_with_protocols(req, protocols)?;
|
||||
Ok(res.streaming(WebsocketContext::create(actor, stream)))
|
||||
}
|
||||
|
||||
/// Prepare `WebSocket` handshake response.
|
||||
///
|
||||
/// This function returns handshake `HttpResponse`, ready to send to peer.
|
||||
/// It does not perform any IO.
|
||||
pub fn handshake(req: &HttpRequest) -> Result<HttpResponseBuilder, HandshakeError> {
|
||||
handshake_with_protocols(req, &[])
|
||||
}
|
||||
|
||||
/// Prepare `WebSocket` handshake response.
|
||||
///
|
||||
/// This function returns handshake `HttpResponse`, ready to send to peer.
|
||||
/// It does not perform any IO.
|
||||
///
|
||||
// /// `protocols` is a sequence of known protocols. On successful handshake,
|
||||
// /// the returned response headers contain the first protocol in this list
|
||||
// /// which the server also knows.
|
||||
pub fn handshake(req: &HttpRequest) -> Result<HttpResponseBuilder, HandshakeError> {
|
||||
/// `protocols` is a sequence of known protocols. On successful handshake,
|
||||
/// the returned response headers contain the first protocol in this list
|
||||
/// which the server also knows.
|
||||
pub fn handshake_with_protocols(
|
||||
req: &HttpRequest,
|
||||
protocols: &[&str],
|
||||
) -> Result<HttpResponseBuilder, HandshakeError> {
|
||||
// WebSocket accepts only GET
|
||||
if *req.method() != Method::GET {
|
||||
return Err(HandshakeError::GetMethodRequired);
|
||||
@ -92,11 +145,28 @@ pub fn handshake(req: &HttpRequest) -> Result<HttpResponseBuilder, HandshakeErro
|
||||
hash_key(key.as_ref())
|
||||
};
|
||||
|
||||
Ok(HttpResponse::build(StatusCode::SWITCHING_PROTOCOLS)
|
||||
// check requested protocols
|
||||
let protocol =
|
||||
req.headers()
|
||||
.get(&header::SEC_WEBSOCKET_PROTOCOL)
|
||||
.and_then(|req_protocols| {
|
||||
let req_protocols = req_protocols.to_str().ok()?;
|
||||
req_protocols
|
||||
.split(", ")
|
||||
.find(|req_p| protocols.iter().any(|p| p == req_p))
|
||||
});
|
||||
|
||||
let mut response = HttpResponse::build(StatusCode::SWITCHING_PROTOCOLS)
|
||||
.upgrade("websocket")
|
||||
.header(header::TRANSFER_ENCODING, "chunked")
|
||||
.header(header::SEC_WEBSOCKET_ACCEPT, key.as_str())
|
||||
.take())
|
||||
.take();
|
||||
|
||||
if let Some(protocol) = protocol {
|
||||
response.header(&header::SEC_WEBSOCKET_PROTOCOL, protocol);
|
||||
}
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
/// Execution context for `WebSockets` actors
|
||||
@ -168,6 +238,24 @@ where
|
||||
#[inline]
|
||||
/// Create a new Websocket context from a request and an actor
|
||||
pub fn create<S>(actor: A, stream: S) -> impl Stream<Item = Bytes, Error = Error>
|
||||
where
|
||||
A: StreamHandler<Message, ProtocolError>,
|
||||
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
||||
{
|
||||
let (_, stream) = WebsocketContext::create_with_addr(actor, stream);
|
||||
stream
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// Create a new Websocket context from a request and an actor.
|
||||
///
|
||||
/// Returns a pair, where the first item is an addr for the created actor,
|
||||
/// and the second item is a stream intended to be set as part of the
|
||||
/// response via `HttpResponseBuilder::streaming()`.
|
||||
pub fn create_with_addr<S>(
|
||||
actor: A,
|
||||
stream: S,
|
||||
) -> (Addr<A>, impl Stream<Item = Bytes, Error = Error>)
|
||||
where
|
||||
A: StreamHandler<Message, ProtocolError>,
|
||||
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
||||
@ -177,9 +265,32 @@ where
|
||||
inner: ContextParts::new(mb.sender_producer()),
|
||||
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
|
||||
@ -197,11 +308,11 @@ where
|
||||
inner: ContextParts::new(mb.sender_producer()),
|
||||
messages: VecDeque::new(),
|
||||
};
|
||||
ctx.add_stream(WsStream::new(stream));
|
||||
ctx.add_stream(WsStream::new(stream, Codec::new()));
|
||||
|
||||
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
|
||||
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);
|
||||
WebsocketContextFut {
|
||||
fut,
|
||||
encoder: Codec::new(),
|
||||
encoder: codec,
|
||||
buf: BytesMut::new(),
|
||||
closed: false,
|
||||
}
|
||||
@ -353,10 +464,10 @@ impl<S> WsStream<S>
|
||||
where
|
||||
S: Stream<Item = Bytes, Error = PayloadError>,
|
||||
{
|
||||
fn new(stream: S) -> Self {
|
||||
fn new(stream: S, codec: Codec) -> Self {
|
||||
Self {
|
||||
stream,
|
||||
decoder: Codec::new(),
|
||||
decoder: codec,
|
||||
buf: BytesMut::new(),
|
||||
closed: false,
|
||||
}
|
||||
@ -414,7 +525,7 @@ where
|
||||
}
|
||||
}
|
||||
Frame::Binary(data) => Message::Binary(
|
||||
data.map(|b| b.freeze()).unwrap_or_else(|| Bytes::new()),
|
||||
data.map(|b| b.freeze()).unwrap_or_else(Bytes::new),
|
||||
),
|
||||
Frame::Ping(s) => Message::Ping(s),
|
||||
Frame::Pong(s) => Message::Pong(s),
|
||||
@ -543,5 +654,87 @@ mod tests {
|
||||
StatusCode::SWITCHING_PROTOCOLS,
|
||||
handshake(&req).unwrap().finish().status()
|
||||
);
|
||||
|
||||
let req = TestRequest::default()
|
||||
.header(
|
||||
header::UPGRADE,
|
||||
header::HeaderValue::from_static("websocket"),
|
||||
)
|
||||
.header(
|
||||
header::CONNECTION,
|
||||
header::HeaderValue::from_static("upgrade"),
|
||||
)
|
||||
.header(
|
||||
header::SEC_WEBSOCKET_VERSION,
|
||||
header::HeaderValue::from_static("13"),
|
||||
)
|
||||
.header(
|
||||
header::SEC_WEBSOCKET_KEY,
|
||||
header::HeaderValue::from_static("13"),
|
||||
)
|
||||
.header(
|
||||
header::SEC_WEBSOCKET_PROTOCOL,
|
||||
header::HeaderValue::from_static("graphql"),
|
||||
)
|
||||
.to_http_request();
|
||||
|
||||
let protocols = ["graphql"];
|
||||
|
||||
assert_eq!(
|
||||
StatusCode::SWITCHING_PROTOCOLS,
|
||||
handshake_with_protocols(&req, &protocols)
|
||||
.unwrap()
|
||||
.finish()
|
||||
.status()
|
||||
);
|
||||
assert_eq!(
|
||||
Some(&header::HeaderValue::from_static("graphql")),
|
||||
handshake_with_protocols(&req, &protocols)
|
||||
.unwrap()
|
||||
.finish()
|
||||
.headers()
|
||||
.get(&header::SEC_WEBSOCKET_PROTOCOL)
|
||||
);
|
||||
|
||||
let req = TestRequest::default()
|
||||
.header(
|
||||
header::UPGRADE,
|
||||
header::HeaderValue::from_static("websocket"),
|
||||
)
|
||||
.header(
|
||||
header::CONNECTION,
|
||||
header::HeaderValue::from_static("upgrade"),
|
||||
)
|
||||
.header(
|
||||
header::SEC_WEBSOCKET_VERSION,
|
||||
header::HeaderValue::from_static("13"),
|
||||
)
|
||||
.header(
|
||||
header::SEC_WEBSOCKET_KEY,
|
||||
header::HeaderValue::from_static("13"),
|
||||
)
|
||||
.header(
|
||||
header::SEC_WEBSOCKET_PROTOCOL,
|
||||
header::HeaderValue::from_static("p1, p2, p3"),
|
||||
)
|
||||
.to_http_request();
|
||||
|
||||
let protocols = vec!["p3", "p2"];
|
||||
|
||||
assert_eq!(
|
||||
StatusCode::SWITCHING_PROTOCOLS,
|
||||
handshake_with_protocols(&req, &protocols)
|
||||
.unwrap()
|
||||
.finish()
|
||||
.status()
|
||||
);
|
||||
assert_eq!(
|
||||
Some(&header::HeaderValue::from_static("p2")),
|
||||
handshake_with_protocols(&req, &protocols)
|
||||
.unwrap()
|
||||
.finish()
|
||||
.headers()
|
||||
.get(&header::SEC_WEBSOCKET_PROTOCOL)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,13 @@
|
||||
# Changes
|
||||
|
||||
## [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
|
||||
|
||||
* Release
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web-codegen"
|
||||
version = "0.1.0"
|
||||
version = "0.1.2"
|
||||
description = "Actix web proc macros"
|
||||
readme = "README.md"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
@ -12,11 +12,11 @@ workspace = ".."
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
quote = "0.6"
|
||||
syn = { version = "0.15", features = ["full", "parsing"] }
|
||||
quote = "0.6.12"
|
||||
syn = { version = "0.15.34", features = ["full", "parsing", "extra-traits"] }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = { version = "1.0.0-beta.5" }
|
||||
actix-http = { version = "0.2.0", features=["ssl"] }
|
||||
actix-web = { version = "1.0.0" }
|
||||
actix-http = { version = "0.2.4", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
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
|
@ -11,6 +11,11 @@
|
||||
//! - [post](attr.post.html)
|
||||
//! - [put](attr.put.html)
|
||||
//! - [delete](attr.delete.html)
|
||||
//! - [head](attr.head.html)
|
||||
//! - [connect](attr.connect.html)
|
||||
//! - [options](attr.options.html)
|
||||
//! - [trace](attr.trace.html)
|
||||
//! - [patch](attr.patch.html)
|
||||
//!
|
||||
//! ### Attributes:
|
||||
//!
|
||||
@ -92,3 +97,63 @@ pub fn delete(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Delete);
|
||||
gen.generate()
|
||||
}
|
||||
|
||||
/// Creates route handler with `HEAD` method guard.
|
||||
///
|
||||
/// Syntax: `#[head("path"[, attributes])]`
|
||||
///
|
||||
/// Attributes are the same as in [head](attr.head.html)
|
||||
#[proc_macro_attribute]
|
||||
pub fn head(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Head);
|
||||
gen.generate()
|
||||
}
|
||||
|
||||
/// Creates route handler with `CONNECT` method guard.
|
||||
///
|
||||
/// Syntax: `#[connect("path"[, attributes])]`
|
||||
///
|
||||
/// Attributes are the same as in [connect](attr.connect.html)
|
||||
#[proc_macro_attribute]
|
||||
pub fn connect(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Connect);
|
||||
gen.generate()
|
||||
}
|
||||
|
||||
/// Creates route handler with `OPTIONS` method guard.
|
||||
///
|
||||
/// Syntax: `#[options("path"[, attributes])]`
|
||||
///
|
||||
/// Attributes are the same as in [options](attr.options.html)
|
||||
#[proc_macro_attribute]
|
||||
pub fn options(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Options);
|
||||
gen.generate()
|
||||
}
|
||||
|
||||
/// Creates route handler with `TRACE` method guard.
|
||||
///
|
||||
/// Syntax: `#[trace("path"[, attributes])]`
|
||||
///
|
||||
/// Attributes are the same as in [trace](attr.trace.html)
|
||||
#[proc_macro_attribute]
|
||||
pub fn trace(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Trace);
|
||||
gen.generate()
|
||||
}
|
||||
|
||||
/// Creates route handler with `PATCH` method guard.
|
||||
///
|
||||
/// Syntax: `#[patch("path"[, attributes])]`
|
||||
///
|
||||
/// Attributes are the same as in [patch](attr.patch.html)
|
||||
#[proc_macro_attribute]
|
||||
pub fn patch(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Patch);
|
||||
gen.generate()
|
||||
}
|
||||
|
@ -12,9 +12,9 @@ enum ResourceType {
|
||||
|
||||
impl fmt::Display for ResourceType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
&ResourceType::Async => write!(f, "to_async"),
|
||||
&ResourceType::Sync => write!(f, "to"),
|
||||
match *self {
|
||||
ResourceType::Async => write!(f, "to_async"),
|
||||
ResourceType::Sync => write!(f, "to"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -25,15 +25,25 @@ pub enum GuardType {
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Head,
|
||||
Connect,
|
||||
Options,
|
||||
Trace,
|
||||
Patch,
|
||||
}
|
||||
|
||||
impl fmt::Display for GuardType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
&GuardType::Get => write!(f, "Get"),
|
||||
&GuardType::Post => write!(f, "Post"),
|
||||
&GuardType::Put => write!(f, "Put"),
|
||||
&GuardType::Delete => write!(f, "Delete"),
|
||||
match *self {
|
||||
GuardType::Get => write!(f, "Get"),
|
||||
GuardType::Post => write!(f, "Post"),
|
||||
GuardType::Put => write!(f, "Put"),
|
||||
GuardType::Delete => write!(f, "Delete"),
|
||||
GuardType::Head => write!(f, "Head"),
|
||||
GuardType::Connect => write!(f, "Connect"),
|
||||
GuardType::Options => write!(f, "Options"),
|
||||
GuardType::Trace => write!(f, "Trace"),
|
||||
GuardType::Patch => write!(f, "Patch"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -82,37 +92,27 @@ impl actix_web::dev::HttpServiceFactory for {name} {{
|
||||
fn guess_resource_type(typ: &syn::Type) -> ResourceType {
|
||||
let mut guess = ResourceType::Sync;
|
||||
|
||||
match typ {
|
||||
syn::Type::ImplTrait(typ) => {
|
||||
for bound in typ.bounds.iter() {
|
||||
match bound {
|
||||
syn::TypeParamBound::Trait(bound) => {
|
||||
for bound in bound.path.segments.iter() {
|
||||
if bound.ident == "Future" {
|
||||
guess = ResourceType::Async;
|
||||
break;
|
||||
} else if bound.ident == "Responder" {
|
||||
guess = ResourceType::Sync;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let syn::Type::ImplTrait(typ) = typ {
|
||||
for bound in typ.bounds.iter() {
|
||||
if let syn::TypeParamBound::Trait(bound) = bound {
|
||||
for bound in bound.path.segments.iter() {
|
||||
if bound.ident == "Future" {
|
||||
guess = ResourceType::Async;
|
||||
break;
|
||||
} else if bound.ident == "Responder" {
|
||||
guess = ResourceType::Sync;
|
||||
break;
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
|
||||
guess
|
||||
}
|
||||
|
||||
impl Args {
|
||||
pub fn new(
|
||||
args: &Vec<syn::NestedMeta>,
|
||||
input: TokenStream,
|
||||
guard: GuardType,
|
||||
) -> Self {
|
||||
pub fn new(args: &[syn::NestedMeta], input: TokenStream, guard: GuardType) -> Self {
|
||||
if args.is_empty() {
|
||||
panic!(
|
||||
"invalid server definition, expected: #[{}(\"some path\")]",
|
||||
@ -154,9 +154,10 @@ impl Args {
|
||||
ResourceType::Async
|
||||
} else {
|
||||
match ast.decl.output {
|
||||
syn::ReturnType::Default => {
|
||||
panic!("Function {} has no return type. Cannot be used as handler")
|
||||
}
|
||||
syn::ReturnType::Default => panic!(
|
||||
"Function {} has no return type. Cannot be used as handler",
|
||||
name
|
||||
),
|
||||
syn::ReturnType::Type(_, ref typ) => guess_resource_type(typ.as_ref()),
|
||||
}
|
||||
};
|
||||
|
@ -1,7 +1,7 @@
|
||||
use actix_http::HttpService;
|
||||
use actix_http_test::TestServer;
|
||||
use actix_web::{http, web::Path, App, HttpResponse, Responder};
|
||||
use actix_web_codegen::{delete, get, post, put};
|
||||
use actix_web_codegen::{connect, delete, get, head, options, patch, post, put, trace};
|
||||
use futures::{future, Future};
|
||||
|
||||
#[get("/test")]
|
||||
@ -14,11 +14,36 @@ fn put_test() -> impl Responder {
|
||||
HttpResponse::Created()
|
||||
}
|
||||
|
||||
#[patch("/test")]
|
||||
fn patch_test() -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[post("/test")]
|
||||
fn post_test() -> impl Responder {
|
||||
HttpResponse::NoContent()
|
||||
}
|
||||
|
||||
#[head("/test")]
|
||||
fn head_test() -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[connect("/test")]
|
||||
fn connect_test() -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[options("/test")]
|
||||
fn options_test() -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[trace("/test")]
|
||||
fn trace_test() -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[get("/test")]
|
||||
fn auto_async() -> impl Future<Item = HttpResponse, Error = actix_web::Error> {
|
||||
future::ok(HttpResponse::Ok().finish())
|
||||
@ -75,6 +100,11 @@ fn test_body() {
|
||||
App::new()
|
||||
.service(post_test)
|
||||
.service(put_test)
|
||||
.service(head_test)
|
||||
.service(connect_test)
|
||||
.service(options_test)
|
||||
.service(trace_test)
|
||||
.service(patch_test)
|
||||
.service(test),
|
||||
)
|
||||
});
|
||||
@ -82,6 +112,26 @@ fn test_body() {
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let request = srv.request(http::Method::HEAD, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let request = srv.request(http::Method::CONNECT, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let request = srv.request(http::Method::OPTIONS, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let request = srv.request(http::Method::TRACE, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let request = srv.request(http::Method::PATCH, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let request = srv.request(http::Method::PUT, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
@ -92,7 +142,6 @@ fn test_body() {
|
||||
assert!(response.status().is_success());
|
||||
assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
|
||||
|
||||
let mut srv = TestServer::new(|| HttpService::new(App::new().service(auto_sync)));
|
||||
let request = srv.request(http::Method::GET, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
@ -1,5 +1,24 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.3] - 2019-07-xx
|
||||
|
||||
* Add `rustls` support
|
||||
|
||||
## [0.2.2] - 2019-07-01
|
||||
|
||||
### Changed
|
||||
|
||||
* Always append a colon after username in basic auth
|
||||
|
||||
* Upgrade `rand` dependency version to 0.7
|
||||
|
||||
|
||||
## [0.2.1] - 2019-06-05
|
||||
|
||||
### Added
|
||||
|
||||
* Add license files
|
||||
|
||||
## [0.2.0] - 2019-05-12
|
||||
|
||||
### Added
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "awc"
|
||||
version = "0.2.0"
|
||||
version = "0.2.3"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix http client."
|
||||
readme = "README.md"
|
||||
@ -29,6 +29,9 @@ default = ["brotli", "flate2-zlib"]
|
||||
# openssl
|
||||
ssl = ["openssl", "actix-http/ssl"]
|
||||
|
||||
# rustls
|
||||
rust-tls = ["rustls", "actix-http/rust-tls"]
|
||||
|
||||
# brotli encoding, requires c compiler
|
||||
brotli = ["actix-http/brotli"]
|
||||
|
||||
@ -40,31 +43,34 @@ flate2-rust = ["actix-http/flate2-rust"]
|
||||
|
||||
[dependencies]
|
||||
actix-codec = "0.1.2"
|
||||
actix-service = "0.4.0"
|
||||
actix-http = "0.2.0"
|
||||
actix-service = "0.4.1"
|
||||
actix-http = "0.2.8"
|
||||
base64 = "0.10.1"
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
derive_more = "0.15.0"
|
||||
futures = "0.1.25"
|
||||
log =" 0.4"
|
||||
mime = "0.3"
|
||||
percent-encoding = "1.0"
|
||||
rand = "0.6"
|
||||
rand = "0.7"
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
serde_urlencoded = "0.5.3"
|
||||
tokio-timer = "0.2.8"
|
||||
openssl = { version="0.10", optional = true }
|
||||
rustls = { version = "0.15.2", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.2"
|
||||
actix-web = { version = "1.0.0-beta.4", features=["ssl"] }
|
||||
actix-http = { version = "0.2.0", features=["ssl"] }
|
||||
actix-web = { version = "1.0.0", features=["ssl"] }
|
||||
actix-http = { version = "0.2.4", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
actix-utils = "0.4.0"
|
||||
actix-server = { version = "0.5.0", features=["ssl"] }
|
||||
actix-utils = "0.4.1"
|
||||
actix-server = { version = "0.6.0", features=["ssl", "rust-tls"] }
|
||||
brotli2 = { version="0.3.2" }
|
||||
flate2 = { version="1.0.2" }
|
||||
env_logger = "0.6"
|
||||
rand = "0.6"
|
||||
tokio-tcp = "0.1"
|
||||
rand = "0.7"
|
||||
tokio-tcp = "0.1"
|
||||
webpki = "0.19"
|
||||
rustls = { version = "0.15.2", features = ["dangerous_configuration"] }
|
||||
|
1
awc/LICENSE-APACHE
Symbolic link
1
awc/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
awc/LICENSE-MIT
Symbolic link
1
awc/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -21,6 +21,12 @@ pub struct ClientBuilder {
|
||||
max_redirects: usize,
|
||||
}
|
||||
|
||||
impl Default for ClientBuilder {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientBuilder {
|
||||
pub fn new() -> Self {
|
||||
ClientBuilder {
|
||||
@ -115,7 +121,7 @@ impl ClientBuilder {
|
||||
{
|
||||
let auth = match password {
|
||||
Some(password) => format!("{}:{}", username, password),
|
||||
None => format!("{}", username),
|
||||
None => format!("{}:", username),
|
||||
};
|
||||
self.header(
|
||||
header::AUTHORIZATION,
|
||||
@ -164,7 +170,7 @@ mod tests {
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
"Basic dXNlcm5hbWU="
|
||||
"Basic dXNlcm5hbWU6"
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -20,7 +20,7 @@ pub(crate) trait Connect {
|
||||
head: RequestHead,
|
||||
body: Body,
|
||||
addr: Option<net::SocketAddr>,
|
||||
) -> Box<Future<Item = ClientResponse, Error = SendRequestError>>;
|
||||
) -> Box<dyn Future<Item = ClientResponse, Error = SendRequestError>>;
|
||||
|
||||
/// Send request, returns Response and Framed
|
||||
fn open_tunnel(
|
||||
@ -28,7 +28,7 @@ pub(crate) trait Connect {
|
||||
head: RequestHead,
|
||||
addr: Option<net::SocketAddr>,
|
||||
) -> Box<
|
||||
Future<
|
||||
dyn Future<
|
||||
Item = (ResponseHead, Framed<BoxedSocket, ClientCodec>),
|
||||
Error = SendRequestError,
|
||||
>,
|
||||
@ -49,7 +49,7 @@ where
|
||||
head: RequestHead,
|
||||
body: Body,
|
||||
addr: Option<net::SocketAddr>,
|
||||
) -> Box<Future<Item = ClientResponse, Error = SendRequestError>> {
|
||||
) -> Box<dyn Future<Item = ClientResponse, Error = SendRequestError>> {
|
||||
Box::new(
|
||||
self.0
|
||||
// connect to the host
|
||||
@ -69,7 +69,7 @@ where
|
||||
head: RequestHead,
|
||||
addr: Option<net::SocketAddr>,
|
||||
) -> Box<
|
||||
Future<
|
||||
dyn Future<
|
||||
Item = (ResponseHead, Framed<BoxedSocket, ClientCodec>),
|
||||
Error = SendRequestError,
|
||||
>,
|
||||
@ -93,21 +93,21 @@ where
|
||||
}
|
||||
|
||||
trait AsyncSocket {
|
||||
fn as_read(&self) -> &AsyncRead;
|
||||
fn as_read_mut(&mut self) -> &mut AsyncRead;
|
||||
fn as_write(&mut self) -> &mut AsyncWrite;
|
||||
fn as_read(&self) -> &dyn AsyncRead;
|
||||
fn as_read_mut(&mut self) -> &mut dyn AsyncRead;
|
||||
fn as_write(&mut self) -> &mut dyn AsyncWrite;
|
||||
}
|
||||
|
||||
struct Socket<T: AsyncRead + AsyncWrite>(T);
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite> AsyncSocket for Socket<T> {
|
||||
fn as_read(&self) -> &AsyncRead {
|
||||
fn as_read(&self) -> &dyn AsyncRead {
|
||||
&self.0
|
||||
}
|
||||
fn as_read_mut(&mut self) -> &mut AsyncRead {
|
||||
fn as_read_mut(&mut self) -> &mut dyn AsyncRead {
|
||||
&mut self.0
|
||||
}
|
||||
fn as_write(&mut self) -> &mut AsyncWrite {
|
||||
fn as_write(&mut self) -> &mut dyn AsyncWrite {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
@ -1,7 +1,8 @@
|
||||
#![allow(clippy::borrow_interior_mutable_const)]
|
||||
//! An HTTP Client
|
||||
//!
|
||||
//! ```rust
|
||||
//! # use futures::future::{Future, lazy};
|
||||
//! use futures::future::{lazy, Future};
|
||||
//! use actix_rt::System;
|
||||
//! use awc::Client;
|
||||
//!
|
||||
@ -38,6 +39,7 @@ pub mod test;
|
||||
pub mod ws;
|
||||
|
||||
pub use self::builder::ClientBuilder;
|
||||
pub use self::connect::BoxedSocket;
|
||||
pub use self::request::ClientRequest;
|
||||
pub use self::response::{ClientResponse, JsonBody, MessageBody};
|
||||
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user