From b07337878fe57b34b2065335ae8cae9ce5a780a0 Mon Sep 17 00:00:00 2001 From: katelyn martin Date: Tue, 13 Oct 2026 13:47:23 -0400 Subject: [PATCH 01/23] style(proto): enforce clippy:let_unit_value (#4231) see https://github.com/hyperium/hyper/issues/4071. this commit addresses the `let_unit_value` clippy lint. only two sites are affected, relating to tracing spans. this commit introduces a `hyper::trace::Disabled` type to act as a ZST marker in places that can sometimes conditionally compile to a `tracing::span::Entered` guard. this is based upon experimenting in . to restate some of those learnings here: ### background hyper contains a `trace` submodule, introduced in hyperium/hyper#3326, that contains macros like the following: ```rust macro_rules! trace { ($($arg:tt)*) => { #[cfg(feature = "tracing")] { tracing::trace!($($arg)+); } } } macro_rules! trace_span { ($($arg:tt)*) => { { #[cfg(feature = "tracing")] { let _span = tracing::trace_span!($($arg)+); _span.entered() } } } } ``` these thinly wrap `tracing`'s macros, to account for the fact that tracing support in hyper is opt-in. it is gated behind a feature flag, and additionally mandates that the `hyper_unstable_tracing` flag be enabled. however, this leads to violations of clippy's `let_unit_value` rule when compiled without the `tracing` feature flag is enabled. this is because `trace_span!` only returns a `tracing::span::Entered` when that flag is active, otherwise it returns `()`. thus, we *must* bind these calls to a variable, so that we properly hold on to the span guard when the tracing flag is active. however, we must contend with the fact that when this flag is not active, strict clippy linting yields us warnings like this: ```text cargo clippy --no-default-features Checking hyper-span-macro-example v0.1.0 error: this let-binding has unit value --> src/main.rs:52:5 | 52 | let _entered = trace_span!("instrumented"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.99.0/index.html#let_unit_value ``` ### why not use `#[allow(..)]` one might try to selectively apply `#[allow(clippy::let_unit_value)]` attributes to stifle this. however, applying attributes to expressions is still a nightly feature we cannot rely on yet, so call-sites for our macros must be updated rather than modifying the code generated by the macro. see rust-lang/rust#15701. this would require us to do something like this throughout the codebase, wherever we create tracing spans: ```rust #[cfg_attr(not(feature = "tracing"), allow(clippy::let_unit_value))] let _entered = trace_span!("instrumented"); ``` `#[cfg_attr]` is a bit esoteric, and if we require that instrumenting code in hyper require this song and dance every time we create a span, it will generally discourage instrumentation. ### changes this commit introduce a `Disabled` type to replace the empty `()` when tracing instrumentation is disabled. this satisfies clippy's `let_unit_value` rule because macros like `trace_span!` will never return `()` no matter which feature flags are active. this _also_ prevents accidentally writing code that would drop span guards once the tracing flag is enabled, because an inert `#[must_use]` guard acts as a stand-in when the flag isn't present. Signed-off-by: katelyn martin --- Cargo.toml | 1 - src/trace.rs | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index f7f7f1e6c4..33fa8fee91 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -120,7 +120,6 @@ 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" 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 + } } } } From a8ab2c7fa4583a37e39ed89db6b22bcb30107d40 Mon Sep 17 00:00:00 2001 From: Trivikram Kamat <16024985+trivikr@users.noreply.github.com> Date: Thu, 29 Oct 2026 12:48:27 -0700 Subject: [PATCH 02/23] style(lib): enforce clippy::redundant_closure_for_method_calls (#4251) See https://github.com/hyperium/hyper/issues/4071. Clippy lint documentation is at https://clippy.rust-lang.org/master/index.html#redundant_closure_for_method_calls. The rule checks for closures which only invoke a method on the closure argument and can be replaced by referencing the method directly. Only three closures matched this rule, which called a single method without arguments. They were replaced by referencing the method directly. --- Cargo.toml | 1 - src/common/buf.rs | 2 +- src/error.rs | 2 +- src/server/conn/http1.rs | 2 +- 4 files changed, 3 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 33fa8fee91..d1738cc1ac 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -125,7 +125,6 @@ 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" 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..bfbcf90cc5 100644 --- a/src/error.rs +++ b/src/error.rs @@ -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/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) } } From 8abd0b4873f5a5fc3a9d16e72c0fda90dc70dd66 Mon Sep 17 00:00:00 2001 From: Trivikram Kamat <16024985+trivikr@users.noreply.github.com> Date: Fri, 30 Oct 2026 11:31:18 -0700 Subject: [PATCH 03/23] style(lib): enforce clippy::trivially_copy_pass_by_ref (#4252) See https://github.com/hyperium/hyper/issues/4071. Lint doc: https://clippy.rust-lang.org/master/index.html#trivially_copy_pass_by_ref The rule checks for functions taking arguments by reference, where the argument type is Copy and small enough to be more efficient to always pass by value. Only four functions were flagged by this rule, where `&self` was changed to `self`. --- Cargo.toml | 1 - src/body/length.rs | 2 +- src/proto/h1/conn.rs | 4 ++-- src/proto/h1/decode.rs | 4 ++-- src/proto/h1/mod.rs | 2 +- 5 files changed, 6 insertions(+), 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index d1738cc1ac..7f372a27ed 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -127,7 +127,6 @@ needless_pass_by_value = "allow" pattern_type_mismatch = "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 diff --git a/src/body/length.rs b/src/body/length.rs index 1ed5e0d031..ba121bde11 100644 --- a/src/body/length.rs +++ b/src/body/length.rs @@ -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/proto/h1/conn.rs b/src/proto/h1/conn.rs index 8a5a734940..1c00f6f774 100644 --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -1068,8 +1068,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..c46a5dba80 100644 --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -301,7 +301,7 @@ impl ChunkedState { ChunkedState::Start } fn step( - &self, + self, cx: &mut Context<'_>, body: &mut R, StepArgs { @@ -318,7 +318,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), diff --git a/src/proto/h1/mod.rs b/src/proto/h1/mod.rs index 344d5a8a4f..37045d6856 100644 --- a/src/proto/h1/mod.rs +++ b/src/proto/h1/mod.rs @@ -108,7 +108,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 } } From cf563e8a97cc389fd8800a9f178e847dc3203d1f Mon Sep 17 00:00:00 2001 From: Trivikram Kamat <16024985+trivikr@users.noreply.github.com> Date: Mon, 2 Nov 2026 08:37:23 -0800 Subject: [PATCH 04/23] style(lib): enforce clippy::unnested_or_patterns (#4256) see https://github.com/hyperium/hyper/issues/4071. Lint doc: https://clippy.rust-lang.org/master/index.html#unnested_or_patterns The rule rewrites patterns in disjunctive normal form (DNF) into conjunctive normal form (CNF). Four patterns were flagged by this rule, which were replaced with equivalent nested ones. --- Cargo.toml | 1 - src/body/length.rs | 2 +- src/error.rs | 2 +- src/proto/h1/role.rs | 7 +++---- src/proto/h2/upgrade.rs | 2 +- 5 files changed, 6 insertions(+), 8 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 7f372a27ed..ed5e00c770 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -127,7 +127,6 @@ needless_pass_by_value = "allow" pattern_type_mismatch = "allow" redundant_else = "allow" struct_excessive_bools = "allow" # TODO: bogus lint? -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" diff --git a/src/body/length.rs b/src/body/length.rs index ba121bde11..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; } diff --git a/src/error.rs b/src/error.rs index bfbcf90cc5..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) ) } diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs index fce1df78af..e976931c76 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, 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)) } From c5e100ca0d5497a021894215bad9222099c32203 Mon Sep 17 00:00:00 2001 From: katelyn martin Date: Mon, 9 Nov 2026 10:12:25 -0500 Subject: [PATCH 05/23] chore(ci): deny warnings in 'features' step (#4253) fixes https://github.com/hyperium/hyper/issues/4232. in #4231, we found that we don't deny warnings when running cargo hack, because of the predicate that conditionally gates a crate-level `#![deny(warnings)]` attribute in `lib.rs`: ```rust // src/lib.rs #![cfg_attr(all(test, feature = "full"), deny(unreachable_pub))] #![cfg_attr(all(test, feature = "full"), deny(warnings))] #![cfg_attr(all(test, feature = "nightly"), feature(test))] ``` while this prevents warnings from existing when running `cargo test --features full`, it does not affect other builds. so, this would not be active in the commands run by the `features` step in CI, which runs the following two `cargo-hack` commands: ```sh RUSTFLAGS="-D dead_code -D unused_imports" \ cargo hack --no-dev-deps check \ --feature-powerset --depth 2 --skip ffi,tracing RUSTFLAGS="--cfg hyper_unstable_tracing -D dead_code -D unused_imports" \ cargo hack --no-dev-deps check \ --feature-powerset --depth 2 --features tracing --skip ffi ``` this commit introduces a new feature, intended for internal use in CI, called `__deny_warnings`. this provides another mechanism to deny warnings when building hyper. `cargo hack` invocations run in CI are updated to enable this flag. because `-D dead_code -D unused_imports` are now redundant, the `RUSTFLAGS` values passed to these steps are also accordingly simplified. Signed-off-by: katelyn martin --- .github/workflows/CI.yml | 8 +++----- Cargo.toml | 1 + src/lib.rs | 6 ++++-- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 5d625ae140..1f8568549f 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -181,14 +181,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/Cargo.toml b/Cargo.toml index ed5e00c770..51db37736f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -96,6 +96,7 @@ capi = [] tracing = ["dep:tracing"] # internal features used in CI +__deny_warnings = [] nightly = [] [lints.rust.unexpected_cfgs] 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))] From b638fc0de351987f3eaffa2bdabd393c8679a9e8 Mon Sep 17 00:00:00 2001 From: Robert Ream Date: Mon, 9 Nov 2026 12:28:32 -0800 Subject: [PATCH 06/23] feat(http2): add an executor getter for server and client (#4250) `Builder::new(exec)` is the only constructor on either HTTP/2 builder and the executor cannot be read back, so a caller that needs it for work alongside a connection keeps a second copy with nothing relating the two. `impl Builder` is unconstrained, so the accessor needs no bound, and returning `&E` leaves cloning to the caller. Signed-off-by: katelyn martin --- src/client/conn/http2.rs | 5 +++++ src/server/conn/http2.rs | 5 +++++ 2 files changed, 10 insertions(+) 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/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). From 378f8479b8b703d098b46de1cec9ea648f12ea69 Mon Sep 17 00:00:00 2001 From: kevin <5299031+kevin9327@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:01:56 +0900 Subject: [PATCH 07/23] fix(http1): drop Content-Length when a response also has Transfer-Encoding (#4264) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The HTTP/1 server decoder already removes Content-Length when Transfer-Encoding is present. The client decoder preferred Transfer-Encoding for the body length, but still exposed both headers. RFC 7230 ยง3.3.3 says Transfer-Encoding overrides Content-Length. Remove the Content-Length header from parsed responses so callers cannot treat it as authoritative. Closes #4263 --- src/proto/h1/role.rs | 42 ++++++++++++++++++++++++++++++------------ 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs index e976931c76..18d587610a 100644 --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1161,6 +1161,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 { @@ -2406,19 +2413,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!( From 88520c3eaea391f8ba49591a84f8439998b76191 Mon Sep 17 00:00:00 2001 From: Shuvro Roy Date: Sat, 14 Nov 2026 00:51:19 +0600 Subject: [PATCH 08/23] fix(http2): keep connection open after rejecting CONNECT (#4235) Continue accepting streams after resetting a CONNECT request with a nonzero Content-Length. Returning from the server loop closes the entire HTTP/2 connection and interrupts unrelated requests. Add a regression test that keeps a GET in flight during the reset and then sends another GET over the same connection. --- src/proto/h2/server.rs | 2 +- tests/server.rs | 69 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/src/proto/h2/server.rs b/src/proto/h2/server.rs index 2098758d9e..03b6180385 100644 --- a/src/proto/h2/server.rs +++ b/src/proto/h2/server.rs @@ -286,7 +286,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/tests/server.rs b/tests/server.rs index 094558cb61..b335433afb 100644 --- a/tests/server.rs +++ b/tests/server.rs @@ -2047,6 +2047,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; From b1e7eabff4683a4fa6a9f97479736a325437bae6 Mon Sep 17 00:00:00 2001 From: Sean McArthur Date: Fri, 13 Nov 2026 13:51:49 -0500 Subject: [PATCH 09/23] chore(github): add human authorship checkbox to issue templates (#4267) --- .github/ISSUE_TEMPLATE/bug_report.yml | 6 ++++++ .github/ISSUE_TEMPLATE/feature_request.md | 3 +++ 2 files changed, 9 insertions(+) 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 [...] From a44e32a7f85a1f98e34307ae17985c0bc1349a03 Mon Sep 17 00:00:00 2001 From: Patrick Hintermayer Date: Mon, 16 Nov 2026 14:48:34 +0100 Subject: [PATCH 10/23] fix(http2): strip all headers named in every Connection header (#4271) HeaderMap::remove returns only the first value, so headers listed in a second Connection line were still sent over HTTP/2. --- src/proto/h2/mod.rs | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) 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")); + } +} From 00a85adb71e8429a615d0f98ca7620aafc2f0baf Mon Sep 17 00:00:00 2001 From: Patrick Hintermayer Date: Mon, 16 Nov 2026 17:13:43 +0100 Subject: [PATCH 11/23] perf(http1): read chunk framing bytes without split_to (#4272) The chunked decoder read every size, CRLF and trailer byte through read_mem(1), paying a split_to().freeze() per byte. Add read_byte to MemRead and use it in the byte! macro. About 3x faster decoding for small chunks. --- src/proto/h1/decode.rs | 59 +++++++++++++++++++++++++++++++++++++++--- src/proto/h1/io.rs | 15 +++++++++++ 2 files changed, 71 insertions(+), 3 deletions(-) diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs index c46a5dba80..78dd2ce754 100644 --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -251,9 +251,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"))); @@ -721,6 +720,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()); diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs index bcd0204d2f..f5829a2786 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)] From 750620646ba0777daa45be3d82bd1704dcf470b8 Mon Sep 17 00:00:00 2001 From: Patrick Hintermayer Date: Mon, 16 Nov 2026 18:13:47 +0100 Subject: [PATCH 12/23] fix(http1): error when final body chunk is shorter than content-length (#4270) A body whose only frame ends the stream goes through write_body_and_end, which ignored a short write and just closed the writer. The client then waited forever for a response. Return the same BodyWriteAborted error that end_body already returns for streamed bodies. --- src/proto/h1/conn.rs | 17 +++++++++-------- src/proto/h1/dispatch.rs | 37 ++++++++++++++++++++++++++++++++++++- src/proto/h1/encode.rs | 16 ++++++++++------ 3 files changed, 55 insertions(+), 15 deletions(-) diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs index 1c00f6f774..108c1d9e5d 100644 --- a/src/proto/h1/conn.rs +++ b/src/proto/h1/conn.rs @@ -778,24 +778,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<()> { 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) } } } From dea9acb5344e0e34bb9196f5493464db68edd24a Mon Sep 17 00:00:00 2001 From: Azhar Date: Tue, 17 Nov 2026 03:58:44 +0530 Subject: [PATCH 13/23] fix(client): fail parked h2 request with connection error on close (#4275) When the h2 connection drops while a request is still waiting for a stream slot, the parked callback was left to drop, and the caller got a misleading DispatchGone user error. Fail it with the connection error instead: canceled on a clean GOAWAY, the h2 reason otherwise. Adds a regression test with a server that only allows one concurrent stream and closes while the second request is parked. Fixes #4269 --- src/proto/h2/client.rs | 22 ++++++++++++++- tests/client.rs | 62 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 1 deletion(-) diff --git a/src/proto/h2/client.rs b/src/proto/h2/client.rs index eb768baa76..6fa1c4b424 100644 --- a/src/proto/h2/client.rs +++ b/src/proto/h2/client.rs @@ -681,7 +681,27 @@ where 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 { diff --git a/tests/client.rs b/tests/client.rs index 4cb6615657..19cadda79f 100644 --- a/tests/client.rs +++ b/tests/client.rs @@ -2971,6 +2971,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(); From ac3f9501de373388fb9914e285134cfec2283bd8 Mon Sep 17 00:00:00 2001 From: Asuka Date: Tue, 17 Nov 2026 22:25:00 +0900 Subject: [PATCH 14/23] fix(http1): avoid adding connection-close to 101 responses (#4248) Do not append Connection: close to an HTTP/1.1 101 response when HTTP keep-alive is disabled The connection is handed off to the upgraded protocol rather than closed Extend the existing upgrade test to cover a request with Connection: close, Upgrade Verify the response headers while retaining the buffered-byte and upgraded-I/O checks Fixes #4244 --- src/proto/h1/conn.rs | 4 +++- src/proto/h1/mod.rs | 4 ++++ src/proto/h1/role.rs | 4 ++++ tests/server.rs | 12 +++++++++--- 4 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs index 108c1d9e5d..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) => { diff --git a/src/proto/h1/mod.rs b/src/proto/h1/mod.rs index 37045d6856..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() } diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs index 18d587610a..d27c429cab 100644 --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -509,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 } diff --git a/tests/server.rs b/tests/server.rs index b335433afb..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(), ) From 47c725c459ede66e68ad705f7da9a901abbbdc17 Mon Sep 17 00:00:00 2001 From: Asuka Date: Tue, 17 Nov 2026 22:40:11 +0900 Subject: [PATCH 15/23] fix(http1): prevent `SendRequest` from reporting ready while a request is pending (#4247) Represent the initial buffer slot with a want and signal each subsequent want only once per receive cycle Do not restore readiness on Pending or withdraw a grant when dequeuing a request Extend the existing regression to check readiness while the request is still queued Fixes #4246 --- src/client/dispatch.rs | 69 ++++++++++++++----------------------- tests/h1_ready_in_flight.rs | 31 ++++++++++------- 2 files changed, 44 insertions(+), 56 deletions(-) diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs index 76a9c3e20c..143fc5a9cb 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,24 +158,25 @@ 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, } } 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; From 5634b91d607ba1b781699765b22f16fd6ec1c8b7 Mon Sep 17 00:00:00 2001 From: mingley <46031485+mingley@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:59:12 -0600 Subject: [PATCH 16/23] fix(http2): prevent requests from hanging during concurrent connection shutdown race (#4242) --- src/client/dispatch.rs | 2 -- src/proto/h2/client.rs | 20 ++++++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/client/dispatch.rs b/src/client/dispatch.rs index 143fc5a9cb..c3140cf6d7 100644 --- a/src/client/dispatch.rs +++ b/src/client/dispatch.rs @@ -180,13 +180,11 @@ impl Receiver { } } - #[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/proto/h2/client.rs b/src/proto/h2/client.rs index 6fa1c4b424..c7dcd1e1e2 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, }) } @@ -434,6 +435,7 @@ where h2_tx: SendRequest>, req_rx: ClientRx, fut_ctx: Option>, + closing: Option>, marker: PhantomData, } @@ -676,6 +678,24 @@ 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(()) => (), From 6b7673f9f04f8938fef1158cf87d78c6bfeabafe Mon Sep 17 00:00:00 2001 From: Sean McArthur Date: Tue, 17 Nov 2026 09:16:22 -0500 Subject: [PATCH 17/23] test(http2): test for http2 connection shutdown race of pending reqs (#4276) --- tests/client.rs | 64 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/tests/client.rs b/tests/client.rs index 19cadda79f..d422338a6a 100644 --- a/tests/client.rs +++ b/tests/client.rs @@ -2464,6 +2464,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; From 4e1c0fbb9db68936c952c481321d96f536568283 Mon Sep 17 00:00:00 2001 From: Shuvro Roy Date: Wed, 18 Nov 2026 02:20:37 +0600 Subject: [PATCH 18/23] fix(http2): report zero body size hint for HEAD responses (#4237) Carry the request method through response mapping and use an exact body length of zero for HEAD responses. Their Content-Length describes the corresponding GET representation, not the bytes in the response body. Preserve the response header and receive stream so delayed completion and trailers remain observable. Cover immediate completion, empty DATA, trailers, missing Content-Length, and a GET response as a control. --- src/proto/h2/client.rs | 12 +++++- tests/client.rs | 92 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 1 deletion(-) diff --git a/src/proto/h2/client.rs b/src/proto/h2/client.rs index c7dcd1e1e2..12b87ecf96 100644 --- a/src/proto/h2/client.rs +++ b/src/proto/h2/client.rs @@ -414,6 +414,7 @@ where B: Body, { is_connect: bool, + is_head: bool, eos: bool, fut: ResponseFuture, body_tx: SendStream>, @@ -569,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(), @@ -588,6 +590,7 @@ pin_project! { { #[pin] fut: ResponseFuture, + is_head: bool, ping: Option, #[pin] send_stream: Option::Data>>>>, @@ -625,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"); @@ -754,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 @@ -786,6 +795,7 @@ where let f = FutCtx { is_connect, + is_head, eos, fut, body_tx, diff --git a/tests/client.rs b/tests/client.rs index d422338a6a..8abf545de4 100644 --- a/tests/client.rs +++ b/tests/client.rs @@ -2980,6 +2980,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(); From 21da6a59db9a90631302e7b173c106b723b9065f Mon Sep 17 00:00:00 2001 From: Shuvro Roy Date: Wed, 18 Nov 2026 02:42:39 +0600 Subject: [PATCH 19/23] fix(http1): preserve streaming bodies when coercing HTTP/2 requests (#4236) Allow chunked framing for HTTP/2 requests serialized as HTTP/1.1. Previously, unknown-length bodies without Content-Length used a zero-length encoder and were silently discarded. Add an integration regression that verifies the HTTP/1.1 version, chunked framing, complete payload, and body termination. --- src/proto/h1/role.rs | 3 ++- tests/client.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/src/proto/h1/role.rs b/src/proto/h1/role.rs index d27c429cab..6c05ad4763 100644 --- a/src/proto/h1/role.rs +++ b/src/proto/h1/role.rs @@ -1359,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 diff --git a/tests/client.rs b/tests/client.rs index 8abf545de4..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(); From 32e7d3fc18682441b34964b94372da3fff91851f Mon Sep 17 00:00:00 2001 From: Sean McArthur Date: Mon, 23 Nov 2026 12:47:26 -0500 Subject: [PATCH 20/23] refactor(http1): reject bare LF in trailers (#4282) Unlike headers, HTTP/1.1 chunked decoding *only* declares CRLF as frame delimiters. Thus, until now, our parser has only cared about finding CRLFs, and then treating anything inside as trailers. See https://errata.rfc-editor.org/eid7633/ If a message body sends 'trailers' with bare LFs, hyper will parse past them, and then eventually ignore any invalid trailers. The change: we now look for bare LFs within the trailer section, and will return a parse error. This is stricer than we need to be. But it appears that some other HTTP/1 implementations improperly treat bare LF as boundaries, and get confused. This is not a bug in hyper. But we do add this to help people using other buggy software. (And to get the AI security scanners to stop claiming there's a big bug in here.) --- src/proto/h1/decode.rs | 55 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/src/proto/h1/decode.rs b/src/proto/h1/decode.rs index 78dd2ce754..547139f68b 100644 --- a/src/proto/h1/decode.rs +++ b/src/proto/h1/decode.rs @@ -546,6 +546,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)), } } @@ -598,6 +602,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 => { @@ -1025,6 +1033,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() { From b28916668d438f6600b75aed848e62ed252003e4 Mon Sep 17 00:00:00 2001 From: katelyn martin Date: Mon, 23 Nov 2026 14:24:07 -0500 Subject: [PATCH 21/23] style(body,proto): enforce clippy::rest_pattern_accessible_field (#4230) see https://github.com/hyperium/hyper/issues/4071. see . this lint disallows `..` patterns for accessible fields. this is helpful because it calls attention to locations that may need to be updated when the contents of a structure changes. allowances are left in place for simple accessors. because the lint_reason feature is not supported across the range of our MSRV, we use `/*reason: explanation*/` comments for now. an explicit allowance of `unneeded_field_pattern` is added, because these two lints conflict: we can either expect exhaustive matching, or we can expect that no fields are explicitly ignored. the former is more verbose, but draws attention to where logic may need to be updated as a type evolves over time. Signed-off-by: katelyn martin --- Cargo.toml | 2 +- src/body/incoming.rs | 24 ++++++++++++++++++++---- src/proto/h1/decode.rs | 7 ++++++- src/proto/h1/io.rs | 2 ++ src/proto/h2/server.rs | 5 ++++- 5 files changed, 33 insertions(+), 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 51db37736f..a27c4a4ccd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -134,7 +134,6 @@ 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 @@ -188,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/proto/h1/decode.rs b/src/proto/h1/decode.rs index 547139f68b..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) ) diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs index f5829a2786..cf8021ae30 100644 --- a/src/proto/h1/io.rs +++ b/src/proto/h1/io.rs @@ -404,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, @@ -412,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/h2/server.rs b/src/proto/h2/server.rs index 03b6180385..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) => { From abf6cdc549e577a194a518bc7caa093e7a3633d2 Mon Sep 17 00:00:00 2001 From: Sean McArthur Date: Mon, 23 Nov 2026 14:37:33 -0500 Subject: [PATCH 22/23] chore(examples): update pretty-env-logger (#4283) --- .github/workflows/CI.yml | 6 ++++++ Cargo.toml | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 1f8568549f..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: diff --git a/Cargo.toml b/Cargo.toml index a27c4a4ccd..8fcc292c10 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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"] } From 55247767429fb29753f724b467869aa6203db532 Mon Sep 17 00:00:00 2001 From: Sean McArthur Date: Mon, 23 Nov 2026 16:15:07 -0500 Subject: [PATCH 23/23] v1.13.0 --- CHANGELOG.md | 25 +++++++++++++++++++++++++ Cargo.toml | 2 +- 2 files changed, 26 insertions(+), 1 deletion(-) 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 8fcc292c10..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"