Dataset Viewer
Auto-converted to Parquet Duplicate
issue_numbers
sequencelengths
1
2
version
stringclasses
20 values
base_commit
stringlengths
40
40
patch
stringlengths
214
153k
hints_text
stringlengths
0
66.9k
created_at
stringlengths
20
20
pull_number
int64
20
3.81k
problem_statement
stringlengths
22
7.42k
instance_id
stringlengths
18
20
test_patch
stringlengths
288
262k
repo
stringclasses
1 value
environment_setup_commit
stringclasses
21 values
[ "3811" ]
0.14
a24f0c0af8e1f4c6b7cc3a47c83eb6e4af88aca6
diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -248,7 +248,11 @@ where } } if curr_len > 0 { + trace!("partial headers; {} bytes so far", curr_len); self.partial_len = Some(curr_len); + } else { + // 1xx gobled some bytes + self.partial_len = None; } } }
Thanks for the sample code, I'll get this fixed today 🫡
2024-12-16T15:39:30Z
3,813
Intermittent panic in is_complete_fast **Version** 1.5.1 **Platform** `Darwin ghost.local 23.5.0 Darwin Kernel Version 23.5.0: Wed May 1 20:19:05 PDT 2024; root:xnu-10063.121.3~5/RELEASE_ARM64_T8112 arm64` **Description** Hyper client can panic when processing broken up 1xx HTTP1 responses. When a server responds with `HTTP/1.1 100 Continue\r\nContent-Type: text/plain\r\nServer: BaseHTTP/0.6 Python/3.12.5\r\nDate: Mon, 16 Dec 2024 03:08:27 GMT\r\n\r\nThis is a sample text/plain document.\n\nThis is not an HTML document.\n\n`, it's possible for hyper to first read `HTTP/1.1 100 Continue\r\nContent-Type: text/plain\r\nServer: BaseHTTP/0.6 Python/3.12.5\r\nDate: Mon, 16 Dec 2024 03:08:27 GMT\r\n\r\n`, followed by `This is a sample text/plain document.\n\nThis is not an HTML document.\n\n`. This triggers a panic in [the code introduced in #3764](https://github.com/hyperium/hyper/pull/3764/files#diff-aa04de01d67bf1f61d03ef30830c744fa331c7918335393ace8c6137fa4d84d6R94), since the prev_length value stored after the first response is longer than the length of the second response. This has been hit independently by both deno and Servo upon upgrading to hyper 1.5.1, since there are web-platform-tests that exercise 1xx responses: https://github.com/web-platform-tests/wpt/blob/master/fetch/security/1xx-response.any.js
hyperium__hyper-3813
diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -2908,6 +2908,63 @@ mod conn { assert_eq!(vec, b"bar=foo"); } + #[tokio::test] + async fn client_100_then_http09() { + let _ = ::pretty_env_logger::try_init(); + + let server = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = server.local_addr().unwrap(); + + thread::spawn(move || { + let mut sock = server.accept().unwrap().0; + sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + sock.set_write_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut buf = [0; 4096]; + sock.read(&mut buf).expect("read 1"); + sock.write_all( + b"\ + HTTP/1.1 100 Continue\r\n\ + Content-Type: text/plain\r\n\ + Server: BaseHTTP/0.6 Python/3.12.5\r\n\ + Date: Mon, 16 Dec 2024 03:08:27 GMT\r\n\ + ", + ) + .unwrap(); + // That it's separate writes is important to this test + thread::sleep(Duration::from_millis(50)); + sock.write_all( + b"\ + \r\n\ + ", + ) + .expect("write 2"); + thread::sleep(Duration::from_millis(50)); + sock.write_all( + b"\ + This is a sample text/plain document, without final headers.\ + \n\n\ + ", + ) + .expect("write 3"); + }); + + let tcp = tcp_connect(&addr).await.unwrap(); + + let (mut client, conn) = conn::Builder::new() + .http09_responses(true) + .handshake(tcp) + .await + .unwrap(); + + tokio::spawn(async move { + let _ = conn.await; + }); + + let req = Request::builder().uri("/a").body(Body::empty()).unwrap(); + let _res = client.send_request(req).await.expect("send_request"); + } + #[tokio::test] async fn http2_detect_conn_eof() { use futures_util::future;
hyperium/hyper
a24f0c0af8e1f4c6b7cc3a47c83eb6e4af88aca6
[ "3811" ]
1.5
a3bda62da36060a38638fba983a0c07c0ab6259d
diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -205,7 +205,11 @@ where return Poll::Ready(Err(crate::Error::new_too_large())); } if curr_len > 0 { + trace!("partial headers; {} bytes so far", curr_len); self.partial_len = Some(curr_len); + } else { + // 1xx gobled some bytes + self.partial_len = None; } } }
Thanks for the sample code, I'll get this fixed today 🫡
2024-12-16T14:50:50Z
3,812
Intermittent panic in is_complete_fast **Version** 1.5.1 **Platform** `Darwin ghost.local 23.5.0 Darwin Kernel Version 23.5.0: Wed May 1 20:19:05 PDT 2024; root:xnu-10063.121.3~5/RELEASE_ARM64_T8112 arm64` **Description** Hyper client can panic when processing broken up 1xx HTTP1 responses. When a server responds with `HTTP/1.1 100 Continue\r\nContent-Type: text/plain\r\nServer: BaseHTTP/0.6 Python/3.12.5\r\nDate: Mon, 16 Dec 2024 03:08:27 GMT\r\n\r\nThis is a sample text/plain document.\n\nThis is not an HTML document.\n\n`, it's possible for hyper to first read `HTTP/1.1 100 Continue\r\nContent-Type: text/plain\r\nServer: BaseHTTP/0.6 Python/3.12.5\r\nDate: Mon, 16 Dec 2024 03:08:27 GMT\r\n\r\n`, followed by `This is a sample text/plain document.\n\nThis is not an HTML document.\n\n`. This triggers a panic in [the code introduced in #3764](https://github.com/hyperium/hyper/pull/3764/files#diff-aa04de01d67bf1f61d03ef30830c744fa331c7918335393ace8c6137fa4d84d6R94), since the prev_length value stored after the first response is longer than the length of the second response. This has been hit independently by both deno and Servo upon upgrading to hyper 1.5.1, since there are web-platform-tests that exercise 1xx responses: https://github.com/web-platform-tests/wpt/blob/master/fetch/security/1xx-response.any.js
hyperium__hyper-3812
diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -2041,6 +2041,63 @@ mod conn { assert_eq!(vec, b"bar=foo"); } + #[tokio::test] + async fn client_100_then_http09() { + let (server, addr) = setup_std_test_server(); + + thread::spawn(move || { + let mut sock = server.accept().unwrap().0; + sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + sock.set_write_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut buf = [0; 4096]; + sock.read(&mut buf).expect("read 1"); + sock.write_all( + b"\ + HTTP/1.1 100 Continue\r\n\ + Content-Type: text/plain\r\n\ + Server: BaseHTTP/0.6 Python/3.12.5\r\n\ + Date: Mon, 16 Dec 2024 03:08:27 GMT\r\n\ + ", + ) + .unwrap(); + // That it's separate writes is important to this test + thread::sleep(Duration::from_millis(50)); + sock.write_all( + b"\ + \r\n\ + ", + ) + .expect("write 2"); + thread::sleep(Duration::from_millis(50)); + sock.write_all( + b"\ + This is a sample text/plain document, without final headers.\ + \n\n\ + ", + ) + .expect("write 3"); + }); + + let tcp = tcp_connect(&addr).await.unwrap(); + + let (mut client, conn) = conn::http1::Builder::new() + .http09_responses(true) + .handshake(tcp) + .await + .unwrap(); + + tokio::spawn(async move { + let _ = conn.await; + }); + + let req = Request::builder() + .uri("/a") + .body(Empty::<Bytes>::new()) + .unwrap(); + let _res = client.send_request(req).await.expect("send_request"); + } + #[tokio::test] async fn test_try_send_request() { use std::future::Future;
hyperium/hyper
a3bda62da36060a38638fba983a0c07c0ab6259d
[ "3790" ]
1.5
eaf2267cdc148604469fb09da22646f31710107a
diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -279,7 +279,7 @@ jobs: - name: Install Rust uses: dtolnay/rust-toolchain@master with: - toolchain: nightly-2024-05-01 # Compatible version for cargo-check-external-types + toolchain: nightly-2024-05-01 # Compatible version for cargo-check-external-types - name: Install cargo-check-external-types uses: taiki-e/cache-cargo-install-action@v2 diff --git a/examples/hello-http2.rs b/examples/hello-http2.rs --- a/examples/hello-http2.rs +++ b/examples/hello-http2.rs @@ -1,13 +1,14 @@ #![deny(warnings)] - -use std::convert::Infallible; -use std::net::SocketAddr; +#![allow(unused_imports)] use http_body_util::Full; use hyper::body::Bytes; +#[cfg(feature = "server")] use hyper::server::conn::http2; use hyper::service::service_fn; use hyper::{Request, Response}; +use std::convert::Infallible; +use std::net::SocketAddr; use tokio::net::TcpListener; // This would normally come from the `hyper-util` crate, but we can't depend diff --git a/examples/hello-http2.rs b/examples/hello-http2.rs --- a/examples/hello-http2.rs +++ b/examples/hello-http2.rs @@ -18,6 +19,7 @@ use support::TokioIo; // An async function that consumes a request, does nothing with it and returns a // response. +#[cfg(feature = "server")] async fn hello(_: Request<hyper::body::Incoming>) -> Result<Response<Full<Bytes>>, Infallible> { Ok(Response::new(Full::new(Bytes::from("Hello, World!")))) } diff --git a/examples/hello-http2.rs b/examples/hello-http2.rs --- a/examples/hello-http2.rs +++ b/examples/hello-http2.rs @@ -40,6 +42,7 @@ where } } +#[cfg(feature = "server")] #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { pretty_env_logger::init(); diff --git a/examples/hello-http2.rs b/examples/hello-http2.rs --- a/examples/hello-http2.rs +++ b/examples/hello-http2.rs @@ -79,3 +82,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { }); } } + +#[cfg(not(feature = "server"))] +fn main() { + panic!("This example requires the 'server' feature to be enabled"); +}
2024-11-28T16:18:04Z
3,799
Make client tests work without server feature Running `cargo test --features http1,http2,client` fails to compile because it uses some types only available when the `server` feature is also enabled. Fixing this would just require adding or adjusting `#[cfg(feature = ...)]` attributes, paying attention to the compiler error messages. For CI, the `ffi` job can be adjusted to no longer enable `server` when running the tests.
hyperium__hyper-3799
diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -195,7 +195,7 @@ jobs: - name: Run FFI unit tests env: RUSTFLAGS: --cfg hyper_unstable_ffi - run: cargo test --features server,client,http1,http2,ffi --lib + run: cargo test --features client,http1,http2,ffi --lib ffi-header: name: Verify hyper.h is up to date diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -506,6 +506,7 @@ mod tests { assert!(encoder.end::<()>().unwrap().is_none()); } + #[cfg(feature = "server")] #[test] fn eof() { let mut encoder = Encoder::close_delimited(); diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1646,6 +1646,7 @@ mod tests { use super::*; + #[cfg(feature = "server")] #[test] fn test_parse_request() { let _ = pretty_env_logger::try_init(); diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1701,6 +1702,7 @@ mod tests { assert_eq!(msg.head.headers["Content-Length"], "0"); } + #[cfg(feature = "server")] #[test] fn test_parse_request_errors() { let mut raw = BytesMut::from("GET htt:p// HTTP/1.1\r\nHost: hyper.rs\r\n\r\n"); diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1814,6 +1816,7 @@ mod tests { Client::parse(&mut raw, ctx).unwrap_err(); } + #[cfg(feature = "server")] #[test] fn test_parse_preserve_header_case_in_request() { let mut raw = diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1852,6 +1855,7 @@ mod tests { ); } + #[cfg(feature = "server")] #[test] fn test_decoder_request() { fn parse(s: &str) -> ParsedMessage<RequestLine> { diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -2462,9 +2466,11 @@ mod tests { Encode { head: &mut head, body: Some(BodyLength::Known(10)), + #[cfg(feature = "server")] keep_alive: true, req_method: &mut None, title_case_headers: true, + #[cfg(feature = "server")] date_header: true, }, &mut vec, diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -2494,9 +2500,11 @@ mod tests { Encode { head: &mut head, body: Some(BodyLength::Known(10)), + #[cfg(feature = "server")] keep_alive: true, req_method: &mut None, title_case_headers: false, + #[cfg(feature = "server")] date_header: true, }, &mut vec, diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -2529,9 +2537,11 @@ mod tests { Encode { head: &mut head, body: Some(BodyLength::Known(10)), + #[cfg(feature = "server")] keep_alive: true, req_method: &mut None, title_case_headers: true, + #[cfg(feature = "server")] date_header: true, }, &mut vec, diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -2545,6 +2555,7 @@ mod tests { ); } + #[cfg(feature = "server")] #[test] fn test_server_encode_connect_method() { let mut head = MessageHead::default(); diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -2566,6 +2577,7 @@ mod tests { assert!(encoder.is_last()); } + #[cfg(feature = "server")] #[test] fn test_server_response_encode_title_case() { use crate::proto::BodyLength; diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -2599,6 +2611,7 @@ mod tests { assert_eq!(&vec[..expected_response.len()], &expected_response[..]); } + #[cfg(feature = "server")] #[test] fn test_server_response_encode_orig_case() { use crate::proto::BodyLength; diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -2634,6 +2647,7 @@ mod tests { assert_eq!(&vec[..expected_response.len()], &expected_response[..]); } + #[cfg(feature = "server")] #[test] fn test_server_response_encode_orig_and_title_case() { use crate::proto::BodyLength; diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -2670,6 +2684,7 @@ mod tests { assert_eq!(&vec[..expected_response.len()], &expected_response[..]); } + #[cfg(feature = "server")] #[test] fn test_disabled_date_header() { use crate::proto::BodyLength; diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -2729,6 +2744,7 @@ mod tests { assert_eq!(parsed.head.headers["server"], "hello\tworld"); } + #[cfg(feature = "server")] #[test] fn parse_too_large_headers() { fn gen_req_with_headers(num: usize) -> String {
hyperium/hyper
a3bda62da36060a38638fba983a0c07c0ab6259d
[ "3786" ]
1.5
3b7375a16f23fb9a0975304ba6616af9323f3f13
diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -23,6 +23,7 @@ jobs: - features - ffi - ffi-header + - ffi-cargo-c - doc - check-external-types - udeps diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -85,6 +85,7 @@ server = ["dep:httpdate", "dep:pin-project-lite", "dep:smallvec"] # C-API support (currently unstable (no semver)) ffi = ["dep:http-body-util", "futures-util?/alloc"] +capi = [] # Utilize tracing (currently unstable) tracing = ["dep:tracing"] diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -106,6 +107,13 @@ rustdoc-args = ["--cfg", "hyper_unstable_ffi", "--cfg", "hyper_unstable_tracing" [package.metadata.playground] features = ["full"] +[package.metadata.capi.header] +generation = false +subdirectory = false + +[package.metadata.capi.install.include] +asset = [{ from="capi/include/hyper.h" }] + [profile.release] codegen-units = 1 incremental = false diff --git a/capi/README.md b/capi/README.md --- a/capi/README.md +++ b/capi/README.md @@ -15,3 +15,11 @@ The C API is part of the Rust library, but isn't compiled by default. Using `car ``` RUSTFLAGS="--cfg hyper_unstable_ffi" cargo rustc --features client,http1,http2,ffi --crate-type cdylib ``` + +### (Optional) With `cargo-c` + +If using `cargo-c`, you can build and install a shared library with the following command: + +``` +RUSTFLAGS="--cfg hyper_unstable_ffi" cargo cbuild --features client,http1,http2,ffi --release +```
For what it's worth I've been happy with cargo-c and the upstream maintainers have been very helpful. In rustls-ffi I'm moving towards replacing the old `Makefile` approach (as linked to from the current curl docs) and instead recommending cargo-c as the blessed path for building the library (static or dynamic). I've installed `cargo-c` locally and tried it out, seems like the only thing that is missing is adding a `capi` feature, and perhaps some options to use the pre-existing header file, and... that's it?
2024-11-19T21:40:38Z
3,787
cargo-c integration and dynamic linking **Is your feature request related to a problem? Please describe.** I'm trying to get the FFI interface of hyper up to speed with rustls-ffi, for integration in an operating system. Compare the current [curl hyper documentation](https://github.com/curl/curl/blob/cb2ae6e8a8614a34bbe7f77f0540cd27aa890b59/docs/internals/HYPER.md) (which wants you to manually build and link cdylib objects) to the current [curl rustls documentation](https://github.com/curl/curl/blob/cb2ae6e8a8614a34bbe7f77f0540cd27aa890b59/docs/RUSTLS.md) (~~that generates and installs a .so file, headers and and pkg-config integration for you~~ @cpu has pointed out this document is not using cargo-c, the rustls-ffi pull request linked below is a better resource to look into). Most of the work to get rustls to this point was done in this pull request: https://github.com/rustls/rustls-ffi/pull/274 **Describe the solution you'd like** I'd like hyper to integrate with the pkg-config ecosystem that Linux distributions build upon, preferably through cargo-c. **Describe alternatives you've considered** The curl hyper integration is currently [planned for removal](https://github.com/curl/curl/blob/7b12c36ca972d9e9a14088cdd88232385e619d44/docs/DEPRECATE.md#Hyper) in January 2025. **Additional context** There may be some additional context in https://github.com/rustls/rustls-ffi/issues/345. There was development work done on cargo-c itself specifically for rustls-ffi that you may want to consider, in case you have concerns about dynamic linking and ABI stability: https://github.com/lu-zero/cargo-c/issues/345
hyperium__hyper-3787
diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -226,6 +227,31 @@ jobs: - name: Ensure that hyper.h is up to date run: ./capi/gen_header.sh --verify + ffi-cargo-c: + name: Test cargo-c support (FFI) + needs: [style] + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install Rust + uses: dtolnay/rust-toolchain@stable + + - uses: Swatinem/rust-cache@v2 + + - name: Install cargo-c + env: + LINK: https://github.com/lu-zero/cargo-c/releases/latest/download + CARGO_C_FILE: cargo-c-x86_64-unknown-linux-musl.tar.gz + run: | + curl -L $LINK/$CARGO_C_FILE | tar xz -C ~/.cargo/bin + + - name: Build with cargo-c + env: + RUSTFLAGS: --cfg hyper_unstable_ffi + run: cargo cbuild --features client,http1,http2,ffi + doc: name: Build docs needs: [style, test]
hyperium/hyper
a3bda62da36060a38638fba983a0c07c0ab6259d
[ "3720" ]
1.4
4c4de90a7e2aa0629b9c167a482399e28ccb0975
diff --git a/benches/server.rs b/benches/server.rs --- a/benches/server.rs +++ b/benches/server.rs @@ -72,7 +72,7 @@ macro_rules! bench_server { tcp.write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n") .unwrap(); let mut buf = Vec::new(); - tcp.read_to_end(&mut buf).unwrap() + tcp.read_to_end(&mut buf).unwrap() - "connection: close\r\n".len() }; let mut tcp = TcpStream::connect(addr).unwrap(); diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -21,7 +21,7 @@ use super::{Decoder, Encode, EncodedBuf, Encoder, Http1Transaction, ParseContext use crate::body::DecodedLength; #[cfg(feature = "server")] use crate::common::time::Time; -use crate::headers::connection_keep_alive; +use crate::headers; use crate::proto::{BodyLength, MessageHead}; #[cfg(feature = "server")] use crate::rt::Sleep; diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -657,7 +657,7 @@ where let outgoing_is_keep_alive = head .headers .get(CONNECTION) - .map_or(false, connection_keep_alive); + .map_or(false, headers::connection_keep_alive); if !outgoing_is_keep_alive { match head.version { diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -680,12 +680,21 @@ where // If we know the remote speaks an older version, we try to fix up any messages // to work with our older peer. fn enforce_version(&mut self, head: &mut MessageHead<T::Outgoing>) { - if let Version::HTTP_10 = self.state.version { - // Fixes response or connection when keep-alive header is not present - self.fix_keep_alive(head); - // If the remote only knows HTTP/1.0, we should force ourselves - // to do only speak HTTP/1.0 as well. - head.version = Version::HTTP_10; + match self.state.version { + Version::HTTP_10 => { + // Fixes response or connection when keep-alive header is not present + self.fix_keep_alive(head); + // If the remote only knows HTTP/1.0, we should force ourselves + // to do only speak HTTP/1.0 as well. + head.version = Version::HTTP_10; + } + Version::HTTP_11 => { + if let KA::Disabled = self.state.keep_alive.status() { + head.headers + .insert(CONNECTION, HeaderValue::from_static("close")); + } + } + _ => (), } // If the remote speaks HTTP/1.1, then it *should* be fine with // both HTTP/1.0 and HTTP/1.1 from us. So again, we just let
Thanks for the report! I could have sworn we did this, but then tweaked the test and you're right, not done. PR is up at #3725. Thank you @seanmonstar! Reopened this until the PR #3725 gets merged.
2024-08-02T20:50:20Z
3,725
No `Connection: close` on HTTP1 Connection Drain When HTTP1 connection draining is activated, the Connection: close header is not attached to responses sent to active connections. This prevents active clients from realizing that the server is requesting that the connection be closed and prevents graceful draining of HTTP1 connections.
hyperium__hyper-3725
diff --git a/benches/pipeline.rs b/benches/pipeline.rs --- a/benches/pipeline.rs +++ b/benches/pipeline.rs @@ -76,7 +76,7 @@ fn hello_world_16(b: &mut test::Bencher) { tcp.write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n") .unwrap(); let mut buf = Vec::new(); - tcp.read_to_end(&mut buf).unwrap() + tcp.read_to_end(&mut buf).unwrap() - "connection: close\r\n".len() } * PIPELINED_REQUESTS; let mut tcp = TcpStream::connect(addr).unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1140,6 +1140,8 @@ fn pipeline_enabled() { assert_eq!(s(lines.next().unwrap()), "HTTP/1.1 200 OK\r"); assert_eq!(s(lines.next().unwrap()), "content-length: 12\r"); + // close because the last request said to close + assert_eq!(s(lines.next().unwrap()), "connection: close\r"); lines.next().unwrap(); // Date assert_eq!(s(lines.next().unwrap()), "\r"); assert_eq!(s(lines.next().unwrap()), "Hello World"); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1181,7 +1183,7 @@ fn http_11_uri_too_long() { let mut req = connect(server.addr()); req.write_all(request_line.as_bytes()).unwrap(); - let expected = "HTTP/1.1 414 URI Too Long\r\ncontent-length: 0\r\n"; + let expected = "HTTP/1.1 414 URI Too Long\r\nconnection: close\r\ncontent-length: 0\r\n"; let mut buf = [0; 256]; let n = req.read(&mut buf).unwrap(); assert!(n >= expected.len(), "read: {:?} >= {:?}", n, expected.len()); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1208,6 +1210,12 @@ async fn disable_keep_alive_mid_request() { "should receive OK response, but buf: {:?}", buf, ); + let sbuf = s(&buf); + assert!( + sbuf.contains("connection: close\r\n"), + "response should have sent close: {:?}", + sbuf, + ); }); let (socket, _) = listener.accept().await.unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -2366,7 +2374,7 @@ fn streaming_body() { buf.starts_with(b"HTTP/1.1 200 OK\r\n"), "response is 200 OK" ); - assert_eq!(buf.len(), 100_789, "full streamed body read"); + assert_eq!(buf.len(), 100_808, "full streamed body read"); } #[test]
hyperium/hyper
4c4de90a7e2aa0629b9c167a482399e28ccb0975
[ "3673" ]
1.3
aa7ff605da3b706e855f9633b8dddeb9463217d4
diff --git a/src/client/conn/http1.rs b/src/client/conn/http1.rs --- a/src/client/conn/http1.rs +++ b/src/client/conn/http1.rs @@ -12,7 +12,7 @@ use futures_util::ready; use http::{Request, Response}; use httparse::ParserConfig; -use super::super::dispatch; +use super::super::dispatch::{self, TrySendError}; use crate::body::{Body, Incoming as IncomingBody}; use crate::proto; diff --git a/src/client/conn/http1.rs b/src/client/conn/http1.rs --- a/src/client/conn/http1.rs +++ b/src/client/conn/http1.rs @@ -200,33 +200,38 @@ where } } - /* - pub(super) fn send_request_retryable( + /// Sends a `Request` on the associated connection. + /// + /// Returns a future that if successful, yields the `Response`. + /// + /// # Error + /// + /// If there was an error before trying to serialize the request to the + /// connection, the message will be returned as part of this error. + pub fn try_send_request( &mut self, req: Request<B>, - ) -> impl Future<Output = Result<Response<Body>, (crate::Error, Option<Request<B>>)>> + Unpin - where - B: Send, - { - match self.dispatch.try_send(req) { - Ok(rx) => { - Either::Left(rx.then(move |res| { - match res { - Ok(Ok(res)) => future::ok(res), - Ok(Err(err)) => future::err(err), - // this is definite bug if it happens, but it shouldn't happen! - Err(_) => panic!("dispatch dropped without returning error"), - } - })) - } - Err(req) => { - debug!("connection was not ready"); - let err = crate::Error::new_canceled().with("connection was not ready"); - Either::Right(future::err((err, Some(req)))) + ) -> impl Future<Output = Result<Response<IncomingBody>, TrySendError<Request<B>>>> { + let sent = self.dispatch.try_send(req); + async move { + match sent { + Ok(rx) => match rx.await { + Ok(Ok(res)) => Ok(res), + Ok(Err(err)) => Err(err), + // this is definite bug if it happens, but it shouldn't happen! + Err(_) => panic!("dispatch dropped without returning error"), + }, + Err(req) => { + debug!("connection was not ready"); + let error = crate::Error::new_canceled().with("connection was not ready"); + Err(TrySendError { + error, + message: Some(req), + }) + } } } } - */ } impl<B> fmt::Debug for SendRequest<B> { diff --git a/src/client/conn/http2.rs b/src/client/conn/http2.rs --- a/src/client/conn/http2.rs +++ b/src/client/conn/http2.rs @@ -13,7 +13,7 @@ use crate::rt::{Read, Write}; use futures_util::ready; use http::{Request, Response}; -use super::super::dispatch; +use super::super::dispatch::{self, TrySendError}; use crate::body::{Body, Incoming as IncomingBody}; use crate::common::time::Time; use crate::proto; diff --git a/src/client/conn/http2.rs b/src/client/conn/http2.rs --- a/src/client/conn/http2.rs +++ b/src/client/conn/http2.rs @@ -152,33 +152,38 @@ where } } - /* - pub(super) fn send_request_retryable( + /// Sends a `Request` on the associated connection. + /// + /// Returns a future that if successful, yields the `Response`. + /// + /// # Error + /// + /// If there was an error before trying to serialize the request to the + /// connection, the message will be returned as part of this error. + pub fn try_send_request( &mut self, req: Request<B>, - ) -> impl Future<Output = Result<Response<Body>, (crate::Error, Option<Request<B>>)>> + Unpin - where - B: Send, - { - match self.dispatch.try_send(req) { - Ok(rx) => { - Either::Left(rx.then(move |res| { - match res { - Ok(Ok(res)) => future::ok(res), - Ok(Err(err)) => future::err(err), - // this is definite bug if it happens, but it shouldn't happen! - Err(_) => panic!("dispatch dropped without returning error"), - } - })) - } - Err(req) => { - debug!("connection was not ready"); - let err = crate::Error::new_canceled().with("connection was not ready"); - Either::Right(future::err((err, Some(req)))) + ) -> impl Future<Output = Result<Response<IncomingBody>, TrySendError<Request<B>>>> { + let sent = self.dispatch.try_send(req); + async move { + match sent { + Ok(rx) => match rx.await { + Ok(Ok(res)) => Ok(res), + Ok(Err(err)) => Err(err), + // this is definite bug if it happens, but it shouldn't happen! + Err(_) => panic!("dispatch dropped without returning error"), + }, + Err(req) => { + debug!("connection was not ready"); + let error = crate::Error::new_canceled().with("connection was not ready"); + Err(TrySendError { + error, + message: Some(req), + }) + } } } } - */ } impl<B> fmt::Debug for SendRequest<B> { diff --git a/src/client/conn/mod.rs b/src/client/conn/mod.rs --- a/src/client/conn/mod.rs +++ b/src/client/conn/mod.rs @@ -18,3 +18,5 @@ pub mod http1; #[cfg(feature = "http2")] pub mod http2; + +pub use super::dispatch::TrySendError; diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -210,17 +220,17 @@ struct Envelope<T, U>(Option<(T, Callback<T, U>)>); impl<T, U> Drop for Envelope<T, U> { fn drop(&mut self) { if let Some((val, cb)) = self.0.take() { - cb.send(Err(( - crate::Error::new_canceled().with("connection closed"), - Some(val), - ))); + cb.send(Err(TrySendError { + error: crate::Error::new_canceled().with("connection closed"), + message: Some(val), + })); } } } pub(crate) enum Callback<T, U> { #[allow(unused)] - Retry(Option<oneshot::Sender<Result<U, (crate::Error, Option<T>)>>>), + Retry(Option<oneshot::Sender<Result<U, TrySendError<T>>>>), NoRetry(Option<oneshot::Sender<Result<U, crate::Error>>>), } diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -229,7 +239,10 @@ impl<T, U> Drop for Callback<T, U> { match self { Callback::Retry(tx) => { if let Some(tx) = tx.take() { - let _ = tx.send(Err((dispatch_gone(), None))); + let _ = tx.send(Err(TrySendError { + error: dispatch_gone(), + message: None, + })); } } Callback::NoRetry(tx) => { diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -269,18 +282,34 @@ impl<T, U> Callback<T, U> { } } - pub(crate) fn send(mut self, val: Result<U, (crate::Error, Option<T>)>) { + pub(crate) fn send(mut self, val: Result<U, TrySendError<T>>) { match self { Callback::Retry(ref mut tx) => { let _ = tx.take().unwrap().send(val); } Callback::NoRetry(ref mut tx) => { - let _ = tx.take().unwrap().send(val.map_err(|e| e.0)); + let _ = tx.take().unwrap().send(val.map_err(|e| e.error)); } } } } +impl<T> TrySendError<T> { + /// Take the message from this error. + /// + /// The message will not always have been recovered. If an error occurs + /// after the message has been serialized onto the connection, it will not + /// be available here. + pub fn take_message(&mut self) -> Option<T> { + self.message.take() + } + + /// Consumes this to return the inner error. + pub fn into_error(self) -> crate::Error { + self.error + } +} + #[cfg(feature = "http2")] pin_project! { pub struct SendWhen<B> diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -325,8 +354,8 @@ where trace!("send_when canceled"); Poll::Ready(()) } - Poll::Ready(Err(err)) => { - call_back.send(Err(err)); + Poll::Ready(Err((error, message))) => { + call_back.send(Err(TrySendError { error, message })); Poll::Ready(()) } } diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -13,6 +13,8 @@ use http::Request; use super::{Http1Transaction, Wants}; use crate::body::{Body, DecodedLength, Incoming as IncomingBody}; +#[cfg(feature = "client")] +use crate::client::dispatch::TrySendError; use crate::common::task; use crate::proto::{BodyLength, Conn, Dispatched, MessageHead, RequestHead}; use crate::upgrade::OnUpgrade; diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -655,7 +657,10 @@ cfg_client! { } Err(err) => { if let Some(cb) = self.callback.take() { - cb.send(Err((err, None))); + cb.send(Err(TrySendError { + error: err, + message: None, + })); Ok(()) } else if !self.rx_closed { self.rx.close(); diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -663,7 +668,10 @@ cfg_client! { trace!("canceling queued request with connection error: {}", err); // in this case, the message was never even started, so it's safe to tell // the user that the request was completely canceled - cb.send(Err((crate::Error::new_canceled().with(err), Some(req)))); + cb.send(Err(TrySendError { + error: crate::Error::new_canceled().with(err), + message: Some(req), + })); Ok(()) } else { Err(err) diff --git a/src/proto/h2/client.rs b/src/proto/h2/client.rs --- a/src/proto/h2/client.rs +++ b/src/proto/h2/client.rs @@ -22,7 +22,7 @@ use pin_project_lite::pin_project; use super::ping::{Ponger, Recorder}; use super::{ping, H2Upgraded, PipeToSendStream, SendBuf}; use crate::body::{Body, Incoming as IncomingBody}; -use crate::client::dispatch::{Callback, SendWhen}; +use crate::client::dispatch::{Callback, SendWhen, TrySendError}; use crate::common::io::Compat; use crate::common::time::Time; use crate::ext::Protocol; diff --git a/src/proto/h2/client.rs b/src/proto/h2/client.rs --- a/src/proto/h2/client.rs +++ b/src/proto/h2/client.rs @@ -662,10 +662,10 @@ where .map_or(false, |len| len != 0) { warn!("h2 connect request with non-zero body not supported"); - cb.send(Err(( - crate::Error::new_h2(h2::Reason::INTERNAL_ERROR.into()), - None, - ))); + cb.send(Err(TrySendError { + error: crate::Error::new_h2(h2::Reason::INTERNAL_ERROR.into()), + message: None, + })); continue; } diff --git a/src/proto/h2/client.rs b/src/proto/h2/client.rs --- a/src/proto/h2/client.rs +++ b/src/proto/h2/client.rs @@ -677,7 +677,10 @@ where Ok(ok) => ok, Err(err) => { debug!("client send request error: {}", err); - cb.send(Err((crate::Error::new_h2(err), None))); + cb.send(Err(TrySendError { + error: crate::Error::new_h2(err), + message: None, + })); continue; } }; diff --git a/src/proto/h2/client.rs b/src/proto/h2/client.rs --- a/src/proto/h2/client.rs +++ b/src/proto/h2/client.rs @@ -702,7 +705,10 @@ where } Poll::Ready(Ok(())) => (), Poll::Ready(Err(err)) => { - f.cb.send(Err((crate::Error::new_h2(err), None))); + f.cb.send(Err(TrySendError { + error: crate::Error::new_h2(err), + message: None, + })); continue; } }
i found the error msg from the drop func,just as follow if Envelope still has req, it means req never send ,should it has the chance to retry? struct Envelope<T, U>(Option<(T, Callback<T, U>)>); impl<T, U> Drop for Envelope<T, U> { fn drop(&mut self) { if let Some((val, cb)) = self.0.take() { cb.send(Err(( crate::Error::new_canceled().with("connection closed"), Some(val), ))); } } } hyper client idle timeout is 20s,and server is tomcat,default keep alive timeout is 60s, it should not cause connection close error interesting,keep eye on it ``` async fn send_request( self, mut req: Request<B>, pool_key: PoolKey, ) -> Result<Response<hyper::body::Incoming>, Error> { let mut pooled = self.connection_for(pool_key).await?; req.extensions_mut() .get_mut::<CaptureConnectionExtension>() .map(|conn| conn.set(&pooled.conn_info)); if pooled.is_http1() { if req.version() == Version::HTTP_2 { warn!("Connection is HTTP/1, but request requires HTTP/2"); return Err(e!(UserUnsupportedVersion)); } if self.config.set_host { let uri = req.uri().clone(); req.headers_mut().entry(HOST).or_insert_with(|| { let hostname = uri.host().expect("authority implies host"); if let Some(port) = get_non_default_port(&uri) { let s = format!("{}:{}", hostname, port); HeaderValue::from_str(&s) } else { HeaderValue::from_str(hostname) } .expect("uri host is valid header value") }); } // CONNECT always sends authority-form, so check it first... if req.method() == Method::CONNECT { authority_form(req.uri_mut()); } else if pooled.conn_info.is_proxied { absolute_form(req.uri_mut()); } else { origin_form(req.uri_mut()); } } else if req.method() == Method::CONNECT { authority_form(req.uri_mut()); } let fut = pooled.send_request(req); //.send_request_retryable(req) //.map_err(ClientError::map_with_reused(pooled.is_reused())); // If the Connector included 'extra' info, add to Response... let extra_info = pooled.conn_info.extra.clone(); let fut = fut.map_ok(move |mut res| { if let Some(extra) = extra_info { extra.set(res.extensions_mut()); } res }); // As of futures@0.1.21, there is a race condition in the mpsc // channel, such that sending when the receiver is closing can // result in the message being stuck inside the queue. It won't // ever notify until the Sender side is dropped. // // To counteract this, we must check if our senders 'want' channel // has been closed after having tried to send. If so, error out... if pooled.is_closed() { return fut.await; } let res = fut.await?; // If pooled is HTTP/2, we can toss this reference immediately. // // when pooled is dropped, it will try to insert back into the // pool. To delay that, spawn a future that completes once the // sender is ready again. // // This *should* only be once the related `Connection` has polled // for a new request to start. // // It won't be ready if there is a body to stream. if pooled.is_http2() || !pooled.is_pool_enabled() || pooled.is_ready() { drop(pooled); } else if !res.body().is_end_stream() { //let (delayed_tx, delayed_rx) = oneshot::channel::<()>(); //res.body_mut().delayed_eof(delayed_rx); let on_idle = future::poll_fn(move |cx| pooled.poll_ready(cx)).map(move |_| { // At this point, `pooled` is dropped, and had a chance // to insert into the pool (if conn was idle) //drop(delayed_tx); }); self.exec.execute(on_idle); } else { // There's no body to delay, but the connection isn't // ready yet. Only re-insert when it's ready let on_idle = future::poll_fn(move |cx| pooled.poll_ready(cx)).map(|_| ()); self.exec.execute(on_idle); } Ok(res) } ``` ``` // As of futures@0.1.21, there is a race condition in the mpsc // channel, such that sending when the receiver is closing can // result in the message being stuck inside the queue. It won't // ever notify until the Sender side is dropped. // // To counteract this, we must check if our senders 'want' channel // has been closed after having tried to send. If so, error out... if pooled.is_closed() { return fut.await; } ``` then Is mpsc::UnboundedSender dropped causing this problem? Any suggestions for modifications?
2024-06-21T20:09:56Z
3,691
hyper client happens cacel error which should retry **Version** List the version(s) of `hyper`, and any relevant hyper dependency (such as `h2` if this is related to HTTP/2). hyper = { version = "1.1.0", features = ["full"] } hyper-util = { version = "0.1.3", features = ["full"] } **Platform** The output of `uname -a` (UNIX), or version and 32 or 64-bit (Windows) linux 64 **Description** hyper client happens cacel error which should retry [short summary of the bug] ```rust let mut connector = HttpConnector::new(); connector.set_nodelay(true); //禁止使用该功能,其会在拿到IPV6和IPV4的时候优先尝试链接IPV6 connector.set_happy_eyeballs_timeout(None); connector.set_connect_timeout(Some(Duration::from_millis(constant::constant_config::CONNECT_TIME_OUT))); // connector.set_send_buffer_size(Some(constant::constant_config::BUFFER_SIZE)); // connector.set_recv_buffer_size(Some(constant::constant_config::BUFFER_SIZE)); connector.set_reuse_address(true); //hyper_util::rt::TokioExecutor::new() 是否会导致上下文切换更多? let http_client = Client::builder(TokioExecutor::new()) .http1_preserve_header_case(true) .http1_title_case_headers(false) .pool_idle_timeout(Duration::from_millis(constant::constant_config::CLIENT_IDLE_TIME_OUT)) //空闲链接 // .pool_max_idle_per_host(constant::constant_config::MAX_IDLE_CONNECTIONS_PER_HOST_HTTP_ALL) // .executor() // .http1_max_buf_size(constant::constant_config::BUFFER_SIZE) .http1_ignore_invalid_headers_in_responses(false) .http1_allow_spaces_after_header_name_in_responses(false) .http1_allow_obsolete_multiline_headers_in_responses(false) .timer(TokioTimer::default()) .pool_timer(TokioTimer::default()) .build(connector); http_client ``` when use http_client send request,i got some error message as follows: ``` request::error("message", "Error { kind: SendRequest, source: Some(hyper::Error(Canceled, \"connection closed\")) }" equest::error("message", "Error { kind: SendRequest, source: Some(hyper::Error(Canceled, \"connection was not ready\")) }") ``` retry_canceled_requests default is true, i think it should not happen these errors
hyperium__hyper-3691
diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -13,10 +13,21 @@ use tokio::sync::{mpsc, oneshot}; #[cfg(feature = "http2")] use crate::{body::Incoming, proto::h2::client::ResponseFutMap}; -#[cfg(test)] -pub(crate) type RetryPromise<T, U> = oneshot::Receiver<Result<U, (crate::Error, Option<T>)>>; +pub(crate) type RetryPromise<T, U> = oneshot::Receiver<Result<U, TrySendError<T>>>; pub(crate) type Promise<T> = oneshot::Receiver<Result<T, crate::Error>>; +/// An error when calling `try_send_request`. +/// +/// There is a possibility of an error occuring on a connection in-between the +/// time that a request is queued and when it is actually written to the IO +/// transport. If that happens, it is safe to return the request back to the +/// caller, as it was never fully sent. +#[derive(Debug)] +pub struct TrySendError<T> { + pub(crate) error: crate::Error, + pub(crate) message: Option<T>, +} + pub(crate) fn channel<T, U>() -> (Sender<T, U>, Receiver<T, U>) { let (tx, rx) = mpsc::unbounded_channel(); let (giver, taker) = want::new(); diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -92,7 +103,7 @@ impl<T, U> Sender<T, U> { } } - #[cfg(test)] + #[cfg(feature = "http1")] pub(crate) fn try_send(&mut self, val: T) -> Result<RetryPromise<T, U>, T> { if !self.can_send() { return Err(val); diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -135,7 +146,6 @@ impl<T, U> UnboundedSender<T, U> { self.giver.is_canceled() } - #[cfg(test)] pub(crate) fn try_send(&mut self, val: T) -> Result<RetryPromise<T, U>, T> { let (tx, rx) = oneshot::channel(); self.inner diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -389,8 +418,8 @@ mod tests { let err = fulfilled .expect("fulfilled") .expect_err("promise should error"); - match (err.0.kind(), err.1) { - (&crate::error::Kind::Canceled, Some(_)) => (), + match (err.error.is_canceled(), err.message) { + (true, Some(_)) => (), e => panic!("expected Error::Cancel(_), found {:?}", e), } } diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -729,9 +737,9 @@ mod tests { let err = tokio_test::assert_ready_ok!(Pin::new(&mut res_rx).poll(cx)) .expect_err("callback should send error"); - match (err.0.kind(), err.1) { - (&crate::error::Kind::Canceled, Some(_)) => (), - other => panic!("expected Canceled, got {:?}", other), + match (err.error.is_canceled(), err.message.as_ref()) { + (true, Some(_)) => (), + _ => panic!("expected Canceled, got {:?}", err), } }); } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -2041,6 +2041,91 @@ mod conn { assert_eq!(vec, b"bar=foo"); } + #[tokio::test] + async fn test_try_send_request() { + use std::future::Future; + let (listener, addr) = setup_tk_test_server().await; + let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>(); + + tokio::spawn(async move { + let mut sock = listener.accept().await.unwrap().0; + let mut buf = [0u8; 8192]; + sock.read(&mut buf).await.expect("read 1"); + sock.write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 0\r\n\r\n") + .await + .expect("write 1"); + let _ = done_rx.await; + }); + + // make polling fair by putting both in spawns + tokio::spawn(async move { + let io = tcp_connect(&addr).await.expect("tcp connect"); + let (mut client, mut conn) = conn::http1::Builder::new() + .handshake::<_, Empty<Bytes>>(io) + .await + .expect("http handshake"); + + // get the conn ready + assert!( + future::poll_fn(|cx| Poll::Ready(Pin::new(&mut conn).poll(cx))) + .await + .is_pending() + ); + assert!(client.is_ready()); + + // use the connection once + let mut fut1 = std::pin::pin!(client.send_request(http::Request::new(Empty::new()))); + let _res1 = future::poll_fn(|cx| loop { + if let Poll::Ready(res) = fut1.as_mut().poll(cx) { + return Poll::Ready(res); + } + return match Pin::new(&mut conn).poll(cx) { + Poll::Ready(_) => panic!("ruh roh"), + Poll::Pending => Poll::Pending, + }; + }) + .await + .expect("resp 1"); + + assert!(client.is_ready()); + + // simulate the server dropping the conn + let _ = done_tx.send(()); + // let the server task die + tokio::task::yield_now().await; + + let mut fut2 = + std::pin::pin!(client.try_send_request(http::Request::new(Empty::new()))); + let poll1 = future::poll_fn(|cx| Poll::Ready(fut2.as_mut().poll(cx))).await; + assert!(poll1.is_pending(), "not already known to error"); + + let mut conn_opt = Some(conn); + // wasn't a known error, req is in queue, and now the next poll, the + // conn will be noticed as errored + let mut err = future::poll_fn(|cx| { + loop { + if let Poll::Ready(res) = fut2.as_mut().poll(cx) { + return Poll::Ready(res); + } + if let Some(ref mut conn) = conn_opt { + match Pin::new(conn).poll(cx) { + Poll::Ready(_) => { + conn_opt = None; + } // ok + Poll::Pending => return Poll::Pending, + }; + } + } + }) + .await + .expect_err("resp 2"); + + assert!(err.take_message().is_some(), "request was returned"); + }) + .await + .unwrap(); + } + #[tokio::test] async fn http2_detect_conn_eof() { use futures_util::future;
hyperium/hyper
aa7ff605da3b706e855f9633b8dddeb9463217d4
[ "2703" ]
1.3
721785efad8537513e48d900a85c05ce79483018
diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -11,6 +11,7 @@ use bytes::{Buf, Bytes}; use futures_util::ready; use http::header::{HeaderValue, CONNECTION, TE}; use http::{HeaderMap, Method, Version}; +use http_body::Frame; use httparse::ParserConfig; use super::io::Buffered; diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -268,10 +269,20 @@ where self.try_keep_alive(cx); } } else if msg.expect_continue && msg.head.version.gt(&Version::HTTP_10) { - self.state.reading = Reading::Continue(Decoder::new(msg.decode)); + let h1_max_header_size = None; // TODO: remove this when we land h1_max_header_size support + self.state.reading = Reading::Continue(Decoder::new( + msg.decode, + self.state.h1_max_headers, + h1_max_header_size, + )); wants = wants.add(Wants::EXPECT); } else { - self.state.reading = Reading::Body(Decoder::new(msg.decode)); + let h1_max_header_size = None; // TODO: remove this when we land h1_max_header_size support + self.state.reading = Reading::Body(Decoder::new( + msg.decode, + self.state.h1_max_headers, + h1_max_header_size, + )); } self.state.allow_trailer_fields = msg diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -312,33 +323,41 @@ where pub(crate) fn poll_read_body( &mut self, cx: &mut Context<'_>, - ) -> Poll<Option<io::Result<Bytes>>> { + ) -> Poll<Option<io::Result<Frame<Bytes>>>> { debug_assert!(self.can_read_body()); let (reading, ret) = match self.state.reading { Reading::Body(ref mut decoder) => { match ready!(decoder.decode(cx, &mut self.io)) { - Ok(slice) => { - let (reading, chunk) = if decoder.is_eof() { - debug!("incoming body completed"); - ( - Reading::KeepAlive, - if !slice.is_empty() { - Some(Ok(slice)) - } else { - None - }, - ) - } else if slice.is_empty() { - error!("incoming body unexpectedly ended"); - // This should be unreachable, since all 3 decoders - // either set eof=true or return an Err when reading - // an empty slice... - (Reading::Closed, None) + Ok(frame) => { + if frame.is_data() { + let slice = frame.data_ref().unwrap_or_else(|| unreachable!()); + let (reading, maybe_frame) = if decoder.is_eof() { + debug!("incoming body completed"); + ( + Reading::KeepAlive, + if !slice.is_empty() { + Some(Ok(frame)) + } else { + None + }, + ) + } else if slice.is_empty() { + error!("incoming body unexpectedly ended"); + // This should be unreachable, since all 3 decoders + // either set eof=true or return an Err when reading + // an empty slice... + (Reading::Closed, None) + } else { + return Poll::Ready(Some(Ok(frame))); + }; + (reading, Poll::Ready(maybe_frame)) + } else if frame.is_trailers() { + (Reading::Closed, Poll::Ready(Some(Ok(frame)))) } else { - return Poll::Ready(Some(Ok(slice))); - }; - (reading, Poll::Ready(chunk)) + trace!("discarding unknown frame"); + (Reading::Closed, Poll::Ready(None)) + } } Err(e) => { debug!("incoming body decode error: {}", e); diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -4,10 +4,13 @@ use std::io; use std::task::{Context, Poll}; use std::usize; -use bytes::Bytes; +use bytes::{BufMut, Bytes, BytesMut}; use futures_util::ready; +use http::{HeaderMap, HeaderName, HeaderValue}; +use http_body::Frame; use super::io::MemRead; +use super::role::DEFAULT_MAX_HEADERS; use super::DecodedLength; use self::Kind::{Chunked, Eof, Length}; diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -17,6 +20,11 @@ use self::Kind::{Chunked, Eof, Length}; /// This limit is currentlty applied for the entire body, not per chunk. const CHUNKED_EXTENSIONS_LIMIT: u64 = 1024 * 16; +/// Maximum number of bytes allowed for all trailer fields. +/// +/// TODO: remove this when we land h1_max_header_size support +const TRAILER_LIMIT: usize = 1024 * 16; + /// Decoders to handle different Transfer-Encodings. /// /// If a message body does not include a Transfer-Encoding, it *should* diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -26,7 +34,7 @@ pub(crate) struct Decoder { kind: Kind, } -#[derive(Debug, Clone, Copy, PartialEq)] +#[derive(Debug, Clone, PartialEq)] enum Kind { /// A Reader used when a Content-Length header is passed with a positive integer. Length(u64), diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -35,6 +43,10 @@ enum Kind { state: ChunkedState, chunk_len: u64, extensions_cnt: u64, + trailers_buf: Option<BytesMut>, + trailers_cnt: usize, + h1_max_headers: Option<usize>, + h1_max_header_size: Option<usize>, }, /// A Reader used for responses that don't indicate a length or chunked. /// diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -81,12 +93,19 @@ impl Decoder { } } - pub(crate) fn chunked() -> Decoder { + pub(crate) fn chunked( + h1_max_headers: Option<usize>, + h1_max_header_size: Option<usize>, + ) -> Decoder { Decoder { kind: Kind::Chunked { state: ChunkedState::new(), chunk_len: 0, extensions_cnt: 0, + trailers_buf: None, + trailers_cnt: 0, + h1_max_headers, + h1_max_header_size, }, } } diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -97,9 +116,13 @@ impl Decoder { } } - pub(super) fn new(len: DecodedLength) -> Self { + pub(super) fn new( + len: DecodedLength, + h1_max_headers: Option<usize>, + h1_max_header_size: Option<usize>, + ) -> Self { match len { - DecodedLength::CHUNKED => Decoder::chunked(), + DecodedLength::CHUNKED => Decoder::chunked(h1_max_headers, h1_max_header_size), DecodedLength::CLOSE_DELIMITED => Decoder::eof(), length => Decoder::length(length.danger_len()), } diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -123,12 +146,12 @@ impl Decoder { &mut self, cx: &mut Context<'_>, body: &mut R, - ) -> Poll<Result<Bytes, io::Error>> { + ) -> Poll<Result<Frame<Bytes>, io::Error>> { trace!("decode; state={:?}", self.kind); match self.kind { Length(ref mut remaining) => { if *remaining == 0 { - Poll::Ready(Ok(Bytes::new())) + Poll::Ready(Ok(Frame::data(Bytes::new()))) } else { let to_read = *remaining as usize; let buf = ready!(body.read_mem(cx, to_read))?; diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -143,37 +166,77 @@ impl Decoder { } else { *remaining -= num; } - Poll::Ready(Ok(buf)) + Poll::Ready(Ok(Frame::data(buf))) } } Chunked { ref mut state, ref mut chunk_len, ref mut extensions_cnt, + ref mut trailers_buf, + ref mut trailers_cnt, + ref h1_max_headers, + ref h1_max_header_size, } => { + let h1_max_headers = h1_max_headers.unwrap_or(DEFAULT_MAX_HEADERS); + let h1_max_header_size = h1_max_header_size.unwrap_or(TRAILER_LIMIT); loop { let mut buf = None; // advances the chunked state - *state = ready!(state.step(cx, body, chunk_len, extensions_cnt, &mut buf))?; + *state = ready!(state.step( + cx, + body, + chunk_len, + extensions_cnt, + &mut buf, + trailers_buf, + trailers_cnt, + h1_max_headers, + h1_max_header_size + ))?; if *state == ChunkedState::End { trace!("end of chunked"); - return Poll::Ready(Ok(Bytes::new())); + + if trailers_buf.is_some() { + trace!("found possible trailers"); + + // decoder enforces that trailers count will not exceed h1_max_headers + if *trailers_cnt >= h1_max_headers { + return Poll::Ready(Err(io::Error::new( + io::ErrorKind::InvalidData, + "chunk trailers count overflow", + ))); + } + match decode_trailers( + &mut trailers_buf.take().expect("Trailer is None"), + *trailers_cnt, + ) { + Ok(headers) => { + return Poll::Ready(Ok(Frame::trailers(headers))); + } + Err(e) => { + return Poll::Ready(Err(e)); + } + } + } + + return Poll::Ready(Ok(Frame::data(Bytes::new()))); } if let Some(buf) = buf { - return Poll::Ready(Ok(buf)); + return Poll::Ready(Ok(Frame::data(buf))); } } } Eof(ref mut is_eof) => { if *is_eof { - Poll::Ready(Ok(Bytes::new())) + Poll::Ready(Ok(Frame::data(Bytes::new()))) } else { // 8192 chosen because its about 2 packets, there probably // won't be that much available, so don't have MemReaders // allocate buffers to big body.read_mem(cx, 8192).map_ok(|slice| { *is_eof = slice.is_empty(); - slice + Frame::data(slice) }) } } diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -216,6 +279,19 @@ macro_rules! or_overflow { ) } +macro_rules! put_u8 { + ($trailers_buf:expr, $byte:expr, $limit:expr) => { + $trailers_buf.put_u8($byte); + + if $trailers_buf.len() >= $limit { + return Poll::Ready(Err(io::Error::new( + io::ErrorKind::InvalidData, + "chunk trailers bytes over limit", + ))); + } + }; +} + impl ChunkedState { fn new() -> ChunkedState { ChunkedState::Start diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -227,6 +303,10 @@ impl ChunkedState { size: &mut u64, extensions_cnt: &mut u64, buf: &mut Option<Bytes>, + trailers_buf: &mut Option<BytesMut>, + trailers_cnt: &mut usize, + h1_max_headers: usize, + h1_max_header_size: usize, ) -> Poll<Result<ChunkedState, io::Error>> { use self::ChunkedState::*; match *self { diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -238,10 +318,17 @@ impl ChunkedState { Body => ChunkedState::read_body(cx, body, size, buf), BodyCr => ChunkedState::read_body_cr(cx, body), BodyLf => ChunkedState::read_body_lf(cx, body), - Trailer => ChunkedState::read_trailer(cx, body), - TrailerLf => ChunkedState::read_trailer_lf(cx, body), - EndCr => ChunkedState::read_end_cr(cx, body), - EndLf => ChunkedState::read_end_lf(cx, body), + Trailer => ChunkedState::read_trailer(cx, body, trailers_buf, h1_max_header_size), + TrailerLf => ChunkedState::read_trailer_lf( + cx, + body, + trailers_buf, + trailers_cnt, + h1_max_headers, + h1_max_header_size, + ), + EndCr => ChunkedState::read_end_cr(cx, body, trailers_buf, h1_max_header_size), + EndLf => ChunkedState::read_end_lf(cx, body, trailers_buf, h1_max_header_size), End => Poll::Ready(Ok(ChunkedState::End)), } } diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -442,19 +529,51 @@ impl ChunkedState { fn read_trailer<R: MemRead>( cx: &mut Context<'_>, rdr: &mut R, + trailers_buf: &mut Option<BytesMut>, + h1_max_header_size: usize, ) -> Poll<Result<ChunkedState, io::Error>> { trace!("read_trailer"); - match byte!(rdr, cx) { + let byte = byte!(rdr, cx); + + put_u8!( + trailers_buf.as_mut().expect("trailers_buf is None"), + byte, + h1_max_header_size + ); + + match byte { b'\r' => Poll::Ready(Ok(ChunkedState::TrailerLf)), _ => Poll::Ready(Ok(ChunkedState::Trailer)), } } + fn read_trailer_lf<R: MemRead>( cx: &mut Context<'_>, rdr: &mut R, + trailers_buf: &mut Option<BytesMut>, + trailers_cnt: &mut usize, + h1_max_headers: usize, + h1_max_header_size: usize, ) -> Poll<Result<ChunkedState, io::Error>> { - match byte!(rdr, cx) { - b'\n' => Poll::Ready(Ok(ChunkedState::EndCr)), + let byte = byte!(rdr, cx); + match byte { + b'\n' => { + if *trailers_cnt >= h1_max_headers { + return Poll::Ready(Err(io::Error::new( + io::ErrorKind::InvalidData, + "chunk trailers count overflow", + ))); + } + *trailers_cnt += 1; + + put_u8!( + trailers_buf.as_mut().expect("trailers_buf is None"), + byte, + h1_max_header_size + ); + + Poll::Ready(Ok(ChunkedState::EndCr)) + } _ => Poll::Ready(Err(io::Error::new( io::ErrorKind::InvalidInput, "Invalid trailer end LF", diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -465,18 +584,48 @@ impl ChunkedState { fn read_end_cr<R: MemRead>( cx: &mut Context<'_>, rdr: &mut R, + trailers_buf: &mut Option<BytesMut>, + h1_max_header_size: usize, ) -> Poll<Result<ChunkedState, io::Error>> { - match byte!(rdr, cx) { - b'\r' => Poll::Ready(Ok(ChunkedState::EndLf)), - _ => Poll::Ready(Ok(ChunkedState::Trailer)), + let byte = byte!(rdr, cx); + match byte { + b'\r' => { + if let Some(trailers_buf) = trailers_buf { + put_u8!(trailers_buf, byte, h1_max_header_size); + } + Poll::Ready(Ok(ChunkedState::EndLf)) + } + byte => { + match trailers_buf { + None => { + // 64 will fit a single Expires header without reallocating + let mut buf = BytesMut::with_capacity(64); + buf.put_u8(byte); + *trailers_buf = Some(buf); + } + Some(ref mut trailers_buf) => { + put_u8!(trailers_buf, byte, h1_max_header_size); + } + } + + Poll::Ready(Ok(ChunkedState::Trailer)) + } } } fn read_end_lf<R: MemRead>( cx: &mut Context<'_>, rdr: &mut R, + trailers_buf: &mut Option<BytesMut>, + h1_max_header_size: usize, ) -> Poll<Result<ChunkedState, io::Error>> { - match byte!(rdr, cx) { - b'\n' => Poll::Ready(Ok(ChunkedState::End)), + let byte = byte!(rdr, cx); + match byte { + b'\n' => { + if let Some(trailers_buf) = trailers_buf { + put_u8!(trailers_buf, byte, h1_max_header_size); + } + Poll::Ready(Ok(ChunkedState::End)) + } _ => Poll::Ready(Err(io::Error::new( io::ErrorKind::InvalidInput, "Invalid chunk end LF", diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -485,6 +634,48 @@ impl ChunkedState { } } +// TODO: disallow Transfer-Encoding, Content-Length, Trailer, etc in trailers ?? +fn decode_trailers(buf: &mut BytesMut, count: usize) -> Result<HeaderMap, io::Error> { + let mut trailers = HeaderMap::new(); + let mut headers = vec![httparse::EMPTY_HEADER; count]; + let res = httparse::parse_headers(&buf, &mut headers); + match res { + Ok(httparse::Status::Complete((_, headers))) => { + for header in headers.iter() { + use std::convert::TryFrom; + let name = match HeaderName::try_from(header.name) { + Ok(name) => name, + Err(_) => { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("Invalid header name: {:?}", &header), + )); + } + }; + + let value = match HeaderValue::from_bytes(header.value) { + Ok(value) => value, + Err(_) => { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("Invalid header value: {:?}", &header), + )); + } + }; + + trailers.insert(name, value); + } + + Ok(trailers) + } + Ok(httparse::Status::Partial) => Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Partial header", + )), + Err(e) => Err(io::Error::new(io::ErrorKind::InvalidInput, e)), + } +} + #[derive(Debug)] struct IncompleteBody; diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -213,17 +213,39 @@ where } } match self.conn.poll_read_body(cx) { - Poll::Ready(Some(Ok(chunk))) => match body.try_send_data(chunk) { - Ok(()) => { - self.body_tx = Some(body); - } - Err(_canceled) => { - if self.conn.can_read_body() { - trace!("body receiver dropped before eof, closing"); - self.conn.close_read(); + Poll::Ready(Some(Ok(frame))) => { + if frame.is_data() { + let chunk = frame.into_data().unwrap_or_else(|_| unreachable!()); + match body.try_send_data(chunk) { + Ok(()) => { + self.body_tx = Some(body); + } + Err(_canceled) => { + if self.conn.can_read_body() { + trace!("body receiver dropped before eof, closing"); + self.conn.close_read(); + } + } + } + } else if frame.is_trailers() { + let trailers = + frame.into_trailers().unwrap_or_else(|_| unreachable!()); + match body.try_send_trailers(trailers) { + Ok(()) => { + self.body_tx = Some(body); + } + Err(_canceled) => { + if self.conn.can_read_body() { + trace!("body receiver dropped before eof, closing"); + self.conn.close_read(); + } + } } + } else { + // we should have dropped all unknown frames in poll_read_body + error!("unexpected frame"); } - }, + } Poll::Ready(None) => { // just drop, the body will close automatically } diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -30,7 +30,7 @@ use crate::proto::h1::{ use crate::proto::RequestHead; use crate::proto::{BodyLength, MessageHead, RequestLine}; -const DEFAULT_MAX_HEADERS: usize = 100; +pub(crate) const DEFAULT_MAX_HEADERS: usize = 100; const AVERAGE_HEADER_SIZE: usize = 30; // totally scientific #[cfg(feature = "server")] const MAX_URI_LEN: usize = (u16::MAX - 1) as usize;
2024-04-17T00:18:10Z
3,637
Receiving HTTP/1.1 trailers
hyperium__hyper-3637
diff --git a/src/body/incoming.rs b/src/body/incoming.rs --- a/src/body/incoming.rs +++ b/src/body/incoming.rs @@ -403,6 +403,19 @@ impl Sender { .map_err(|err| err.into_inner().expect("just sent Ok")) } + #[cfg(feature = "http1")] + pub(crate) fn try_send_trailers( + &mut self, + trailers: HeaderMap, + ) -> Result<(), Option<HeaderMap>> { + let tx = match self.trailers_tx.take() { + Some(tx) => tx, + None => return Err(None), + }; + + tx.send(trailers).map_err(|err| Some(err)) + } + #[cfg(test)] pub(crate) fn abort(mut self) { self.send_error(crate::Error::new_body_write_aborted()); diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -181,7 +244,7 @@ impl Decoder { } #[cfg(test)] - async fn decode_fut<R: MemRead>(&mut self, body: &mut R) -> Result<Bytes, io::Error> { + async fn decode_fut<R: MemRead>(&mut self, body: &mut R) -> Result<Frame<Bytes>, io::Error> { futures_util::future::poll_fn(move |cx| self.decode(cx, body)).await } } diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -554,9 +745,20 @@ mod tests { let rdr = &mut s.as_bytes(); let mut size = 0; let mut ext_cnt = 0; + let mut trailers_cnt = 0; loop { let result = futures_util::future::poll_fn(|cx| { - state.step(cx, rdr, &mut size, &mut ext_cnt, &mut None) + state.step( + cx, + rdr, + &mut size, + &mut ext_cnt, + &mut None, + &mut None, + &mut trailers_cnt, + DEFAULT_MAX_HEADERS, + TRAILER_LIMIT, + ) }) .await; let desc = format!("read_size failed for {:?}", s); diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -573,9 +775,20 @@ mod tests { let rdr = &mut s.as_bytes(); let mut size = 0; let mut ext_cnt = 0; + let mut trailers_cnt = 0; loop { let result = futures_util::future::poll_fn(|cx| { - state.step(cx, rdr, &mut size, &mut ext_cnt, &mut None) + state.step( + cx, + rdr, + &mut size, + &mut ext_cnt, + &mut None, + &mut None, + &mut trailers_cnt, + DEFAULT_MAX_HEADERS, + TRAILER_LIMIT, + ) }) .await; state = match result { diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -639,7 +852,16 @@ mod tests { async fn test_read_sized_early_eof() { let mut bytes = &b"foo bar"[..]; let mut decoder = Decoder::length(10); - assert_eq!(decoder.decode_fut(&mut bytes).await.unwrap().len(), 7); + assert_eq!( + decoder + .decode_fut(&mut bytes) + .await + .unwrap() + .data_ref() + .unwrap() + .len(), + 7 + ); let e = decoder.decode_fut(&mut bytes).await.unwrap_err(); assert_eq!(e.kind(), io::ErrorKind::UnexpectedEof); } diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -651,8 +873,17 @@ mod tests { 9\r\n\ foo bar\ "[..]; - let mut decoder = Decoder::chunked(); - assert_eq!(decoder.decode_fut(&mut bytes).await.unwrap().len(), 7); + let mut decoder = Decoder::chunked(None, None); + assert_eq!( + decoder + .decode_fut(&mut bytes) + .await + .unwrap() + .data_ref() + .unwrap() + .len(), + 7 + ); let e = decoder.decode_fut(&mut bytes).await.unwrap_err(); assert_eq!(e.kind(), io::ErrorKind::UnexpectedEof); } diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -661,10 +892,12 @@ mod tests { #[tokio::test] async fn test_read_chunked_single_read() { let mut mock_buf = &b"10\r\n1234567890abcdef\r\n0\r\n"[..]; - let buf = Decoder::chunked() + let buf = Decoder::chunked(None, None) .decode_fut(&mut mock_buf) .await - .expect("decode"); + .expect("decode") + .into_data() + .expect("unknown frame type"); assert_eq!(16, buf.len()); let result = String::from_utf8(buf.as_ref().to_vec()).expect("decode String"); assert_eq!("1234567890abcdef", &result); diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -684,8 +917,13 @@ mod tests { scratch.extend(b"0\r\n\r\n"); let mut mock_buf = Bytes::from(scratch); - let mut decoder = Decoder::chunked(); - let buf1 = decoder.decode_fut(&mut mock_buf).await.expect("decode1"); + let mut decoder = Decoder::chunked(None, None); + let buf1 = decoder + .decode_fut(&mut mock_buf) + .await + .expect("decode1") + .into_data() + .expect("unknown frame type"); assert_eq!(&buf1[..], b"A"); let err = decoder diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -700,7 +938,7 @@ mod tests { #[tokio::test] async fn test_read_chunked_trailer_with_missing_lf() { let mut mock_buf = &b"10\r\n1234567890abcdef\r\n0\r\nbad\r\r\n"[..]; - let mut decoder = Decoder::chunked(); + let mut decoder = Decoder::chunked(None, None); decoder.decode_fut(&mut mock_buf).await.expect("decode"); let e = decoder.decode_fut(&mut mock_buf).await.unwrap_err(); assert_eq!(e.kind(), io::ErrorKind::InvalidInput); diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -710,20 +948,35 @@ mod tests { #[tokio::test] async fn test_read_chunked_after_eof() { let mut mock_buf = &b"10\r\n1234567890abcdef\r\n0\r\n\r\n"[..]; - let mut decoder = Decoder::chunked(); + let mut decoder = Decoder::chunked(None, None); // normal read - let buf = decoder.decode_fut(&mut mock_buf).await.unwrap(); + let buf = decoder + .decode_fut(&mut mock_buf) + .await + .unwrap() + .into_data() + .expect("unknown frame type"); assert_eq!(16, buf.len()); let result = String::from_utf8(buf.as_ref().to_vec()).expect("decode String"); assert_eq!("1234567890abcdef", &result); // eof read - let buf = decoder.decode_fut(&mut mock_buf).await.expect("decode"); + let buf = decoder + .decode_fut(&mut mock_buf) + .await + .expect("decode") + .into_data() + .expect("unknown frame type"); assert_eq!(0, buf.len()); // ensure read after eof also returns eof - let buf = decoder.decode_fut(&mut mock_buf).await.expect("decode"); + let buf = decoder + .decode_fut(&mut mock_buf) + .await + .expect("decode") + .into_data() + .expect("unknown frame type"); assert_eq!(0, buf.len()); } diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -751,7 +1004,9 @@ mod tests { let buf = decoder .decode_fut(&mut ins) .await - .expect("unexpected decode error"); + .expect("unexpected decode error") + .into_data() + .expect("unexpected frame type"); if buf.is_empty() { break; // eof } diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -783,7 +1038,7 @@ mod tests { async fn test_read_chunked_async() { let content = "3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n"; let expected = "foobar"; - all_async_cases(content, expected, Decoder::chunked()).await; + all_async_cases(content, expected, Decoder::chunked(None, None)).await; } #[cfg(not(miri))] diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -808,10 +1063,15 @@ mod tests { b.bytes = LEN as u64; b.iter(|| { - let mut decoder = Decoder::chunked(); + let mut decoder = Decoder::chunked(None, None); rt.block_on(async { let mut raw = content.clone(); - let chunk = decoder.decode_fut(&mut raw).await.unwrap(); + let chunk = decoder + .decode_fut(&mut raw) + .await + .unwrap() + .into_data() + .unwrap(); assert_eq!(chunk.len(), LEN); }); }); diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -830,7 +1090,12 @@ mod tests { let mut decoder = Decoder::length(LEN as u64); rt.block_on(async { let mut raw = content.clone(); - let chunk = decoder.decode_fut(&mut raw).await.unwrap(); + let chunk = decoder + .decode_fut(&mut raw) + .await + .unwrap() + .into_data() + .unwrap(); assert_eq!(chunk.len(), LEN); }); }); diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -843,4 +1108,110 @@ mod tests { .build() .expect("rt build") } + + #[test] + fn test_decode_trailers() { + let mut buf = BytesMut::new(); + buf.extend_from_slice( + b"Expires: Wed, 21 Oct 2015 07:28:00 GMT\r\nX-Stream-Error: failed to decode\r\n\r\n", + ); + let headers = decode_trailers(&mut buf, 2).expect("decode_trailers"); + assert_eq!(headers.len(), 2); + assert_eq!( + headers.get("Expires").unwrap(), + "Wed, 21 Oct 2015 07:28:00 GMT" + ); + assert_eq!(headers.get("X-Stream-Error").unwrap(), "failed to decode"); + } + + #[tokio::test] + async fn test_trailer_max_headers_enforced() { + let h1_max_headers = 10; + let mut scratch = vec![]; + scratch.extend(b"10\r\n1234567890abcdef\r\n0\r\n"); + for i in 0..h1_max_headers { + scratch.extend(format!("trailer{}: {}\r\n", i, i).as_bytes()); + } + scratch.extend(b"\r\n"); + let mut mock_buf = Bytes::from(scratch); + + let mut decoder = Decoder::chunked(Some(h1_max_headers), None); + + // ready chunked body + let buf = decoder + .decode_fut(&mut mock_buf) + .await + .unwrap() + .into_data() + .expect("unknown frame type"); + assert_eq!(16, buf.len()); + + // eof read + let err = decoder + .decode_fut(&mut mock_buf) + .await + .expect_err("trailer fields over limit"); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + } + + #[tokio::test] + async fn test_trailer_max_header_size_huge_trailer() { + let max_header_size = 1024; + let mut scratch = vec![]; + scratch.extend(b"10\r\n1234567890abcdef\r\n0\r\n"); + scratch.extend(format!("huge_trailer: {}\r\n", "x".repeat(max_header_size)).as_bytes()); + scratch.extend(b"\r\n"); + let mut mock_buf = Bytes::from(scratch); + + let mut decoder = Decoder::chunked(None, Some(max_header_size)); + + // ready chunked body + let buf = decoder + .decode_fut(&mut mock_buf) + .await + .unwrap() + .into_data() + .expect("unknown frame type"); + assert_eq!(16, buf.len()); + + // eof read + let err = decoder + .decode_fut(&mut mock_buf) + .await + .expect_err("trailers over limit"); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + } + + #[tokio::test] + async fn test_trailer_max_header_size_many_small_trailers() { + let max_headers = 10; + let header_size = 64; + let mut scratch = vec![]; + scratch.extend(b"10\r\n1234567890abcdef\r\n0\r\n"); + + for i in 0..max_headers { + scratch.extend(format!("trailer{}: {}\r\n", i, "x".repeat(header_size)).as_bytes()); + } + + scratch.extend(b"\r\n"); + let mut mock_buf = Bytes::from(scratch); + + let mut decoder = Decoder::chunked(None, Some(max_headers * header_size)); + + // ready chunked body + let buf = decoder + .decode_fut(&mut mock_buf) + .await + .unwrap() + .into_data() + .expect("unknown frame type"); + assert_eq!(16, buf.len()); + + // eof read + let err = decoder + .decode_fut(&mut mock_buf) + .await + .expect_err("trailers over limit"); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + } } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -34,6 +34,17 @@ where b.collect().await.map(|c| c.to_bytes()) } +async fn concat_with_trailers<B>(b: B) -> Result<(Bytes, Option<HeaderMap>), B::Error> +where + B: hyper::body::Body, +{ + let collect = b.collect().await?; + let trailers = collect.trailers().cloned(); + let bytes = collect.to_bytes(); + + Ok((bytes, trailers)) +} + async fn tcp_connect(addr: &SocketAddr) -> std::io::Result<TokioIo<TcpStream>> { TcpStream::connect(*addr).await.map(TokioIo::new) } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -122,6 +133,9 @@ macro_rules! test { status: $client_status:ident, headers: { $($response_header_name:expr => $response_header_val:expr,)* }, body: $response_body:expr, + $(trailers: {$( + $response_trailer_name:expr => $response_trailer_val:expr, + )*},)? ) => ( #[test] fn $name() { diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -158,12 +172,23 @@ macro_rules! test { ); )* - let body = rt.block_on(concat(res)) + let (body, _trailers) = rt.block_on(concat_with_trailers(res)) .expect("body concat wait"); let expected_res_body = Option::<&[u8]>::from($response_body) .unwrap_or_default(); assert_eq!(body.as_ref(), expected_res_body); + + $($( + assert_eq!( + _trailers.as_ref().expect("trailers is None") + .get($response_trailer_name) + .expect(concat!("trailer header '", stringify!($response_trailer_name), "'")), + $response_trailer_val, + "trailer '{}'", + stringify!($response_trailer_name), + ); + )*)? } ); ( diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -679,6 +704,94 @@ test! { body: None, } +test! { + name: client_res_body_chunked_with_trailer, + + server: + expected: "GET / HTTP/1.1\r\nte: trailers\r\nhost: {addr}\r\n\r\n", + reply: "\ + HTTP/1.1 200 OK\r\n\ + transfer-encoding: chunked\r\n\ + trailer: chunky-trailer\r\n\ + \r\n\ + 5\r\n\ + hello\r\n\ + 0\r\n\ + chunky-trailer: header data\r\n\ + \r\n\ + ", + + client: + request: { + method: GET, + url: "http://{addr}/", + headers: { + "te" => "trailers", + }, + }, + response: + status: OK, + headers: { + "Transfer-Encoding" => "chunked", + }, + body: &b"hello"[..], + trailers: { + "chunky-trailer" => "header data", + }, +} + +test! { + name: client_res_body_chunked_with_pathological_trailers, + + server: + expected: "GET / HTTP/1.1\r\nte: trailers\r\nhost: {addr}\r\n\r\n", + reply: "\ + HTTP/1.1 200 OK\r\n\ + transfer-encoding: chunked\r\n\ + trailer: chunky-trailer1, chunky-trailer2, chunky-trailer3, chunky-trailer4, chunky-trailer5\r\n\ + \r\n\ + 5\r\n\ + hello\r\n\ + 0\r\n\ + chunky-trailer1: header data1\r\n\ + chunky-trailer2: header data2\r\n\ + chunky-trailer3: header data3\r\n\ + chunky-trailer4: header data4\r\n\ + chunky-trailer5: header data5\r\n\ + sneaky-trailer: not in trailer header\r\n\ + transfer-encoding: chunked\r\n\ + content-length: 5\r\n\ + trailer: foo\r\n\ + \r\n\ + ", + + client: + request: { + method: GET, + url: "http://{addr}/", + headers: { + "te" => "trailers", + }, + }, + response: + status: OK, + headers: { + "Transfer-Encoding" => "chunked", + }, + body: &b"hello"[..], + trailers: { + "chunky-trailer1" => "header data1", + "chunky-trailer2" => "header data2", + "chunky-trailer3" => "header data3", + "chunky-trailer4" => "header data4", + "chunky-trailer5" => "header data5", + "sneaky-trailer" => "not in trailer header", + "transfer-encoding" => "chunked", + "content-length" => "5", + "trailer" => "foo", + }, +} + test! { name: client_get_req_body_sized, diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -2693,7 +2693,7 @@ async fn http2_keep_alive_count_server_pings() { } #[test] -fn http1_trailer_fields() { +fn http1_trailer_send_fields() { let body = futures_util::stream::once(async move { Ok("hello".into()) }); let mut headers = HeaderMap::new(); headers.insert("chunky-trailer", "header data".parse().unwrap()); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -2780,6 +2780,35 @@ fn http1_trailer_fields_not_allowed() { assert_eq!(body, expected_body); } +#[test] +fn http1_trailer_recv_fields() { + let server = serve(); + let mut req = connect(server.addr()); + req.write_all( + b"\ + POST / HTTP/1.1\r\n\ + trailer: chunky-trailer\r\n\ + host: example.domain\r\n\ + transfer-encoding: chunked\r\n\ + \r\n\ + 5\r\n\ + hello\r\n\ + 0\r\n\ + chunky-trailer: header data\r\n\ + \r\n\ + ", + ) + .expect("writing"); + + assert_eq!(server.body(), b"hello"); + + let trailers = server.trailers(); + assert_eq!( + trailers.get("chunky-trailer"), + Some(&"header data".parse().unwrap()) + ); +} + // ------------------------------------------------- // the Server that is used to run all the tests with // ------------------------------------------------- diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -2787,6 +2816,7 @@ fn http1_trailer_fields_not_allowed() { struct Serve { addr: SocketAddr, msg_rx: mpsc::Receiver<Msg>, + trailers_rx: mpsc::Receiver<HeaderMap>, reply_tx: Mutex<spmc::Sender<Reply>>, shutdown_signal: Option<oneshot::Sender<()>>, thread: Option<thread::JoinHandle<()>>, diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -2820,6 +2850,10 @@ impl Serve { Ok(buf) } + fn trailers(&self) -> HeaderMap { + self.trailers_rx.recv().expect("trailers") + } + fn reply(&self) -> ReplyBuilder<'_> { ReplyBuilder { tx: &self.reply_tx } } diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -2933,6 +2967,7 @@ impl Drop for Serve { #[derive(Clone)] struct TestService { tx: mpsc::Sender<Msg>, + trailers_tx: mpsc::Sender<HeaderMap>, reply: spmc::Receiver<Reply>, } diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -2963,6 +2998,7 @@ impl Service<Request<IncomingBody>> for TestService { fn call(&self, mut req: Request<IncomingBody>) -> Self::Future { let tx = self.tx.clone(); + let trailers_tx = self.trailers_tx.clone(); let replies = self.reply.clone(); Box::pin(async move { diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -2972,6 +3008,9 @@ impl Service<Request<IncomingBody>> for TestService { if frame.is_data() { tx.send(Msg::Chunk(frame.into_data().unwrap().to_vec())) .unwrap(); + } else if frame.is_trailers() { + let trailers = frame.into_trailers().unwrap(); + trailers_tx.send(trailers).unwrap(); } } Err(err) => { diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -3100,6 +3139,7 @@ impl ServeOptions { let (addr_tx, addr_rx) = mpsc::channel(); let (msg_tx, msg_rx) = mpsc::channel(); + let (trailers_tx, trailers_rx) = mpsc::channel(); let (reply_tx, reply_rx) = spmc::channel(); let (shutdown_tx, mut shutdown_rx) = oneshot::channel(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -3123,6 +3163,7 @@ impl ServeOptions { loop { let msg_tx = msg_tx.clone(); + let trailers_tx = trailers_tx.clone(); let reply_rx = reply_rx.clone(); tokio::select! { diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -3135,6 +3176,7 @@ impl ServeOptions { let reply_rx = reply_rx.clone(); let service = TestService { tx: msg_tx, + trailers_tx, reply: reply_rx, }; diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -3162,6 +3204,7 @@ impl ServeOptions { Serve { msg_rx, + trailers_rx, reply_tx: Mutex::new(reply_tx), addr, shutdown_signal: Some(shutdown_tx),
hyperium/hyper
aa7ff605da3b706e855f9633b8dddeb9463217d4
[ "3615", "3615" ]
1.2
bc9a86f58f8bd5c35b2bfd7e632ec132280d79ba
diff --git a/src/server/conn/http1.rs b/src/server/conn/http1.rs --- a/src/server/conn/http1.rs +++ b/src/server/conn/http1.rs @@ -482,7 +482,11 @@ where /// This `Connection` should continue to be polled until shutdown /// can finish. pub fn graceful_shutdown(mut self: Pin<&mut Self>) { - Pin::new(self.inner.as_mut().unwrap()).graceful_shutdown() + // Connection (`inner`) is `None` if it was upgraded (and `poll` is `Ready`). + // In that case, we don't need to call `graceful_shutdown`. + if let Some(conn) = self.inner.as_mut() { + Pin::new(conn).graceful_shutdown() + } } }
2024-03-30T11:42:44Z
3,616
Panic on graceful shutdown for http/1 **Version** Encountered with `1.x` **Platform** Doesn't matter **Description** Attempt to call `graceful_shutdown` for H1 connection which is upgraded (=> `Poll::Ready`) leads to panic: ``` panic was raised: panicked at /usr/local/cargo/registry/src/index.crates.io-6f17d22bba15001f/hyper-1.2.0/src/server/conn/http1.rs:483:38: called `Option::unwrap()` on a `None` value ``` The reason is this line: ```rs Pin::new(self.inner.as_mut().unwrap()).graceful_shutdown() ``` When connection is Upgraded (& future is `Ready`), it's `None` https://github.com/hyperium/hyper/blob/bc9a86f58f8bd5c35b2bfd7e632ec132280d79ba/src/server/conn/http1.rs#L502-L506 So we should avoid unwrapping Panic on graceful shutdown for http/1 **Version** Encountered with `1.x` **Platform** Doesn't matter **Description** Attempt to call `graceful_shutdown` for H1 connection which is upgraded (=> `Poll::Ready`) leads to panic: ``` panic was raised: panicked at /usr/local/cargo/registry/src/index.crates.io-6f17d22bba15001f/hyper-1.2.0/src/server/conn/http1.rs:483:38: called `Option::unwrap()` on a `None` value ``` The reason is this line: ```rs Pin::new(self.inner.as_mut().unwrap()).graceful_shutdown() ``` When connection is Upgraded (& future is `Ready`), it's `None` https://github.com/hyperium/hyper/blob/bc9a86f58f8bd5c35b2bfd7e632ec132280d79ba/src/server/conn/http1.rs#L502-L506 So we should avoid unwrapping
hyperium__hyper-3616
diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1256,6 +1256,67 @@ async fn disable_keep_alive_post_request() { child.join().unwrap(); } +#[tokio::test] +async fn http1_graceful_shutdown_after_upgrade() { + let (listener, addr) = setup_tcp_listener(); + let (read_101_tx, read_101_rx) = oneshot::channel(); + + thread::spawn(move || { + let mut tcp = connect(&addr); + tcp.write_all( + b"\ + GET / HTTP/1.1\r\n\ + Upgrade: foobar\r\n\ + Connection: upgrade\r\n\ + \r\n\ + eagerly optimistic\ + ", + ) + .expect("write 1"); + let mut buf = [0; 256]; + tcp.read(&mut buf).expect("read 1"); + + let response = s(&buf); + assert!(response.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); + assert!(!has_header(&response, "content-length")); + let _ = read_101_tx.send(()); + }); + + let (upgrades_tx, upgrades_rx) = mpsc::channel(); + let svc = service_fn(move |req: Request<IncomingBody>| { + let on_upgrade = hyper::upgrade::on(req); + let _ = upgrades_tx.send(on_upgrade); + future::ok::<_, hyper::Error>( + Response::builder() + .status(101) + .header("upgrade", "foobar") + .body(Empty::<Bytes>::new()) + .unwrap(), + ) + }); + + let (socket, _) = listener.accept().await.unwrap(); + let socket = TokioIo::new(socket); + + let mut conn = http1::Builder::new() + .serve_connection(socket, svc) + .with_upgrades(); + (&mut conn).await.unwrap(); + + let on_upgrade = upgrades_rx.recv().unwrap(); + + // wait so that we don't write until other side saw 101 response + read_101_rx.await.unwrap(); + + let upgraded = on_upgrade.await.expect("on_upgrade"); + let parts = upgraded.downcast::<TokioIo<TkTcpStream>>().unwrap(); + assert_eq!(parts.read_buf, "eagerly optimistic"); + + pin!(conn); + // graceful shutdown doesn't cause issues or panic. It should be ignored after upgrade + conn.as_mut().graceful_shutdown(); +} + #[tokio::test] async fn empty_parse_eof_does_not_return_error() { let (listener, addr) = setup_tcp_listener();
hyperium/hyper
bc9a86f58f8bd5c35b2bfd7e632ec132280d79ba
[ "3477" ]
1.1
a9fa893f18c6409abae2e1dcbba0f4487df54d4f
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -41,6 +41,8 @@ want = { version = "0.3", optional = true } [dev-dependencies] form_urlencoded = "1" +futures-channel = { version = "0.3", features = ["sink"] } +futures-util = { version = "0.3", default-features = false, features = ["sink"] } http-body-util = "0.1" pretty_env_logger = "0.5" spmc = "0.3" diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -294,7 +291,7 @@ impl Opts { .build() .expect("rt build"), ); - //let exec = rt.clone(); + let exec = rt.clone(); let req_len = self.request_body.map(|b| b.len()).unwrap_or(0) as u64; let req_len = if self.request_chunks > 0 { diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -344,19 +341,21 @@ impl Opts { let make_request = || { let chunk_cnt = self.request_chunks; let body = if chunk_cnt > 0 { - /* - let (mut tx, body) = Body::channel(); + let (mut tx, rx) = futures_channel::mpsc::channel(0); + let chunk = self .request_body .expect("request_chunks means request_body"); exec.spawn(async move { + use futures_util::SinkExt; + use hyper::body::Frame; for _ in 0..chunk_cnt { - tx.send_data(chunk.into()).await.expect("send_data"); + tx.send(Ok(Frame::data(bytes::Bytes::from(chunk)))) + .await + .expect("send_data"); } }); - body - */ - todo!("request_chunks"); + http_body_util::StreamBody::new(rx).boxed() } else if let Some(chunk) = self.request_body { http_body_util::Full::new(bytes::Bytes::from(chunk)).boxed() } else {
Can I take this one?
2024-01-08T16:38:08Z
3,517
Re-enable end-to-end request chunks benchmarks The request chunks benchmarks were disabled as part of the upgrade to v1.0. It should now be easier to re-enable them. - Update the [code](https://github.com/hyperium/hyper/blob/d3cfb9e0b1928701cfdd96c9551c4bd81c24e83a/benches/end_to_end.rs#L347-L358) to use an async `mpsc` channel, and wrap it in a `http_body_util::StreamBody`. - Remove `#[ignore]` from the benchmarks that were using chunks.
hyperium__hyper-3517
diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -140,7 +140,6 @@ fn http2_parallel_x10_req_10mb(b: &mut test::Bencher) { } #[bench] -#[ignore] fn http2_parallel_x10_req_10kb_100_chunks(b: &mut test::Bencher) { let body = &[b'x'; 1024 * 10]; opts() diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -152,7 +151,6 @@ fn http2_parallel_x10_req_10kb_100_chunks(b: &mut test::Bencher) { } #[bench] -#[ignore] fn http2_parallel_x10_req_10kb_100_chunks_adaptive_window(b: &mut test::Bencher) { let body = &[b'x'; 1024 * 10]; opts() diff --git a/benches/end_to_end.rs b/benches/end_to_end.rs --- a/benches/end_to_end.rs +++ b/benches/end_to_end.rs @@ -165,7 +163,6 @@ fn http2_parallel_x10_req_10kb_100_chunks_adaptive_window(b: &mut test::Bencher) } #[bench] -#[ignore] fn http2_parallel_x10_req_10kb_100_chunks_max_window(b: &mut test::Bencher) { let body = &[b'x'; 1024 * 10]; opts() diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -342,7 +342,7 @@ mod tests { use super::{channel, Callback, Receiver}; #[derive(Debug)] - struct Custom(i32); + struct Custom(#[allow(dead_code)] i32); impl<T, U> Future for Receiver<T, U> { type Output = Option<(T, Callback<T, U>)>;
hyperium/hyper
a9fa893f18c6409abae2e1dcbba0f4487df54d4f
[ "2719" ]
0.3
6fd696e10974f10b2c6b9d16393bbbfa21c2333f
diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -8,7 +8,7 @@ use std::time::Duration; use crate::rt::{Read, Write}; use bytes::{Buf, Bytes}; -use http::header::{HeaderValue, CONNECTION}; +use http::header::{HeaderValue, CONNECTION, TE}; use http::{HeaderMap, Method, Version}; use httparse::ParserConfig; diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -75,6 +75,7 @@ where // We assume a modern world where the remote speaks HTTP/1.1. // If they tell us otherwise, we'll downgrade in `read_head`. version: Version::HTTP_11, + allow_trailer_fields: false, }, _marker: PhantomData, } diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -264,6 +265,13 @@ where self.state.reading = Reading::Body(Decoder::new(msg.decode)); } + self.state.allow_trailer_fields = msg + .head + .headers + .get(TE) + .map(|te_header| te_header == "trailers") + .unwrap_or(false); + Poll::Ready(Some(Ok((msg.head, msg.decode, wants)))) } diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -640,6 +648,31 @@ where self.state.writing = state; } + pub(crate) fn write_trailers(&mut self, trailers: HeaderMap) { + if T::is_server() && self.state.allow_trailer_fields == false { + debug!("trailers not allowed to be sent"); + return; + } + debug_assert!(self.can_write_body() && self.can_buffer_body()); + + match self.state.writing { + Writing::Body(ref encoder) => { + if let Some(enc_buf) = + encoder.encode_trailers(trailers, self.state.title_case_headers) + { + self.io.buffer(enc_buf); + + self.state.writing = if encoder.is_last() || encoder.is_close_delimited() { + Writing::Closed + } else { + Writing::KeepAlive + }; + } + } + _ => unreachable!("write_trailers invalid state: {:?}", self.state.writing), + } + } + pub(crate) fn write_body_and_end(&mut self, chunk: B) { debug_assert!(self.can_write_body() && self.can_buffer_body()); // empty chunks should be discarded at Dispatcher level diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -842,6 +875,8 @@ struct State { upgrade: Option<crate::upgrade::Pending>, /// Either HTTP/1.0 or 1.1 connection version: Version, + /// Flag to track if trailer fields are allowed to be sent + allow_trailer_fields: bool, } #[derive(Debug)] diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -351,27 +351,33 @@ where *clear_body = true; crate::Error::new_user_body(e) })?; - let chunk = if let Ok(data) = frame.into_data() { - data - } else { - trace!("discarding non-data frame"); - continue; - }; - let eos = body.is_end_stream(); - if eos { - *clear_body = true; - if chunk.remaining() == 0 { - trace!("discarding empty chunk"); - self.conn.end_body()?; + + if frame.is_data() { + let chunk = frame.into_data().unwrap_or_else(|_| unreachable!()); + let eos = body.is_end_stream(); + if eos { + *clear_body = true; + if chunk.remaining() == 0 { + trace!("discarding empty chunk"); + self.conn.end_body()?; + } else { + self.conn.write_body_and_end(chunk); + } } else { - self.conn.write_body_and_end(chunk); + if chunk.remaining() == 0 { + trace!("discarding empty chunk"); + continue; + } + self.conn.write_body(chunk); } + } else if frame.is_trailers() { + *clear_body = true; + self.conn.write_trailers( + frame.into_trailers().unwrap_or_else(|_| unreachable!()), + ); } else { - if chunk.remaining() == 0 { - trace!("discarding empty chunk"); - continue; - } - self.conn.write_body(chunk); + trace!("discarding unknown frame"); + continue; } } else { *clear_body = true; diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -1,10 +1,19 @@ +use std::collections::HashMap; use std::fmt; use std::io::IoSlice; use bytes::buf::{Chain, Take}; -use bytes::Buf; +use bytes::{Buf, Bytes}; +use http::{ + header::{ + AUTHORIZATION, CACHE_CONTROL, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_RANGE, + CONTENT_TYPE, HOST, MAX_FORWARDS, SET_COOKIE, TE, TRAILER, TRANSFER_ENCODING, + }, + HeaderMap, HeaderName, HeaderValue, +}; use super::io::WriteBuf; +use super::role::{write_headers, write_headers_title_case}; type StaticBuf = &'static [u8]; diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -26,7 +35,7 @@ pub(crate) struct NotEof(u64); #[derive(Debug, PartialEq, Clone)] enum Kind { /// An Encoder for when Transfer-Encoding includes `chunked`. - Chunked, + Chunked(Option<Vec<HeaderValue>>), /// An Encoder for when Content-Length is set. /// /// Enforces that the body is not longer than the Content-Length header. diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -45,6 +54,7 @@ enum BufKind<B> { Limited(Take<B>), Chunked(Chain<Chain<ChunkSize, B>, StaticBuf>), ChunkedEnd(StaticBuf), + Trailers(Chain<Chain<StaticBuf, Bytes>, StaticBuf>), } impl Encoder { diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -55,7 +65,7 @@ impl Encoder { } } pub(crate) fn chunked() -> Encoder { - Encoder::new(Kind::Chunked) + Encoder::new(Kind::Chunked(None)) } pub(crate) fn length(len: u64) -> Encoder { diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -67,6 +77,16 @@ impl Encoder { Encoder::new(Kind::CloseDelimited) } + pub(crate) fn into_chunked_with_trailing_fields(self, trailers: Vec<HeaderValue>) -> Encoder { + match self.kind { + Kind::Chunked(_) => Encoder { + kind: Kind::Chunked(Some(trailers)), + is_last: self.is_last, + }, + _ => self, + } + } + pub(crate) fn is_eof(&self) -> bool { matches!(self.kind, Kind::Length(0)) } diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -89,10 +109,17 @@ impl Encoder { } } + pub(crate) fn is_chunked(&self) -> bool { + match self.kind { + Kind::Chunked(_) => true, + _ => false, + } + } + pub(crate) fn end<B>(&self) -> Result<Option<EncodedBuf<B>>, NotEof> { match self.kind { Kind::Length(0) => Ok(None), - Kind::Chunked => Ok(Some(EncodedBuf { + Kind::Chunked(_) => Ok(Some(EncodedBuf { kind: BufKind::ChunkedEnd(b"0\r\n\r\n"), })), #[cfg(feature = "server")] diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -109,7 +136,7 @@ impl Encoder { debug_assert!(len > 0, "encode() called with empty buf"); let kind = match self.kind { - Kind::Chunked => { + Kind::Chunked(_) => { trace!("encoding chunked {}B", len); let buf = ChunkSize::new(len) .chain(msg) diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -136,6 +163,53 @@ impl Encoder { EncodedBuf { kind } } + pub(crate) fn encode_trailers<B>( + &self, + trailers: HeaderMap, + title_case_headers: bool, + ) -> Option<EncodedBuf<B>> { + match &self.kind { + Kind::Chunked(Some(ref allowed_trailer_fields)) => { + let allowed_trailer_field_map = allowed_trailer_field_map(&allowed_trailer_fields); + + let mut cur_name = None; + let mut allowed_trailers = HeaderMap::new(); + + for (opt_name, value) in trailers { + if let Some(n) = opt_name { + cur_name = Some(n); + } + let name = cur_name.as_ref().expect("current header name"); + + if allowed_trailer_field_map.contains_key(name.as_str()) + && valid_trailer_field(name) + { + allowed_trailers.insert(name, value); + } + } + + let mut buf = Vec::new(); + if title_case_headers { + write_headers_title_case(&allowed_trailers, &mut buf); + } else { + write_headers(&allowed_trailers, &mut buf); + } + + if buf.is_empty() { + return None; + } + + Some(EncodedBuf { + kind: BufKind::Trailers(b"0\r\n".chain(Bytes::from(buf)).chain(b"\r\n")), + }) + } + _ => { + debug!("attempted to encode trailers for non-chunked response"); + None + } + } + } + pub(super) fn encode_and_end<B>(&self, msg: B, dst: &mut WriteBuf<EncodedBuf<B>>) -> bool where B: Buf, diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -144,7 +218,7 @@ impl Encoder { debug_assert!(len > 0, "encode() called with empty buf"); match self.kind { - Kind::Chunked => { + Kind::Chunked(_) => { trace!("encoding chunked {}B", len); let buf = ChunkSize::new(len) .chain(msg) diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -181,6 +255,40 @@ impl Encoder { } } +fn valid_trailer_field(name: &HeaderName) -> bool { + match name { + &AUTHORIZATION => false, + &CACHE_CONTROL => false, + &CONTENT_ENCODING => false, + &CONTENT_LENGTH => false, + &CONTENT_RANGE => false, + &CONTENT_TYPE => false, + &HOST => false, + &MAX_FORWARDS => false, + &SET_COOKIE => false, + &TRAILER => false, + &TRANSFER_ENCODING => false, + &TE => false, + _ => true, + } +} + +fn allowed_trailer_field_map(allowed_trailer_fields: &Vec<HeaderValue>) -> HashMap<String, ()> { + let mut trailer_map = HashMap::new(); + + for header_value in allowed_trailer_fields { + if let Ok(header_str) = header_value.to_str() { + let items: Vec<&str> = header_str.split(',').map(|item| item.trim()).collect(); + + for item in items { + trailer_map.entry(item.to_string()).or_insert(()); + } + } + } + + trailer_map +} + impl<B> Buf for EncodedBuf<B> where B: Buf, diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -192,6 +300,7 @@ where BufKind::Limited(ref b) => b.remaining(), BufKind::Chunked(ref b) => b.remaining(), BufKind::ChunkedEnd(ref b) => b.remaining(), + BufKind::Trailers(ref b) => b.remaining(), } } diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -202,6 +311,7 @@ where BufKind::Limited(ref b) => b.chunk(), BufKind::Chunked(ref b) => b.chunk(), BufKind::ChunkedEnd(ref b) => b.chunk(), + BufKind::Trailers(ref b) => b.chunk(), } } diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -212,6 +322,7 @@ where BufKind::Limited(ref mut b) => b.advance(cnt), BufKind::Chunked(ref mut b) => b.advance(cnt), BufKind::ChunkedEnd(ref mut b) => b.advance(cnt), + BufKind::Trailers(ref mut b) => b.advance(cnt), } } diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -222,6 +333,7 @@ where BufKind::Limited(ref b) => b.chunks_vectored(dst), BufKind::Chunked(ref b) => b.chunks_vectored(dst), BufKind::ChunkedEnd(ref b) => b.chunks_vectored(dst), + BufKind::Trailers(ref b) => b.chunks_vectored(dst), } } } diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -629,6 +629,7 @@ impl Server { }; let mut encoder = Encoder::length(0); + let mut allowed_trailer_fields: Option<Vec<HeaderValue>> = None; let mut wrote_date = false; let mut cur_name = None; let mut is_name_written = false; diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -815,6 +816,38 @@ impl Server { header::DATE => { wrote_date = true; } + header::TRAILER => { + // check that we actually can send a chunked body... + if msg.head.version == Version::HTTP_10 + || !Server::can_chunked(msg.req_method, msg.head.subject) + { + continue; + } + + if !is_name_written { + is_name_written = true; + header_name_writer.write_header_name_with_colon( + dst, + "trailer: ", + header::TRAILER, + ); + extend(dst, value.as_bytes()); + } else { + extend(dst, b", "); + extend(dst, value.as_bytes()); + } + + match allowed_trailer_fields { + Some(ref mut allowed_trailer_fields) => { + allowed_trailer_fields.push(value); + } + None => { + allowed_trailer_fields = Some(vec![value]); + } + } + + continue 'headers; + } _ => (), } //TODO: this should perhaps instead combine them into diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -899,6 +932,12 @@ impl Server { extend(dst, b"\r\n"); } + if encoder.is_chunked() { + if let Some(allowed_trailer_fields) = allowed_trailer_fields { + encoder = encoder.into_chunked_with_trailing_fields(allowed_trailer_fields); + } + } + Ok(encoder.set_last(is_last)) } } diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1306,6 +1345,19 @@ impl Client { } }; + let encoder = encoder.map(|enc| { + if enc.is_chunked() { + let allowed_trailer_fields: Vec<HeaderValue> = + headers.get_all(header::TRAILER).iter().cloned().collect(); + + if !allowed_trailer_fields.is_empty() { + return enc.into_chunked_with_trailing_fields(allowed_trailer_fields); + } + } + + enc + }); + // This is because we need a second mutable borrow to remove // content-length header. if let Some(encoder) = encoder { diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1468,8 +1520,7 @@ fn title_case(dst: &mut Vec<u8>, name: &[u8]) { } } -#[cfg(feature = "client")] -fn write_headers_title_case(headers: &HeaderMap, dst: &mut Vec<u8>) { +pub(crate) fn write_headers_title_case(headers: &HeaderMap, dst: &mut Vec<u8>) { for (name, value) in headers { title_case(dst, name.as_str().as_bytes()); extend(dst, b": "); diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1478,8 +1529,7 @@ fn write_headers_title_case(headers: &HeaderMap, dst: &mut Vec<u8>) { } } -#[cfg(feature = "client")] -fn write_headers(headers: &HeaderMap, dst: &mut Vec<u8>) { +pub(crate) fn write_headers(headers: &HeaderMap, dst: &mut Vec<u8>) { for (name, value) in headers { extend(dst, name.as_str().as_bytes()); extend(dst, b": ");
@Xuanwo I've updated the issue above to include a list of things I think that needs to be done. If anything is missing, we can add more instructions here!
2023-10-26T10:31:05Z
3,375
Sending HTTP/1.1 trailers Here's a list of pieces needed to make this work: - Update [`proto::h1::Dispatcher::poll_write()`](https://github.com/hyperium/hyper/blob/f1b89c117cffebed4b2b8eb2d221fd9b25c1d3d1/src/proto/h1/dispatch.rs#L365) so that when all data items are done (is `None`), check the body for trails `poll_trailers`. - It might be we want to add some state to the dispatcher like `Wants::TRAILERS`, if we received a request with `TE: trailers`. This could be useful to skip checking for trailers if the request never said it supports them. - It's likely that new state will need to be added, in case the data is done, but polling the trailers is `Pending`. - Add `proto::h1::Conn::write_trailers()` [after `write_body()`](https://github.com/hyperium/hyper/blob/f1b89c117cffebed4b2b8eb2d221fd9b25c1d3d1/src/proto/h1/conn.rs#L626). The dispatcher would call this. - Add [`proto::h1::Encoder::encode_trailers()`](https://github.com/hyperium/hyper/blob/f1b89c117cffebed4b2b8eb2d221fd9b25c1d3d1/src/proto/h1/encode.rs#L51) that flattens the `HeaderMap` into a `Buf`. - A few unit tests for encoding trailers in the `encode` file. - A couple tests, at least one in each of `tests/client.rs` and `tests/server.rs` that both sides can send trailers.
hyperium__hyper-3375
diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -327,7 +439,16 @@ impl std::error::Error for NotEof {} #[cfg(test)] mod tests { + use std::iter::FromIterator; + use bytes::BufMut; + use http::{ + header::{ + AUTHORIZATION, CACHE_CONTROL, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_RANGE, + CONTENT_TYPE, HOST, MAX_FORWARDS, SET_COOKIE, TE, TRAILER, TRANSFER_ENCODING, + }, + HeaderMap, HeaderName, HeaderValue, + }; use super::super::io::Cursor; use super::Encoder; diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -402,4 +523,145 @@ mod tests { assert!(!encoder.is_eof()); encoder.end::<()>().unwrap(); } + + #[test] + fn chunked_with_valid_trailers() { + let encoder = Encoder::chunked(); + let trailers = vec![HeaderValue::from_static("chunky-trailer")]; + let encoder = encoder.into_chunked_with_trailing_fields(trailers); + + let headers = HeaderMap::from_iter( + vec![ + ( + HeaderName::from_static("chunky-trailer"), + HeaderValue::from_static("header data"), + ), + ( + HeaderName::from_static("should-not-be-included"), + HeaderValue::from_static("oops"), + ), + ] + .into_iter(), + ); + + let buf1 = encoder.encode_trailers::<&[u8]>(headers, false).unwrap(); + + let mut dst = Vec::new(); + dst.put(buf1); + assert_eq!(dst, b"0\r\nchunky-trailer: header data\r\n\r\n"); + } + + #[test] + fn chunked_with_multiple_trailer_headers() { + let encoder = Encoder::chunked(); + let trailers = vec![ + HeaderValue::from_static("chunky-trailer"), + HeaderValue::from_static("chunky-trailer-2"), + ]; + let encoder = encoder.into_chunked_with_trailing_fields(trailers); + + let headers = HeaderMap::from_iter( + vec![ + ( + HeaderName::from_static("chunky-trailer"), + HeaderValue::from_static("header data"), + ), + ( + HeaderName::from_static("chunky-trailer-2"), + HeaderValue::from_static("more header data"), + ), + ] + .into_iter(), + ); + + let buf1 = encoder.encode_trailers::<&[u8]>(headers, false).unwrap(); + + let mut dst = Vec::new(); + dst.put(buf1); + assert_eq!( + dst, + b"0\r\nchunky-trailer: header data\r\nchunky-trailer-2: more header data\r\n\r\n" + ); + } + + #[test] + fn chunked_with_no_trailer_header() { + let encoder = Encoder::chunked(); + + let headers = HeaderMap::from_iter( + vec![( + HeaderName::from_static("chunky-trailer"), + HeaderValue::from_static("header data"), + )] + .into_iter(), + ); + + assert!(encoder + .encode_trailers::<&[u8]>(headers.clone(), false) + .is_none()); + + let trailers = vec![]; + let encoder = encoder.into_chunked_with_trailing_fields(trailers); + + assert!(encoder.encode_trailers::<&[u8]>(headers, false).is_none()); + } + + #[test] + fn chunked_with_invalid_trailers() { + let encoder = Encoder::chunked(); + + let trailers = format!( + "{},{},{},{},{},{},{},{},{},{},{},{}", + AUTHORIZATION, + CACHE_CONTROL, + CONTENT_ENCODING, + CONTENT_LENGTH, + CONTENT_RANGE, + CONTENT_TYPE, + HOST, + MAX_FORWARDS, + SET_COOKIE, + TRAILER, + TRANSFER_ENCODING, + TE, + ); + let trailers = vec![HeaderValue::from_str(&trailers).unwrap()]; + let encoder = encoder.into_chunked_with_trailing_fields(trailers); + + let mut headers = HeaderMap::new(); + headers.insert(AUTHORIZATION, HeaderValue::from_static("header data")); + headers.insert(CACHE_CONTROL, HeaderValue::from_static("header data")); + headers.insert(CONTENT_ENCODING, HeaderValue::from_static("header data")); + headers.insert(CONTENT_LENGTH, HeaderValue::from_static("header data")); + headers.insert(CONTENT_RANGE, HeaderValue::from_static("header data")); + headers.insert(CONTENT_TYPE, HeaderValue::from_static("header data")); + headers.insert(HOST, HeaderValue::from_static("header data")); + headers.insert(MAX_FORWARDS, HeaderValue::from_static("header data")); + headers.insert(SET_COOKIE, HeaderValue::from_static("header data")); + headers.insert(TRAILER, HeaderValue::from_static("header data")); + headers.insert(TRANSFER_ENCODING, HeaderValue::from_static("header data")); + headers.insert(TE, HeaderValue::from_static("header data")); + + assert!(encoder.encode_trailers::<&[u8]>(headers, true).is_none()); + } + + #[test] + fn chunked_with_title_case_headers() { + let encoder = Encoder::chunked(); + let trailers = vec![HeaderValue::from_static("chunky-trailer")]; + let encoder = encoder.into_chunked_with_trailing_fields(trailers); + + let headers = HeaderMap::from_iter( + vec![( + HeaderName::from_static("chunky-trailer"), + HeaderValue::from_static("header data"), + )] + .into_iter(), + ); + let buf1 = encoder.encode_trailers::<&[u8]>(headers, true).unwrap(); + + let mut dst = Vec::new(); + dst.put(buf1); + assert_eq!(dst, b"0\r\nChunky-Trailer: header data\r\n\r\n"); + } } diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -5,6 +5,7 @@ use std::convert::Infallible; use std::fmt; use std::future::Future; use std::io::{Read, Write}; +use std::iter::FromIterator; use std::net::{SocketAddr, TcpListener}; use std::pin::Pin; use std::thread; diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -13,7 +14,7 @@ use std::time::Duration; use http::uri::PathAndQuery; use http_body_util::{BodyExt, StreamBody}; use hyper::body::Frame; -use hyper::header::HeaderValue; +use hyper::header::{HeaderMap, HeaderName, HeaderValue}; use hyper::{Method, Request, StatusCode, Uri, Version}; use bytes::Bytes; diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -408,6 +409,15 @@ macro_rules! __client_req_prop { Frame::data, ))); }}; + + ($req_builder:ident, $body:ident, $addr:ident, body_stream_with_trailers: $body_e:expr) => {{ + use support::trailers::StreamBodyWithTrailers; + let (body, trailers) = $body_e; + $body = BodyExt::boxed(StreamBodyWithTrailers::with_trailers( + futures_util::TryStreamExt::map_ok(body, Frame::data), + trailers, + )); + }}; } macro_rules! __client_req_header { diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -631,6 +641,44 @@ test! { body: &b"hello"[..], } +test! { + name: client_post_req_body_chunked_with_trailer, + + server: + expected: "\ + POST / HTTP/1.1\r\n\ + trailer: chunky-trailer\r\n\ + host: {addr}\r\n\ + transfer-encoding: chunked\r\n\ + \r\n\ + 5\r\n\ + hello\r\n\ + 0\r\n\ + chunky-trailer: header data\r\n\ + \r\n\ + ", + reply: REPLY_OK, + + client: + request: { + method: POST, + url: "http://{addr}/", + headers: { + "trailer" => "chunky-trailer", + }, + body_stream_with_trailers: ( + (futures_util::stream::once(async { Ok::<_, Infallible>(Bytes::from("hello"))})), + HeaderMap::from_iter(vec![( + HeaderName::from_static("chunky-trailer"), + HeaderValue::from_static("header data") + )].into_iter())), + }, + response: + status: OK, + headers: {}, + body: None, +} + test! { name: client_get_req_body_sized, diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -19,7 +19,7 @@ use futures_channel::oneshot; use futures_util::future::{self, Either, FutureExt}; use h2::client::SendRequest; use h2::{RecvStream, SendStream}; -use http::header::{HeaderName, HeaderValue}; +use http::header::{HeaderMap, HeaderName, HeaderValue}; use http_body_util::{combinators::BoxBody, BodyExt, Empty, Full, StreamBody}; use hyper::rt::Timer; use hyper::rt::{Read as AsyncRead, Write as AsyncWrite}; diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -2595,6 +2595,94 @@ async fn http2_keep_alive_count_server_pings() { .expect("timed out waiting for pings"); } +#[test] +fn http1_trailer_fields() { + let body = futures_util::stream::once(async move { Ok("hello".into()) }); + let mut headers = HeaderMap::new(); + headers.insert("chunky-trailer", "header data".parse().unwrap()); + // Invalid trailer field that should not be sent + headers.insert("Host", "www.example.com".parse().unwrap()); + // Not specified in Trailer header, so should not be sent + headers.insert("foo", "bar".parse().unwrap()); + + let server = serve(); + server + .reply() + .header("transfer-encoding", "chunked") + .header("trailer", "chunky-trailer") + .body_stream_with_trailers(body, headers); + let mut req = connect(server.addr()); + req.write_all( + b"\ + GET / HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Connection: keep-alive\r\n\ + TE: trailers\r\n\ + \r\n\ + ", + ) + .expect("writing"); + + let chunky_trailer_chunk = b"\r\nchunky-trailer: header data\r\n\r\n"; + let res = read_until(&mut req, |buf| buf.ends_with(chunky_trailer_chunk)).expect("reading"); + let sres = s(&res); + + let expected_head = + "HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\ntrailer: chunky-trailer\r\n"; + assert_eq!(&sres[..expected_head.len()], expected_head); + + // skip the date header + let date_fragment = "GMT\r\n\r\n"; + let pos = sres.find(date_fragment).expect("find GMT"); + let body = &sres[pos + date_fragment.len()..]; + + let expected_body = "5\r\nhello\r\n0\r\nchunky-trailer: header data\r\n\r\n"; + assert_eq!(body, expected_body); +} + +#[test] +fn http1_trailer_fields_not_allowed() { + let body = futures_util::stream::once(async move { Ok("hello".into()) }); + let mut headers = HeaderMap::new(); + headers.insert("chunky-trailer", "header data".parse().unwrap()); + + let server = serve(); + server + .reply() + .header("transfer-encoding", "chunked") + .header("trailer", "chunky-trailer") + .body_stream_with_trailers(body, headers); + let mut req = connect(server.addr()); + + // TE: trailers is not specified in request headers + req.write_all( + b"\ + GET / HTTP/1.1\r\n\ + Host: example.domain\r\n\ + Connection: keep-alive\r\n\ + \r\n\ + ", + ) + .expect("writing"); + + let last_chunk = b"\r\n0\r\n\r\n"; + let res = read_until(&mut req, |buf| buf.ends_with(last_chunk)).expect("reading"); + let sres = s(&res); + + let expected_head = + "HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\ntrailer: chunky-trailer\r\n"; + assert_eq!(&sres[..expected_head.len()], expected_head); + + // skip the date header + let date_fragment = "GMT\r\n\r\n"; + let pos = sres.find(date_fragment).expect("find GMT"); + let body = &sres[pos + date_fragment.len()..]; + + // no trailer fields should be sent because TE: trailers was not in request headers + let expected_body = "5\r\nhello\r\n0\r\n\r\n"; + assert_eq!(body, expected_body); +} + // ------------------------------------------------- // the Server that is used to run all the tests with // ------------------------------------------------- diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -2700,6 +2788,19 @@ impl<'a> ReplyBuilder<'a> { self.tx.lock().unwrap().send(Reply::Body(body)).unwrap(); } + fn body_stream_with_trailers<S>(self, stream: S, trailers: HeaderMap) + where + S: futures_util::Stream<Item = Result<Bytes, BoxError>> + Send + Sync + 'static, + { + use futures_util::TryStreamExt; + use hyper::body::Frame; + use support::trailers::StreamBodyWithTrailers; + let mut stream_body = StreamBodyWithTrailers::new(stream.map_ok(Frame::data)); + stream_body.set_trailers(trailers); + let body = BodyExt::boxed(stream_body); + self.tx.lock().unwrap().send(Reply::Body(body)).unwrap(); + } + #[allow(dead_code)] fn error<E: Into<BoxError>>(self, err: E) { self.tx diff --git a/tests/support/mod.rs b/tests/support/mod.rs --- a/tests/support/mod.rs +++ b/tests/support/mod.rs @@ -24,6 +24,8 @@ mod tokiort; #[allow(unused)] pub use tokiort::{TokioExecutor, TokioIo, TokioTimer}; +pub mod trailers; + #[allow(unused_macros)] macro_rules! t { ( diff --git /dev/null b/tests/support/trailers.rs new file mode 100644 --- /dev/null +++ b/tests/support/trailers.rs @@ -0,0 +1,76 @@ +use bytes::Buf; +use futures_util::stream::Stream; +use http::header::HeaderMap; +use http_body::{Body, Frame}; +use pin_project_lite::pin_project; +use std::{ + pin::Pin, + task::{Context, Poll}, +}; + +pin_project! { + /// A body created from a [`Stream`]. + #[derive(Clone, Debug)] + pub struct StreamBodyWithTrailers<S> { + #[pin] + stream: S, + trailers: Option<HeaderMap>, + } +} + +impl<S> StreamBodyWithTrailers<S> { + /// Create a new `StreamBodyWithTrailers`. + pub fn new(stream: S) -> Self { + Self { + stream, + trailers: None, + } + } + + pub fn with_trailers(stream: S, trailers: HeaderMap) -> Self { + Self { + stream, + trailers: Some(trailers), + } + } + + pub fn set_trailers(&mut self, trailers: HeaderMap) { + self.trailers = Some(trailers); + } +} + +impl<S, D, E> Body for StreamBodyWithTrailers<S> +where + S: Stream<Item = Result<Frame<D>, E>>, + D: Buf, +{ + type Data = D; + type Error = E; + + fn poll_frame( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> { + let project = self.project(); + match project.stream.poll_next(cx) { + Poll::Ready(Some(result)) => Poll::Ready(Some(result)), + Poll::Ready(None) => match project.trailers.take() { + Some(trailers) => Poll::Ready(Some(Ok(Frame::trailers(trailers)))), + None => Poll::Ready(None), + }, + Poll::Pending => Poll::Pending, + } + } +} + +impl<S: Stream> Stream for StreamBodyWithTrailers<S> { + type Item = S::Item; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { + self.project().stream.poll_next(cx) + } + + fn size_hint(&self) -> (usize, Option<usize>) { + self.stream.size_hint() + } +}
hyperium/hyper
6fd696e10974f10b2c6b9d16393bbbfa21c2333f
[ "2844" ]
0.3
0891c9e3084453f4ff239c5059f3dddcbe25f1fb
diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -8,6 +8,18 @@ pub type Result<T> = std::result::Result<T, Error>; type Cause = Box<dyn StdError + Send + Sync>; /// Represents errors that can occur handling HTTP streams. +/// +/// # Formatting +/// +/// The `Display` implementation of this type will only print the details of +/// this level of error, even though it may have been caused by another error +/// and contain that error in its source. To print all the relevant +/// information, including the source chain, using something like +/// `std::error::Report`, or equivalent 3rd party types. +/// +/// The contents of the formatted error message of this specific `Error` type +/// is unspecified. **You must not depend on it.** The wording and details may +/// change in any version, with the goal of improving error messages. pub struct Error { inner: Box<ErrorImpl>, } diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -170,11 +182,6 @@ impl Error { self.find_source::<TimedOut>().is_some() } - /// Consumes the error, returning its cause. - pub fn into_cause(self) -> Option<Box<dyn StdError + Send + Sync>> { - self.inner.cause - } - pub(super) fn new(kind: Kind) -> Error { Error { inner: Box::new(ErrorImpl { kind, cause: None }), diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -324,11 +331,6 @@ impl Error { } } - /// The error's standalone message, without the message from the source. - pub fn message(&self) -> impl fmt::Display + '_ { - self.description() - } - fn description(&self) -> &str { match self.inner.kind { Kind::Parse(Parse::Method) => "invalid HTTP method parsed", diff --git a/src/error.rs b/src/error.rs --- a/src/error.rs +++ b/src/error.rs @@ -410,11 +412,7 @@ impl fmt::Debug for Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - if let Some(ref cause) = self.inner.cause { - write!(f, "{}: {}", self.description(), cause) - } else { - f.write_str(self.description()) - } + f.write_str(self.description()) } }
I filed a proposal for the working group: https://github.com/rust-lang/project-error-handling/issues/53
2023-09-11T20:09:02Z
3,312
Figure out hyper::Error Display including source chain The current `Display` output of `Error` [doesn't match what many people think it should](https://github.com/hyperium/hyper/blob/master/docs/ROADMAP.md#errors), namely that it prints the error chain. We need to either: - Change `hyper::Error` to not print the source as well. - Influence the errors-wg to allow printing the chain in `Display`, like proposed in https://github.com/seanmonstar/errors/issues/1.
hyperium__hyper-3312
diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -2318,10 +2318,6 @@ mod conn { let error = client.send_request(req).await.unwrap_err(); assert!(error.is_user()); - assert_eq!( - error.to_string(), - "dispatch task is gone: user code panicked" - ); } async fn drain_til_eof<T: tokio::io::AsyncRead + Unpin>(mut sock: T) -> io::Result<()> { diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -523,6 +523,7 @@ fn post_with_chunked_body() { #[test] fn post_with_chunked_overflow() { + use std::error::Error as _; let server = serve(); let mut req = connect(server.addr()); req.write_all( diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -542,7 +543,7 @@ fn post_with_chunked_overflow() { .unwrap(); req.read(&mut [0; 256]).unwrap(); - let err = server.body_err().to_string(); + let err = server.body_err().source().unwrap().to_string(); assert!( err.contains("overflow"), "error should be overflow: {:?}",
hyperium/hyper
6fd696e10974f10b2c6b9d16393bbbfa21c2333f
[ "2872" ]
0.3
a45d5d5a04369f93334fc893875d8d1a49054e04
diff --git a/src/body/incoming.rs b/src/body/incoming.rs --- a/src/body/incoming.rs +++ b/src/body/incoming.rs @@ -201,7 +201,16 @@ impl Body for Incoming { ping.record_data(bytes.len()); return Poll::Ready(Some(Ok(Frame::data(bytes)))); } - Some(Err(e)) => return Poll::Ready(Some(Err(crate::Error::new_body(e)))), + Some(Err(e)) => { + return match e.reason() { + // These reasons should cause the body reading to stop, but not fail it. + // The same logic as for `Read for H2Upgraded` is applied here. + Some(h2::Reason::NO_ERROR) | Some(h2::Reason::CANCEL) => { + Poll::Ready(None) + } + _ => Poll::Ready(Some(Err(crate::Error::new_body(e)))), + }; + } None => { *data_done = true; // fall through to trailers diff --git a/src/proto/mod.rs b/src/proto/mod.rs --- a/src/proto/mod.rs +++ b/src/proto/mod.rs @@ -50,7 +50,7 @@ pub(crate) enum BodyLength { Unknown, } -/// Status of when a Disaptcher future completes. +/// Status of when a Dispatcher future completes. pub(crate) enum Dispatched { /// Dispatcher completely shutdown connection. Shutdown,
Yea, I think we've talked about this in a previous issue, but don't remember where. `h2` is making the "error" (the reset) trump any other frames that have been received. It should likely be changed to return all other received frames, and *then* return the error. But _somewhere_ in the stack it should probably just suppress the `RST_STREAM(NO_ERROR)` and return the response, because the response is what's going to be meaningful to the user. The `RST_STREAM` here is just being used as a "shut up and listen" signal. Yes, it should return the response, that's why I mean. And then the body can return that there was a `NO_ERROR` error. It should still be given to the user, so they know something happened. Stumbled on this. How can I suppress the specific failure `RST_STREAM(NO_ERROR)` somehow? How can I workaround this? I'm also in for contributing this fix :)
2023-07-23T01:01:36Z
3,275
Client: handle `RST_STREAM` with `NO_ERROR` set for the reason **Version** ``` hyper = "0.14.18" h2 = "0.3.13" ``` **Platform** ``` > uname -a Linux <REDACTED> 5.17.5-76051705-generic #202204271406~1651504840~22.04~63e51bd SMP PREEMPT Mon May 2 15: x86_64 x86_64 x86_64 GNU/Linux ``` **Description** I've found that Google Cloud Storage's API can respond with HTTP/2 `RST_STREAM` frame with `NO_ERROR` set for the reason, which appears to mean "stop sending the request body and read my response" according to https://datatracker.ietf.org/doc/html/rfc7540#section-8.1 > A server can send a complete response prior to the client sending an entire request if the response does not depend on any portion of the request that has not been sent and received. When this is true, a server MAY request that the client abort transmission of a request without error by sending a RST_STREAM with an error code of NO_ERROR after sending a complete response (i.e., a frame with the END_STREAM flag). Clients MUST NOT discard responses as a result of receiving such a RST_STREAM, though clients can always discard responses at their discretion for other reasons. I believe this is happening in response to a `PutObject` request when the bucket is being rate limited for writes. The server is trying to tell the client to stop sending the request body because it won't be processed, and instead it should immediately read the response to discover the `429 Too Many Requests` error code. However, Hyper's client implementation appears to just return the `RST_STREAM` message as an error and discards the response instead of handling it, which gives a hilariously confusing error message of: ``` error reading a body from connection: stream error received: not a result of an error ``` To be compliant with the spec, the implementation should stop sending the body and immediately read the response and return it. For context, I'm using the Gcloud Storage API via https://crates.io/crates/aws-sdk-s3 (because the Gcloud Rust SDK doesn't support streaming bodies, but thankfully Gcloud Storage exposes an S3-compatible API), which uses Hyper internally. `aws-sdk-s3` appears to be returning the error from Hyper verbatim, however.
hyperium__hyper-3275
diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -1338,7 +1338,7 @@ mod conn { use bytes::{Buf, Bytes}; use futures_channel::{mpsc, oneshot}; use futures_util::future::{self, poll_fn, FutureExt, TryFutureExt}; - use http_body_util::{BodyExt, Empty, StreamBody}; + use http_body_util::{BodyExt, Empty, Full, StreamBody}; use hyper::rt::Timer; use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; use tokio::net::{TcpListener as TkTcpListener, TcpStream}; diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -2126,6 +2126,62 @@ mod conn { .expect("client should be open"); } + #[tokio::test] + async fn http2_responds_before_consuming_request_body() { + // Test that a early-response from server works correctly (request body wasn't fully consumed). + // https://github.com/hyperium/hyper/issues/2872 + use hyper::service::service_fn; + + let _ = pretty_env_logger::try_init(); + + let (listener, addr) = setup_tk_test_server().await; + + // Spawn an HTTP2 server that responds before reading the whole request body. + // It's normal case to decline the request due to headers or size of the body. + tokio::spawn(async move { + let sock = TokioIo::new(listener.accept().await.unwrap().0); + hyper::server::conn::http2::Builder::new(TokioExecutor) + .timer(TokioTimer) + .serve_connection( + sock, + service_fn(|_req| async move { + Ok::<_, hyper::Error>(Response::new(Full::new(Bytes::from( + "No bread for you!", + )))) + }), + ) + .await + .expect("serve_connection"); + }); + + let io = tcp_connect(&addr).await.expect("tcp connect"); + let (mut client, conn) = conn::http2::Builder::new(TokioExecutor) + .timer(TokioTimer) + .handshake(io) + .await + .expect("http handshake"); + + tokio::spawn(async move { + conn.await.expect("client conn shouldn't error"); + }); + + // Use a channel to keep request stream open + let (_tx, recv) = mpsc::channel::<Result<Frame<Bytes>, Box<dyn Error + Send + Sync>>>(0); + let req = Request::post("/a").body(StreamBody::new(recv)).unwrap(); + let resp = client.send_request(req).await.expect("send_request"); + assert!(resp.status().is_success()); + + let mut body = String::new(); + concat(resp.into_body()) + .await + .unwrap() + .reader() + .read_to_string(&mut body) + .unwrap(); + + assert_eq!(&body, "No bread for you!"); + } + #[tokio::test] async fn h2_connect() { let (listener, addr) = setup_tk_test_server().await;
hyperium/hyper
6fd696e10974f10b2c6b9d16393bbbfa21c2333f
[ "2872" ]
0.14
d77c2599bc023b258b90a17f5b633c8b7b0cbd4b
diff --git a/src/body/body.rs b/src/body/body.rs --- a/src/body/body.rs +++ b/src/body/body.rs @@ -323,7 +323,12 @@ impl Body { ping.record_data(bytes.len()); Poll::Ready(Some(Ok(bytes))) } - Some(Err(e)) => Poll::Ready(Some(Err(crate::Error::new_body(e)))), + Some(Err(e)) => match e.reason() { + // These reasons should cause stop of body reading, but nor fail it. + // The same logic as for `AsyncRead for H2Upgraded` is applied here. + Some(h2::Reason::NO_ERROR) | Some(h2::Reason::CANCEL) => Poll::Ready(None), + _ => Poll::Ready(Some(Err(crate::Error::new_body(e)))), + }, None => Poll::Ready(None), }, diff --git a/src/proto/mod.rs b/src/proto/mod.rs --- a/src/proto/mod.rs +++ b/src/proto/mod.rs @@ -50,7 +50,7 @@ pub(crate) enum BodyLength { Unknown, } -/// Status of when a Disaptcher future completes. +/// Status of when a Dispatcher future completes. pub(crate) enum Dispatched { /// Dispatcher completely shutdown connection. Shutdown,
Yea, I think we've talked about this in a previous issue, but don't remember where. `h2` is making the "error" (the reset) trump any other frames that have been received. It should likely be changed to return all other received frames, and *then* return the error. But _somewhere_ in the stack it should probably just suppress the `RST_STREAM(NO_ERROR)` and return the response, because the response is what's going to be meaningful to the user. The `RST_STREAM` here is just being used as a "shut up and listen" signal. Yes, it should return the response, that's why I mean. And then the body can return that there was a `NO_ERROR` error. It should still be given to the user, so they know something happened. Stumbled on this. How can I suppress the specific failure `RST_STREAM(NO_ERROR)` somehow? How can I workaround this? I'm also in for contributing this fix :)
2023-07-23T01:01:19Z
3,274
Client: handle `RST_STREAM` with `NO_ERROR` set for the reason **Version** ``` hyper = "0.14.18" h2 = "0.3.13" ``` **Platform** ``` > uname -a Linux <REDACTED> 5.17.5-76051705-generic #202204271406~1651504840~22.04~63e51bd SMP PREEMPT Mon May 2 15: x86_64 x86_64 x86_64 GNU/Linux ``` **Description** I've found that Google Cloud Storage's API can respond with HTTP/2 `RST_STREAM` frame with `NO_ERROR` set for the reason, which appears to mean "stop sending the request body and read my response" according to https://datatracker.ietf.org/doc/html/rfc7540#section-8.1 > A server can send a complete response prior to the client sending an entire request if the response does not depend on any portion of the request that has not been sent and received. When this is true, a server MAY request that the client abort transmission of a request without error by sending a RST_STREAM with an error code of NO_ERROR after sending a complete response (i.e., a frame with the END_STREAM flag). Clients MUST NOT discard responses as a result of receiving such a RST_STREAM, though clients can always discard responses at their discretion for other reasons. I believe this is happening in response to a `PutObject` request when the bucket is being rate limited for writes. The server is trying to tell the client to stop sending the request body because it won't be processed, and instead it should immediately read the response to discover the `429 Too Many Requests` error code. However, Hyper's client implementation appears to just return the `RST_STREAM` message as an error and discards the response instead of handling it, which gives a hilariously confusing error message of: ``` error reading a body from connection: stream error received: not a result of an error ``` To be compliant with the spec, the implementation should stop sending the body and immediately read the response and return it. For context, I'm using the Gcloud Storage API via https://crates.io/crates/aws-sdk-s3 (because the Gcloud Rust SDK doesn't support streaming bodies, but thankfully Gcloud Storage exposes an S3-compatible API), which uses Hyper internally. `aws-sdk-s3` appears to be returning the error from Hyper verbatim, however.
hyperium__hyper-3274
diff --git a/tests/client.rs b/tests/client.rs --- a/tests/client.rs +++ b/tests/client.rs @@ -3154,6 +3154,61 @@ mod conn { .expect("client should be open"); } + #[tokio::test] + async fn http2_responds_before_consuming_request_body() { + // Test that a early-response from server works correctly (request body wasn't fully consumed). + // https://github.com/hyperium/hyper/issues/2872 + use hyper::service::service_fn; + + let _ = pretty_env_logger::try_init(); + + let listener = TkTcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0))) + .await + .unwrap(); + let addr = listener.local_addr().unwrap(); + + // Spawn an HTTP2 server that responds before reading the whole request body. + // It's normal case to decline the request due to headers or size of the body. + tokio::spawn(async move { + let sock = listener.accept().await.unwrap().0; + hyper::server::conn::Http::new() + .http2_only(true) + .serve_connection( + sock, + service_fn(|_req| async move { + Ok::<_, hyper::Error>(http::Response::new(hyper::Body::from( + "No bread for you!", + ))) + }), + ) + .await + .expect("serve_connection"); + }); + + let io = tcp_connect(&addr).await.expect("tcp connect"); + let (mut client, conn) = conn::Builder::new() + .http2_only(true) + .handshake::<_, Body>(io) + .await + .expect("http handshake"); + + tokio::spawn(async move { + conn.await.expect("client conn shouldn't error"); + }); + + // Use a channel to keep request stream open + let (_tx, body) = hyper::Body::channel(); + let req = Request::post("/a").body(body).unwrap(); + let resp = client.send_request(req).await.expect("send_request"); + assert!(resp.status().is_success()); + + let body = hyper::body::to_bytes(resp.into_body()) + .await + .expect("get response body with no error"); + + assert_eq!(body.as_ref(), b"No bread for you!"); + } + #[tokio::test] async fn h2_connect() { let _ = pretty_env_logger::try_init();
hyperium/hyper
a24f0c0af8e1f4c6b7cc3a47c83eb6e4af88aca6
[ "2730" ]
0.3
d92d3917d950e4c61c37c2170f3ce273d2a0f7d1
diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -175,6 +175,13 @@ where } } + #[cfg(feature = "server")] + pub(crate) fn has_initial_read_write_state(&self) -> bool { + matches!(self.state.reading, Reading::Init) + && matches!(self.state.writing, Writing::Init) + && self.io.read_buf().is_empty() + } + fn should_error_on_eof(&self) -> bool { // If we're idle, it's probably just the connection closing gracefully. T::should_error_on_parse_eof() && !self.state.is_idle() diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -82,7 +82,11 @@ where #[cfg(feature = "server")] pub(crate) fn disable_keep_alive(&mut self) { self.conn.disable_keep_alive(); - if self.conn.is_write_closed() { + + // If keep alive has been disabled and no read or write has been seen on + // the connection yet, we must be in a state where the server is being asked to + // shut down before any data has been seen on the connection + if self.conn.is_write_closed() || self.conn.has_initial_read_write_state() { self.close(); } }
Yea, I think this is behavior is currently on purpose. Whether it _should_ be is a fair question. I think at the time, I assumed that a _new_ connection would usually have a request incoming ASAP, whereas an idle connection might not, and so it was better to allow that request to come in. We could alter that behavior, if we document a good reason for _why_ we're making that change. Also, I imagine using the `http1_header_read_timeout` option could help here. I agree that it's *more likely* for the first request to show up than a follow up request, but it seems weird to bake that assumption into graceful_shutdown IMO. For reference, I'm using graceful_shutdown in some logic to shut down connections after a certain period of idleness (I can't just terminate the connection future since I want the TLS session to shut down cleanly for session reuse). Right now, the current behavior will miss connections that are opened and never make a request. Does `http1_header_read_timeout` start counting immediately or just once the first byte of the header is received? In any case, I don't think that'd help for an h2 connection, right? Any progress on this? I was trying to figure out why my program wasn't exiting when I expected it to and found this issue. If I send the graceful shutdown signal the server will process one more request before actually exiting. So a user sending the shutdown command through a web app won't actually be shutting anything down. > Does http1_header_read_timeout start counting immediately or just once the first byte of the header is received? In any case, I don't think that'd help for an h2 connection, right? From some testing just now, the answer to the first part is "no". If I start-up an `http1::Connection` with a header timeout configured and connect to it simply with `nc` then the connection stays up indefinitely. Once I send any data (even a blank line) the timer starts counting and the connection is closed as expected after the timeout. This seems like a thing to slide into RC2 or RC3. > I can't just terminate the connection future since I want the TLS session to shut down cleanly for session reuse @sfackler Does this mean you'd have the connection write out a 408 response and then finish? Or simply calling `poll_shutdown` and then return the future like if it were in keep-alive state? I guess calling shutdown will make the TLS shutdown start, right? Yeah it just needs to call shutdown on the underlying IO object, which will handle the SSL shutdown protocol. I think I can take this one.
2023-07-06T18:47:14Z
3,261
Connection::graceful_shutdown always waits for the first request. **Version** hyper 0.14.16 **Platform** Linux DESKTOP-DHO88R7 4.19.104-microsoft-standard #1 SMP Wed Feb 19 06:37:35 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux **Description** If you gracefully shut down a server connection future before the first request, Hyper will not actually shut the connection down until a request is processed: ```rust use hyper::server::conn::Http; use hyper::Response; use tokio::io::AsyncReadExt; use tokio::net::{TcpListener, TcpStream}; use tokio::pin; #[tokio::main] async fn main() { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); tokio::spawn(server(listener)); let mut stream = TcpStream::connect(addr).await.unwrap(); println!("connected"); let mut buf = vec![]; stream.read_to_end(&mut buf).await.unwrap(); } async fn server(listener: TcpListener) { let socket = listener.accept().await.unwrap().0; let service = hyper::service::service_fn(|_: hyper::Request<hyper::Body>| async { Err::<Response<hyper::Body>, _>("no") }); let future = Http::new() .http1_only(true) .serve_connection(socket, service); pin!(future); future.as_mut().graceful_shutdown(); future.await.unwrap(); } ``` I would expect this program to exit almost instantly since there is no request being processed when the graceful_shutdown is invoked. However, it instead blocks forever waiting on the client to send headers. The behavior actually appears to be that the shutdown is processed immediately after the first request is fully handled.
hyperium__hyper-3261
diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -31,6 +31,7 @@ use hyper::body::{Body, Incoming as IncomingBody}; use hyper::server::conn::{http1, http2}; use hyper::service::{service_fn, Service}; use hyper::{Method, Request, Response, StatusCode, Uri, Version}; +use tokio::pin; mod support; diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -1139,11 +1140,17 @@ async fn disable_keep_alive_mid_request() { let child = thread::spawn(move || { let mut req = connect(&addr); req.write_all(b"GET / HTTP/1.1\r\n").unwrap(); + thread::sleep(Duration::from_millis(10)); tx1.send(()).unwrap(); rx2.recv().unwrap(); req.write_all(b"Host: localhost\r\n\r\n").unwrap(); let mut buf = vec![]; req.read_to_end(&mut buf).unwrap(); + assert!( + buf.starts_with(b"HTTP/1.1 200 OK\r\n"), + "should receive OK response, but buf: {:?}", + buf, + ); }); let (socket, _) = listener.accept().await.unwrap(); diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -2152,6 +2159,31 @@ async fn max_buf_size() { .expect_err("should TooLarge error"); } +#[cfg(feature = "http1")] +#[tokio::test] +async fn graceful_shutdown_before_first_request_no_block() { + let (listener, addr) = setup_tcp_listener(); + + tokio::spawn(async move { + let socket = listener.accept().await.unwrap().0; + + let future = http1::Builder::new().serve_connection(socket, HelloWorld); + pin!(future); + future.as_mut().graceful_shutdown(); + + future.await.unwrap(); + }); + + let mut stream = TkTcpStream::connect(addr).await.unwrap(); + + let mut buf = vec![]; + + tokio::time::timeout(Duration::from_secs(5), stream.read_to_end(&mut buf)) + .await + .expect("timed out waiting for graceful shutdown") + .expect("error receiving response"); +} + #[test] fn streaming_body() { use futures_util::StreamExt;
hyperium/hyper
6fd696e10974f10b2c6b9d16393bbbfa21c2333f
[ "3253" ]
0.14
297dc4c8ea2dbc844d030418f79a6869fd67f496
diff --git a/src/body/body.rs b/src/body/body.rs --- a/src/body/body.rs +++ b/src/body/body.rs @@ -602,17 +602,16 @@ impl Sender { } /// Aborts the body in an abnormal fashion. - pub fn abort(self) { + pub fn abort(mut self) { + self.send_error(crate::Error::new_body_write_aborted()); + } + + pub(crate) fn send_error(&mut self, err: crate::Error) { let _ = self .data_tx // clone so the send works even if buffer is full .clone() - .try_send(Err(crate::Error::new_body_write_aborted())); - } - - #[cfg(feature = "http1")] - pub(crate) fn send_error(&mut self, err: crate::Error) { - let _ = self.data_tx.try_send(Err(err)); + .try_send(Err(err)); } } diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -118,6 +118,10 @@ where should_shutdown: bool, ) -> Poll<crate::Result<Dispatched>> { Poll::Ready(ready!(self.poll_inner(cx, should_shutdown)).or_else(|e| { + // Be sure to alert a streaming body of the failure. + if let Some(mut body) = self.body_tx.take() { + body.send_error(crate::Error::new_body("connection error")); + } // An error means we're shutting down either way. // We just try to give the error to the user, // and close the connection with an Ok. If we diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -367,7 +371,12 @@ where self.conn.end_body()?; } } else { - return Poll::Pending; + // If there's no body_rx, end the body + if self.conn.can_write_body() { + self.conn.end_body()?; + } else { + return Poll::Pending; + } } } }
I've been playing around with the demo on my own machine, and even without the timeout, I see what you're describing. When I turn on tracing, I see that the connection task encounters a _write_ error, because the socket is closed, and then that closes up the task. I would guess that it depends on what exact option the connection task is doing when you kill the curl process: if it was trying to read, it will see a read error, if it was trying to write, it will log it and close up. So, I'd say that at least the problem is that when the connection task is closing, the request body sender (the internal side giving you the request body bytes) doesn't notice it should send a final error item. My problem domain is storage systems, and when user uploads a file of unknown length (via chunked encoding) it is really important to get reliable information on how stream has ended. With current state of things, drop of the client might result in new object being successfully uploaded to storage system with only partial content.
2023-06-19T18:36:20Z
3,257
Missing error when reading stream of data out of an interrupted chunked-encoded request **Version** hyper 0.14.26 tokio 1.28.1 **Platform** ```Linux my-hostname 5.10.0-18-amd64 #1 SMP Debian 5.10.140-1 (2022-09-02) x86_64 GNU/Linux``` **Description** Error is not propagated via stream in some cases when client drops the connection during chunked-encoding stream. I tried this code: ```rust use futures_util::stream::StreamExt; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request, Response, Server}; use tokio::sync::mpsc; use tokio::time::{sleep, Duration}; async fn echo(mut req: Request<Body>) -> Result<Response<Body>, hyper::Error> { println!("reading body!"); // Create a channel to communicate between the reading and responding tasks let (tx, rx) = mpsc::channel::<Vec<u8>>(1); // Spawn a task to read the request body and discard it tokio::spawn(async move { while let Some(maybe_chunk) = req.body_mut().next().await { match maybe_chunk { Ok(chunk) => { // Uncomment me! // sleep(Duration::from_millis(100)).await; let _ = tx.send(chunk.to_vec()).await; } Err(err) => { println!("Got error: {}", err); } } } println!("finished reading body!"); }); // Create a response with a data stream that is filled by the reading task let stream = tokio_stream::wrappers::ReceiverStream::new(rx); let response = Response::builder() .body(Body::wrap_stream(stream.map(Result::<_, hyper::Error>::Ok))) .expect("Failed to build response"); Ok(response) } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { let addr = ([0, 0, 0, 0], 3000).into(); let service = make_service_fn(|_| async { Ok::<_, hyper::Error>(service_fn(echo)) }); let server = Server::bind(&addr).serve(service); println!("Listening on http://{}", addr); server.await?; Ok(()) } ``` Cargo.toml dependencies: ```toml [dependencies] tokio = { version = "1", features = ["full"] } hyper = { version="0.14", features=["full"] } http = "*" futures = "*" futures-util = "0.3.28" tokio-stream = "0.1.14" ``` Service above is an echo-server, which sends back the stream of data that it receives. To get the repro, please launch the service, and on another terminal start the "endless" curl command like this: ``` $ cat /dev/zero | curl -XPOST http://127.0.0.1:3000/ -H "Transfer-Encoding: chunked" -T - -o /dev/null ``` It will read `/dev/zero`, pipe it to curl, which will send it as data stream with chunked transfer encoding, sending the output stream to `/dev/null`. After some time, terminate curl with `Ctrl+C`. Service reports the error on the stream as expected, terminal output will look like this: ``` Listening on http://0.0.0.0:3000 reading body! Got error: error reading a body from connection: Connection reset by peer (os error 104) finished reading body! ``` But if we uncomment the sleep line, and repeat the experiment, there will be no error, as indicated by service output: ``` Listening on http://0.0.0.0:3000 reading body! finished reading body! ``` I'm observing this weird behavior on a larger codebase that does approximately the same as sample server presented above. One more interesting observation, even when sleep is in place, it does not repro (i.e. error is reported properly) with this netcat: ``` $ echo -ne "GET /echo-buffer HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n6\r\naabbcc" | nc localhos t 3000; echo HTTP/1.1 200 OK transfer-encoding: chunked date: Fri, 16 Jun 2023 16:04:58 GMT 6 aabbcc ^C ``` My larger codebase also works as expected with netcat. Is there a race somewhere?
hyperium__hyper-3257
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -62,7 +62,7 @@ tokio = { version = "1", features = [ ] } tokio-test = "0.4" tokio-util = { version = "0.7", features = ["codec"] } -tower = { version = "0.4", features = ["make", "util"] } +tower = { version = "0.4", default-features = false, features = ["make", "util"] } url = "2.2" [target.'cfg(any(target_os = "linux", target_os = "macos"))'.dev-dependencies] diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -93,6 +93,7 @@ mod response_body_lengths { } fn run_test(case: TestCase) { + let _ = pretty_env_logger::try_init(); assert!( case.version == 0 || case.version == 1, "TestCase.version must 0 or 1" diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -157,18 +158,22 @@ mod response_body_lengths { let n = body.find("\r\n\r\n").unwrap() + 4; if case.expects_chunked { - let len = body.len(); - assert_eq!( - &body[n + 1..n + 3], - "\r\n", - "expected body chunk size header" - ); - assert_eq!(&body[n + 3..len - 7], body_str, "expected body"); - assert_eq!( - &body[len - 7..], - "\r\n0\r\n\r\n", - "expected body final chunk size header" - ); + if body_str.len() > 0 { + let len = body.len(); + assert_eq!( + &body[n + 1..n + 3], + "\r\n", + "expected body chunk size header" + ); + assert_eq!(&body[n + 3..len - 7], body_str, "expected body"); + assert_eq!( + &body[len - 7..], + "\r\n0\r\n\r\n", + "expected body final chunk size header" + ); + } else { + assert_eq!(&body[n..], "0\r\n\r\n"); + } } else { assert_eq!(&body[n..], body_str, "expected body"); } diff --git a/tests/server.rs b/tests/server.rs --- a/tests/server.rs +++ b/tests/server.rs @@ -219,6 +224,17 @@ mod response_body_lengths { }); } + #[test] + fn chunked_response_known_empty() { + run_test(TestCase { + version: 1, + headers: &[("transfer-encoding", "chunked")], + body: Bd::Known(""), + expects_chunked: true, // should still send chunked, and 0\r\n\r\n + expects_con_len: false, + }); + } + #[test] fn chunked_response_unknown() { run_test(TestCase {
hyperium/hyper
a24f0c0af8e1f4c6b7cc3a47c83eb6e4af88aca6
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1