Skip to main content

hyper/proto/h2/
server.rs

1use std::error::Error as StdError;
2use std::future::Future;
3use std::pin::Pin;
4use std::task::{Context, Poll};
5use std::time::Duration;
6
7use bytes::Bytes;
8use futures_core::ready;
9use h2::server::{Connection, Handshake, SendResponse};
10use h2::{Reason, RecvStream};
11use http::{Method, Request};
12use pin_project_lite::pin_project;
13
14use super::{ping, PipeToSendStream, SendBuf};
15use crate::body::{Body, Incoming as IncomingBody};
16use crate::common::date;
17use crate::common::io::Compat;
18use crate::common::time::Time;
19use crate::ext::Protocol;
20use crate::headers;
21use crate::proto::h2::ping::Recorder;
22use crate::proto::Dispatched;
23use crate::rt::bounds::{Http2ServerConnExec, Http2UpgradedExec};
24use crate::rt::{Read, Write};
25use crate::service::HttpService;
26
27use crate::upgrade::{OnUpgrade, Pending, Upgraded};
28use crate::Response;
29
30// Our defaults are chosen for the "majority" case, which usually are not
31// resource constrained, and so the spec default of 64kb can be too limiting
32// for performance.
33//
34// At the same time, a server more often has multiple clients connected, and
35// so is more likely to use more resources than a client would.
36const DEFAULT_CONN_WINDOW: u32 = 1024 * 1024; // 1mb
37const DEFAULT_STREAM_WINDOW: u32 = 1024 * 1024; // 1mb
38const DEFAULT_MAX_FRAME_SIZE: u32 = 1024 * 16; // 16kb
39const DEFAULT_MAX_SEND_BUF_SIZE: usize = 1024 * 400; // 400kb
40const DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE: u32 = 1024 * 16; // 16kb
41const DEFAULT_MAX_LOCAL_ERROR_RESET_STREAMS: usize = 1024;
42
43#[derive(Clone, Debug)]
44pub(crate) struct Config {
45    pub(crate) adaptive_window: bool,
46    pub(crate) initial_conn_window_size: u32,
47    pub(crate) initial_stream_window_size: u32,
48    pub(crate) max_frame_size: u32,
49    pub(crate) enable_connect_protocol: bool,
50    pub(crate) max_concurrent_streams: Option<u32>,
51    pub(crate) max_pending_accept_reset_streams: Option<usize>,
52    pub(crate) max_local_error_reset_streams: Option<usize>,
53    pub(crate) keep_alive_interval: Option<Duration>,
54    pub(crate) keep_alive_timeout: Duration,
55    pub(crate) max_send_buffer_size: usize,
56    pub(crate) header_table_size: Option<u32>,
57    pub(crate) max_header_list_size: u32,
58    pub(crate) date_header: bool,
59}
60
61impl Default for Config {
62    fn default() -> Config {
63        Config {
64            adaptive_window: false,
65            initial_conn_window_size: DEFAULT_CONN_WINDOW,
66            initial_stream_window_size: DEFAULT_STREAM_WINDOW,
67            max_frame_size: DEFAULT_MAX_FRAME_SIZE,
68            enable_connect_protocol: false,
69            max_concurrent_streams: Some(200),
70            max_pending_accept_reset_streams: None,
71            max_local_error_reset_streams: Some(DEFAULT_MAX_LOCAL_ERROR_RESET_STREAMS),
72            header_table_size: None,
73            keep_alive_interval: None,
74            keep_alive_timeout: Duration::from_secs(20),
75            max_send_buffer_size: DEFAULT_MAX_SEND_BUF_SIZE,
76            max_header_list_size: DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE,
77            date_header: true,
78        }
79    }
80}
81
82pin_project! {
83    pub(crate) struct Server<T, S, B, E>
84    where
85        S: HttpService<IncomingBody>,
86        B: Body,
87    {
88        exec: E,
89        timer: Time,
90        service: S,
91        state: State<T, B>,
92        date_header: bool,
93        close_pending: bool
94    }
95}
96
97//#[expect(clippy::large_enum_variant, reason = "the whole future is boxed")]
98#[allow(clippy::large_enum_variant)]
99enum State<T, B>
100where
101    B: Body,
102{
103    Handshaking {
104        ping_config: ping::Config,
105        hs: Handshake<Compat<T>, SendBuf<B::Data>>,
106    },
107    Serving(Serving<T, B>),
108}
109
110struct Serving<T, B>
111where
112    B: Body,
113{
114    ping: Option<(ping::Recorder, ping::Ponger)>,
115    conn: Connection<Compat<T>, SendBuf<B::Data>>,
116    closing: Option<crate::Error>,
117    date_header: bool,
118}
119
120impl<T, S, B, E> Server<T, S, B, E>
121where
122    T: Read + Write + Unpin,
123    S: HttpService<IncomingBody, ResBody = B>,
124    S::Error: Into<Box<dyn StdError + Send + Sync>>,
125    B: Body + 'static,
126    E: Http2ServerConnExec<S::Future, B>,
127{
128    pub(crate) fn new(
129        io: T,
130        service: S,
131        config: &Config,
132        exec: E,
133        timer: Time,
134    ) -> Server<T, S, B, E> {
135        let mut builder = h2::server::Builder::default();
136        builder
137            .initial_window_size(config.initial_stream_window_size)
138            .initial_connection_window_size(config.initial_conn_window_size)
139            .max_frame_size(config.max_frame_size)
140            .max_header_list_size(config.max_header_list_size)
141            .max_local_error_reset_streams(config.max_local_error_reset_streams)
142            .max_send_buffer_size(config.max_send_buffer_size);
143        if let Some(max) = config.max_concurrent_streams {
144            builder.max_concurrent_streams(max);
145        }
146        if let Some(max) = config.max_pending_accept_reset_streams {
147            builder.max_pending_accept_reset_streams(max);
148        }
149        if let Some(size) = config.header_table_size {
150            builder.header_table_size(size);
151        }
152        if config.enable_connect_protocol {
153            builder.enable_connect_protocol();
154        }
155        let handshake = builder.handshake(Compat::new(io));
156
157        let bdp = if config.adaptive_window {
158            Some(config.initial_stream_window_size)
159        } else {
160            None
161        };
162
163        let ping_config = ping::Config {
164            bdp_initial_window: bdp,
165            keep_alive_interval: config.keep_alive_interval,
166            keep_alive_timeout: config.keep_alive_timeout,
167            // If keep-alive is enabled for servers, always enabled while
168            // idle, so it can more aggressively close dead connections.
169            keep_alive_while_idle: true,
170        };
171
172        Server {
173            exec,
174            timer,
175            state: State::Handshaking {
176                ping_config,
177                hs: handshake,
178            },
179            service,
180            date_header: config.date_header,
181            close_pending: false,
182        }
183    }
184
185    pub(crate) fn graceful_shutdown(&mut self) {
186        trace!("graceful_shutdown");
187        match &mut self.state {
188            State::Handshaking { .. } => {
189                self.close_pending = true;
190            }
191            State::Serving(srv) => {
192                if srv.closing.is_none() {
193                    srv.conn.graceful_shutdown();
194                }
195            }
196        }
197    }
198}
199
200impl<T, S, B, E> Future for Server<T, S, B, E>
201where
202    T: Read + Write + Unpin,
203    S: HttpService<IncomingBody, ResBody = B>,
204    S::Error: Into<Box<dyn StdError + Send + Sync>>,
205    B: Body + 'static,
206    E: Http2ServerConnExec<S::Future, B>,
207{
208    type Output = crate::Result<Dispatched>;
209
210    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
211        let me = &mut *self;
212        loop {
213            let next = match &mut me.state {
214                State::Handshaking { hs, ping_config } => {
215                    let mut conn = ready!(Pin::new(hs).poll(cx).map_err(crate::Error::new_h2))?;
216                    let ping = if ping_config.is_enabled() {
217                        let pp = conn.ping_pong().expect("conn.ping_pong");
218                        Some(ping::channel(pp, ping_config.clone(), me.timer.clone()))
219                    } else {
220                        None
221                    };
222                    State::Serving(Serving {
223                        ping,
224                        conn,
225                        closing: None,
226                        date_header: me.date_header,
227                    })
228                }
229                State::Serving(srv) => {
230                    // graceful_shutdown was called before handshaking finished,
231                    if me.close_pending && srv.closing.is_none() {
232                        srv.conn.graceful_shutdown();
233                    }
234                    ready!(srv.poll_server(cx, &mut me.service, &mut me.exec))?;
235                    return Poll::Ready(Ok(Dispatched::Shutdown));
236                }
237            };
238            me.state = next;
239        }
240    }
241}
242
243impl<T, B> Serving<T, B>
244where
245    T: Read + Write + Unpin,
246    B: Body + 'static,
247{
248    fn poll_server<S, E>(
249        &mut self,
250        cx: &mut Context<'_>,
251        service: &mut S,
252        exec: &mut E,
253    ) -> Poll<crate::Result<()>>
254    where
255        S: HttpService<IncomingBody, ResBody = B>,
256        S::Error: Into<Box<dyn StdError + Send + Sync>>,
257        E: Http2ServerConnExec<S::Future, B>,
258    {
259        if self.closing.is_none() {
260            loop {
261                self.poll_ping(cx);
262
263                match ready!(self.conn.poll_accept(cx)) {
264                    Some(Ok((req, mut respond))) => {
265                        trace!("incoming request");
266                        let content_length = headers::content_length_parse_all(req.headers());
267                        let ping = self
268                            .ping
269                            .as_ref()
270                            .map_or_else(ping::disabled, |ping| ping.0.clone());
271
272                        // Record the headers received
273                        ping.record_non_data();
274
275                        let is_connect = req.method() == Method::CONNECT;
276                        let (mut parts, stream) = req.into_parts();
277                        let (mut req, connect_parts) = if !is_connect {
278                            (
279                                Request::from_parts(
280                                    parts,
281                                    IncomingBody::h2(stream, content_length.into(), ping),
282                                ),
283                                None,
284                            )
285                        } else {
286                            if content_length.map_or(false, |len| len != 0) {
287                                warn!("h2 connect request with non-zero body not supported");
288                                respond.send_reset(h2::Reason::INTERNAL_ERROR);
289                                return Poll::Ready(Ok(()));
290                            }
291                            let (pending, upgrade) = crate::upgrade::pending();
292                            debug_assert!(parts.extensions.get::<OnUpgrade>().is_none());
293                            parts.extensions.insert(upgrade);
294                            (
295                                Request::from_parts(parts, IncomingBody::empty()),
296                                Some(ConnectParts {
297                                    pending,
298                                    ping,
299                                    recv_stream: stream,
300                                }),
301                            )
302                        };
303
304                        if let Some(protocol) = req.extensions_mut().remove::<h2::ext::Protocol>() {
305                            req.extensions_mut().insert(Protocol::from_inner(protocol));
306                        }
307
308                        let fut = H2Stream::new(
309                            service.call(req),
310                            connect_parts,
311                            respond,
312                            self.date_header,
313                            exec.clone(),
314                        );
315
316                        exec.execute_h2stream(fut);
317                    }
318                    Some(Err(e)) => {
319                        return Poll::Ready(Err(crate::Error::new_h2(e)));
320                    }
321                    None => {
322                        // no more incoming streams...
323                        if let Some((ping, _)) = &self.ping {
324                            ping.ensure_not_timed_out()?;
325                        }
326
327                        trace!("incoming connection complete");
328                        return Poll::Ready(Ok(()));
329                    }
330                }
331            }
332        }
333
334        debug_assert!(
335            self.closing.is_some(),
336            "poll_server broke loop without closing"
337        );
338
339        ready!(self.conn.poll_closed(cx).map_err(crate::Error::new_h2))?;
340
341        Poll::Ready(Err(self.closing.take().expect("polled after error")))
342    }
343
344    fn poll_ping(&mut self, cx: &mut Context<'_>) {
345        if let Some((_, estimator)) = &mut self.ping {
346            match estimator.poll(cx) {
347                Poll::Ready(ping::Ponged::SizeUpdate(wnd)) => {
348                    self.conn.set_target_window_size(wnd);
349                    let _ = self.conn.set_initial_window_size(wnd);
350                }
351                Poll::Ready(ping::Ponged::KeepAliveTimedOut) => {
352                    debug!("keep-alive timed out, closing connection");
353                    self.conn.abrupt_shutdown(h2::Reason::NO_ERROR);
354                }
355                Poll::Pending => {}
356            }
357        }
358    }
359}
360
361pin_project! {
362    #[allow(missing_debug_implementations)]
363    pub struct H2Stream<F, B, E>
364    where
365        B: Body,
366    {
367        reply: SendResponse<SendBuf<B::Data>>,
368        #[pin]
369        state: H2StreamState<F, B>,
370        date_header: bool,
371        exec: E,
372    }
373}
374
375pin_project! {
376    #[project = H2StreamStateProj]
377    enum H2StreamState<F, B>
378    where
379        B: Body,
380    {
381        Service {
382            #[pin]
383            fut: F,
384            connect_parts: Option<ConnectParts>,
385        },
386        Body {
387            #[pin]
388            pipe: PipeToSendStream<B>,
389        },
390    }
391}
392
393struct ConnectParts {
394    pending: Pending,
395    ping: Recorder,
396    recv_stream: RecvStream,
397}
398
399impl<F, B, E> H2Stream<F, B, E>
400where
401    B: Body,
402{
403    fn new(
404        fut: F,
405        connect_parts: Option<ConnectParts>,
406        respond: SendResponse<SendBuf<B::Data>>,
407        date_header: bool,
408        exec: E,
409    ) -> H2Stream<F, B, E> {
410        H2Stream {
411            reply: respond,
412            state: H2StreamState::Service { fut, connect_parts },
413            date_header,
414            exec,
415        }
416    }
417}
418
419macro_rules! reply {
420    ($me:expr, $res:expr, $eos:expr) => {{
421        match $me.reply.send_response($res, $eos) {
422            Ok(tx) => tx,
423            Err(e) => {
424                debug!("send response error: {}", e);
425                $me.reply.send_reset(Reason::INTERNAL_ERROR);
426                return Poll::Ready(Err(crate::Error::new_h2(e)));
427            }
428        }
429    }};
430}
431
432impl<F, B, Ex, E> H2Stream<F, B, Ex>
433where
434    F: Future<Output = Result<Response<B>, E>>,
435    B: Body,
436    B::Data: 'static,
437    B::Error: Into<Box<dyn StdError + Send + Sync>>,
438    Ex: Http2UpgradedExec<B::Data>,
439    E: Into<Box<dyn StdError + Send + Sync>>,
440{
441    fn poll2(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<crate::Result<()>> {
442        let mut me = self.as_mut().project();
443        loop {
444            let next = match me.state.as_mut().project() {
445                H2StreamStateProj::Service {
446                    fut: h,
447                    connect_parts,
448                } => {
449                    let res = match h.poll(cx) {
450                        Poll::Ready(Ok(r)) => r,
451                        Poll::Pending => {
452                            // Response is not yet ready, so we want to check if the client has sent a
453                            // RST_STREAM frame which would cancel the current request.
454                            if let Poll::Ready(reason) =
455                                me.reply.poll_reset(cx).map_err(crate::Error::new_h2)?
456                            {
457                                debug!("stream received RST_STREAM: {:?}", reason);
458                                return Poll::Ready(Err(crate::Error::new_h2(reason.into())));
459                            }
460                            return Poll::Pending;
461                        }
462                        Poll::Ready(Err(e)) => {
463                            let err = crate::Error::new_user_service(e);
464                            warn!("http2 service errored: {}", err);
465                            me.reply.send_reset(err.h2_reason());
466                            return Poll::Ready(Err(err));
467                        }
468                    };
469
470                    let (head, body) = res.into_parts();
471                    let mut res = ::http::Response::from_parts(head, ());
472                    super::strip_connection_headers(
473                        res.headers_mut(),
474                        super::MessageKind::Response,
475                    );
476
477                    // set Date header if it isn't already set if instructed
478                    if *me.date_header {
479                        res.headers_mut()
480                            .entry(::http::header::DATE)
481                            .or_insert_with(date::update_and_header_value);
482                    }
483
484                    if let Some(connect_parts) = connect_parts.take() {
485                        if res.status().is_success() {
486                            if headers::content_length_parse_all(res.headers())
487                                .map_or(false, |len| len != 0)
488                            {
489                                warn!("h2 successful response to CONNECT request with body not supported");
490                                me.reply.send_reset(h2::Reason::INTERNAL_ERROR);
491                                return Poll::Ready(Err(crate::Error::new_user_header()));
492                            }
493                            if res
494                                .headers_mut()
495                                .remove(::http::header::CONTENT_LENGTH)
496                                .is_some()
497                            {
498                                warn!("successful response to CONNECT request disallows content-length header");
499                            }
500                            let send_stream = reply!(me, res, false);
501                            let (h2_up, up_task) = super::upgrade::pair(
502                                send_stream,
503                                connect_parts.recv_stream,
504                                connect_parts.ping,
505                            );
506                            connect_parts
507                                .pending
508                                .fulfill(Upgraded::new(h2_up, Bytes::new()));
509                            self.exec.execute_upgrade(up_task);
510                            return Poll::Ready(Ok(()));
511                        }
512                    }
513
514                    if !body.is_end_stream() {
515                        // automatically set Content-Length from body...
516                        if let Some(len) = body.size_hint().exact() {
517                            headers::set_content_length_if_missing(res.headers_mut(), len);
518                        }
519
520                        let body_tx = reply!(me, res, false);
521                        H2StreamState::Body {
522                            pipe: PipeToSendStream::new(body, body_tx),
523                        }
524                    } else {
525                        reply!(me, res, true);
526                        return Poll::Ready(Ok(()));
527                    }
528                }
529                H2StreamStateProj::Body { pipe } => {
530                    return pipe.poll(cx);
531                }
532            };
533            me.state.set(next);
534        }
535    }
536}
537
538impl<F, B, Ex, E> Future for H2Stream<F, B, Ex>
539where
540    F: Future<Output = Result<Response<B>, E>>,
541    B: Body,
542    B::Data: 'static,
543    B::Error: Into<Box<dyn StdError + Send + Sync>>,
544    Ex: Http2UpgradedExec<B::Data>,
545    E: Into<Box<dyn StdError + Send + Sync>>,
546{
547    type Output = ();
548
549    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
550        self.poll2(cx).map(|res| {
551            if let Err(_e) = res {
552                debug!("stream error: {}", _e);
553            }
554        })
555    }
556}