Skip to content

Commit 031b44e

Browse files
committed
fix(http2): received Body::size_hint() now return 0 if implicitly empty
An HTTP/2 stream may include a set of headers, and a flag signalling END-STREAM, even if a `content-length` isn't included. hyper wouldn't notice, and so the `Body` would report a size-hint of `0..MAX`. hyper now notices that the stream is ended, and couldn't possibly include any bytes for the body, and thus will give a size-hint of `0` exactly.
1 parent ce82425 commit 031b44e

File tree

3 files changed

+32
-5
lines changed

3 files changed

+32
-5
lines changed

src/body/body.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,9 +204,14 @@ impl Body {
204204
#[cfg(all(feature = "http2", any(feature = "client", feature = "server")))]
205205
pub(crate) fn h2(
206206
recv: h2::RecvStream,
207-
content_length: DecodedLength,
207+
mut content_length: DecodedLength,
208208
ping: ping::Recorder,
209209
) -> Self {
210+
// If the stream is already EOS, then regardless of the supposed length,
211+
// this body is exactly ZERO bytes long.
212+
if recv.is_end_stream() {
213+
content_length = DecodedLength::ZERO;
214+
}
210215
let body = Body::new(Kind::H2 {
211216
ping,
212217
content_length,

src/proto/h2/server.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -484,12 +484,13 @@ where
484484
}
485485
}
486486

487-
// automatically set Content-Length from body...
488-
if let Some(len) = body.size_hint().exact() {
489-
headers::set_content_length_if_missing(res.headers_mut(), len);
490-
}
491487

492488
if !body.is_end_stream() {
489+
// automatically set Content-Length from body...
490+
if let Some(len) = body.size_hint().exact() {
491+
headers::set_content_length_if_missing(res.headers_mut(), len);
492+
}
493+
493494
let body_tx = reply!(me, res, false);
494495
H2StreamState::Body {
495496
pipe: PipeToSendStream::new(body, body_tx),

tests/server.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,27 @@ mod response_body_lengths {
361361
assert_eq!(res.headers().get("content-length").unwrap(), "10");
362362
assert_eq!(res.body().size_hint().exact(), Some(10));
363363
}
364+
365+
#[tokio::test]
366+
async fn http2_implicit_empty_size_hint() {
367+
use http_body::Body;
368+
369+
let server = serve();
370+
let addr_str = format!("http://{}", server.addr());
371+
server
372+
.reply();
373+
374+
let client = Client::builder()
375+
.http2_only(true)
376+
.build_http::<hyper::Body>();
377+
let uri = addr_str
378+
.parse::<hyper::Uri>()
379+
.expect("server addr should parse");
380+
381+
let res = client.get(uri).await.unwrap();
382+
assert_eq!(res.headers().get("content-length"), None);
383+
assert_eq!(res.body().size_hint().exact(), Some(0));
384+
}
364385
}
365386

366387
#[test]

0 commit comments

Comments
 (0)