hyper/server/conn/
http2.rs

1//! HTTP/2 Server Connections
2
3use std::error::Error as StdError;
4use std::fmt;
5use std::future::Future;
6use std::pin::Pin;
7use std::sync::Arc;
8use std::task::{Context, Poll};
9use std::time::Duration;
10
11use crate::rt::{Read, Write};
12use futures_util::ready;
13use pin_project_lite::pin_project;
14
15use crate::body::{Body, Incoming as IncomingBody};
16use crate::proto;
17use crate::rt::bounds::Http2ServerConnExec;
18use crate::service::HttpService;
19use crate::{common::time::Time, rt::Timer};
20
21pin_project! {
22    /// A [`Future`](core::future::Future) representing an HTTP/2 connection, bound to a
23    /// [`Service`](crate::service::Service), returned from
24    /// [`Builder::serve_connection`](struct.Builder.html#method.serve_connection).
25    ///
26    /// To drive HTTP on this connection this future **must be polled**, typically with
27    /// `.await`. If it isn't polled, no progress will be made on this connection.
28    #[must_use = "futures do nothing unless polled"]
29    pub struct Connection<T, S, E>
30    where
31        S: HttpService<IncomingBody>,
32    {
33        conn: proto::h2::Server<T, S, S::ResBody, E>,
34    }
35}
36
37/// A configuration builder for HTTP/2 server connections.
38///
39/// **Note**: The default values of options are *not considered stable*. They
40/// are subject to change at any time.
41#[derive(Clone, Debug)]
42pub struct Builder<E> {
43    exec: E,
44    timer: Time,
45    h2_builder: proto::h2::server::Config,
46}
47
48// ===== impl Connection =====
49
50impl<I, S, E> fmt::Debug for Connection<I, S, E>
51where
52    S: HttpService<IncomingBody>,
53{
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        f.debug_struct("Connection").finish()
56    }
57}
58
59impl<I, B, S, E> Connection<I, S, E>
60where
61    S: HttpService<IncomingBody, ResBody = B>,
62    S::Error: Into<Box<dyn StdError + Send + Sync>>,
63    I: Read + Write + Unpin,
64    B: Body + 'static,
65    B::Error: Into<Box<dyn StdError + Send + Sync>>,
66    E: Http2ServerConnExec<S::Future, B>,
67{
68    /// Start a graceful shutdown process for this connection.
69    ///
70    /// This `Connection` should continue to be polled until shutdown
71    /// can finish.
72    ///
73    /// # Note
74    ///
75    /// This should only be called while the `Connection` future is still
76    /// pending. If called after `Connection::poll` has resolved, this does
77    /// nothing.
78    pub fn graceful_shutdown(mut self: Pin<&mut Self>) {
79        self.conn.graceful_shutdown();
80    }
81}
82
83impl<I, B, S, E> Future for Connection<I, S, E>
84where
85    S: HttpService<IncomingBody, ResBody = B>,
86    S::Error: Into<Box<dyn StdError + Send + Sync>>,
87    I: Read + Write + Unpin,
88    B: Body + 'static,
89    B::Error: Into<Box<dyn StdError + Send + Sync>>,
90    E: Http2ServerConnExec<S::Future, B>,
91{
92    type Output = crate::Result<()>;
93
94    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
95        match ready!(Pin::new(&mut self.conn).poll(cx)) {
96            Ok(_done) => {
97                //TODO: the proto::h2::Server no longer needs to return
98                //the Dispatched enum
99                Poll::Ready(Ok(()))
100            }
101            Err(e) => Poll::Ready(Err(e)),
102        }
103    }
104}
105
106// ===== impl Builder =====
107
108impl<E> Builder<E> {
109    /// Create a new connection builder.
110    ///
111    /// This starts with the default options, and an executor which is a type
112    /// that implements [`Http2ServerConnExec`] trait.
113    ///
114    /// [`Http2ServerConnExec`]: crate::rt::bounds::Http2ServerConnExec
115    pub fn new(exec: E) -> Self {
116        Self {
117            exec,
118            timer: Time::Empty,
119            h2_builder: Default::default(),
120        }
121    }
122
123    /// Configures the maximum number of pending reset streams allowed before a GOAWAY will be sent.
124    ///
125    /// This will default to the default value set by the [`h2` crate](https://crates.io/crates/h2).
126    /// As of v0.4.0, it is 20.
127    ///
128    /// See <https://github.com/hyperium/hyper/issues/2877> for more information.
129    pub fn max_pending_accept_reset_streams(&mut self, max: impl Into<Option<usize>>) -> &mut Self {
130        self.h2_builder.max_pending_accept_reset_streams = max.into();
131        self
132    }
133
134    /// Configures the maximum number of local reset streams allowed before a GOAWAY will be sent.
135    ///
136    /// If not set, hyper will use a default, currently of 1024.
137    ///
138    /// If `None` is supplied, hyper will not apply any limit.
139    /// This is not advised, as it can potentially expose servers to DOS vulnerabilities.
140    ///
141    /// See <https://rustsec.org/advisories/RUSTSEC-2024-0003.html> for more information.
142    #[cfg(feature = "http2")]
143    #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
144    pub fn max_local_error_reset_streams(&mut self, max: impl Into<Option<usize>>) -> &mut Self {
145        self.h2_builder.max_local_error_reset_streams = max.into();
146        self
147    }
148
149    /// Sets the [`SETTINGS_INITIAL_WINDOW_SIZE`][spec] option for HTTP2
150    /// stream-level flow control.
151    ///
152    /// Passing `None` will do nothing.
153    ///
154    /// If not set, hyper will use a default.
155    ///
156    /// [spec]: https://httpwg.org/specs/rfc9113.html#SETTINGS_INITIAL_WINDOW_SIZE
157    pub fn initial_stream_window_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
158        if let Some(sz) = sz.into() {
159            self.h2_builder.adaptive_window = false;
160            self.h2_builder.initial_stream_window_size = sz;
161        }
162        self
163    }
164
165    /// Sets the max connection-level flow control for HTTP2.
166    ///
167    /// Passing `None` will do nothing.
168    ///
169    /// If not set, hyper will use a default.
170    pub fn initial_connection_window_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
171        if let Some(sz) = sz.into() {
172            self.h2_builder.adaptive_window = false;
173            self.h2_builder.initial_conn_window_size = sz;
174        }
175        self
176    }
177
178    /// Sets whether to use an adaptive flow control.
179    ///
180    /// Enabling this will override the limits set in
181    /// `initial_stream_window_size` and
182    /// `initial_connection_window_size`.
183    pub fn adaptive_window(&mut self, enabled: bool) -> &mut Self {
184        use proto::h2::SPEC_WINDOW_SIZE;
185
186        self.h2_builder.adaptive_window = enabled;
187        if enabled {
188            self.h2_builder.initial_conn_window_size = SPEC_WINDOW_SIZE;
189            self.h2_builder.initial_stream_window_size = SPEC_WINDOW_SIZE;
190        }
191        self
192    }
193
194    /// Sets the maximum frame size to use for HTTP2.
195    ///
196    /// Passing `None` will do nothing.
197    ///
198    /// If not set, hyper will use a default.
199    pub fn max_frame_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
200        if let Some(sz) = sz.into() {
201            self.h2_builder.max_frame_size = sz;
202        }
203        self
204    }
205
206    /// Sets the [`SETTINGS_MAX_CONCURRENT_STREAMS`][spec] option for HTTP2
207    /// connections.
208    ///
209    /// Default is 200, but not part of the stability of hyper. It could change
210    /// in a future release. You are encouraged to set your own limit.
211    ///
212    /// Passing `None` will remove any limit.
213    ///
214    /// [spec]: https://httpwg.org/specs/rfc9113.html#SETTINGS_MAX_CONCURRENT_STREAMS
215    pub fn max_concurrent_streams(&mut self, max: impl Into<Option<u32>>) -> &mut Self {
216        self.h2_builder.max_concurrent_streams = max.into();
217        self
218    }
219
220    /// Sets an interval for HTTP2 Ping frames should be sent to keep a
221    /// connection alive.
222    ///
223    /// Pass `None` to disable HTTP2 keep-alive.
224    ///
225    /// Default is currently disabled.
226    pub fn keep_alive_interval(&mut self, interval: impl Into<Option<Duration>>) -> &mut Self {
227        self.h2_builder.keep_alive_interval = interval.into();
228        self
229    }
230
231    /// Sets a timeout for receiving an acknowledgement of the keep-alive ping.
232    ///
233    /// If the ping is not acknowledged within the timeout, the connection will
234    /// be closed. Does nothing if `keep_alive_interval` is disabled.
235    ///
236    /// Default is 20 seconds.
237    pub fn keep_alive_timeout(&mut self, timeout: Duration) -> &mut Self {
238        self.h2_builder.keep_alive_timeout = timeout;
239        self
240    }
241
242    /// Set the maximum write buffer size for each HTTP/2 stream.
243    ///
244    /// Default is currently ~400KB, but may change.
245    ///
246    /// # Panics
247    ///
248    /// The value must be no larger than `u32::MAX`.
249    pub fn max_send_buf_size(&mut self, max: usize) -> &mut Self {
250        assert!(max <= u32::MAX as usize);
251        self.h2_builder.max_send_buffer_size = max;
252        self
253    }
254
255    /// Enables the [extended CONNECT protocol].
256    ///
257    /// [extended CONNECT protocol]: https://datatracker.ietf.org/doc/html/rfc8441#section-4
258    pub fn enable_connect_protocol(&mut self) -> &mut Self {
259        self.h2_builder.enable_connect_protocol = true;
260        self
261    }
262
263    /// Sets the max size of received header frames.
264    ///
265    /// Default is currently 16KB, but can change.
266    pub fn max_header_list_size(&mut self, max: u32) -> &mut Self {
267        self.h2_builder.max_header_list_size = max;
268        self
269    }
270
271    /// Set the timer used in background tasks.
272    pub fn timer<M>(&mut self, timer: M) -> &mut Self
273    where
274        M: Timer + Send + Sync + 'static,
275    {
276        self.timer = Time::Timer(Arc::new(timer));
277        self
278    }
279
280    /// Set whether the `date` header should be included in HTTP responses.
281    ///
282    /// Note that including the `date` header is recommended by RFC 7231.
283    ///
284    /// Default is true.
285    pub fn auto_date_header(&mut self, enabled: bool) -> &mut Self {
286        self.h2_builder.date_header = enabled;
287        self
288    }
289
290    /// Bind a connection together with a [`Service`](crate::service::Service).
291    ///
292    /// This returns a Future that must be polled in order for HTTP to be
293    /// driven on the connection.
294    pub fn serve_connection<S, I, Bd>(&self, io: I, service: S) -> Connection<I, S, E>
295    where
296        S: HttpService<IncomingBody, ResBody = Bd>,
297        S::Error: Into<Box<dyn StdError + Send + Sync>>,
298        Bd: Body + 'static,
299        Bd::Error: Into<Box<dyn StdError + Send + Sync>>,
300        I: Read + Write + Unpin,
301        E: Http2ServerConnExec<S::Future, Bd>,
302    {
303        let proto = proto::h2::Server::new(
304            io,
305            service,
306            &self.h2_builder,
307            self.exec.clone(),
308            self.timer.clone(),
309        );
310        Connection { conn: proto }
311    }
312}