Skip to main content

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_core::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: proto::h2::server::Config::default(),
120        }
121    }
122
123    /// Returns the executor this builder was created with.
124    pub fn executor(&self) -> &E {
125        &self.exec
126    }
127
128    /// Configures the maximum number of pending reset streams allowed before a GOAWAY will be sent.
129    ///
130    /// This will default to the default value set by the [`h2` crate](https://crates.io/crates/h2).
131    /// As of v0.4.0, it is 20.
132    ///
133    /// See <https://github.com/hyperium/hyper/issues/2877> for more information.
134    pub fn max_pending_accept_reset_streams(&mut self, max: impl Into<Option<usize>>) -> &mut Self {
135        self.h2_builder.max_pending_accept_reset_streams = max.into();
136        self
137    }
138
139    /// Configures the maximum number of local reset streams allowed before a GOAWAY will be sent.
140    ///
141    /// If not set, hyper will use a default, currently of 1024.
142    ///
143    /// If `None` is supplied, hyper will not apply any limit.
144    /// This is not advised, as it can potentially expose servers to DOS vulnerabilities.
145    ///
146    /// See <https://rustsec.org/advisories/RUSTSEC-2024-0003.html> for more information.
147    #[cfg(feature = "http2")]
148    #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
149    pub fn max_local_error_reset_streams(&mut self, max: impl Into<Option<usize>>) -> &mut Self {
150        self.h2_builder.max_local_error_reset_streams = max.into();
151        self
152    }
153
154    /// Sets the [`SETTINGS_INITIAL_WINDOW_SIZE`][spec] option for HTTP2
155    /// stream-level flow control.
156    ///
157    /// Passing `None` will do nothing.
158    ///
159    /// If not set, hyper will use a default.
160    ///
161    /// [spec]: https://httpwg.org/specs/rfc9113.html#SETTINGS_INITIAL_WINDOW_SIZE
162    pub fn initial_stream_window_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
163        if let Some(sz) = sz.into() {
164            self.h2_builder.adaptive_window = false;
165            self.h2_builder.initial_stream_window_size = sz;
166        }
167        self
168    }
169
170    /// Sets the max connection-level flow control for HTTP2.
171    ///
172    /// Passing `None` will do nothing.
173    ///
174    /// If not set, hyper will use a default.
175    pub fn initial_connection_window_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
176        if let Some(sz) = sz.into() {
177            self.h2_builder.adaptive_window = false;
178            self.h2_builder.initial_conn_window_size = sz;
179        }
180        self
181    }
182
183    /// Sets whether to use an adaptive flow control.
184    ///
185    /// Enabling this will override the limits set in
186    /// `initial_stream_window_size` and
187    /// `initial_connection_window_size`.
188    pub fn adaptive_window(&mut self, enabled: bool) -> &mut Self {
189        use proto::h2::SPEC_WINDOW_SIZE;
190
191        self.h2_builder.adaptive_window = enabled;
192        if enabled {
193            self.h2_builder.initial_conn_window_size = SPEC_WINDOW_SIZE;
194            self.h2_builder.initial_stream_window_size = SPEC_WINDOW_SIZE;
195        }
196        self
197    }
198
199    /// Sets the maximum frame size to use for HTTP2.
200    ///
201    /// Passing `None` will do nothing.
202    ///
203    /// If not set, hyper will use a default.
204    pub fn max_frame_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self {
205        if let Some(sz) = sz.into() {
206            self.h2_builder.max_frame_size = sz;
207        }
208        self
209    }
210
211    /// Sets the [`SETTINGS_MAX_CONCURRENT_STREAMS`][spec] option for HTTP2
212    /// connections.
213    ///
214    /// Default is 200, but not part of the stability of hyper. It could change
215    /// in a future release. You are encouraged to set your own limit.
216    ///
217    /// Passing `None` will remove any limit.
218    ///
219    /// [spec]: https://httpwg.org/specs/rfc9113.html#SETTINGS_MAX_CONCURRENT_STREAMS
220    pub fn max_concurrent_streams(&mut self, max: impl Into<Option<u32>>) -> &mut Self {
221        self.h2_builder.max_concurrent_streams = max.into();
222        self
223    }
224
225    /// Sets an interval for HTTP2 Ping frames should be sent to keep a
226    /// connection alive.
227    ///
228    /// Pass `None` to disable HTTP2 keep-alive.
229    ///
230    /// Default is currently disabled.
231    pub fn keep_alive_interval(&mut self, interval: impl Into<Option<Duration>>) -> &mut Self {
232        self.h2_builder.keep_alive_interval = interval.into();
233        self
234    }
235
236    /// Sets a timeout for receiving an acknowledgement of the keep-alive ping.
237    ///
238    /// If the ping is not acknowledged within the timeout, the connection will
239    /// be closed. Does nothing if `keep_alive_interval` is disabled.
240    ///
241    /// Default is 20 seconds.
242    pub fn keep_alive_timeout(&mut self, timeout: Duration) -> &mut Self {
243        self.h2_builder.keep_alive_timeout = timeout;
244        self
245    }
246
247    /// Set the maximum write buffer size for each HTTP/2 stream.
248    ///
249    /// Default is currently ~400KB, but may change.
250    ///
251    /// # Panics
252    ///
253    /// The value must be no larger than `u32::MAX`.
254    pub fn max_send_buf_size(&mut self, max: usize) -> &mut Self {
255        assert!(max <= u32::MAX as usize);
256        self.h2_builder.max_send_buffer_size = max;
257        self
258    }
259
260    /// Enables the [extended CONNECT protocol].
261    ///
262    /// [extended CONNECT protocol]: https://datatracker.ietf.org/doc/html/rfc8441#section-4
263    pub fn enable_connect_protocol(&mut self) -> &mut Self {
264        self.h2_builder.enable_connect_protocol = true;
265        self
266    }
267
268    /// Sets the header table size.
269    ///
270    /// This setting informs the peer of the maximum size of the header compression
271    /// table used to encode header blocks, in octets. The encoder may select any value
272    /// equal to or less than the header table size specified by the sender.
273    ///
274    /// The default value of crate `h2` is 4,096.
275    pub fn header_table_size(&mut self, size: impl Into<Option<u32>>) -> &mut Self {
276        self.h2_builder.header_table_size = size.into();
277        self
278    }
279
280    /// Sets the max size of received header frames.
281    ///
282    /// Default is currently 16KB, but can change.
283    pub fn max_header_list_size(&mut self, max: u32) -> &mut Self {
284        self.h2_builder.max_header_list_size = max;
285        self
286    }
287
288    /// Set the timer used in background tasks.
289    pub fn timer<M>(&mut self, timer: M) -> &mut Self
290    where
291        M: Timer + Send + Sync + 'static,
292    {
293        self.timer = Time::Timer(Arc::new(timer));
294        self
295    }
296
297    /// Set whether the `date` header should be included in HTTP responses.
298    ///
299    /// Note that including the `date` header is recommended by RFC 7231.
300    ///
301    /// Default is true.
302    pub fn auto_date_header(&mut self, enabled: bool) -> &mut Self {
303        self.h2_builder.date_header = enabled;
304        self
305    }
306
307    /// Bind a connection together with a [`Service`](crate::service::Service).
308    ///
309    /// This returns a Future that must be polled in order for HTTP to be
310    /// driven on the connection.
311    pub fn serve_connection<S, I, Bd>(&self, io: I, service: S) -> Connection<I, S, E>
312    where
313        S: HttpService<IncomingBody, ResBody = Bd>,
314        S::Error: Into<Box<dyn StdError + Send + Sync>>,
315        Bd: Body + 'static,
316        Bd::Error: Into<Box<dyn StdError + Send + Sync>>,
317        I: Read + Write + Unpin,
318        E: Http2ServerConnExec<S::Future, Bd>,
319    {
320        let proto = proto::h2::Server::new(
321            io,
322            service,
323            &self.h2_builder,
324            self.exec.clone(),
325            self.timer.clone(),
326        );
327        Connection { conn: proto }
328    }
329}