diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 23abc6275d..6d09fd1181 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -2,6 +2,12 @@ name: "Bug report 🐛" description: Create a report to help us improve labels: ["C-bug"] body: + - type: checkboxes + attributes: + label: Human words + description: Communication between humans should be written by a human, not an LLM. + options: + - label: The words are written by a [human](https://seanmonstar.com/micro/20260729-i-want-your-own-words/). - type: input id: version attributes: diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index fa9eaf989e..bb878ca782 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -7,6 +7,9 @@ assignees: '' --- +**Are the words provided written by a human, not an LLM?** +- [ ] The words have been written by a [human](https://seanmonstar.com/micro/20260729-i-want-your-own-words/). + **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 5d625ae140..c9d9053e0b 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -125,6 +125,12 @@ jobs: - uses: dtolnay/rust-toolchain@stable + - name: Install cargo-hack + uses: taiki-e/install-action@cargo-hack + + - name: Remove dev dependencies + run: cargo hack --remove-dev-deps + - name: Resolve MSRV aware dependencies run: cargo update env: @@ -181,14 +187,12 @@ jobs: - uses: Swatinem/rust-cache@v2 - name: check --feature-powerset - run: cargo hack --no-dev-deps check --feature-powerset --depth 2 --skip ffi,tracing - env: - RUSTFLAGS: "-D dead_code -D unused_imports" + run: cargo hack --no-dev-deps check --feature-powerset --depth 2 --features __deny_warnings --skip ffi,tracing - name: check --feature-powerset with tracing feature - run: cargo hack --no-dev-deps check --feature-powerset --depth 2 --features tracing --skip ffi + run: cargo hack --no-dev-deps check --feature-powerset --depth 2 --features tracing,__deny_warnings --skip ffi env: - RUSTFLAGS: "--cfg hyper_unstable_tracing -D dead_code -D unused_imports" + RUSTFLAGS: "--cfg hyper_unstable_tracing" ffi: name: Test C API (FFI) diff --git a/CHANGELOG.md b/CHANGELOG.md index 30fbb11685..9a4b24e042 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,28 @@ +## v1.13.0 (2026-11-23) + + +#### Bug Fixes + +* **client:** fail parked h2 request with connection error on close (#4275) ([dea9acb5](https://github.com/hyperium/hyper/commit/dea9acb5344e0e34bb9196f5493464db68edd24a), closes [#4269](https://github.com/hyperium/hyper/issues/4269)) +* **http1:** + * preserve streaming bodies when coercing HTTP/2 requests (#4236) ([21da6a59](https://github.com/hyperium/hyper/commit/21da6a59db9a90631302e7b173c106b723b9065f)) + * prevent `SendRequest` from reporting ready while a request is pending (#4247) ([47c725c4](https://github.com/hyperium/hyper/commit/47c725c459ede66e68ad705f7da9a901abbbdc17), closes [#4246](https://github.com/hyperium/hyper/issues/4246)) + * avoid adding connection-close to 101 responses (#4248) ([ac3f9501](https://github.com/hyperium/hyper/commit/ac3f9501de373388fb9914e285134cfec2283bd8), closes [#4244](https://github.com/hyperium/hyper/issues/4244)) + * error when final body chunk is shorter than content-length (#4270) ([75062064](https://github.com/hyperium/hyper/commit/750620646ba0777daa45be3d82bd1704dcf470b8)) + * drop Content-Length when a response also has Transfer-Encoding (#4264) ([378f8479](https://github.com/hyperium/hyper/commit/378f8479b8b703d098b46de1cec9ea648f12ea69), closes [#4263](https://github.com/hyperium/hyper/issues/4263)) + * drain in-flight requests before dispatcher shutdown (#4222) ([97fff93e](https://github.com/hyperium/hyper/commit/97fff93e53f9e6a993f2d6a25d50883b7b8752a7), closes [#4202](https://github.com/hyperium/hyper/issues/4202)) +* **http2:** + * report zero body size hint for HEAD responses (#4237) ([4e1c0fbb](https://github.com/hyperium/hyper/commit/4e1c0fbb9db68936c952c481321d96f536568283)) + * prevent requests from hanging during concurrent connection shutdown race (#4242) ([5634b91d](https://github.com/hyperium/hyper/commit/5634b91d607ba1b781699765b22f16fd6ec1c8b7)) + * strip all headers named in every Connection header (#4271) ([a44e32a7](https://github.com/hyperium/hyper/commit/a44e32a7f85a1f98e34307ae17985c0bc1349a03)) + * keep connection open after rejecting CONNECT (#4235) ([88520c3e](https://github.com/hyperium/hyper/commit/88520c3eaea391f8ba49591a84f8439998b76191)) + + +#### Features + +* **http2:** add an executor getter for server and client (#4250) ([b638fc0d](https://github.com/hyperium/hyper/commit/b638fc0de351987f3eaffa2bdabd393c8679a9e8)) + + ## v1.12.0 (2026-10-06) diff --git a/Cargo.toml b/Cargo.toml index f7f7f1e6c4..1c93ac7eb8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hyper" -version = "1.12.0" +version = "1.13.0" description = "A protective and efficient HTTP library for all." readme = "README.md" homepage = "https://hyper.rs" @@ -46,7 +46,7 @@ form_urlencoded = "1" futures-channel = { version = "0.3", features = ["sink"] } futures-util = { version = "0.3", default-features = false, features = ["alloc", "sink"] } http-body-util = "0.1" -pretty_env_logger = "0.5" +pretty_env_logger = "0.6" pin-project-lite = "0.2.4" spmc = "0.3" serde = { version = "1.0", features = ["derive"] } @@ -96,6 +96,7 @@ capi = [] tracing = ["dep:tracing"] # internal features used in CI +__deny_warnings = [] nightly = [] [lints.rust.unexpected_cfgs] @@ -120,24 +121,19 @@ checked_conversions = "allow" else_if_without_else = "allow" float_arithmetic = "allow" indexing_slicing = "allow" -let_unit_value = "allow" match_wild_err_arm = "allow" multiple_inherent_impl = "allow" multiple_unsafe_ops_per_block = "allow" needless_pass_by_value = "allow" pattern_type_mismatch = "allow" -redundant_closure_for_method_calls = "allow" redundant_else = "allow" struct_excessive_bools = "allow" # TODO: bogus lint? -trivially_copy_pass_by_ref = "allow" -unnested_or_patterns = "allow" unused_async = "allow" # TODO: is it for API? unused_trait_names = "allow" # TODO: kinda annoying, but might be good to deny unwrap_in_result = "allow" wildcard_enum_match_arm = "allow" definition_in_module_root = "allow" unnecessary_rest_pattern = "allow" -rest_pattern_accessible_field = "allow" needless_bool = "allow" # explicitly allowed @@ -191,6 +187,7 @@ too_many_lines = "allow" # reconsider someday? type_complexity = "allow" # not helpful used_underscore_items = "allow" unnecessary_safety_comment = "allow" # more safety comments are a good thing +unneeded_field_pattern = "allow" # exhaustive matching is helpful unseparated_literal_suffix = "allow" # i don't like 0_u8 (do i?) [package.metadata.docs.rs] diff --git a/src/body/incoming.rs b/src/body/incoming.rs index b026a24d6b..ff9e3c02a3 100644 --- a/src/body/incoming.rs +++ b/src/body/incoming.rs @@ -235,9 +235,17 @@ impl Body for Incoming { match &self.kind { Kind::Empty => true, #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))] - Kind::Chan { content_length, .. } => *content_length == DecodedLength::ZERO, + Kind::Chan { + content_length, + rx: _, + } => *content_length == DecodedLength::ZERO, #[cfg(all(feature = "http2", any(feature = "client", feature = "server")))] - Kind::H2 { recv: h2, .. } => h2.is_end_stream(), + Kind::H2 { + recv: h2, + content_length: _, + data_done: _, + ping: _, + } => h2.is_end_stream(), #[cfg(feature = "ffi")] Kind::Ffi(..) => false, } @@ -259,9 +267,17 @@ impl Body for Incoming { match self.kind { Kind::Empty => SizeHint::with_exact(0), #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))] - Kind::Chan { content_length, .. } => opt_len(content_length), + Kind::Chan { + content_length, + rx: _, + } => opt_len(content_length), #[cfg(all(feature = "http2", any(feature = "client", feature = "server")))] - Kind::H2 { content_length, .. } => opt_len(content_length), + Kind::H2 { + content_length, + data_done: _, + ping: _, + recv: _, + } => opt_len(content_length), #[cfg(feature = "ffi")] Kind::Ffi(..) => SizeHint::default(), } diff --git a/src/body/length.rs b/src/body/length.rs index 1ed5e0d031..385a8b3c3b 100644 --- a/src/body/length.rs +++ b/src/body/length.rs @@ -68,7 +68,7 @@ impl DecodedLength { ))] pub(crate) fn sub_if(&mut self, amt: u64) { match self { - &mut DecodedLength::CHUNKED | &mut DecodedLength::CLOSE_DELIMITED => (), + &mut (DecodedLength::CHUNKED | DecodedLength::CLOSE_DELIMITED) => (), DecodedLength(known) => { *known -= amt; } @@ -81,7 +81,7 @@ impl DecodedLength { /// /// It would return false if "chunked" or otherwise size-unknown. #[cfg(all(any(feature = "client", feature = "server"), feature = "http2"))] - pub(crate) fn is_exact(&self) -> bool { + pub(crate) fn is_exact(self) -> bool { self.0 <= MAX_LEN } } diff --git a/src/client/conn/http2.rs b/src/client/conn/http2.rs index 4df19a10cc..9e19d26949 100644 --- a/src/client/conn/http2.rs +++ b/src/client/conn/http2.rs @@ -314,6 +314,11 @@ where } } + /// Returns the executor this builder was created with. + pub fn executor(&self) -> &Ex { + &self.exec + } + /// Provide a timer to execute background HTTP2 tasks. pub fn timer(&mut self, timer: M) -> &mut Builder where diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs index 76a9c3e20c..c3140cf6d7 100644 --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -30,14 +30,16 @@ pub struct TrySendError { pub(crate) fn channel() -> (Sender, Receiver) { let (tx, rx) = mpsc::unbounded_channel(); - let (giver, taker) = want::new(); - let tx = Sender { - #[cfg(feature = "http1")] - buffered_once: false, - giver, - inner: tx, + let (giver, mut taker) = want::new(); + // Seed with one want so the first request can be sent before the + // receiver is polled; every request must consume a want + taker.want(); + let tx = Sender { giver, inner: tx }; + let rx = Receiver { + inner: rx, + taker, + wanting: true, }; - let rx = Receiver { inner: rx, taker }; (tx, rx) } @@ -46,17 +48,11 @@ pub(crate) fn channel() -> (Sender, Receiver) { /// While the inner sender is unbounded, the Giver is used to determine /// if the Receiver is ready for another request. pub(crate) struct Sender { - /// One message is always allowed, even if the Receiver hasn't asked - /// for it yet. This boolean keeps track of whether we've sent one - /// without notice. - #[cfg(feature = "http1")] - buffered_once: bool, - /// The Giver helps watch that the Receiver side has been polled - /// when the queue is empty. This helps us know when a request and - /// response have been fully processed, and a connection is ready - /// for more. + // Controls whether the sender is permitted to dispatch a request + // Beyond the initial request, the Receiver only grants readiness once + // the preceding request/response cycle has fully completed giver: want::Giver, - /// Actually bounded by the Giver, plus `buffered_once`. + // Capacity is enforced via the Giver inner: mpsc::UnboundedSender>, } @@ -89,23 +85,9 @@ impl Sender { self.giver.is_canceled() } - #[cfg(feature = "http1")] - fn can_send(&mut self) -> bool { - if self.giver.give() || !self.buffered_once { - // If the receiver is ready *now*, then of course we can send. - // - // If the receiver isn't ready yet, but we don't have anything - // in the channel yet, then allow one message. - self.buffered_once = true; - true - } else { - false - } - } - #[cfg(feature = "http1")] pub(crate) fn try_send(&mut self, val: T) -> Result, T> { - if !self.can_send() { + if !self.giver.give() { return Err(val); } let (tx, rx) = oneshot::channel(); @@ -117,7 +99,7 @@ impl Sender { #[cfg(feature = "http1")] pub(crate) fn send(&mut self, val: T) -> Result, T> { - if !self.can_send() { + if !self.giver.give() { return Err(val); } let (tx, rx) = oneshot::channel(); @@ -176,34 +158,33 @@ impl Clone for UnboundedSender { pub(crate) struct Receiver { inner: mpsc::UnboundedReceiver>, taker: want::Taker, + // Tracks whether readiness (`want`) has already been granted for the next request + wanting: bool, } impl Receiver { pub(crate) fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll)>> { + if !self.wanting { + self.taker.want(); + self.wanting = true; + } match self.inner.poll_recv(cx) { Poll::Ready(item) => { - // A want signaled after finding the queue empty can land after - // the Sender's `give()` for the message taken here, as can one - // signaled on a coop-budget Pending with a message queued. - // Withdraw it, or the Sender reports this connection as ready - // while it is still serving this message. - self.taker.unwant(); + self.wanting = false; Poll::Ready(item.map(|mut env| env.0.take().expect("envelope not dropped"))) } - Poll::Pending => { - self.taker.want(); - Poll::Pending - } + // Avoid re-signaling `want` here: the sender might have already claimed it + // and enqueued a request, even if polling the channel returns `Pending` + // due to Tokio's coop budget exhaustion or a concurrent send + Poll::Pending => Poll::Pending, } } - #[cfg(feature = "http1")] pub(crate) fn close(&mut self) { self.taker.cancel(); self.inner.close(); } - #[cfg(feature = "http1")] pub(crate) fn poll_close(&mut self, cx: &mut Context<'_>) -> Poll<()> { self.close(); // A send that started before close may still be publishing its envelope. diff --git a/src/common/buf.rs b/src/common/buf.rs index 0bf02497f4..fba2aaaebe 100644 --- a/src/common/buf.rs +++ b/src/common/buf.rs @@ -29,7 +29,7 @@ impl BufList { impl Buf for BufList { #[inline] fn remaining(&self) -> usize { - self.bufs.iter().map(|buf| buf.remaining()).sum() + self.bufs.iter().map(Buf::remaining).sum() } #[inline] diff --git a/src/error.rs b/src/error.rs index 1ccd09b7a9..48609ffcb3 100644 --- a/src/error.rs +++ b/src/error.rs @@ -193,7 +193,7 @@ impl Error { pub fn is_parse_too_large(&self) -> bool { matches!( self.inner.kind, - Kind::Parse(Parse::TooLarge) | Kind::Parse(Parse::UriTooLong) + Kind::Parse(Parse::TooLarge | Parse::UriTooLong) ) } @@ -354,7 +354,7 @@ impl Error { // Find an h2::Reason somewhere in the cause stack, if it exists, // otherwise assume an INTERNAL_ERROR. self.find_source::() - .and_then(|h2_err| h2_err.reason()) + .and_then(h2::Error::reason) .unwrap_or(h2::Reason::INTERNAL_ERROR) } diff --git a/src/lib.rs b/src/lib.rs index 8d6e2d2d5a..c7894a608a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,8 +1,10 @@ #![deny(missing_docs)] #![deny(missing_debug_implementations)] #![cfg_attr(test, deny(rust_2018_idioms))] -#![cfg_attr(all(test, feature = "full"), deny(unreachable_pub))] -#![cfg_attr(all(test, feature = "full"), deny(warnings))] +#![cfg_attr( + any(all(test, feature = "full"), feature = "__deny_warnings"), + deny(warnings, unreachable_pub) +)] #![cfg_attr(all(test, feature = "nightly"), feature(test))] #![cfg_attr(docsrs, feature(doc_cfg))] diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs index 8a5a734940..6a5bed9fc8 100644 --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -707,7 +707,9 @@ where // to do only speak HTTP/1.0 as well. head.version = Version::HTTP_10; } - Version::HTTP_11 => { + // A 101 hands off the connection to another protocol, so disabled + // HTTP keep-alive must not add a close option to the upgrade response + Version::HTTP_11 if !T::is_switching_protocols(head) => { if let KA::Disabled = self.state.keep_alive.status() { match head.headers.entry(CONNECTION) { Entry::Occupied(mut entry) => { @@ -778,24 +780,25 @@ where } } - pub(crate) fn write_body_and_end(&mut self, chunk: B) { + pub(crate) fn write_body_and_end(&mut self, chunk: B) -> crate::Result<()> { debug_assert!(self.can_write_body() && self.can_buffer_body()); // empty chunks should be discarded at Dispatcher level debug_assert!(chunk.remaining() != 0); let state = match &mut self.state.writing { - Writing::Body(encoder) => { - let can_keep_alive = encoder.encode_and_end(chunk, self.io.write_buf()); - if can_keep_alive { - Writing::KeepAlive - } else { - Writing::Closed + Writing::Body(encoder) => match encoder.encode_and_end(chunk, self.io.write_buf()) { + Ok(true) => Writing::KeepAlive, + Ok(false) => Writing::Closed, + Err(not_eof) => { + self.state.writing = Writing::Closed; + return Err(crate::Error::new_body_write_aborted().with(not_eof)); } - } + }, _ => unreachable!("write_body invalid state: {:?}", self.state.writing), }; self.state.writing = state; + Ok(()) } pub(crate) fn end_body(&mut self) -> crate::Result<()> { @@ -1068,8 +1071,8 @@ impl KA { *self = KA::Disabled; } - fn status(&self) -> KA { - *self + fn status(self) -> KA { + self } } diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs index 9d8ed7f408..9b27f1adc1 100644 --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -135,7 +135,12 @@ impl Decoder { Length(0) | Chunked { state: ChunkedState::End, - .. + chunk_len: _, + extensions_cnt: _, + trailers_buf: _, + trailers_cnt: _, + h1_max_headers: _, + h1_max_header_size: _, } | Eof(true) ) @@ -251,9 +256,8 @@ impl fmt::Debug for Decoder { macro_rules! byte ( ($rdr:ident, $cx:expr) => ({ - let buf = ready!($rdr.read_mem($cx, 1))?; - if !buf.is_empty() { - buf[0] + if let Some(b) = ready!($rdr.read_byte($cx))? { + b } else { return Poll::Ready(Err(io::Error::new(io::ErrorKind::UnexpectedEof, "unexpected EOF during chunk size line"))); @@ -301,7 +305,7 @@ impl ChunkedState { ChunkedState::Start } fn step( - &self, + self, cx: &mut Context<'_>, body: &mut R, StepArgs { @@ -318,7 +322,7 @@ impl ChunkedState { Body, BodyCr, BodyLf, End, EndCr, EndLf, Extension, Size, SizeLf, SizeLws, Start, Trailer, TrailerLf, }; - match *self { + match self { Start => ChunkedState::read_start(cx, body, chunk_size), Size => ChunkedState::read_size(cx, body, chunk_size), SizeLws => ChunkedState::read_size_lws(cx, body), @@ -547,6 +551,10 @@ impl ChunkedState { match byte { b'\r' => Poll::Ready(Ok(ChunkedState::TrailerLf)), + b'\n' => Poll::Ready(Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Invalid trailer line ending", + ))), _ => Poll::Ready(Ok(ChunkedState::Trailer)), } } @@ -599,6 +607,10 @@ impl ChunkedState { } Poll::Ready(Ok(ChunkedState::EndLf)) } + b'\n' => Poll::Ready(Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Invalid trailer line ending", + ))), byte => { match trailers_buf { None => { @@ -721,6 +733,60 @@ mod tests { } } + impl MemRead for BytesMut { + fn read_mem(&mut self, _: &mut Context<'_>, len: usize) -> Poll> { + let n = std::cmp::min(len, self.len()); + Poll::Ready(Ok(self.split_to(n).freeze())) + } + fn read_byte(&mut self, _: &mut Context<'_>) -> Poll>> { + if self.is_empty() { + return Poll::Ready(Ok(None)); + } + let b = self[0]; + bytes::Buf::advance(self, 1); + Poll::Ready(Ok(Some(b))) + } + } + + #[cfg(all(feature = "nightly", not(miri)))] + fn bench_chunked_body(b: &mut test::Bencher, n_chunks: usize, chunk: usize) { + let rt = new_runtime(); + let mut vec = Vec::new(); + for _ in 0..n_chunks { + vec.extend(format!("{:x}\r\n", chunk).as_bytes()); + vec.extend(std::iter::repeat(b'a').take(chunk)); + vec.extend(b"\r\n"); + } + vec.extend(b"0\r\n\r\n"); + b.bytes = (n_chunks * chunk) as u64; + b.iter(|| { + let mut raw = BytesMut::from(&vec[..]); + let mut decoder = Decoder::chunked(None, None); + rt.block_on(async { + let mut total = 0; + loop { + let d = decoder + .decode_fut(&mut raw) + .await + .unwrap() + .into_data() + .unwrap(); + if d.is_empty() { + break; + } + total += d.len(); + } + assert_eq!(total, n_chunks * chunk); + }); + }); + } + + #[cfg(all(feature = "nightly", not(miri)))] + #[bench] + fn bench_decode_chunked_small_chunks(b: &mut test::Bencher) { + bench_chunked_body(b, 100, 16) + } + impl MemRead for Bytes { fn read_mem(&mut self, _: &mut Context<'_>, len: usize) -> Poll> { let n = std::cmp::min(len, self.len()); @@ -972,6 +1038,53 @@ mod tests { assert_eq!(e.kind(), io::ErrorKind::InvalidInput); } + #[tokio::test] + async fn test_read_chunked_trailer_with_bare_lf() { + for trailers in [ + "\n", + "\nGET /smuggled HTTP/1.1\r\nHost: a\r\n\r\n", + "X\n: value\r\n\r\n", + "X: val\nue\r\n\r\n", + "X: value\n\nGET /smuggled HTTP/1.1\r\nHost: a\r\n\r\n", + "X: value\r\n\n", + "X: value\r\nY: value\n\r\n", + ] { + let body = format!("5\r\nhello\r\n0\r\n{trailers}"); + let mut mock_buf = body.as_bytes(); + let mut decoder = Decoder::chunked(None, None); + assert_eq!( + decoder + .decode_fut(&mut mock_buf) + .await + .unwrap() + .into_data() + .unwrap(), + "hello" + ); + let err = decoder.decode_fut(&mut mock_buf).await.unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{trailers:?}"); + } + } + + #[tokio::test] + async fn test_read_chunked_trailers_preserves_next_request() { + let next_request = "GET /next HTTP/1.1\r\nHost: a\r\n\r\n"; + let body = format!("0\r\nX: value\r\nY: value\r\n\r\n{next_request}"); + let mut mock_buf = body.as_bytes(); + let mut decoder = Decoder::chunked(None, None); + let trailers = decoder + .decode_fut(&mut mock_buf) + .await + .unwrap() + .into_trailers() + .unwrap(); + assert_eq!(trailers.len(), 2); + assert_eq!(trailers["x"], "value"); + assert_eq!(trailers["y"], "value"); + assert!(decoder.is_eof()); + assert_eq!(mock_buf, next_request.as_bytes()); + } + #[cfg(not(miri))] #[tokio::test] async fn test_read_chunked_after_eof() { diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs index 6ccbecba94..26c62391ec 100644 --- a/src/proto/h1/dispatch.rs +++ b/src/proto/h1/dispatch.rs @@ -433,7 +433,7 @@ where trace!("discarding empty chunk"); self.conn.end_body()?; } else { - self.conn.write_body_and_end(chunk); + self.conn.write_body_and_end(chunk)?; } } else { if chunk.remaining() == 0 { @@ -1005,6 +1005,41 @@ mod tests { assert!(!tx.is_ready()); } + #[tokio::test] + async fn client_body_shorter_than_content_length_errors() { + let _ = pretty_env_logger::try_init(); + + let (io, _handle) = tokio_test::io::Builder::new() + .write(b"POST / HTTP/1.1\r\ncontent-length: 10\r\n\r\nhello") + .wait(std::time::Duration::from_secs(2)) + .build_with_handle(); + + let (mut tx, rx) = crate::client::dispatch::channel(); + let conn = Conn::<_, bytes::Bytes, ClientTransaction>::new(Compat::new(io)); + let dispatcher = Dispatcher::new(Client::new(rx), conn); + let _dispatcher = tokio::spawn(async move { dispatcher.await }); + + // The body ends with its only chunk, so it takes the write_body_and_end path. + let body = { + let (mut tx, body) = IncomingBody::new_channel(DecodedLength::new(5), false); + tx.try_send_data("hello".into()).unwrap(); + body + }; + + let req = crate::Request::builder() + .method("POST") + .header("content-length", "10") + .body(body) + .unwrap(); + + let err = tokio::time::timeout(Duration::from_secs(1), tx.try_send(req).unwrap()) + .await + .expect("request should not hang") + .expect("callback dropped") + .expect_err("short body should error"); + assert!(err.error().is_body_write_aborted(), "{:?}", err.error()); + } + #[cfg(not(miri))] #[tokio::test] async fn body_empty_chunks_ignored() { diff --git a/src/proto/h1/encode.rs b/src/proto/h1/encode.rs index 4a9fd4348b..b4771f2d2f 100644 --- a/src/proto/h1/encode.rs +++ b/src/proto/h1/encode.rs @@ -221,7 +221,11 @@ impl Encoder { } } - pub(super) fn encode_and_end(&self, msg: B, dst: &mut WriteBuf>) -> bool + pub(super) fn encode_and_end( + &self, + msg: B, + dst: &mut WriteBuf>, + ) -> Result where B: Buf, { @@ -235,7 +239,7 @@ impl Encoder { .chain(msg) .chain(b"\r\n0\r\n\r\n" as &'static [u8]); dst.buffer(buf); - !self.is_last + Ok(!self.is_last) } Kind::Length(remaining) => { use std::cmp::Ordering; @@ -244,16 +248,16 @@ impl Encoder { match (len as u64).cmp(&remaining) { Ordering::Equal => { dst.buffer(msg); - !self.is_last + Ok(!self.is_last) } #[allow(clippy::cast_possible_truncation)] Ordering::Greater => { dst.buffer(msg.take(remaining as usize)); - !self.is_last + Ok(!self.is_last) } Ordering::Less => { dst.buffer(msg); - false + Err(NotEof(remaining - len as u64)) } } } @@ -261,7 +265,7 @@ impl Encoder { Kind::CloseDelimited => { trace!("close delimited write {}B", len); dst.buffer(msg); - false + Ok(false) } } } diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs index bcd0204d2f..cf8021ae30 100644 --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -351,6 +351,11 @@ impl Unpin for Buffered {} // TODO: This trait is old... at least rename to PollBytes or something... pub(crate) trait MemRead { fn read_mem(&mut self, cx: &mut Context<'_>, len: usize) -> Poll>; + + /// Reads one byte, `None` on EOF. + fn read_byte(&mut self, cx: &mut Context<'_>) -> Poll>> { + self.read_mem(cx, 1).map_ok(|b| b.first().copied()) + } } impl MemRead for Buffered @@ -367,6 +372,16 @@ where Poll::Ready(Ok(self.read_buf.split_to(::std::cmp::min(len, n)).freeze())) } } + + // Skips the split/freeze (and its refcount traffic) of `read_mem` for chunk framing bytes. + fn read_byte(&mut self, cx: &mut Context<'_>) -> Poll>> { + if self.read_buf.is_empty() && ready!(self.poll_read_from_io(cx))? == 0 { + return Poll::Ready(Ok(None)); + } + let b = self.read_buf[0]; + self.read_buf.advance(1); + Poll::Ready(Ok(Some(b))) + } } #[derive(Clone, Copy, Debug)] @@ -389,6 +404,7 @@ impl ReadStrategy { } } + #[allow(clippy::rest_pattern_accessible_field/*reason: this is an accessor*/)] fn next(&self) -> usize { match *self { ReadStrategy::Adaptive { next, .. } => next, @@ -397,6 +413,7 @@ impl ReadStrategy { } } + #[allow(clippy::rest_pattern_accessible_field/*reason: this is an accessor*/)] fn max(&self) -> usize { match *self { ReadStrategy::Adaptive { max, .. } => max, diff --git a/src/proto/h1/mod.rs b/src/proto/h1/mod.rs index 344d5a8a4f..a20e942032 100644 --- a/src/proto/h1/mod.rs +++ b/src/proto/h1/mod.rs @@ -37,6 +37,10 @@ pub(crate) trait Http1Transaction { fn on_error(err: &crate::Error) -> Option>; + fn is_switching_protocols(_head: &MessageHead) -> bool { + false + } + fn is_client() -> bool { !Self::is_server() } @@ -108,7 +112,7 @@ impl Wants { Wants(self.0 | other.0) } - fn contains(&self, other: Wants) -> bool { + fn contains(self, other: Wants) -> bool { (self.0 & other.0) == other.0 } } diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs index fce1df78af..6c05ad4763 100644 --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -493,10 +493,9 @@ impl Http1Transaction for Server { fn on_error(err: &crate::Error) -> Option> { use crate::error::Kind; let status = match *err.kind() { - Kind::Parse(Parse::Method) - | Kind::Parse(Parse::Header(_)) - | Kind::Parse(Parse::Uri) - | Kind::Parse(Parse::Version) => StatusCode::BAD_REQUEST, + Kind::Parse(Parse::Method | Parse::Header(_) | Parse::Uri | Parse::Version) => { + StatusCode::BAD_REQUEST + } Kind::Parse(Parse::TooLarge) => StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE, Kind::Parse(Parse::UriTooLong) => StatusCode::URI_TOO_LONG, _ => return None, @@ -510,6 +509,10 @@ impl Http1Transaction for Server { Some(msg) } + fn is_switching_protocols(head: &MessageHead) -> bool { + head.subject == StatusCode::SWITCHING_PROTOCOLS + } + fn is_server() -> bool { true } @@ -1162,6 +1165,13 @@ impl Http1Transaction for Client { headers.append(name, value); } + // https://tools.ietf.org/html/rfc7230#section-3.3.3 + // Transfer-Encoding overrides Content-Length; drop the latter so + // the exposed headers match the server-side decoder. + if headers.contains_key(header::TRANSFER_ENCODING) { + headers.remove(header::CONTENT_LENGTH); + } + let mut extensions = http::Extensions::default(); if let Some(header_case_map) = header_case_map { @@ -1349,7 +1359,8 @@ impl Client { }; // HTTP/1.0 doesn't know about chunked - let can_chunked = head.version == Version::HTTP_11; + // HTTP/2 requests are serialized as HTTP/1.1. + let can_chunked = matches!(head.version, Version::HTTP_11 | Version::HTTP_2); let headers = &mut head.headers; // If the user already set specific headers, we should respect them, regardless @@ -2407,19 +2418,30 @@ mod tests { DecodedLength::CLOSE_DELIMITED ); - // transfer-encoding and content-length = chunked - assert_eq!( - parse( - "\ - HTTP/1.1 200 OK\r\n\ - content-length: 10\r\n\ - transfer-encoding: chunked\r\n\ - \r\n\ - " - ) - .decode, - DecodedLength::CHUNKED + // transfer-encoding and content-length = chunked; Content-Length is dropped + let msg = parse( + "\ + HTTP/1.1 200 OK\r\n\ + content-length: 100000\r\n\ + transfer-encoding: chunked\r\n\ + \r\n\ + ", + ); + assert_eq!(msg.decode, DecodedLength::CHUNKED); + assert!(!msg.head.headers.contains_key(header::CONTENT_LENGTH)); + assert!(msg.head.headers.contains_key(header::TRANSFER_ENCODING)); + + let msg = parse( + "\ + HTTP/1.1 200 OK\r\n\ + transfer-encoding: chunked\r\n\ + content-length: 100000\r\n\ + \r\n\ + ", ); + assert_eq!(msg.decode, DecodedLength::CHUNKED); + assert!(!msg.head.headers.contains_key(header::CONTENT_LENGTH)); + assert!(msg.head.headers.contains_key(header::TRANSFER_ENCODING)); // HEAD can have content-length, but not body assert_eq!( diff --git a/src/proto/h2/client.rs b/src/proto/h2/client.rs index eb768baa76..12b87ecf96 100644 --- a/src/proto/h2/client.rs +++ b/src/proto/h2/client.rs @@ -201,6 +201,7 @@ where h2_tx, req_rx, fut_ctx: None, + closing: None, marker: PhantomData, }) } @@ -413,6 +414,7 @@ where B: Body, { is_connect: bool, + is_head: bool, eos: bool, fut: ResponseFuture, body_tx: SendStream>, @@ -434,6 +436,7 @@ where h2_tx: SendRequest>, req_rx: ClientRx, fut_ctx: Option>, + closing: Option>, marker: PhantomData, } @@ -567,6 +570,7 @@ where send_when: SendWhen { when: ResponseFutMap { fut: f.fut, + is_head: f.is_head, ping: Some(ping), send_stream: Some(send_stream), exec: self.executor.clone(), @@ -586,6 +590,7 @@ pin_project! { { #[pin] fut: ResponseFuture, + is_head: bool, ping: Option, #[pin] send_stream: Option::Data>>>>, @@ -623,7 +628,12 @@ where // record that we got the response headers ping.record_non_data(); - let content_length = headers::content_length_parse_all(res.headers()); + let content_length = if *this.is_head { + // HEAD Content-Length describes the corresponding GET response body. + Some(0) + } else { + headers::content_length_parse_all(res.headers()) + }; if let (Some(mut send_stream), StatusCode::OK) = (send_stream, res.status()) { if content_length.map_or(false, |len| len != 0) { warn!("h2 connect response with non-zero body not supported"); @@ -676,12 +686,50 @@ where type Output = crate::Result; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + if self.closing.is_none() { + let res = ready!(self.poll_dispatch(cx)); + self.closing = Some(res); + } + ready!(self.req_rx.poll_close(cx)); + Poll::Ready(self.closing.take().expect("Future polled twice")) + } +} + +impl ClientTask +where + B: Body + 'static + Unpin, + B::Data: Send, + B::Error: Into>, + E: Http2ClientConnExec + Clone + Unpin, + T: Read + Write + Unpin, +{ + fn poll_dispatch(&mut self, cx: &mut Context<'_>) -> Poll> { loop { match ready!(self.h2_tx.poll_ready(cx)) { Ok(()) => (), Err(err) => { self.ping.ensure_not_timed_out()?; - return if err.reason() == Some(::h2::Reason::NO_ERROR) { + let graceful = err.reason() == Some(::h2::Reason::NO_ERROR); + // A request may be parked in fut_ctx waiting for its + // stream to open. Fail it here with the connection + // error instead of letting it fall through to + // Callback::drop, which reports a misleading + // DispatchGone user error. + if let Some(f) = self.fut_ctx.take() { + let cb_err = if graceful { + crate::Error::new_canceled().with("connection closed") + } else { + match err.reason() { + Some(reason) => crate::Error::new_h2(reason.into()), + None => crate::Error::new_canceled().with("connection closed"), + } + }; + f.cb.send(Err(TrySendError { + error: cb_err, + message: None, + })); + } + return if graceful { trace!("connection gracefully shutdown"); Poll::Ready(Ok(Dispatched::Shutdown)) } else { @@ -714,6 +762,7 @@ where } let is_connect = req.method() == Method::CONNECT; + let is_head = req.method() == Method::HEAD; let eos = body.is_end_stream(); if is_connect @@ -746,6 +795,7 @@ where let f = FutCtx { is_connect, + is_head, eos, fut, body_tx, diff --git a/src/proto/h2/mod.rs b/src/proto/h2/mod.rs index 393d4179ab..0330afe7cf 100644 --- a/src/proto/h2/mod.rs +++ b/src/proto/h2/mod.rs @@ -69,7 +69,7 @@ fn strip_connection_headers(headers: &mut HeaderMap, kind: MessageKind) { warn!("TE headers illegal in HTTP/2 responses"); } - if let Some(header) = headers.remove(CONNECTION) { + if let http::header::Entry::Occupied(entry) = headers.entry(CONNECTION) { warn!( "Connection header illegal in HTTP/2: {}", CONNECTION.as_str() @@ -80,10 +80,14 @@ fn strip_connection_headers(headers: &mut HeaderMap, kind: MessageKind) { // Iterate these names and remove them as headers. Connection-specific headers are // forbidden in HTTP2, as that information has been moved into frame types of the h2 // protocol. - if let Ok(header_contents) = header.to_str() { - for name in header_contents.split(',') { - let name = name.trim(); - headers.remove(name); + let (_, values) = entry.remove_entry_mult(); + let values: Vec<_> = values.collect(); + for header in values { + if let Ok(header_contents) = header.to_str() { + for name in header_contents.split(',') { + let name = name.trim(); + headers.remove(name); + } } } } @@ -327,3 +331,24 @@ impl Buf for SendBuf { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn strip_connection_headers_multiple_values() { + let mut headers = HeaderMap::new(); + headers.append(CONNECTION, "x-a".parse().unwrap()); + headers.append(CONNECTION, "x-b, x-c".parse().unwrap()); + headers.insert("x-a", "1".parse().unwrap()); + headers.insert("x-b", "2".parse().unwrap()); + headers.insert("x-c", "3".parse().unwrap()); + headers.insert("x-d", "4".parse().unwrap()); + + strip_connection_headers(&mut headers, MessageKind::Request); + + assert_eq!(headers.len(), 1); + assert!(headers.contains_key("x-d")); + } +} diff --git a/src/proto/h2/server.rs b/src/proto/h2/server.rs index 2098758d9e..d18171495d 100644 --- a/src/proto/h2/server.rs +++ b/src/proto/h2/server.rs @@ -185,7 +185,10 @@ where pub(crate) fn graceful_shutdown(&mut self) { trace!("graceful_shutdown"); match &mut self.state { - State::Handshaking { .. } => { + State::Handshaking { + ping_config: _, + hs: _, + } => { self.close_pending = true; } State::Serving(srv) => { @@ -286,7 +289,7 @@ where if content_length.map_or(false, |len| len != 0) { warn!("h2 connect request with non-zero body not supported"); respond.send_reset(h2::Reason::INTERNAL_ERROR); - return Poll::Ready(Ok(())); + continue; } let (pending, upgrade) = crate::upgrade::pending(); debug_assert!(parts.extensions.get::().is_none()); diff --git a/src/proto/h2/upgrade.rs b/src/proto/h2/upgrade.rs index def1fcfc96..50addbc998 100644 --- a/src/proto/h2/upgrade.rs +++ b/src/proto/h2/upgrade.rs @@ -179,7 +179,7 @@ impl Read for H2Upgraded { } Some(Err(e)) => { return Poll::Ready(match e.reason() { - Some(Reason::NO_ERROR) | Some(Reason::CANCEL) => Ok(()), + Some(Reason::NO_ERROR | Reason::CANCEL) => Ok(()), Some(Reason::STREAM_CLOSED) => { Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, e)) } diff --git a/src/server/conn/http1.rs b/src/server/conn/http1.rs index 8dc83ab586..12ab61cc4f 100644 --- a/src/server/conn/http1.rs +++ b/src/server/conn/http1.rs @@ -555,7 +555,7 @@ where /// Return the inner IO object, and additional information provided the connection /// has not yet been upgraded. pub fn into_parts(self) -> Option> { - self.inner.map(|conn| conn.into_parts()) + self.inner.map(Connection::into_parts) } } diff --git a/src/server/conn/http2.rs b/src/server/conn/http2.rs index e4dac78bea..72f28ecbbd 100644 --- a/src/server/conn/http2.rs +++ b/src/server/conn/http2.rs @@ -120,6 +120,11 @@ impl Builder { } } + /// Returns the executor this builder was created with. + pub fn executor(&self) -> &E { + &self.exec + } + /// Configures the maximum number of pending reset streams allowed before a GOAWAY will be sent. /// /// This will default to the default value set by the [`h2` crate](https://crates.io/crates/h2). diff --git a/src/trace.rs b/src/trace.rs index 88f9a243a0..54f931f1c7 100644 --- a/src/trace.rs +++ b/src/trace.rs @@ -10,6 +10,27 @@ compile_error!( " ); +/// A type representing a RAII guard from a disabled tracing span. +/// +/// When the `tracing` feature flag is not active we do not enter tracing +/// spans. This type does nothing when dropped, and does not guard any +/// resources. +/// +/// This helps avoid expressions that conditionally compile to either `()` or +/// `tracing::span::Entered` depending on which feature flags are enabled. +// +// This ZST (zero sized type) marker only exists when the tracing flag is not +// active. +#[cfg(not(feature = "tracing"))] +// This module allows `unused_macros`. Similarly, we allow dead code in case +// none of the macros exported by this module are used elsewhere. +#[allow(dead_code)] +// This type is marked as a `#[must_use]` type not for its own semantic +// constraints, but to enforce consistency with code paths associated with +// the `tracing` feature flag. +#[must_use = "once a span has been entered, it should be exited"] +pub(crate) struct Disabled; + macro_rules! debug { ($($arg:tt)+) => { #[cfg(feature = "tracing")] @@ -27,6 +48,10 @@ macro_rules! debug_span { let _span = tracing::debug_span!($($arg)+); _span.entered() } + #[cfg(not(feature = "tracing"))] + { + crate::trace::Disabled + } } } } @@ -48,6 +73,10 @@ macro_rules! error_span { let _span = tracing::error_span!($($arg)+); _span.entered() } + #[cfg(not(feature = "tracing"))] + { + crate::trace::Disabled + } } } } @@ -69,6 +98,10 @@ macro_rules! info_span { let _span = tracing::info_span!($($arg)+); _span.entered() } + #[cfg(not(feature = "tracing"))] + { + crate::trace::Disabled + } } } } @@ -90,6 +123,10 @@ macro_rules! trace_span { let _span = tracing::trace_span!($($arg)+); _span.entered() } + #[cfg(not(feature = "tracing"))] + { + crate::trace::Disabled + } } } } @@ -123,6 +160,10 @@ macro_rules! warn_span { let _span = tracing::warn_span!($($arg)+); _span.entered() } + #[cfg(not(feature = "tracing"))] + { + crate::trace::Disabled + } } } } diff --git a/tests/client.rs b/tests/client.rs index 4cb6615657..85e5c7aeb3 100644 --- a/tests/client.rs +++ b/tests/client.rs @@ -1992,6 +1992,50 @@ mod conn { rt.block_on(future::join(res, rx).map(|r| r.0)).unwrap(); } + #[tokio::test] + async fn http1_conn_coerces_http2_streaming_request() { + tokio::time::timeout(Duration::from_secs(5), async { + let (client_io, server_io) = tokio::io::duplex(1024); + let svc = hyper::service::service_fn(|req: Request| async { + assert_eq!(req.method(), Method::POST); + assert_eq!(req.version(), hyper::Version::HTTP_11); + let chunked = req.headers().get("transfer-encoding").cloned(); + let body = concat(req).await?; + assert_eq!(body, "hello world"); + assert_eq!(chunked.as_ref().unwrap(), "chunked"); + Ok::<_, hyper::Error>(Response::new(Full::new(body))) + }); + let server = tokio::spawn( + hyper::server::conn::http1::Builder::new() + .serve_connection(TokioIo::new(server_io), svc), + ); + + let (mut client, connection) = conn::http1::handshake(TokioIo::new(client_io)) + .await + .unwrap(); + let connection = tokio::spawn(connection); + let body = StreamBody::new(futures_util::stream::iter([ + Ok::<_, std::convert::Infallible>(Frame::data(Bytes::from_static(b"hello"))), + Ok(Frame::data(Bytes::from_static(b" world"))), + ])); + assert_eq!(body.size_hint().exact(), None); + let req = Request::post("/a") + .version(hyper::Version::HTTP_2) + .body(body) + .unwrap(); + + let response = client.send_request(req).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(concat(response).await.unwrap(), "hello world"); + + drop(client); + connection.await.unwrap().unwrap(); + server.await.unwrap().unwrap(); + }) + .await + .expect("coerced request body should reach the server"); + } + #[test] fn pipeline() { let (server, addr) = setup_std_test_server(); @@ -2464,6 +2508,70 @@ mod conn { .unwrap(); } + #[tokio::test] + async fn http2_shutdown_drains_queued_request_before_resolving() { + use std::future::Future; + + #[derive(Clone)] + struct CaptureExecutor(std::sync::mpsc::Sender + Send>>>); + + impl hyper::rt::Executor for CaptureExecutor + where + F: Future + Send + 'static, + { + fn execute(&self, future: F) { + self.0.send(Box::pin(future)).unwrap(); + } + } + + let (io, peer) = tokio::io::duplex(4096); + let (tasks_tx, tasks_rx) = std::sync::mpsc::channel(); + let (mut client, mut conn) = conn::http2::Builder::new(CaptureExecutor(tasks_tx)) + .handshake::<_, Empty>(TokioIo::new(io)) + .await + .unwrap(); + + drop(peer); + // Finish the transport task without polling the request dispatcher. + let connection_task = tasks_rx.try_recv().unwrap(); + tokio::time::timeout(Duration::from_secs(5), connection_task) + .await + .expect("transport task should finish"); + + let response = client.try_send_request(Request::new(Empty::::new())); + + let first_poll = future::poll_fn(|cx| { + // Force the dispatch receiver to yield even though a request is queued. + loop { + let budget = tokio::task::consume_budget(); + tokio::pin!(budget); + if budget.poll(cx).is_pending() { + break; + } + } + Poll::Ready(Pin::new(&mut conn).poll(cx)) + }) + .await; + assert!( + first_poll.is_pending(), + "shutdown must wait for dispatch to drain" + ); + + let _ = tokio::time::timeout(Duration::from_secs(5), &mut conn) + .await + .expect("connection should finish draining"); + let err = tokio::time::timeout(Duration::from_secs(5), response) + .await + .expect("queued request should be canceled while connection is retained") + .expect_err("request should fail"); + assert!(err.error().is_canceled()); + assert!( + err.message().is_some(), + "unsent request should be recoverable" + ); + drop(conn); + } + #[tokio::test] async fn http2_detect_conn_eof() { use futures_util::future; @@ -2916,6 +3024,98 @@ mod conn { assert_eq!(trailers.get("grpc").unwrap(), "0"); } + #[tokio::test] + async fn http2_head_response_size_hint() { + tokio::time::timeout(Duration::from_secs(5), async { + for (method, end_stream, trailers, content_length) in [ + (Method::HEAD, true, false, Some("5")), + (Method::HEAD, false, false, Some("5")), + (Method::HEAD, false, true, Some("5")), + (Method::HEAD, false, false, None), + (Method::GET, false, false, Some("5")), + ] { + let (client_io, server_io) = tokio::io::duplex(4096); + let (finish_tx, finish_rx) = oneshot::channel(); + let expected_body = if method == Method::HEAD { + Bytes::new() + } else { + Bytes::from_static(b"hello") + }; + let response_body = expected_body.clone(); + let expected_method = method.clone(); + let server = tokio::spawn(async move { + let mut h2 = h2::server::handshake(server_io).await.unwrap(); + let (req, mut respond) = h2.accept().await.unwrap().unwrap(); + assert_eq!(req.method(), expected_method); + drop(req); + + let mut response = Response::builder(); + if let Some(value) = content_length { + response = response.header("content-length", value); + } + let mut stream = respond + .send_response(response.body(()).unwrap(), end_stream) + .unwrap(); + let finish = async move { + finish_rx.await.unwrap(); + if !end_stream { + if trailers { + let mut headers = hyper::HeaderMap::new(); + headers.insert("x-finished", "yes".parse().unwrap()); + stream.send_trailers(headers).unwrap(); + } else { + stream.send_data(response_body, true).unwrap(); + } + } + }; + let ((), result) = future::join(finish, poll_fn(|cx| h2.poll_closed(cx))).await; + result.unwrap(); + }); + + let (mut client, connection) = conn::http2::Builder::new(TokioExecutor) + .handshake(TokioIo::new(client_io)) + .await + .unwrap(); + let connection = tokio::spawn(connection); + let request = Request::builder() + .method(method) + .uri("https://localhost/") + .body(Empty::::new()) + .unwrap(); + let response = client.send_request(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + response + .headers() + .get("content-length") + .map(|v| v.to_str().unwrap()), + content_length, + ); + let mut body = response.into_body(); + assert_eq!(body.size_hint().exact(), Some(expected_body.len() as u64)); + assert_eq!(body.is_end_stream(), end_stream); + + finish_tx.send(()).unwrap(); + let collected = (&mut body).collect().await.unwrap(); + if trailers { + assert_eq!(collected.trailers().unwrap()["x-finished"], "yes"); + } else { + assert!(collected.trailers().is_none()); + } + assert_eq!(collected.to_bytes(), expected_body); + assert_eq!(body.size_hint().exact(), Some(0)); + assert!(body.is_end_stream()); + drop(body); + + drop(client); + connection.await.unwrap().unwrap(); + server.await.unwrap(); + } + }) + .await + .expect("response bodies should complete"); + } + #[tokio::test] async fn h2_connect() { let (client_io, server_io, _) = setup_duplex_test_server(); @@ -2971,6 +3171,68 @@ mod conn { upgraded.shutdown().await.unwrap(); } + #[tokio::test] + async fn h2_pending_open_fails_with_connection_error_on_close() { + // A request parked waiting for a stream slot (the server only + // allows one concurrent stream and the first is still open) must + // fail with a connection error when the peer goes away, not with + // a misleading DispatchGone user error. + let (client_io, server_io, _) = setup_duplex_test_server(); + + tokio::spawn(async move { + let sock = server_io; + let mut h2 = h2::server::Builder::new() + .max_concurrent_streams(1) + .handshake::<_, bytes::Bytes>(sock) + .await + .unwrap(); + + // Accept the first request and hold its stream open, so the + // second request parks waiting for a stream slot. + let (_req, respond) = h2.accept().await.unwrap().unwrap(); + tokio::time::sleep(Duration::from_millis(200)).await; + // Close the connection while the second request is parked. + drop(respond); + drop(h2); + }); + + let io = TokioIo::new(client_io); + let (mut client, conn) = conn::http2::Builder::new(TokioExecutor) + .handshake(io) + .await + .expect("http handshake"); + + tokio::spawn(async move { + let _ = conn.await; + }); + + let mut client2 = client.clone(); + let req1 = Request::builder() + .uri("http://localhost/") + .body(Empty::::new()) + .unwrap(); + let res1 = tokio::spawn(async move { client.send_request(req1).await }); + let req2 = Request::builder() + .uri("http://localhost/") + .body(Empty::::new()) + .unwrap(); + let res2 = tokio::spawn(async move { client2.send_request(req2).await }); + + // The first request stays open on the server, the second parks. + // Both fail once the connection closes; the parked one must not + // come back as a user (DispatchGone) error. + let err = res2.await.unwrap().expect_err("parked request must fail"); + assert!( + !err.is_user(), + "parked request failed with a user error instead of a connection error: {err:?}" + ); + assert!( + err.is_canceled(), + "parked request should fail as canceled when the connection closes: {err:?}" + ); + let _ = res1.await; + } + #[tokio::test] async fn h2_connect_rejected() { let (client_io, server_io, _) = setup_duplex_test_server(); diff --git a/tests/h1_ready_in_flight.rs b/tests/h1_ready_in_flight.rs index f2317ba308..19edc104cc 100644 --- a/tests/h1_ready_in_flight.rs +++ b/tests/h1_ready_in_flight.rs @@ -1,16 +1,15 @@ // Test: an HTTP/1 client connection must not report ready while a request is // in flight on it. // -// The dispatch `Receiver` signals want when its queue reports `Pending`, and -// `SendRequest::is_ready` reports that want. The signal can go stale: the -// connection task can find its queue empty and a request land before it -// signals, or tokio's coop budget can make the queue report `Pending` with a -// request already in it. The request is then taken with want still set, so -// `is_ready` stays true until the response is complete. Pools that return a -// connection on `is_ready`, such as hyper-util's legacy client, then give that -// connection to the next request, which waits behind the whole response. +// Re-granting `want` on every `Pending` poll from the dispatch channel can +// falsely mark the connection as ready while a request is already in flight +// (eg, during a concurrent send or when Tokio's coop budget runs out with +// a buffered request) +// Revoking readiness when the request is dequeued is too late, as the caller +// may have already seen `Ready` and will fail on send // -// The coop path is deterministic, so the test drives that one. +// Deterministically trigger coop exhaustion and verify readiness state both +// before and after dequeuing the buffered request use std::future::Future; use std::io; @@ -73,14 +72,20 @@ async fn h1_connection_is_not_ready_while_a_request_is_in_flight() { let _response = sender.send_request(Request::new(Empty::new())); assert!(!sender.is_ready()); - // Out of coop budget, the queue reports Pending with the request in it, so - // the connection signals ready again. A connection task preempted between - // finding its queue empty and signaling leaves the same stale signal. + // With the coop budget exhausted, polling the queue yields `Pending` even + // though a request is buffered + // Readiness must not be re-signaled here poll_fn(|cx| { while let Poll::Ready(restore) = tokio::task::coop::poll_proceed(cx) { restore.made_progress(); } - poll_conn(&mut conn, cx) + let _ = poll_conn(&mut conn, cx); + assert!( + sender.poll_ready(cx).is_pending(), + "dispatcher should not report ready while a request is still buffered" + ); + assert!(!sender.is_ready()); + Poll::Ready(()) }) .await; tokio::task::yield_now().await; diff --git a/tests/server.rs b/tests/server.rs index 094558cb61..f62e1228a5 100644 --- a/tests/server.rs +++ b/tests/server.rs @@ -1819,18 +1819,23 @@ async fn upgrades_new() { b"\ GET / HTTP/1.1\r\n\ Upgrade: foobar\r\n\ - Connection: upgrade\r\n\ + Connection: close, Upgrade\r\n\ \r\n\ eagerly optimistic\ ", ) .expect("write 1"); let mut buf = [0; 256]; - tcp.read(&mut buf).expect("read 1"); + let response = read_until(&mut tcp, |buf| buf.ends_with(b"\r\n\r\n")).expect("read 1"); - let response = s(&buf); + let response = s(&response); assert!(response.starts_with("HTTP/1.1 101 Switching Protocols\r\n")); assert!(!has_header(response, "content-length")); + assert!( + response.contains("\r\nconnection: upgrade\r\n"), + "{response}" + ); + assert!(!response.contains("close"), "{response}"); let _ = read_101_tx.send(()); let n = tcp.read(&mut buf).expect("read 2"); @@ -1846,6 +1851,7 @@ async fn upgrades_new() { Response::builder() .status(101) .header("upgrade", "foobar") + .header("connection", "upgrade") .body(Empty::::new()) .unwrap(), ) @@ -2047,6 +2053,75 @@ async fn h2_connect() { .unwrap(); } +#[tokio::test] +async fn h2_connect_with_content_length_only_resets_stream() { + tokio::time::timeout(Duration::from_secs(5), async { + let (client_io, server_io) = tokio::io::duplex(4096); + let (started_tx, started_rx) = oneshot::channel(); + let (release_tx, release_rx) = oneshot::channel(); + let pending = Mutex::new(Some((started_tx, release_rx))); + + let svc = service_fn(move |req: Request| { + assert_eq!(req.method(), Method::GET); + let pending = if req.uri().path() == "/pending" { + pending.lock().unwrap().take() + } else { + None + }; + async move { + if let Some((started_tx, release_rx)) = pending { + started_tx.send(()).unwrap(); + release_rx.await.unwrap(); + } + Ok::<_, hyper::Error>(Response::new(Full::new(Bytes::from_static(b"hello")))) + } + }); + let server = tokio::spawn( + http2::Builder::new(TokioExecutor).serve_connection(TokioIo::new(server_io), svc), + ); + + let (mut client, connection) = h2::client::handshake(client_io).await.unwrap(); + let connection = tokio::spawn(connection); + + let request = Request::get("https://localhost/pending").body(()).unwrap(); + let (pending_response, _) = client.send_request(request, true).unwrap(); + started_rx.await.unwrap(); + + let request = Request::connect("localhost:443") + .header("content-length", "1") + .body(()) + .unwrap(); + let (response, request_body) = client.send_request(request, false).unwrap(); + let err = response.await.expect_err("CONNECT should be reset"); + assert_eq!(err.reason(), Some(h2::Reason::INTERNAL_ERROR)); + drop(request_body); + + release_tx.send(()).unwrap(); + let response = pending_response.await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let mut body = response.into_body(); + assert_eq!(body.data().await.unwrap().unwrap(), "hello"); + assert!(body.data().await.is_none()); + drop(body); + + let mut client = client.ready().await.unwrap(); + let request = Request::get("https://localhost/after").body(()).unwrap(); + let (response, _) = client.send_request(request, true).unwrap(); + let response = response.await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let mut body = response.into_body(); + assert_eq!(body.data().await.unwrap().unwrap(), "hello"); + assert!(body.data().await.is_none()); + drop(body); + + drop(client); + connection.await.unwrap().unwrap(); + server.await.unwrap().unwrap(); + }) + .await + .expect("connection should remain usable after resetting CONNECT"); +} + #[tokio::test] async fn h2_connect_multiplex() { use futures_util::stream::FuturesUnordered;