Skip to content

Commit 57299e2

Browse files
committed
WIP: feat: SetHost, Http1RequestTarget and DelayedResposne middlewares
1 parent f898015 commit 57299e2

File tree

6 files changed

+201
-1
lines changed

6 files changed

+201
-1
lines changed

Cargo.toml

+5-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,11 @@ repository = "https://github.com/hyperium/hyper-util"
99
license = "MIT"
1010
authors = ["Sean McArthur <[email protected]>"]
1111
keywords = ["http", "hyper", "hyperium"]
12-
categories = ["network-programming", "web-programming::http-client", "web-programming::http-server"]
12+
categories = [
13+
"network-programming",
14+
"web-programming::http-client",
15+
"web-programming::http-server",
16+
]
1317
edition = "2018"
1418

1519
publish = false # no accidents while in dev

src/client/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ pub mod connect;
66
pub mod legacy;
77
#[doc(hidden)]
88
pub mod pool;
9+
pub mod services;
+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
use std::{
2+
future,
3+
pin::Pin,
4+
task::{Context, Poll},
5+
};
6+
7+
use futures_channel::oneshot;
8+
use futures_util::Future;
9+
use http::Response;
10+
use hyper::body::Body;
11+
use hyper::service::Service;
12+
use pin_project_lite::pin_project;
13+
14+
pub struct DelayedResponse<S> {
15+
inner: S,
16+
}
17+
18+
impl<S, Req, B> Service<Req> for DelayedResponse<S>
19+
where
20+
S: Service<Req, Response = Response<B>>,
21+
B: Body,
22+
{
23+
type Response = S::Response;
24+
type Error = S::Error;
25+
type Future = DelayedResponseFuture<S::Future>;
26+
27+
fn call(&self, req: Req) -> Self::Future {
28+
DelayedResponseFuture {
29+
inner: self.inner.call(req),
30+
}
31+
}
32+
}
33+
34+
pin_project! {
35+
struct DelayedResponseFuture<F> {
36+
#[pin]
37+
inner: F,
38+
}
39+
}
40+
41+
impl<F, E, B> Future for DelayedResponseFuture<F>
42+
where
43+
F: Future<Output = Result<Response<B>, E>>,
44+
B: Body,
45+
{
46+
type Output = F::Output;
47+
48+
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
49+
match self.project().inner.poll(cx) {
50+
Poll::Ready(res) => {
51+
let res = res?;
52+
let (delayed_tx, delayed_rx) = oneshot::channel();
53+
res.body_mut().delayed_eof(delayed_rx);
54+
let on_idle = future::poll_fn(move |cx| pooled.poll_ready(cx)).map(move |_| {
55+
// At this point, `pooled` is dropped, and had a chance
56+
// to insert into the pool (if conn was idle)
57+
drop(delayed_tx);
58+
});
59+
60+
self.executor.execute(on_idle);
61+
Poll::Ready(Ok(res))
62+
}
63+
Poll::Pending => Poll::Pending,
64+
}
65+
}
66+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
use http::{uri::Scheme, Method, Request, Uri};
2+
use hyper::service::Service;
3+
use tracing::warn;
4+
5+
pub struct Http1RequestTarget<S> {
6+
inner: S,
7+
}
8+
9+
impl<S, B> Service<Request<B>> for Http1RequestTarget<S>
10+
where
11+
S: Service<Request<B>>,
12+
{
13+
type Response = S::Response;
14+
type Error = S::Error;
15+
type Future = S::Future;
16+
17+
fn call(&self, mut req: Request<B>) -> Self::Future {
18+
// CONNECT always sends authority-form, so check it first...
19+
if req.method() == Method::CONNECT {
20+
authority_form(req.uri_mut());
21+
// TODO: this middleware must be connection pool aware
22+
// } else if pooled.conn_info.is_proxied {
23+
// absolute_form(req.uri_mut());
24+
} else {
25+
origin_form(req.uri_mut());
26+
}
27+
self.inner.call(req)
28+
}
29+
}
30+
31+
fn origin_form(uri: &mut Uri) {
32+
let path = match uri.path_and_query() {
33+
Some(path) if path.as_str() != "/" => {
34+
let mut parts = ::http::uri::Parts::default();
35+
parts.path_and_query = Some(path.clone());
36+
Uri::from_parts(parts).expect("path is valid uri")
37+
}
38+
_none_or_just_slash => {
39+
debug_assert!(Uri::default() == "/");
40+
Uri::default()
41+
}
42+
};
43+
*uri = path
44+
}
45+
46+
fn absolute_form(uri: &mut Uri) {
47+
debug_assert!(uri.scheme().is_some(), "absolute_form needs a scheme");
48+
debug_assert!(
49+
uri.authority().is_some(),
50+
"absolute_form needs an authority"
51+
);
52+
// If the URI is to HTTPS, and the connector claimed to be a proxy,
53+
// then it *should* have tunneled, and so we don't want to send
54+
// absolute-form in that case.
55+
if uri.scheme() == Some(&Scheme::HTTPS) {
56+
origin_form(uri);
57+
}
58+
}
59+
60+
fn authority_form(uri: &mut Uri) {
61+
if let Some(path) = uri.path_and_query() {
62+
// `https://hyper.rs` would parse with `/` path, don't
63+
// annoy people about that...
64+
if path != "/" {
65+
warn!("HTTP/1.1 CONNECT request stripping path: {:?}", path);
66+
}
67+
}
68+
*uri = match uri.authority() {
69+
Some(auth) => {
70+
let mut parts = ::http::uri::Parts::default();
71+
parts.authority = Some(auth.clone());
72+
Uri::from_parts(parts).expect("authority is valid")
73+
}
74+
None => {
75+
unreachable!("authority_form with relative uri");
76+
}
77+
};
78+
}

