repo stringclasses 1 value | pull_number int64 3.25k 3.81k | instance_id stringclasses 6 values | issue_numbers sequencelengths 1 2 | base_commit stringclasses 6 values | patch stringclasses 6 values | test_patch stringclasses 6 values | problem_statement stringclasses 6 values | hints_text stringclasses 6 values | created_at stringclasses 6 values | version stringclasses 4 values | environment_setup_commit stringclasses 4 values | FAIL_TO_PASS sequencelengths 1 4 | PASS_TO_PASS sequencelengths 51 252 | FAIL_TO_FAIL sequencelengths 0 1 | PASS_TO_FAIL sequencelengths 0 0 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hyperium/hyper | 3,812 | hyperium__hyper-3812 | [
"3811"
] | a3bda62da36060a38638fba983a0c07c0ab6259d | diff --git a/src/proto/h1/io.rs b/src/proto/h1/io.rs
--- a/src/proto/h1/io.rs
+++ b/src/proto/h1/io.rs
@@ -205,7 +205,11 @@ where
return Poll::Ready(Err(crate::Error::new_too_large()));
}
if curr_len > 0 {
+ trace!("partial headers; {} bytes so far", curr_len);
self.partial_len = Some(curr_len);
+ } else {
+ // 1xx gobled some bytes
+ self.partial_len = None;
}
}
}
| diff --git a/tests/client.rs b/tests/client.rs
--- a/tests/client.rs
+++ b/tests/client.rs
@@ -2041,6 +2041,63 @@ mod conn {
assert_eq!(vec, b"bar=foo");
}
+ #[tokio::test]
+ async fn client_100_then_http09() {
+ let (server, addr) = setup_std_test_server();
+
+ thread::spawn(move || {
+ let mut sock = server.accept().unwrap().0;
+ sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
+ sock.set_write_timeout(Some(Duration::from_secs(5)))
+ .unwrap();
+ let mut buf = [0; 4096];
+ sock.read(&mut buf).expect("read 1");
+ sock.write_all(
+ b"\
+ HTTP/1.1 100 Continue\r\n\
+ Content-Type: text/plain\r\n\
+ Server: BaseHTTP/0.6 Python/3.12.5\r\n\
+ Date: Mon, 16 Dec 2024 03:08:27 GMT\r\n\
+ ",
+ )
+ .unwrap();
+ // That it's separate writes is important to this test
+ thread::sleep(Duration::from_millis(50));
+ sock.write_all(
+ b"\
+ \r\n\
+ ",
+ )
+ .expect("write 2");
+ thread::sleep(Duration::from_millis(50));
+ sock.write_all(
+ b"\
+ This is a sample text/plain document, without final headers.\
+ \n\n\
+ ",
+ )
+ .expect("write 3");
+ });
+
+ let tcp = tcp_connect(&addr).await.unwrap();
+
+ let (mut client, conn) = conn::http1::Builder::new()
+ .http09_responses(true)
+ .handshake(tcp)
+ .await
+ .unwrap();
+
+ tokio::spawn(async move {
+ let _ = conn.await;
+ });
+
+ let req = Request::builder()
+ .uri("/a")
+ .body(Empty::<Bytes>::new())
+ .unwrap();
+ let _res = client.send_request(req).await.expect("send_request");
+ }
+
#[tokio::test]
async fn test_try_send_request() {
use std::future::Future;
| Intermittent panic in is_complete_fast
**Version**
1.5.1
**Platform**
`Darwin ghost.local 23.5.0 Darwin Kernel Version 23.5.0: Wed May 1 20:19:05 PDT 2024; root:xnu-10063.121.3~5/RELEASE_ARM64_T8112 arm64`
**Description**
Hyper client can panic when processing broken up 1xx HTTP1 responses.
When a server responds with `HTTP/1.1 100 Continue\r\nContent-Type: text/plain\r\nServer: BaseHTTP/0.6 Python/3.12.5\r\nDate: Mon, 16 Dec 2024 03:08:27 GMT\r\n\r\nThis is a sample text/plain document.\n\nThis is not an HTML document.\n\n`, it's possible for hyper to first read `HTTP/1.1 100 Continue\r\nContent-Type: text/plain\r\nServer: BaseHTTP/0.6 Python/3.12.5\r\nDate: Mon, 16 Dec 2024 03:08:27 GMT\r\n\r\n`, followed by `This is a sample text/plain document.\n\nThis is not an HTML document.\n\n`.
This triggers a panic in [the code introduced in #3764](https://github.com/hyperium/hyper/pull/3764/files#diff-aa04de01d67bf1f61d03ef30830c744fa331c7918335393ace8c6137fa4d84d6R94), since the prev_length value stored after the first response is longer than the length of the second response.
This has been hit independently by both deno and Servo upon upgrading to hyper 1.5.1, since there are web-platform-tests that exercise 1xx responses: https://github.com/web-platform-tests/wpt/blob/master/fetch/security/1xx-response.any.js
| Thanks for the sample code, I'll get this fixed today 🫡 | 2024-12-16T14:50:50Z | 1.5 | a3bda62da36060a38638fba983a0c07c0ab6259d | [
"conn::client_100_then_http09"
] | [
"client_always_rejects_http09",
"client_error_parse_version",
"client_connect_method",
"client_100_continue",
"client_allows_http09_when_requested",
"client_h1_rejects_http2",
"client_get_req_body_sized",
"client_get_req_body_unknown_http10",
"client_get_req_body_unknown",
"client_head_ignores_bod... | [] | [] |
hyperium/hyper | 3,725 | hyperium__hyper-3725 | [
"3720"
] | 4c4de90a7e2aa0629b9c167a482399e28ccb0975 | diff --git a/benches/server.rs b/benches/server.rs
--- a/benches/server.rs
+++ b/benches/server.rs
@@ -72,7 +72,7 @@ macro_rules! bench_server {
tcp.write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
.unwrap();
let mut buf = Vec::new();
- tcp.read_to_end(&mut buf).unwrap()
+ tcp.read_to_end(&mut buf).unwrap() - "connection: close\r\n".len()
};
let mut tcp = TcpStream::connect(addr).unwrap();
diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs
--- a/src/proto/h1/conn.rs
+++ b/src/proto/h1/conn.rs
@@ -21,7 +21,7 @@ use super::{Decoder, Encode, EncodedBuf, Encoder, Http1Transaction, ParseContext
use crate::body::DecodedLength;
#[cfg(feature = "server")]
use crate::common::time::Time;
-use crate::headers::connection_keep_alive;
+use crate::headers;
use crate::proto::{BodyLength, MessageHead};
#[cfg(feature = "server")]
use crate::rt::Sleep;
diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs
--- a/src/proto/h1/conn.rs
+++ b/src/proto/h1/conn.rs
@@ -657,7 +657,7 @@ where
let outgoing_is_keep_alive = head
.headers
.get(CONNECTION)
- .map_or(false, connection_keep_alive);
+ .map_or(false, headers::connection_keep_alive);
if !outgoing_is_keep_alive {
match head.version {
diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs
--- a/src/proto/h1/conn.rs
+++ b/src/proto/h1/conn.rs
@@ -680,12 +680,21 @@ where
// If we know the remote speaks an older version, we try to fix up any messages
// to work with our older peer.
fn enforce_version(&mut self, head: &mut MessageHead<T::Outgoing>) {
- if let Version::HTTP_10 = self.state.version {
- // Fixes response or connection when keep-alive header is not present
- self.fix_keep_alive(head);
- // If the remote only knows HTTP/1.0, we should force ourselves
- // to do only speak HTTP/1.0 as well.
- head.version = Version::HTTP_10;
+ match self.state.version {
+ Version::HTTP_10 => {
+ // Fixes response or connection when keep-alive header is not present
+ self.fix_keep_alive(head);
+ // If the remote only knows HTTP/1.0, we should force ourselves
+ // to do only speak HTTP/1.0 as well.
+ head.version = Version::HTTP_10;
+ }
+ Version::HTTP_11 => {
+ if let KA::Disabled = self.state.keep_alive.status() {
+ head.headers
+ .insert(CONNECTION, HeaderValue::from_static("close"));
+ }
+ }
+ _ => (),
}
// If the remote speaks HTTP/1.1, then it *should* be fine with
// both HTTP/1.0 and HTTP/1.1 from us. So again, we just let
| diff --git a/benches/pipeline.rs b/benches/pipeline.rs
--- a/benches/pipeline.rs
+++ b/benches/pipeline.rs
@@ -76,7 +76,7 @@ fn hello_world_16(b: &mut test::Bencher) {
tcp.write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
.unwrap();
let mut buf = Vec::new();
- tcp.read_to_end(&mut buf).unwrap()
+ tcp.read_to_end(&mut buf).unwrap() - "connection: close\r\n".len()
} * PIPELINED_REQUESTS;
let mut tcp = TcpStream::connect(addr).unwrap();
diff --git a/tests/server.rs b/tests/server.rs
--- a/tests/server.rs
+++ b/tests/server.rs
@@ -1140,6 +1140,8 @@ fn pipeline_enabled() {
assert_eq!(s(lines.next().unwrap()), "HTTP/1.1 200 OK\r");
assert_eq!(s(lines.next().unwrap()), "content-length: 12\r");
+ // close because the last request said to close
+ assert_eq!(s(lines.next().unwrap()), "connection: close\r");
lines.next().unwrap(); // Date
assert_eq!(s(lines.next().unwrap()), "\r");
assert_eq!(s(lines.next().unwrap()), "Hello World");
diff --git a/tests/server.rs b/tests/server.rs
--- a/tests/server.rs
+++ b/tests/server.rs
@@ -1181,7 +1183,7 @@ fn http_11_uri_too_long() {
let mut req = connect(server.addr());
req.write_all(request_line.as_bytes()).unwrap();
- let expected = "HTTP/1.1 414 URI Too Long\r\ncontent-length: 0\r\n";
+ let expected = "HTTP/1.1 414 URI Too Long\r\nconnection: close\r\ncontent-length: 0\r\n";
let mut buf = [0; 256];
let n = req.read(&mut buf).unwrap();
assert!(n >= expected.len(), "read: {:?} >= {:?}", n, expected.len());
diff --git a/tests/server.rs b/tests/server.rs
--- a/tests/server.rs
+++ b/tests/server.rs
@@ -1208,6 +1210,12 @@ async fn disable_keep_alive_mid_request() {
"should receive OK response, but buf: {:?}",
buf,
);
+ let sbuf = s(&buf);
+ assert!(
+ sbuf.contains("connection: close\r\n"),
+ "response should have sent close: {:?}",
+ sbuf,
+ );
});
let (socket, _) = listener.accept().await.unwrap();
diff --git a/tests/server.rs b/tests/server.rs
--- a/tests/server.rs
+++ b/tests/server.rs
@@ -2366,7 +2374,7 @@ fn streaming_body() {
buf.starts_with(b"HTTP/1.1 200 OK\r\n"),
"response is 200 OK"
);
- assert_eq!(buf.len(), 100_789, "full streamed body read");
+ assert_eq!(buf.len(), 100_808, "full streamed body read");
}
#[test]
| No `Connection: close` on HTTP1 Connection Drain
When HTTP1 connection draining is activated, the Connection: close header is not attached to responses sent to active connections. This prevents active clients from realizing that the server is requesting that the connection be closed and prevents graceful draining of HTTP1 connections.
| Thanks for the report! I could have sworn we did this, but then tweaked the test and you're right, not done. PR is up at #3725.
Thank you @seanmonstar!
Reopened this until the PR #3725 gets merged. | 2024-08-02T20:50:20Z | 1.4 | 4c4de90a7e2aa0629b9c167a482399e28ccb0975 | [
"disable_keep_alive_mid_request",
"http_11_uri_too_long",
"pipeline_enabled",
"streaming_body"
] | [
"body::incoming::tests::channel_buffers_one",
"body::incoming::tests::channel_abort_when_buffer_is_full",
"body::incoming::tests::channel_abort",
"body::incoming::tests::channel_notices_closure",
"body::incoming::tests::channel_empty",
"body::incoming::tests::channel_ready",
"body::incoming::tests::chan... | [
"src/ext/mod.rs - ext::OriginalHeaderOrder::get_in_order (line 201) - compile"
] | [] |
hyperium/hyper | 3,616 | hyperium__hyper-3616 | [
"3615",
"3615"
] | bc9a86f58f8bd5c35b2bfd7e632ec132280d79ba | diff --git a/src/server/conn/http1.rs b/src/server/conn/http1.rs
--- a/src/server/conn/http1.rs
+++ b/src/server/conn/http1.rs
@@ -482,7 +482,11 @@ where
/// This `Connection` should continue to be polled until shutdown
/// can finish.
pub fn graceful_shutdown(mut self: Pin<&mut Self>) {
- Pin::new(self.inner.as_mut().unwrap()).graceful_shutdown()
+ // Connection (`inner`) is `None` if it was upgraded (and `poll` is `Ready`).
+ // In that case, we don't need to call `graceful_shutdown`.
+ if let Some(conn) = self.inner.as_mut() {
+ Pin::new(conn).graceful_shutdown()
+ }
}
}
| diff --git a/tests/server.rs b/tests/server.rs
--- a/tests/server.rs
+++ b/tests/server.rs
@@ -1256,6 +1256,67 @@ async fn disable_keep_alive_post_request() {
child.join().unwrap();
}
+#[tokio::test]
+async fn http1_graceful_shutdown_after_upgrade() {
+ let (listener, addr) = setup_tcp_listener();
+ let (read_101_tx, read_101_rx) = oneshot::channel();
+
+ thread::spawn(move || {
+ let mut tcp = connect(&addr);
+ tcp.write_all(
+ b"\
+ GET / HTTP/1.1\r\n\
+ Upgrade: foobar\r\n\
+ Connection: upgrade\r\n\
+ \r\n\
+ eagerly optimistic\
+ ",
+ )
+ .expect("write 1");
+ let mut buf = [0; 256];
+ tcp.read(&mut buf).expect("read 1");
+
+ let response = s(&buf);
+ assert!(response.starts_with("HTTP/1.1 101 Switching Protocols\r\n"));
+ assert!(!has_header(&response, "content-length"));
+ let _ = read_101_tx.send(());
+ });
+
+ let (upgrades_tx, upgrades_rx) = mpsc::channel();
+ let svc = service_fn(move |req: Request<IncomingBody>| {
+ let on_upgrade = hyper::upgrade::on(req);
+ let _ = upgrades_tx.send(on_upgrade);
+ future::ok::<_, hyper::Error>(
+ Response::builder()
+ .status(101)
+ .header("upgrade", "foobar")
+ .body(Empty::<Bytes>::new())
+ .unwrap(),
+ )
+ });
+
+ let (socket, _) = listener.accept().await.unwrap();
+ let socket = TokioIo::new(socket);
+
+ let mut conn = http1::Builder::new()
+ .serve_connection(socket, svc)
+ .with_upgrades();
+ (&mut conn).await.unwrap();
+
+ let on_upgrade = upgrades_rx.recv().unwrap();
+
+ // wait so that we don't write until other side saw 101 response
+ read_101_rx.await.unwrap();
+
+ let upgraded = on_upgrade.await.expect("on_upgrade");
+ let parts = upgraded.downcast::<TokioIo<TkTcpStream>>().unwrap();
+ assert_eq!(parts.read_buf, "eagerly optimistic");
+
+ pin!(conn);
+ // graceful shutdown doesn't cause issues or panic. It should be ignored after upgrade
+ conn.as_mut().graceful_shutdown();
+}
+
#[tokio::test]
async fn empty_parse_eof_does_not_return_error() {
let (listener, addr) = setup_tcp_listener();
| Panic on graceful shutdown for http/1
**Version**
Encountered with `1.x`
**Platform**
Doesn't matter
**Description**
Attempt to call `graceful_shutdown` for H1 connection which is upgraded (=> `Poll::Ready`) leads to panic:
```
panic was raised: panicked at /usr/local/cargo/registry/src/index.crates.io-6f17d22bba15001f/hyper-1.2.0/src/server/conn/http1.rs:483:38:
called `Option::unwrap()` on a `None` value
```
The reason is this line:
```rs
Pin::new(self.inner.as_mut().unwrap()).graceful_shutdown()
```
When connection is Upgraded (& future is `Ready`), it's `None` https://github.com/hyperium/hyper/blob/bc9a86f58f8bd5c35b2bfd7e632ec132280d79ba/src/server/conn/http1.rs#L502-L506
So we should avoid unwrapping
Panic on graceful shutdown for http/1
**Version**
Encountered with `1.x`
**Platform**
Doesn't matter
**Description**
Attempt to call `graceful_shutdown` for H1 connection which is upgraded (=> `Poll::Ready`) leads to panic:
```
panic was raised: panicked at /usr/local/cargo/registry/src/index.crates.io-6f17d22bba15001f/hyper-1.2.0/src/server/conn/http1.rs:483:38:
called `Option::unwrap()` on a `None` value
```
The reason is this line:
```rs
Pin::new(self.inner.as_mut().unwrap()).graceful_shutdown()
```
When connection is Upgraded (& future is `Ready`), it's `None` https://github.com/hyperium/hyper/blob/bc9a86f58f8bd5c35b2bfd7e632ec132280d79ba/src/server/conn/http1.rs#L502-L506
So we should avoid unwrapping
| 2024-03-30T11:42:44Z | 1.2 | bc9a86f58f8bd5c35b2bfd7e632ec132280d79ba | [
"http1_graceful_shutdown_after_upgrade"
] | [
"disconnect_after_reading_request_before_responding",
"disable_keep_alive_post_request",
"expect_continue_sends_100",
"h2_connect_multiplex",
"disable_keep_alive_mid_request",
"expect_continue_waits_for_body_poll",
"expect_continue_but_http_10_is_ignored",
"expect_continue_but_no_body_is_ignored",
"... | [] | [] | |
hyperium/hyper | 3,275 | hyperium__hyper-3275 | [
"2872"
] | a45d5d5a04369f93334fc893875d8d1a49054e04 | diff --git a/src/body/incoming.rs b/src/body/incoming.rs
--- a/src/body/incoming.rs
+++ b/src/body/incoming.rs
@@ -201,7 +201,16 @@ impl Body for Incoming {
ping.record_data(bytes.len());
return Poll::Ready(Some(Ok(Frame::data(bytes))));
}
- Some(Err(e)) => return Poll::Ready(Some(Err(crate::Error::new_body(e)))),
+ Some(Err(e)) => {
+ return match e.reason() {
+ // These reasons should cause the body reading to stop, but not fail it.
+ // The same logic as for `Read for H2Upgraded` is applied here.
+ Some(h2::Reason::NO_ERROR) | Some(h2::Reason::CANCEL) => {
+ Poll::Ready(None)
+ }
+ _ => Poll::Ready(Some(Err(crate::Error::new_body(e)))),
+ };
+ }
None => {
*data_done = true;
// fall through to trailers
diff --git a/src/proto/mod.rs b/src/proto/mod.rs
--- a/src/proto/mod.rs
+++ b/src/proto/mod.rs
@@ -50,7 +50,7 @@ pub(crate) enum BodyLength {
Unknown,
}
-/// Status of when a Disaptcher future completes.
+/// Status of when a Dispatcher future completes.
pub(crate) enum Dispatched {
/// Dispatcher completely shutdown connection.
Shutdown,
| diff --git a/tests/client.rs b/tests/client.rs
--- a/tests/client.rs
+++ b/tests/client.rs
@@ -1338,7 +1338,7 @@ mod conn {
use bytes::{Buf, Bytes};
use futures_channel::{mpsc, oneshot};
use futures_util::future::{self, poll_fn, FutureExt, TryFutureExt};
- use http_body_util::{BodyExt, Empty, StreamBody};
+ use http_body_util::{BodyExt, Empty, Full, StreamBody};
use hyper::rt::Timer;
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
use tokio::net::{TcpListener as TkTcpListener, TcpStream};
diff --git a/tests/client.rs b/tests/client.rs
--- a/tests/client.rs
+++ b/tests/client.rs
@@ -2126,6 +2126,62 @@ mod conn {
.expect("client should be open");
}
+ #[tokio::test]
+ async fn http2_responds_before_consuming_request_body() {
+ // Test that a early-response from server works correctly (request body wasn't fully consumed).
+ // https://github.com/hyperium/hyper/issues/2872
+ use hyper::service::service_fn;
+
+ let _ = pretty_env_logger::try_init();
+
+ let (listener, addr) = setup_tk_test_server().await;
+
+ // Spawn an HTTP2 server that responds before reading the whole request body.
+ // It's normal case to decline the request due to headers or size of the body.
+ tokio::spawn(async move {
+ let sock = TokioIo::new(listener.accept().await.unwrap().0);
+ hyper::server::conn::http2::Builder::new(TokioExecutor)
+ .timer(TokioTimer)
+ .serve_connection(
+ sock,
+ service_fn(|_req| async move {
+ Ok::<_, hyper::Error>(Response::new(Full::new(Bytes::from(
+ "No bread for you!",
+ ))))
+ }),
+ )
+ .await
+ .expect("serve_connection");
+ });
+
+ let io = tcp_connect(&addr).await.expect("tcp connect");
+ let (mut client, conn) = conn::http2::Builder::new(TokioExecutor)
+ .timer(TokioTimer)
+ .handshake(io)
+ .await
+ .expect("http handshake");
+
+ tokio::spawn(async move {
+ conn.await.expect("client conn shouldn't error");
+ });
+
+ // Use a channel to keep request stream open
+ let (_tx, recv) = mpsc::channel::<Result<Frame<Bytes>, Box<dyn Error + Send + Sync>>>(0);
+ let req = Request::post("/a").body(StreamBody::new(recv)).unwrap();
+ let resp = client.send_request(req).await.expect("send_request");
+ assert!(resp.status().is_success());
+
+ let mut body = String::new();
+ concat(resp.into_body())
+ .await
+ .unwrap()
+ .reader()
+ .read_to_string(&mut body)
+ .unwrap();
+
+ assert_eq!(&body, "No bread for you!");
+ }
+
#[tokio::test]
async fn h2_connect() {
let (listener, addr) = setup_tk_test_server().await;
| Client: handle `RST_STREAM` with `NO_ERROR` set for the reason
**Version**
```
hyper = "0.14.18"
h2 = "0.3.13"
```
**Platform**
```
> uname -a
Linux <REDACTED> 5.17.5-76051705-generic #202204271406~1651504840~22.04~63e51bd SMP PREEMPT Mon May 2 15: x86_64 x86_64 x86_64 GNU/Linux
```
**Description**
I've found that Google Cloud Storage's API can respond with HTTP/2 `RST_STREAM` frame with `NO_ERROR` set for the reason, which appears to mean "stop sending the request body and read my response" according to https://datatracker.ietf.org/doc/html/rfc7540#section-8.1
> A server can send a complete response prior to the client sending an entire
request if the response does not depend on any portion of the request
that has not been sent and received. When this is true, a server MAY
request that the client abort transmission of a request without error
by sending a RST_STREAM with an error code of NO_ERROR after sending
a complete response (i.e., a frame with the END_STREAM flag).
Clients MUST NOT discard responses as a result of receiving such a
RST_STREAM, though clients can always discard responses at their
discretion for other reasons.
I believe this is happening in response to a `PutObject` request when the bucket is being rate limited for writes. The server is trying to tell the client to stop sending the request body because it won't be processed, and instead it should immediately read the response to discover the `429 Too Many Requests` error code.
However, Hyper's client implementation appears to just return the `RST_STREAM` message as an error and discards the response instead of handling it, which gives a hilariously confusing error message of:
```
error reading a body from connection: stream error received: not a result of an error
```
To be compliant with the spec, the implementation should stop sending the body and immediately read the response and return it.
For context, I'm using the Gcloud Storage API via https://crates.io/crates/aws-sdk-s3 (because the Gcloud Rust SDK doesn't support streaming bodies, but thankfully Gcloud Storage exposes an S3-compatible API), which uses Hyper internally. `aws-sdk-s3` appears to be returning the error from Hyper verbatim, however.
| Yea, I think we've talked about this in a previous issue, but don't remember where. `h2` is making the "error" (the reset) trump any other frames that have been received. It should likely be changed to return all other received frames, and *then* return the error.
But _somewhere_ in the stack it should probably just suppress the `RST_STREAM(NO_ERROR)` and return the response, because the response is what's going to be meaningful to the user. The `RST_STREAM` here is just being used as a "shut up and listen" signal.
Yes, it should return the response, that's why I mean. And then the body can return that there was a `NO_ERROR` error. It should still be given to the user, so they know something happened.
Stumbled on this. How can I suppress the specific failure `RST_STREAM(NO_ERROR)` somehow? How can I workaround this? I'm also in for contributing this fix :) | 2023-07-23T01:01:36Z | 1.0 | 6fd696e10974f10b2c6b9d16393bbbfa21c2333f | [
"conn::http2_responds_before_consuming_request_body"
] | [
"client_always_rejects_http09",
"client_allows_http09_when_requested",
"client_error_parse_status_out_of_range",
"client_connect_method_with_absolute_uri",
"client_get_req_body_implicitly_empty",
"client_h1_rejects_http2",
"client_get_req_body_chunked_http10",
"client_get",
"client_error_unexpected_... | [] | [] |
hyperium/hyper | 3,261 | hyperium__hyper-3261 | [
"2730"
] | d92d3917d950e4c61c37c2170f3ce273d2a0f7d1 | diff --git a/src/proto/h1/conn.rs b/src/proto/h1/conn.rs
--- a/src/proto/h1/conn.rs
+++ b/src/proto/h1/conn.rs
@@ -175,6 +175,13 @@ where
}
}
+ #[cfg(feature = "server")]
+ pub(crate) fn has_initial_read_write_state(&self) -> bool {
+ matches!(self.state.reading, Reading::Init)
+ && matches!(self.state.writing, Writing::Init)
+ && self.io.read_buf().is_empty()
+ }
+
fn should_error_on_eof(&self) -> bool {
// If we're idle, it's probably just the connection closing gracefully.
T::should_error_on_parse_eof() && !self.state.is_idle()
diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs
--- a/src/proto/h1/dispatch.rs
+++ b/src/proto/h1/dispatch.rs
@@ -82,7 +82,11 @@ where
#[cfg(feature = "server")]
pub(crate) fn disable_keep_alive(&mut self) {
self.conn.disable_keep_alive();
- if self.conn.is_write_closed() {
+
+ // If keep alive has been disabled and no read or write has been seen on
+ // the connection yet, we must be in a state where the server is being asked to
+ // shut down before any data has been seen on the connection
+ if self.conn.is_write_closed() || self.conn.has_initial_read_write_state() {
self.close();
}
}
| diff --git a/tests/server.rs b/tests/server.rs
--- a/tests/server.rs
+++ b/tests/server.rs
@@ -31,6 +31,7 @@ use hyper::body::{Body, Incoming as IncomingBody};
use hyper::server::conn::{http1, http2};
use hyper::service::{service_fn, Service};
use hyper::{Method, Request, Response, StatusCode, Uri, Version};
+use tokio::pin;
mod support;
diff --git a/tests/server.rs b/tests/server.rs
--- a/tests/server.rs
+++ b/tests/server.rs
@@ -1139,11 +1140,17 @@ async fn disable_keep_alive_mid_request() {
let child = thread::spawn(move || {
let mut req = connect(&addr);
req.write_all(b"GET / HTTP/1.1\r\n").unwrap();
+ thread::sleep(Duration::from_millis(10));
tx1.send(()).unwrap();
rx2.recv().unwrap();
req.write_all(b"Host: localhost\r\n\r\n").unwrap();
let mut buf = vec![];
req.read_to_end(&mut buf).unwrap();
+ assert!(
+ buf.starts_with(b"HTTP/1.1 200 OK\r\n"),
+ "should receive OK response, but buf: {:?}",
+ buf,
+ );
});
let (socket, _) = listener.accept().await.unwrap();
diff --git a/tests/server.rs b/tests/server.rs
--- a/tests/server.rs
+++ b/tests/server.rs
@@ -2152,6 +2159,31 @@ async fn max_buf_size() {
.expect_err("should TooLarge error");
}
+#[cfg(feature = "http1")]
+#[tokio::test]
+async fn graceful_shutdown_before_first_request_no_block() {
+ let (listener, addr) = setup_tcp_listener();
+
+ tokio::spawn(async move {
+ let socket = listener.accept().await.unwrap().0;
+
+ let future = http1::Builder::new().serve_connection(socket, HelloWorld);
+ pin!(future);
+ future.as_mut().graceful_shutdown();
+
+ future.await.unwrap();
+ });
+
+ let mut stream = TkTcpStream::connect(addr).await.unwrap();
+
+ let mut buf = vec![];
+
+ tokio::time::timeout(Duration::from_secs(5), stream.read_to_end(&mut buf))
+ .await
+ .expect("timed out waiting for graceful shutdown")
+ .expect("error receiving response");
+}
+
#[test]
fn streaming_body() {
use futures_util::StreamExt;
| Connection::graceful_shutdown always waits for the first request.
**Version**
hyper 0.14.16
**Platform**
Linux DESKTOP-DHO88R7 4.19.104-microsoft-standard #1 SMP Wed Feb 19 06:37:35 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
**Description**
If you gracefully shut down a server connection future before the first request, Hyper will not actually shut the connection down until a request is processed:
```rust
use hyper::server::conn::Http;
use hyper::Response;
use tokio::io::AsyncReadExt;
use tokio::net::{TcpListener, TcpStream};
use tokio::pin;
#[tokio::main]
async fn main() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(server(listener));
let mut stream = TcpStream::connect(addr).await.unwrap();
println!("connected");
let mut buf = vec![];
stream.read_to_end(&mut buf).await.unwrap();
}
async fn server(listener: TcpListener) {
let socket = listener.accept().await.unwrap().0;
let service = hyper::service::service_fn(|_: hyper::Request<hyper::Body>| async {
Err::<Response<hyper::Body>, _>("no")
});
let future = Http::new()
.http1_only(true)
.serve_connection(socket, service);
pin!(future);
future.as_mut().graceful_shutdown();
future.await.unwrap();
}
```
I would expect this program to exit almost instantly since there is no request being processed when the graceful_shutdown is invoked. However, it instead blocks forever waiting on the client to send headers.
The behavior actually appears to be that the shutdown is processed immediately after the first request is fully handled.
| Yea, I think this is behavior is currently on purpose. Whether it _should_ be is a fair question. I think at the time, I assumed that a _new_ connection would usually have a request incoming ASAP, whereas an idle connection might not, and so it was better to allow that request to come in.
We could alter that behavior, if we document a good reason for _why_ we're making that change. Also, I imagine using the `http1_header_read_timeout` option could help here.
I agree that it's *more likely* for the first request to show up than a follow up request, but it seems weird to bake that assumption into graceful_shutdown IMO. For reference, I'm using graceful_shutdown in some logic to shut down connections after a certain period of idleness (I can't just terminate the connection future since I want the TLS session to shut down cleanly for session reuse). Right now, the current behavior will miss connections that are opened and never make a request.
Does `http1_header_read_timeout` start counting immediately or just once the first byte of the header is received? In any case, I don't think that'd help for an h2 connection, right?
Any progress on this? I was trying to figure out why my program wasn't exiting when I expected it to and found this issue. If I send the graceful shutdown signal the server will process one more request before actually exiting. So a user sending the shutdown command through a web app won't actually be shutting anything down.
> Does http1_header_read_timeout start counting immediately or just once the first byte of the header is received? In any case, I don't think that'd help for an h2 connection, right?
From some testing just now, the answer to the first part is "no". If I start-up an `http1::Connection` with a header timeout configured and connect to it simply with `nc` then the connection stays up indefinitely. Once I send any data (even a blank line) the timer starts counting and the connection is closed as expected after the timeout.
This seems like a thing to slide into RC2 or RC3.
> I can't just terminate the connection future since I want the TLS session to shut down cleanly for session reuse
@sfackler Does this mean you'd have the connection write out a 408 response and then finish? Or simply calling `poll_shutdown` and then return the future like if it were in keep-alive state? I guess calling shutdown will make the TLS shutdown start, right?
Yeah it just needs to call shutdown on the underlying IO object, which will handle the SSL shutdown protocol.
I think I can take this one. | 2023-07-06T18:47:14Z | 1.0 | 6fd696e10974f10b2c6b9d16393bbbfa21c2333f | [
"graceful_shutdown_before_first_request_no_block"
] | [
"get_with_body",
"empty_parse_eof_does_not_return_error",
"expect_continue_accepts_upper_cased_expectation",
"disable_keep_alive_post_request",
"h2_connect_multiplex",
"disable_keep_alive_mid_request",
"header_name_too_long",
"h2_connect_empty_frames",
"disconnect_after_reading_request_before_respon... | [] | [] |
hyperium/hyper | 3,254 | hyperium__hyper-3254 | [
"3252"
] | aa330bcba0ac0cb30868181ac870947604b9ecbf | diff --git a/src/proto/h1/dispatch.rs b/src/proto/h1/dispatch.rs
--- a/src/proto/h1/dispatch.rs
+++ b/src/proto/h1/dispatch.rs
@@ -366,7 +366,12 @@ where
self.conn.end_body()?;
}
} else {
- return Poll::Pending;
+ // If there's no body_rx, end the body
+ if self.conn.can_write_body() {
+ self.conn.end_body()?;
+ } else {
+ return Poll::Pending;
+ }
}
}
}
| diff --git a/tests/server.rs b/tests/server.rs
--- a/tests/server.rs
+++ b/tests/server.rs
@@ -92,6 +92,7 @@ mod response_body_lengths {
}
fn run_test(case: TestCase) {
+ let _ = pretty_env_logger::try_init();
assert!(
case.version == 0 || case.version == 1,
"TestCase.version must 0 or 1"
diff --git a/tests/server.rs b/tests/server.rs
--- a/tests/server.rs
+++ b/tests/server.rs
@@ -155,18 +156,22 @@ mod response_body_lengths {
let n = body.find("\r\n\r\n").unwrap() + 4;
if case.expects_chunked {
- let len = body.len();
- assert_eq!(
- &body[n + 1..n + 3],
- "\r\n",
- "expected body chunk size header"
- );
- assert_eq!(&body[n + 3..len - 7], body_str, "expected body");
- assert_eq!(
- &body[len - 7..],
- "\r\n0\r\n\r\n",
- "expected body final chunk size header"
- );
+ if body_str.len() > 0 {
+ let len = body.len();
+ assert_eq!(
+ &body[n + 1..n + 3],
+ "\r\n",
+ "expected body chunk size header"
+ );
+ assert_eq!(&body[n + 3..len - 7], body_str, "expected body");
+ assert_eq!(
+ &body[len - 7..],
+ "\r\n0\r\n\r\n",
+ "expected body final chunk size header"
+ );
+ } else {
+ assert_eq!(&body[n..], "0\r\n\r\n");
+ }
} else {
assert_eq!(&body[n..], body_str, "expected body");
}
diff --git a/tests/server.rs b/tests/server.rs
--- a/tests/server.rs
+++ b/tests/server.rs
@@ -217,6 +222,17 @@ mod response_body_lengths {
});
}
+ #[test]
+ fn chunked_response_known_empty() {
+ run_test(TestCase {
+ version: 1,
+ headers: &[("transfer-encoding", "chunked")],
+ body: Bd::Known(""),
+ expects_chunked: true, // should still send chunked, and 0\r\n\r\n
+ expects_con_len: false,
+ });
+ }
+
#[test]
fn chunked_response_unknown() {
run_test(TestCase {
| Chunked HTTP/1.1 doesn't send the last zero-chunk when body is empty
**Version**
hyper 0.14.26, h2 0.3.19, http 0.2.9
**Platform**
Linux 5.15, Ubuntu 22.04
**Description**
In HTTP/1.1, when `transfer-encoding: chunked` is set, all the data should be sent at a format of chunk. However, in hyper, if the body part is empty, e.g. `Body::empty()` or `Body::from_static(b"")`, hyper server doesn't send `b"0\r\n\r\n"` to the client, causing infitite wait on the client side. When the body contains some bytes, e.g. `Body::from_static(b"0")`, hyper will send a non-zero size chunk as well as a zero-size last chunk. According to pseudo code from [RFC9112 7.1.3](https://datatracker.ietf.org/doc/html/rfc9112#name-decoding-chunked), zero size body should be allowed.
I expect hyper sends valid last chunk `b"0\r\n\r\n"` to the client when the body is empty. Manually sending it is impossible with public API so I have no workaround now.
Source code to reproduce the behavior:
```rust
async fn get_302() -> anyhow::Result<Response<Body>> {
let resp_builder = http::response::Builder::new();
let (mut parts, body) = resp_builder
.status(302)
.version(Version::HTTP_11)
.header(header::LOCATION, "127.0.0.1:1234/ok")
.header(header::TRANSFER_ENCODING, "chunked")
.body(Body::empty())
.unwrap().into_parts();
Ok(Response::from_parts(parts, body))
}
async fn run_server() {
let listener = TcpListener::bind("127.0.0.1:1234").await.unwrap();
let service = service_fn(|req| {
get_302()
});
while let (conn, _) = listener.accept().await.unwrap() {
let _ = Http::new().http1_only(true).serve_connection(conn, service).await;
}
}
#[tokio::main]
async fn main() {
run_server().await
}
```
| Oh, interesting. This is _supposed_ to work, and we have a matrix of `response_body_lengths` tests for a bunch of combinations (headers existing, body type knows it's own length, etc), and I noticed this specific combination wasn't included (chunked header set, known empty). Adding it, and the test does indeed hang. I'll look into why. | 2023-06-16T17:01:17Z | 1.0 | 6fd696e10974f10b2c6b9d16393bbbfa21c2333f | [
"response_body_lengths::chunked_response_known_empty"
] | [
"empty_parse_eof_does_not_return_error",
"disconnect_after_reading_request_before_responding",
"disable_keep_alive",
"expect_continue_sends_100",
"disable_keep_alive_mid_request",
"expect_continue_accepts_upper_cased_expectation",
"get_should_ignore_body",
"disable_keep_alive_post_request",
"expect_... | [] | [] |
README.md exists but content is empty.
- Downloads last month
- 5