src/client/services/mod.rs

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
mod delayed_response;
2+
mod http1_request_target;
3+
mod set_host;
4+
5+
pub use delayed_response::DelayedResponse;
6+
pub use http1_request_target::Http1RequestTarget;
7+
pub use set_host::SetHost;

src/client/services/set_host.rs

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
use http::{header::HOST, uri::Port, HeaderValue, Request, Uri};
2+
use hyper::service::Service;
3+
4+
pub struct SetHost<S> {
5+
inner: S,
6+
}
7+
8+
impl<S, B> Service<Request<B>> for SetHost<S>
9+
where
10+
S: Service<Request<B>>,
11+
{
12+
type Response = S::Response;
13+
type Error = S::Error;
14+
type Future = S::Future;
15+
16+
fn call(&self, mut req: Request<B>) -> Self::Future {
17+
let uri = req.uri().clone();
18+
req.headers_mut().entry(HOST).or_insert_with(|| {
19+
let hostname = uri.host().expect("authority implies host");
20+
if let Some(port) = get_non_default_port(&uri) {
21+
let s = format!("{}:{}", hostname, port);
22+
HeaderValue::from_str(&s)
23+
} else {
24+
HeaderValue::from_str(hostname)
25+
}
26+
.expect("uri host is valid header value")
27+
});
28+
self.inner.call(req)
29+
}
30+
}
31+
32+
fn get_non_default_port(uri: &Uri) -> Option<Port<&str>> {
33+
match (uri.port().map(|p| p.as_u16()), is_schema_secure(uri)) {
34+
(Some(443), true) => None,
35+
(Some(80), false) => None,
36+
_ => uri.port(),
37+
}
38+
}
39+
40+
fn is_schema_secure(uri: &Uri) -> bool {
41+
uri.scheme_str()
42+
.map(|scheme_str| matches!(scheme_str, "wss" | "https"))
43+
.unwrap_or_default()
44+
}

0 commit comments

Comments
 (0)