Skip to main content

h2/
server.rs

1//! Server implementation of the HTTP/2 protocol.
2//!
3//! # Getting started
4//!
5//! Running an HTTP/2 server requires the caller to manage accepting the
6//! connections as well as getting the connections to a state that is ready to
7//! begin the HTTP/2 handshake. See [here](../index.html#handshake) for more
8//! details.
9//!
10//! This could be as basic as using Tokio's [`TcpListener`] to accept
11//! connections, but usually it means using either ALPN or HTTP/1.1 protocol
12//! upgrades.
13//!
14//! Once a connection is obtained, it is passed to [`handshake`],
15//! which will begin the [HTTP/2 handshake]. This returns a future that
16//! completes once the handshake process is performed and HTTP/2 streams may
17//! be received.
18//!
19//! [`handshake`] uses default configuration values. There are a number of
20//! settings that can be changed by using [`Builder`] instead.
21//!
22//! # Inbound streams
23//!
24//! The [`Connection`] instance is used to accept inbound HTTP/2 streams. It
25//! does this by implementing [`futures::Stream`]. When a new stream is
26//! received, a call to [`Connection::accept`] will return `(request, response)`.
27//! The `request` handle (of type [`http::Request<RecvStream>`]) contains the
28//! HTTP request head as well as provides a way to receive the inbound data
29//! stream and the trailers. The `response` handle (of type [`SendResponse`])
30//! allows responding to the request, stream the response payload, send
31//! trailers, and send push promises.
32//!
33//! The send ([`SendStream`]) and receive ([`RecvStream`]) halves of the stream
34//! can be operated independently.
35//!
36//! # Managing the connection
37//!
38//! The [`Connection`] instance is used to manage connection state. The caller
39//! is required to call either [`Connection::accept`] or
40//! [`Connection::poll_close`] in order to advance the connection state. Simply
41//! operating on [`SendStream`] or [`RecvStream`] will have no effect unless the
42//! connection state is advanced.
43//!
44//! It is not required to call **both** [`Connection::accept`] and
45//! [`Connection::poll_close`]. If the caller is ready to accept a new stream,
46//! then only [`Connection::accept`] should be called. When the caller **does
47//! not** want to accept a new stream, [`Connection::poll_close`] should be
48//! called.
49//!
50//! The [`Connection`] instance should only be dropped once
51//! [`Connection::poll_close`] returns `Ready`. Once [`Connection::accept`]
52//! returns `Ready(None)`, there will no longer be any more inbound streams. At
53//! this point, only [`Connection::poll_close`] should be called.
54//!
55//! # Shutting down the server
56//!
57//! Graceful shutdown of the server is [not yet
58//! implemented](https://github.com/hyperium/h2/issues/69).
59//!
60//! # Example
61//!
62//! A basic HTTP/2 server example that runs over TCP and assumes [prior
63//! knowledge], i.e. both the client and the server assume that the TCP socket
64//! will use the HTTP/2 protocol without prior negotiation.
65//!
66//! ```no_run
67//! use h2::server;
68//! use http::{Response, StatusCode};
69//! use tokio::net::TcpListener;
70//!
71//! #[tokio::main]
72//! pub async fn main() {
73//!     let mut listener = TcpListener::bind("127.0.0.1:5928").await.unwrap();
74//!
75//!     // Accept all incoming TCP connections.
76//!     loop {
77//!         if let Ok((socket, _peer_addr)) = listener.accept().await {
78//!             // Spawn a new task to process each connection.
79//!             tokio::spawn(async {
80//!                 // Start the HTTP/2 connection handshake
81//!                 let mut h2 = server::handshake(socket).await.unwrap();
82//!                 // Accept all inbound HTTP/2 streams sent over the
83//!                 // connection.
84//!                 while let Some(request) = h2.accept().await {
85//!                     let (request, mut respond) = request.unwrap();
86//!                     println!("Received request: {:?}", request);
87//!
88//!                     // Build a response with no body
89//!                     let response = Response::builder()
90//!                         .status(StatusCode::OK)
91//!                         .body(())
92//!                         .unwrap();
93//!
94//!                     // Send the response back to the client
95//!                     respond.send_response(response, true)
96//!                         .unwrap();
97//!                 }
98//!
99//!             });
100//!         }
101//!     }
102//! }
103//! ```
104//!
105//! [prior knowledge]: http://httpwg.org/specs/rfc7540.html#known-http
106//! [`handshake`]: fn.handshake.html
107//! [HTTP/2 handshake]: http://httpwg.org/specs/rfc7540.html#ConnectionHeader
108//! [`Builder`]: struct.Builder.html
109//! [`Connection`]: struct.Connection.html
110//! [`Connection::poll`]: struct.Connection.html#method.poll
111//! [`Connection::poll_close`]: struct.Connection.html#method.poll_close
112//! [`futures::Stream`]: https://docs.rs/futures/0.1/futures/stream/trait.Stream.html
113//! [`http::Request<RecvStream>`]: ../struct.RecvStream.html
114//! [`RecvStream`]: ../struct.RecvStream.html
115//! [`SendStream`]: ../struct.SendStream.html
116//! [`TcpListener`]: https://docs.rs/tokio-core/0.1/tokio_core/net/struct.TcpListener.html
117
118use crate::codec::{Codec, UserError};
119use crate::frame::{self, Pseudo, PushPromiseHeaderError, Reason, Settings, StreamId};
120use crate::proto::{self, Config, Error, Prioritized};
121use crate::{FlowControl, PingPong, RecvStream, SendStream};
122
123use bytes::{Buf, Bytes};
124use http::{HeaderMap, Method, Request, Response};
125use std::future::Future;
126use std::pin::Pin;
127use std::task::{Context, Poll};
128use std::time::Duration;
129use std::{fmt, io};
130use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
131use tracing::instrument::{Instrument, Instrumented};
132
133/// In progress HTTP/2 connection handshake future.
134///
135/// This type implements `Future`, yielding a `Connection` instance once the
136/// handshake has completed.
137///
138/// The handshake is completed once the connection preface is fully received
139/// from the client **and** the initial settings frame is sent to the client.
140///
141/// The handshake future does not wait for the initial settings frame from the
142/// client.
143///
144/// See [module] level docs for more details.
145///
146/// [module]: index.html
147#[must_use = "futures do nothing unless polled"]
148pub struct Handshake<T, B: Buf = Bytes> {
149    /// The config to pass to Connection::new after handshake succeeds.
150    builder: Builder,
151    /// The current state of the handshake.
152    state: Handshaking<T, B>,
153    /// Span tracking the handshake
154    span: tracing::Span,
155}
156
157/// Accepts inbound HTTP/2 streams on a connection.
158///
159/// A `Connection` is backed by an I/O resource (usually a TCP socket) and
160/// implements the HTTP/2 server logic for that connection. It is responsible
161/// for receiving inbound streams initiated by the client as well as driving the
162/// internal state forward.
163///
164/// `Connection` values are created by calling [`handshake`]. Once a
165/// `Connection` value is obtained, the caller must call [`poll`] or
166/// [`poll_close`] in order to drive the internal connection state forward.
167///
168/// See [module level] documentation for more details
169///
170/// [module level]: index.html
171/// [`handshake`]: struct.Connection.html#method.handshake
172/// [`poll`]: struct.Connection.html#method.poll
173/// [`poll_close`]: struct.Connection.html#method.poll_close
174///
175/// # Examples
176///
177/// ```
178/// # use tokio::io::{AsyncRead, AsyncWrite};
179/// # use h2::server;
180/// # use h2::server::*;
181/// #
182/// # async fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T) {
183/// let mut server = server::handshake(my_io).await.unwrap();
184/// while let Some(request) = server.accept().await {
185///     tokio::spawn(async move {
186///         let (request, respond) = request.unwrap();
187///         // Process the request and send the response back to the client
188///         // using `respond`.
189///     });
190/// }
191/// # }
192/// #
193/// # pub fn main() {}
194/// ```
195#[must_use = "streams do nothing unless polled"]
196pub struct Connection<T, B: Buf> {
197    connection: proto::Connection<T, Peer, B>,
198}
199
200/// Builds server connections with custom configuration values.
201///
202/// Methods can be chained in order to set the configuration values.
203///
204/// The server is constructed by calling [`handshake`] and passing the I/O
205/// handle that will back the HTTP/2 server.
206///
207/// New instances of `Builder` are obtained via [`Builder::new`].
208///
209/// See function level documentation for details on the various server
210/// configuration settings.
211///
212/// [`Builder::new`]: struct.Builder.html#method.new
213/// [`handshake`]: struct.Builder.html#method.handshake
214///
215/// # Examples
216///
217/// ```
218/// # use tokio::io::{AsyncRead, AsyncWrite};
219/// # use h2::server::*;
220/// #
221/// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
222/// # -> Handshake<T>
223/// # {
224/// // `server_fut` is a future representing the completion of the HTTP/2
225/// // handshake.
226/// let server_fut = Builder::new()
227///     .initial_window_size(1_000_000)
228///     .max_concurrent_streams(1000)
229///     .handshake(my_io);
230/// # server_fut
231/// # }
232/// #
233/// # pub fn main() {}
234/// ```
235#[derive(Clone, Debug)]
236pub struct Builder {
237    /// Time to keep locally reset streams around before reaping.
238    reset_stream_duration: Duration,
239
240    /// Maximum number of locally reset streams to keep at a time.
241    reset_stream_max: usize,
242
243    /// Maximum number of remotely reset streams to allow in the pending
244    /// accept queue.
245    pending_accept_reset_stream_max: usize,
246
247    /// Initial `Settings` frame to send as part of the handshake.
248    settings: Settings,
249
250    /// Initial target window size for new connections.
251    initial_target_connection_window_size: Option<u32>,
252
253    /// Maximum amount of bytes to "buffer" for writing per stream.
254    max_send_buffer_size: usize,
255
256    /// Maximum number of locally reset streams due to protocol error across
257    /// the lifetime of the connection.
258    ///
259    /// When this gets exceeded, we issue GOAWAYs.
260    local_max_error_reset_streams: Option<usize>,
261
262    /// connection-level budget for DATA framing overhead.
263    ///
264    /// When this gets exhausted, we issue a GOAWAY with `ENHANCE_YOUR_CALM`.
265    data_frame_budget: proto::DataFrameBudget,
266}
267
268/// Send a response back to the client
269///
270/// A `SendResponse` instance is provided when receiving a request and is used
271/// to send the associated response back to the client. It is also used to
272/// explicitly reset the stream with a custom reason.
273///
274/// It will also be used to initiate push promises linked with the associated
275/// stream.
276///
277/// If the `SendResponse` instance is dropped without sending a response, then
278/// the HTTP/2 stream will be reset.
279///
280/// See [module] level docs for more details.
281///
282/// [module]: index.html
283#[derive(Debug)]
284pub struct SendResponse<B: Buf> {
285    inner: proto::StreamRef<B>,
286}
287
288/// Send a response to a promised request
289///
290/// A `SendPushedResponse` instance is provided when promising a request and is used
291/// to send the associated response to the client. It is also used to
292/// explicitly reset the stream with a custom reason.
293///
294/// It can not be used to initiate push promises.
295///
296/// If the `SendPushedResponse` instance is dropped without sending a response, then
297/// the HTTP/2 stream will be reset.
298///
299/// See [module] level docs for more details.
300///
301/// [module]: index.html
302pub struct SendPushedResponse<B: Buf> {
303    inner: SendResponse<B>,
304}
305
306// Manual implementation necessary because of rust-lang/rust#26925
307impl<B: Buf + fmt::Debug> fmt::Debug for SendPushedResponse<B> {
308    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
309        write!(f, "SendPushedResponse {{ {:?} }}", self.inner)
310    }
311}
312
313/// Stages of an in-progress handshake.
314enum Handshaking<T, B: Buf> {
315    /// State 1. Connection is flushing pending SETTINGS frame.
316    Flushing(Instrumented<Flush<T, Prioritized<B>>>),
317    /// State 2. Connection is waiting for the client preface.
318    ReadingPreface(Instrumented<ReadPreface<T, Prioritized<B>>>),
319    /// State 3. Handshake is done, polling again would panic.
320    Done,
321}
322
323/// Flush a Sink
324struct Flush<T, B> {
325    codec: Option<Codec<T, B>>,
326}
327
328/// Read the client connection preface
329struct ReadPreface<T, B> {
330    codec: Option<Codec<T, B>>,
331    pos: usize,
332}
333
334#[derive(Debug)]
335pub(crate) struct Peer;
336
337const PREFACE: [u8; 24] = *b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
338
339/// Creates a new configured HTTP/2 server with default configuration
340/// values backed by `io`.
341///
342/// It is expected that `io` already be in an appropriate state to commence
343/// the [HTTP/2 handshake]. See [Handshake] for more details.
344///
345/// Returns a future which resolves to the [`Connection`] instance once the
346/// HTTP/2 handshake has been completed. The returned [`Connection`]
347/// instance will be using default configuration values. Use [`Builder`] to
348/// customize the configuration values used by a [`Connection`] instance.
349///
350/// [HTTP/2 handshake]: http://httpwg.org/specs/rfc7540.html#ConnectionHeader
351/// [Handshake]: ../index.html#handshake
352/// [`Connection`]: struct.Connection.html
353///
354/// # Examples
355///
356/// ```
357/// # use tokio::io::{AsyncRead, AsyncWrite};
358/// # use h2::server;
359/// # use h2::server::*;
360/// #
361/// # async fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
362/// # {
363/// let connection = server::handshake(my_io).await.unwrap();
364/// // The HTTP/2 handshake has completed, now use `connection` to
365/// // accept inbound HTTP/2 streams.
366/// # }
367/// #
368/// # pub fn main() {}
369/// ```
370pub fn handshake<T>(io: T) -> Handshake<T, Bytes>
371where
372    T: AsyncRead + AsyncWrite + Unpin,
373{
374    Builder::new().handshake(io)
375}
376
377// ===== impl Connection =====
378
379impl<T, B> Connection<T, B>
380where
381    T: AsyncRead + AsyncWrite + Unpin,
382    B: Buf,
383{
384    fn handshake2(io: T, builder: Builder) -> Handshake<T, B> {
385        let span = tracing::trace_span!("server_handshake");
386        let entered = span.enter();
387
388        // Create the codec.
389        let mut codec = Codec::new(io);
390
391        if let Some(max) = builder.settings.max_frame_size() {
392            codec.set_max_recv_frame_size(max as usize);
393        }
394
395        if let Some(max) = builder.settings.max_header_list_size() {
396            codec.set_max_recv_header_list_size(max as usize);
397        }
398
399        // Send initial settings frame.
400        codec
401            .buffer(builder.settings.clone().into())
402            .expect("invalid SETTINGS frame");
403
404        // Create the handshake future.
405        let state =
406            Handshaking::Flushing(Flush::new(codec).instrument(tracing::trace_span!("flush")));
407
408        drop(entered);
409
410        Handshake {
411            builder,
412            state,
413            span,
414        }
415    }
416
417    /// Accept the next incoming request on this connection.
418    pub async fn accept(
419        &mut self,
420    ) -> Option<Result<(Request<RecvStream>, SendResponse<B>), crate::Error>> {
421        crate::poll_fn(move |cx| self.poll_accept(cx)).await
422    }
423
424    #[doc(hidden)]
425    pub fn poll_accept(
426        &mut self,
427        cx: &mut Context<'_>,
428    ) -> Poll<Option<Result<(Request<RecvStream>, SendResponse<B>), crate::Error>>> {
429        // Always try to advance the internal state. Getting Pending also is
430        // needed to allow this function to return Pending.
431        if self.poll_closed(cx)?.is_ready() {
432            // If the socket is closed, don't return anything
433            // TODO: drop any pending streams
434            return Poll::Ready(None);
435        }
436
437        if let Some(inner) = self.connection.next_incoming() {
438            tracing::trace!("received incoming");
439            let (head, _) = inner.take_request().into_parts();
440            let body = RecvStream::new(FlowControl::new(inner.clone_to_opaque()));
441
442            let request = Request::from_parts(head, body);
443            let respond = SendResponse { inner };
444
445            return Poll::Ready(Some(Ok((request, respond))));
446        }
447
448        Poll::Pending
449    }
450
451    /// Sets the target window size for the whole connection.
452    ///
453    /// If `size` is greater than the current value, then a `WINDOW_UPDATE`
454    /// frame will be immediately sent to the remote, increasing the connection
455    /// level window by `size - current_value`.
456    ///
457    /// If `size` is less than the current value, nothing will happen
458    /// immediately. However, as window capacity is released by
459    /// [`FlowControl`] instances, no `WINDOW_UPDATE` frames will be sent
460    /// out until the number of "in flight" bytes drops below `size`.
461    ///
462    /// The default value is 65,535. The automatic small-DATA-frame budget is
463    /// updated to match this target.
464    ///
465    /// See [`FlowControl`] documentation for more details.
466    ///
467    /// [`FlowControl`]: ../struct.FlowControl.html
468    /// [library level]: ../index.html#flow-control
469    pub fn set_target_window_size(&mut self, size: u32) {
470        assert!(size <= proto::MAX_WINDOW_SIZE);
471        self.connection.set_target_window_size(size);
472    }
473
474    /// Set a new `INITIAL_WINDOW_SIZE` setting (in octets) for stream-level
475    /// flow control for received data.
476    ///
477    /// The `SETTINGS` will be sent to the remote, and only applied once the
478    /// remote acknowledges the change.
479    ///
480    /// This can be used to increase or decrease the window size for existing
481    /// streams.
482    ///
483    /// # Errors
484    ///
485    /// Returns an error if a previous call is still pending acknowledgement
486    /// from the remote endpoint.
487    pub fn set_initial_window_size(&mut self, size: u32) -> Result<(), crate::Error> {
488        assert!(size <= proto::MAX_WINDOW_SIZE);
489        self.connection.set_initial_window_size(size)?;
490        Ok(())
491    }
492
493    /// Enables the [extended CONNECT protocol].
494    ///
495    /// [extended CONNECT protocol]: https://datatracker.ietf.org/doc/html/rfc8441#section-4
496    ///
497    /// # Errors
498    ///
499    /// Returns an error if a previous call is still pending acknowledgement
500    /// from the remote endpoint.
501    pub fn enable_connect_protocol(&mut self) -> Result<(), crate::Error> {
502        self.connection.set_enable_connect_protocol()?;
503        Ok(())
504    }
505
506    /// Returns `Ready` when the underlying connection has closed.
507    ///
508    /// If any new inbound streams are received during a call to `poll_closed`,
509    /// they will be queued and returned on the next call to [`poll_accept`].
510    ///
511    /// This function will advance the internal connection state, driving
512    /// progress on all the other handles (e.g. [`RecvStream`] and [`SendStream`]).
513    ///
514    /// See [here](index.html#managing-the-connection) for more details.
515    ///
516    /// [`poll_accept`]: struct.Connection.html#method.poll_accept
517    /// [`RecvStream`]: ../struct.RecvStream.html
518    /// [`SendStream`]: ../struct.SendStream.html
519    pub fn poll_closed(&mut self, cx: &mut Context) -> Poll<Result<(), crate::Error>> {
520        self.connection.poll(cx).map_err(Into::into)
521    }
522
523    /// Sets the connection to a GOAWAY state.
524    ///
525    /// Does not terminate the connection. Must continue being polled to close
526    /// connection.
527    ///
528    /// After flushing the GOAWAY frame, the connection is closed. Any
529    /// outstanding streams do not prevent the connection from closing. This
530    /// should usually be reserved for shutting down when something bad
531    /// external to `h2` has happened, and open streams cannot be properly
532    /// handled.
533    ///
534    /// For graceful shutdowns, see [`graceful_shutdown`](Connection::graceful_shutdown).
535    pub fn abrupt_shutdown(&mut self, reason: Reason) {
536        self.connection.go_away_from_user(reason);
537    }
538
539    /// Starts a [graceful shutdown][1] process.
540    ///
541    /// Must continue being polled to close connection.
542    ///
543    /// It's possible to receive more requests after calling this method, since
544    /// they might have been in-flight from the client already. After about
545    /// 1 RTT, no new requests should be accepted. Once all active streams
546    /// have completed, the connection is closed.
547    ///
548    /// [1]: http://httpwg.org/specs/rfc7540.html#GOAWAY
549    pub fn graceful_shutdown(&mut self) {
550        self.connection.go_away_gracefully();
551    }
552
553    /// Takes a `PingPong` instance from the connection.
554    ///
555    /// # Note
556    ///
557    /// This may only be called once. Calling multiple times will return `None`.
558    pub fn ping_pong(&mut self) -> Option<PingPong> {
559        self.connection.take_user_pings().map(PingPong::new)
560    }
561
562    /// Checks if there are any streams
563    pub fn has_streams(&self) -> bool {
564        self.connection.has_streams()
565    }
566
567    /// Returns the maximum number of concurrent streams that may be initiated
568    /// by the server on this connection.
569    ///
570    /// This limit is configured by the client peer by sending the
571    /// [`SETTINGS_MAX_CONCURRENT_STREAMS` parameter][1] in a `SETTINGS` frame.
572    /// This method returns the currently acknowledged value received from the
573    /// remote.
574    ///
575    /// [1]: https://tools.ietf.org/html/rfc7540#section-5.1.2
576    pub fn max_concurrent_send_streams(&self) -> usize {
577        self.connection.max_send_streams()
578    }
579
580    /// Returns the maximum number of concurrent streams that may be initiated
581    /// by the client on this connection.
582    ///
583    /// This returns the value of the [`SETTINGS_MAX_CONCURRENT_STREAMS`
584    /// parameter][1] sent in a `SETTINGS` frame that has been
585    /// acknowledged by the remote peer. The value to be sent is configured by
586    /// the [`Builder::max_concurrent_streams`][2] method before handshaking
587    /// with the remote peer.
588    ///
589    /// [1]: https://tools.ietf.org/html/rfc7540#section-5.1.2
590    /// [2]: ../struct.Builder.html#method.max_concurrent_streams
591    pub fn max_concurrent_recv_streams(&self) -> usize {
592        self.connection.max_recv_streams()
593    }
594
595    // Could disappear at anytime.
596    #[doc(hidden)]
597    #[cfg(feature = "unstable")]
598    pub fn num_wired_streams(&self) -> usize {
599        self.connection.num_wired_streams()
600    }
601}
602
603#[cfg(feature = "stream")]
604impl<T, B> futures_core::Stream for Connection<T, B>
605where
606    T: AsyncRead + AsyncWrite + Unpin,
607    B: Buf,
608{
609    type Item = Result<(Request<RecvStream>, SendResponse<B>), crate::Error>;
610
611    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
612        self.poll_accept(cx)
613    }
614}
615
616impl<T, B> fmt::Debug for Connection<T, B>
617where
618    T: fmt::Debug,
619    B: fmt::Debug + Buf,
620{
621    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
622        fmt.debug_struct("Connection")
623            .field("connection", &self.connection)
624            .finish()
625    }
626}
627
628// ===== impl Builder =====
629
630impl Builder {
631    /// Returns a new server builder instance initialized with default
632    /// configuration values.
633    ///
634    /// Configuration methods can be chained on the return value.
635    ///
636    /// # Examples
637    ///
638    /// ```
639    /// # use tokio::io::{AsyncRead, AsyncWrite};
640    /// # use h2::server::*;
641    /// #
642    /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
643    /// # -> Handshake<T>
644    /// # {
645    /// // `server_fut` is a future representing the completion of the HTTP/2
646    /// // handshake.
647    /// let server_fut = Builder::new()
648    ///     .initial_window_size(1_000_000)
649    ///     .max_concurrent_streams(1000)
650    ///     .handshake(my_io);
651    /// # server_fut
652    /// # }
653    /// #
654    /// # pub fn main() {}
655    /// ```
656    pub fn new() -> Builder {
657        Builder {
658            reset_stream_duration: Duration::from_secs(proto::DEFAULT_RESET_STREAM_SECS),
659            reset_stream_max: proto::DEFAULT_RESET_STREAM_MAX,
660            pending_accept_reset_stream_max: proto::DEFAULT_REMOTE_RESET_STREAM_MAX,
661            settings: Settings::default(),
662            initial_target_connection_window_size: None,
663            max_send_buffer_size: proto::DEFAULT_MAX_SEND_BUFFER_SIZE,
664            local_max_error_reset_streams: Some(proto::DEFAULT_LOCAL_RESET_COUNT_MAX),
665            data_frame_budget: proto::DataFrameBudget::Auto,
666        }
667    }
668
669    /// Indicates the initial window size (in octets) for stream-level
670    /// flow control for received data.
671    ///
672    /// The initial window of a stream is used as part of flow control. For more
673    /// details, see [`FlowControl`].
674    ///
675    /// The default value is 65,535.
676    ///
677    /// [`FlowControl`]: ../struct.FlowControl.html
678    ///
679    /// # Examples
680    ///
681    /// ```
682    /// # use tokio::io::{AsyncRead, AsyncWrite};
683    /// # use h2::server::*;
684    /// #
685    /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
686    /// # -> Handshake<T>
687    /// # {
688    /// // `server_fut` is a future representing the completion of the HTTP/2
689    /// // handshake.
690    /// let server_fut = Builder::new()
691    ///     .initial_window_size(1_000_000)
692    ///     .handshake(my_io);
693    /// # server_fut
694    /// # }
695    /// #
696    /// # pub fn main() {}
697    /// ```
698    pub fn initial_window_size(&mut self, size: u32) -> &mut Self {
699        self.settings.set_initial_window_size(Some(size));
700        self
701    }
702
703    /// Indicates the initial window size (in octets) for connection-level flow control
704    /// for received data.
705    ///
706    /// The initial window of a connection is used as part of flow control. For more details,
707    /// see [`FlowControl`].
708    ///
709    /// The default value is 65,535.
710    ///
711    /// [`FlowControl`]: ../struct.FlowControl.html
712    ///
713    /// # Examples
714    ///
715    /// ```
716    /// # use tokio::io::{AsyncRead, AsyncWrite};
717    /// # use h2::server::*;
718    /// #
719    /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
720    /// # -> Handshake<T>
721    /// # {
722    /// // `server_fut` is a future representing the completion of the HTTP/2
723    /// // handshake.
724    /// let server_fut = Builder::new()
725    ///     .initial_connection_window_size(1_000_000)
726    ///     .handshake(my_io);
727    /// # server_fut
728    /// # }
729    /// #
730    /// # pub fn main() {}
731    /// ```
732    pub fn initial_connection_window_size(&mut self, size: u32) -> &mut Self {
733        self.initial_target_connection_window_size = Some(size);
734        self
735    }
736
737    /// Indicates the size (in octets) of the largest HTTP/2 frame payload that the
738    /// configured server is able to accept.
739    ///
740    /// The sender may send data frames that are **smaller** than this value,
741    /// but any data larger than `max` will be broken up into multiple `DATA`
742    /// frames.
743    ///
744    /// The value **must** be between 16,384 and 16,777,215. The default value is 16,384.
745    ///
746    /// # Examples
747    ///
748    /// ```
749    /// # use tokio::io::{AsyncRead, AsyncWrite};
750    /// # use h2::server::*;
751    /// #
752    /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
753    /// # -> Handshake<T>
754    /// # {
755    /// // `server_fut` is a future representing the completion of the HTTP/2
756    /// // handshake.
757    /// let server_fut = Builder::new()
758    ///     .max_frame_size(1_000_000)
759    ///     .handshake(my_io);
760    /// # server_fut
761    /// # }
762    /// #
763    /// # pub fn main() {}
764    /// ```
765    ///
766    /// # Panics
767    ///
768    /// This function panics if `max` is not within the legal range specified
769    /// above.
770    pub fn max_frame_size(&mut self, max: u32) -> &mut Self {
771        self.settings.set_max_frame_size(Some(max));
772        self
773    }
774
775    /// Sets the max size of received header frames.
776    ///
777    /// This advisory setting informs a peer of the maximum size of header list
778    /// that the sender is prepared to accept, in octets. The value is based on
779    /// the uncompressed size of header fields, including the length of the name
780    /// and value in octets plus an overhead of 32 octets for each header field.
781    ///
782    /// This setting is also used to limit the maximum amount of data that is
783    /// buffered to decode HEADERS frames.
784    ///
785    /// # Examples
786    ///
787    /// ```
788    /// # use tokio::io::{AsyncRead, AsyncWrite};
789    /// # use h2::server::*;
790    /// #
791    /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
792    /// # -> Handshake<T>
793    /// # {
794    /// // `server_fut` is a future representing the completion of the HTTP/2
795    /// // handshake.
796    /// let server_fut = Builder::new()
797    ///     .max_header_list_size(16 * 1024)
798    ///     .handshake(my_io);
799    /// # server_fut
800    /// # }
801    /// #
802    /// # pub fn main() {}
803    /// ```
804    pub fn max_header_list_size(&mut self, max: u32) -> &mut Self {
805        self.settings.set_max_header_list_size(Some(max));
806        self
807    }
808
809    /// Sets the header table size.
810    ///
811    /// This setting informs the peer of the maximum size of the header compression
812    /// table used to encode header blocks, in octets. The encoder may select any value
813    /// equal to or less than the header table size specified by the sender.
814    ///
815    /// The default value is 4,096.
816    pub fn header_table_size(&mut self, size: u32) -> &mut Self {
817        self.settings.set_header_table_size(Some(size));
818        self
819    }
820
821    /// Sets the maximum number of concurrent streams.
822    ///
823    /// The maximum concurrent streams setting only controls the maximum number
824    /// of streams that can be initiated by the remote peer. In other words,
825    /// when this setting is set to 100, this does not limit the number of
826    /// concurrent streams that can be created by the caller.
827    ///
828    /// It is recommended that this value be no smaller than 100, so as to not
829    /// unnecessarily limit parallelism. However, any value is legal, including
830    /// 0. If `max` is set to 0, then the remote will not be permitted to
831    /// initiate streams.
832    ///
833    /// Note that streams in the reserved state, i.e., push promises that have
834    /// been reserved but the stream has not started, do not count against this
835    /// setting.
836    ///
837    /// Also note that if the remote *does* exceed the value set here, it is not
838    /// a protocol level error. Instead, the `h2` library will immediately reset
839    /// the stream.
840    ///
841    /// See [Section 5.1.2] in the HTTP/2 spec for more details.
842    ///
843    /// [Section 5.1.2]: https://http2.github.io/http2-spec/#rfc.section.5.1.2
844    ///
845    /// # Examples
846    ///
847    /// ```
848    /// # use tokio::io::{AsyncRead, AsyncWrite};
849    /// # use h2::server::*;
850    /// #
851    /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
852    /// # -> Handshake<T>
853    /// # {
854    /// // `server_fut` is a future representing the completion of the HTTP/2
855    /// // handshake.
856    /// let server_fut = Builder::new()
857    ///     .max_concurrent_streams(1000)
858    ///     .handshake(my_io);
859    /// # server_fut
860    /// # }
861    /// #
862    /// # pub fn main() {}
863    /// ```
864    pub fn max_concurrent_streams(&mut self, max: u32) -> &mut Self {
865        self.settings.set_max_concurrent_streams(Some(max));
866        self
867    }
868
869    /// Sets the maximum number of concurrent locally reset streams.
870    ///
871    /// When a stream is explicitly reset by either calling
872    /// [`SendResponse::send_reset`] or by dropping a [`SendResponse`] instance
873    /// before completing the stream, the HTTP/2 specification requires that
874    /// any further frames received for that stream must be ignored for "some
875    /// time".
876    ///
877    /// In order to satisfy the specification, internal state must be maintained
878    /// to implement the behavior. This state grows linearly with the number of
879    /// streams that are locally reset.
880    ///
881    /// The `max_concurrent_reset_streams` setting configures sets an upper
882    /// bound on the amount of state that is maintained. When this max value is
883    /// reached, the oldest reset stream is purged from memory.
884    ///
885    /// Once the stream has been fully purged from memory, any additional frames
886    /// received for that stream will result in a connection level protocol
887    /// error, forcing the connection to terminate.
888    ///
889    /// The default value is currently 50.
890    ///
891    /// # Examples
892    ///
893    /// ```
894    /// # use tokio::io::{AsyncRead, AsyncWrite};
895    /// # use h2::server::*;
896    /// #
897    /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
898    /// # -> Handshake<T>
899    /// # {
900    /// // `server_fut` is a future representing the completion of the HTTP/2
901    /// // handshake.
902    /// let server_fut = Builder::new()
903    ///     .max_concurrent_reset_streams(1000)
904    ///     .handshake(my_io);
905    /// # server_fut
906    /// # }
907    /// #
908    /// # pub fn main() {}
909    /// ```
910    pub fn max_concurrent_reset_streams(&mut self, max: usize) -> &mut Self {
911        self.reset_stream_max = max;
912        self
913    }
914
915    /// Sets the maximum number of local resets due to protocol errors made by the remote end.
916    ///
917    /// Invalid frames and many other protocol errors will lead to resets being generated for those streams.
918    /// Too many of these often indicate a malicious client, and there are attacks which can abuse this to DOS servers.
919    /// This limit protects against these DOS attacks by limiting the amount of resets we can be forced to generate.
920    ///
921    /// When the number of local resets exceeds this threshold, the server will issue GOAWAYs with an error code of
922    /// `ENHANCE_YOUR_CALM` to the client.
923    ///
924    /// If you really want to disable this, supply [`Option::None`] here.
925    /// Disabling this is not recommended and may expose you to DOS attacks.
926    ///
927    /// The default value is currently 1024, but could change.
928    pub fn max_local_error_reset_streams(&mut self, max: Option<usize>) -> &mut Self {
929        self.local_max_error_reset_streams = max;
930        self
931    }
932
933    /// Sets the maximum number of pending-accept remotely-reset streams.
934    ///
935    /// Streams that have been received by the peer, but not accepted by the
936    /// user, can also receive a RST_STREAM. This is a legitimate pattern: one
937    /// could send a request and then shortly after, realize it is not needed,
938    /// sending a CANCEL.
939    ///
940    /// However, since those streams are now "closed", they don't count towards
941    /// the max concurrent streams. So, they will sit in the accept queue,
942    /// using memory.
943    ///
944    /// When the number of remotely-reset streams sitting in the pending-accept
945    /// queue reaches this maximum value, a connection error with the code of
946    /// `ENHANCE_YOUR_CALM` will be sent to the peer, and returned by the
947    /// `Future`.
948    ///
949    /// The default value is currently 20, but could change.
950    ///
951    /// # Examples
952    ///
953    ///
954    /// ```
955    /// # use tokio::io::{AsyncRead, AsyncWrite};
956    /// # use h2::server::*;
957    /// #
958    /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
959    /// # -> Handshake<T>
960    /// # {
961    /// // `server_fut` is a future representing the completion of the HTTP/2
962    /// // handshake.
963    /// let server_fut = Builder::new()
964    ///     .max_pending_accept_reset_streams(100)
965    ///     .handshake(my_io);
966    /// # server_fut
967    /// # }
968    /// #
969    /// # pub fn main() {}
970    /// ```
971    pub fn max_pending_accept_reset_streams(&mut self, max: usize) -> &mut Self {
972        self.pending_accept_reset_stream_max = max;
973        self
974    }
975
976    /// Sets the maximum send buffer size per stream.
977    ///
978    /// Once a stream has buffered up to (or over) the maximum, the stream's
979    /// flow control will not "poll" additional capacity. Once bytes for the
980    /// stream have been written to the connection, the send buffer capacity
981    /// will be freed up again.
982    ///
983    /// The default is currently ~400KB, but may change.
984    ///
985    /// # Panics
986    ///
987    /// This function panics if `max` is larger than `u32::MAX`.
988    pub fn max_send_buffer_size(&mut self, max: usize) -> &mut Self {
989        assert!(max <= u32::MAX as usize);
990        self.max_send_buffer_size = max;
991        self
992    }
993
994    /// Sets the maximum number of concurrent locally reset streams.
995    ///
996    /// When a stream is explicitly reset by either calling
997    /// [`SendResponse::send_reset`] or by dropping a [`SendResponse`] instance
998    /// before completing the stream, the HTTP/2 specification requires that
999    /// any further frames received for that stream must be ignored for "some
1000    /// time".
1001    ///
1002    /// In order to satisfy the specification, internal state must be maintained
1003    /// to implement the behavior. This state grows linearly with the number of
1004    /// streams that are locally reset.
1005    ///
1006    /// The `reset_stream_duration` setting configures the max amount of time
1007    /// this state will be maintained in memory. Once the duration elapses, the
1008    /// stream state is purged from memory.
1009    ///
1010    /// Once the stream has been fully purged from memory, any additional frames
1011    /// received for that stream will result in a connection level protocol
1012    /// error, forcing the connection to terminate.
1013    ///
1014    /// The default value is currently 1 second.
1015    ///
1016    /// # Examples
1017    ///
1018    /// ```
1019    /// # use tokio::io::{AsyncRead, AsyncWrite};
1020    /// # use h2::server::*;
1021    /// # use std::time::Duration;
1022    /// #
1023    /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
1024    /// # -> Handshake<T>
1025    /// # {
1026    /// // `server_fut` is a future representing the completion of the HTTP/2
1027    /// // handshake.
1028    /// let server_fut = Builder::new()
1029    ///     .reset_stream_duration(Duration::from_secs(10))
1030    ///     .handshake(my_io);
1031    /// # server_fut
1032    /// # }
1033    /// #
1034    /// # pub fn main() {}
1035    /// ```
1036    pub fn reset_stream_duration(&mut self, dur: Duration) -> &mut Self {
1037        self.reset_stream_duration = dur;
1038        self
1039    }
1040
1041    /// Enables the [extended CONNECT protocol].
1042    ///
1043    /// [extended CONNECT protocol]: https://datatracker.ietf.org/doc/html/rfc8441#section-4
1044    pub fn enable_connect_protocol(&mut self) -> &mut Self {
1045        self.settings.set_enable_connect_protocol(Some(1));
1046        self
1047    }
1048
1049    /// Sets a connection-level budget for limiting memory overhead from
1050    /// received small DATA frames.
1051    ///
1052    /// HTTP/2 flow control accounts for DATA payload bytes, but not the
1053    /// additional memory required to buffer each DATA frame. An excessive
1054    /// number of small frames may therefore consume disproportionate memory.
1055    ///
1056    /// Small DATA frames consume this budget. The budget is restored when
1057    /// buffered frames are consumed by the application, while sufficiently
1058    /// large frames may also restore budget. Empty DATA frames are limited
1059    /// separately and do not consume this budget.
1060    ///
1061    /// When this budget is exhausted, the connection is closed with
1062    /// `ENHANCE_YOUR_CALM`.
1063    ///
1064    /// By default, the budget is half the target connection window, with a
1065    /// minimum of 25,600 bytes. Changing the target window at runtime also
1066    /// updates the permitted framing overhead.
1067    pub fn data_frame_budget(&mut self, budget: usize) -> &mut Self {
1068        self.data_frame_budget = proto::DataFrameBudget::Configured(budget);
1069        self
1070    }
1071
1072    /// Creates a new configured HTTP/2 server backed by `io`.
1073    ///
1074    /// It is expected that `io` already be in an appropriate state to commence
1075    /// the [HTTP/2 handshake]. See [Handshake] for more details.
1076    ///
1077    /// Returns a future which resolves to the [`Connection`] instance once the
1078    /// HTTP/2 handshake has been completed.
1079    ///
1080    /// This function also allows the caller to configure the send payload data
1081    /// type. See [Outbound data type] for more details.
1082    ///
1083    /// [HTTP/2 handshake]: http://httpwg.org/specs/rfc7540.html#ConnectionHeader
1084    /// [Handshake]: ../index.html#handshake
1085    /// [`Connection`]: struct.Connection.html
1086    /// [Outbound data type]: ../index.html#outbound-data-type.
1087    ///
1088    /// # Examples
1089    ///
1090    /// Basic usage:
1091    ///
1092    /// ```
1093    /// # use tokio::io::{AsyncRead, AsyncWrite};
1094    /// # use h2::server::*;
1095    /// #
1096    /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
1097    /// # -> Handshake<T>
1098    /// # {
1099    /// // `server_fut` is a future representing the completion of the HTTP/2
1100    /// // handshake.
1101    /// let server_fut = Builder::new()
1102    ///     .handshake(my_io);
1103    /// # server_fut
1104    /// # }
1105    /// #
1106    /// # pub fn main() {}
1107    /// ```
1108    ///
1109    /// Configures the send-payload data type. In this case, the outbound data
1110    /// type will be `&'static [u8]`.
1111    ///
1112    /// ```
1113    /// # use tokio::io::{AsyncRead, AsyncWrite};
1114    /// # use h2::server::*;
1115    /// #
1116    /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
1117    /// # -> Handshake<T, &'static [u8]>
1118    /// # {
1119    /// // `server_fut` is a future representing the completion of the HTTP/2
1120    /// // handshake.
1121    /// let server_fut: Handshake<_, &'static [u8]> = Builder::new()
1122    ///     .handshake(my_io);
1123    /// # server_fut
1124    /// # }
1125    /// #
1126    /// # pub fn main() {}
1127    /// ```
1128    pub fn handshake<T, B>(&self, io: T) -> Handshake<T, B>
1129    where
1130        T: AsyncRead + AsyncWrite + Unpin,
1131        B: Buf,
1132    {
1133        Connection::handshake2(io, self.clone())
1134    }
1135}
1136
1137impl Default for Builder {
1138    fn default() -> Builder {
1139        Builder::new()
1140    }
1141}
1142
1143// ===== impl SendResponse =====
1144
1145impl<B: Buf> SendResponse<B> {
1146    /// Send an interim informational response (1xx status codes)
1147    ///
1148    /// This method can be called multiple times before calling `send_response()`
1149    /// to send the final response. Only 1xx status codes are allowed.
1150    ///
1151    /// Interim informational responses are used to provide early feedback to the client
1152    /// before the final response is ready. Common examples include:
1153    /// - 100 Continue: Indicates the client should continue with the request
1154    /// - 103 Early Hints: Provides early hints about resources to preload
1155    ///
1156    /// # Arguments
1157    /// * `response` - HTTP response with 1xx status code and headers
1158    ///
1159    /// # Returns
1160    /// * `Ok(())` - Interim Informational response sent successfully
1161    /// * `Err(Error)` - Failed to send (invalid status code, connection error, etc.)
1162    ///
1163    /// # Examples
1164    /// ```rust
1165    /// use h2::server;
1166    /// use http::{Response, StatusCode};
1167    ///
1168    /// # async fn example(mut send_response: h2::server::SendResponse<bytes::Bytes>) -> Result<(), h2::Error> {
1169    /// // Send 100 Continue before processing request body
1170    /// let continue_response = Response::builder()
1171    ///     .status(StatusCode::CONTINUE)
1172    ///     .body(())
1173    ///     .unwrap();
1174    /// send_response.send_informational(continue_response)?;
1175    ///
1176    /// // Later send the final response
1177    /// let final_response = Response::builder()
1178    ///     .status(StatusCode::OK)
1179    ///     .body(())
1180    ///     .unwrap();
1181    /// let _stream = send_response.send_response(final_response, false)?;
1182    /// # Ok(())
1183    /// # }
1184    /// ```
1185    ///
1186    /// # Errors
1187    /// This method will return an error if:
1188    /// - The response status code is not in the 1xx range
1189    /// - The final response has already been sent
1190    /// - There is a connection-level error
1191    pub fn send_informational(&mut self, response: Response<()>) -> Result<(), crate::Error> {
1192        let stream_id = self.inner.stream_id();
1193        let status = response.status();
1194
1195        tracing::trace!(
1196            "send_informational called with status: {} on stream: {:?}",
1197            status,
1198            stream_id
1199        );
1200
1201        // Validate that this is an informational response (1xx status code)
1202        if !response.status().is_informational() {
1203            tracing::trace!(
1204                "invalid informational status code: {} on stream: {:?}",
1205                status,
1206                stream_id
1207            );
1208            return Err(crate::Error::from(
1209                UserError::InvalidInformationalStatusCode,
1210            ));
1211        }
1212
1213        tracing::trace!(
1214            "converting informational response to HEADERS frame without END_STREAM flag for stream: {:?}",
1215            stream_id
1216        );
1217
1218        let frame = Peer::convert_send_message(
1219            stream_id, response, false, // NOT end_of_stream for informational responses
1220        );
1221
1222        tracing::trace!(
1223            "sending interim informational headers frame for stream: {:?}",
1224            stream_id
1225        );
1226
1227        // Use the proper H2 streams API for sending interim informational headers
1228        // This bypasses the normal response flow and allows multiple informational responses
1229        let result = self
1230            .inner
1231            .send_informational_headers(frame)
1232            .map_err(Into::into);
1233
1234        match &result {
1235            Ok(()) => tracing::trace!(
1236                "Successfully sent informational headers for stream: {:?}",
1237                stream_id
1238            ),
1239            Err(e) => tracing::trace!(
1240                "Failed to send informational headers for stream: {:?}: {:?}",
1241                stream_id,
1242                e
1243            ),
1244        }
1245
1246        result
1247    }
1248
1249    /// Send a response to a client request.
1250    ///
1251    /// On success, a [`SendStream`] instance is returned. This instance can be
1252    /// used to stream the response body and send trailers.
1253    ///
1254    /// If a body or trailers will be sent on the returned [`SendStream`]
1255    /// instance, then `end_of_stream` must be set to `false` when calling this
1256    /// function.
1257    ///
1258    /// The [`SendResponse`] instance is already associated with a received
1259    /// request.  This function may only be called once per instance and only if
1260    /// [`send_reset`] has not been previously called.
1261    ///
1262    /// [`SendResponse`]: #
1263    /// [`SendStream`]: ../struct.SendStream.html
1264    /// [`send_reset`]: #method.send_reset
1265    pub fn send_response(
1266        &mut self,
1267        response: Response<()>,
1268        end_of_stream: bool,
1269    ) -> Result<SendStream<B>, crate::Error> {
1270        self.inner
1271            .send_response(response, end_of_stream)
1272            .map(|_| SendStream::new(self.inner.clone()))
1273            .map_err(Into::into)
1274    }
1275
1276    /// Push a request and response to the client
1277    ///
1278    /// On success, a [`SendResponse`] instance is returned.
1279    ///
1280    /// [`SendResponse`]: #
1281    pub fn push_request(
1282        &mut self,
1283        request: Request<()>,
1284    ) -> Result<SendPushedResponse<B>, crate::Error> {
1285        self.inner
1286            .send_push_promise(request)
1287            .map(|inner| SendPushedResponse {
1288                inner: SendResponse { inner },
1289            })
1290            .map_err(Into::into)
1291    }
1292
1293    /// Send a stream reset to the peer.
1294    ///
1295    /// This essentially cancels the stream, including any inbound or outbound
1296    /// data streams.
1297    ///
1298    /// If this function is called before [`send_response`], a call to
1299    /// [`send_response`] will result in an error.
1300    ///
1301    /// If this function is called while a [`SendStream`] instance is active,
1302    /// any further use of the instance will result in an error.
1303    ///
1304    /// This function should only be called once.
1305    ///
1306    /// [`send_response`]: #method.send_response
1307    /// [`SendStream`]: ../struct.SendStream.html
1308    pub fn send_reset(&mut self, reason: Reason) {
1309        self.inner.send_reset(reason)
1310    }
1311
1312    /// Polls to be notified when the client resets this stream.
1313    ///
1314    /// If stream is still open, this returns `Poll::Pending`, and
1315    /// registers the task to be notified if a `RST_STREAM` is received.
1316    ///
1317    /// If a `RST_STREAM` frame is received for this stream, calling this
1318    /// method will yield the `Reason` for the reset.
1319    ///
1320    /// # Error
1321    ///
1322    /// Calling this method after having called `send_response` will return
1323    /// a user error.
1324    pub fn poll_reset(&mut self, cx: &mut Context) -> Poll<Result<Reason, crate::Error>> {
1325        self.inner.poll_reset(cx, proto::PollReset::AwaitingHeaders)
1326    }
1327
1328    /// Returns the stream ID of the response stream.
1329    ///
1330    /// # Panics
1331    ///
1332    /// If the lock on the stream store has been poisoned.
1333    pub fn stream_id(&self) -> crate::StreamId {
1334        crate::StreamId::from_internal(self.inner.stream_id())
1335    }
1336}
1337
1338// ===== impl SendPushedResponse =====
1339
1340impl<B: Buf> SendPushedResponse<B> {
1341    /// Send a response to a promised request.
1342    ///
1343    /// On success, a [`SendStream`] instance is returned. This instance can be
1344    /// used to stream the response body and send trailers.
1345    ///
1346    /// If a body or trailers will be sent on the returned [`SendStream`]
1347    /// instance, then `end_of_stream` must be set to `false` when calling this
1348    /// function.
1349    ///
1350    /// The [`SendPushedResponse`] instance is associated with a promised
1351    /// request.  This function may only be called once per instance and only if
1352    /// [`send_reset`] has not been previously called.
1353    ///
1354    /// [`SendPushedResponse`]: #
1355    /// [`SendStream`]: ../struct.SendStream.html
1356    /// [`send_reset`]: #method.send_reset
1357    pub fn send_response(
1358        &mut self,
1359        response: Response<()>,
1360        end_of_stream: bool,
1361    ) -> Result<SendStream<B>, crate::Error> {
1362        self.inner.send_response(response, end_of_stream)
1363    }
1364
1365    /// Send a stream reset to the peer.
1366    ///
1367    /// This essentially cancels the stream, including any inbound or outbound
1368    /// data streams.
1369    ///
1370    /// If this function is called before [`send_response`], a call to
1371    /// [`send_response`] will result in an error.
1372    ///
1373    /// If this function is called while a [`SendStream`] instance is active,
1374    /// any further use of the instance will result in an error.
1375    ///
1376    /// This function should only be called once.
1377    ///
1378    /// [`send_response`]: #method.send_response
1379    /// [`SendStream`]: ../struct.SendStream.html
1380    pub fn send_reset(&mut self, reason: Reason) {
1381        self.inner.send_reset(reason)
1382    }
1383
1384    /// Polls to be notified when the client resets this stream.
1385    ///
1386    /// If stream is still open, this returns `Poll::Pending`, and
1387    /// registers the task to be notified if a `RST_STREAM` is received.
1388    ///
1389    /// If a `RST_STREAM` frame is received for this stream, calling this
1390    /// method will yield the `Reason` for the reset.
1391    ///
1392    /// # Error
1393    ///
1394    /// Calling this method after having called `send_response` will return
1395    /// a user error.
1396    pub fn poll_reset(&mut self, cx: &mut Context) -> Poll<Result<Reason, crate::Error>> {
1397        self.inner.poll_reset(cx)
1398    }
1399
1400    /// Returns the stream ID of the response stream.
1401    ///
1402    /// # Panics
1403    ///
1404    /// If the lock on the stream store has been poisoned.
1405    pub fn stream_id(&self) -> crate::StreamId {
1406        self.inner.stream_id()
1407    }
1408}
1409
1410// ===== impl Flush =====
1411
1412impl<T, B: Buf> Flush<T, B> {
1413    fn new(codec: Codec<T, B>) -> Self {
1414        Flush { codec: Some(codec) }
1415    }
1416}
1417
1418impl<T, B> Future for Flush<T, B>
1419where
1420    T: AsyncWrite + Unpin,
1421    B: Buf,
1422{
1423    type Output = Result<Codec<T, B>, crate::Error>;
1424
1425    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1426        // Flush the codec
1427        ready!(self.codec.as_mut().unwrap().flush(cx)).map_err(crate::Error::from_io)?;
1428
1429        // Return the codec
1430        Poll::Ready(Ok(self.codec.take().unwrap()))
1431    }
1432}
1433
1434impl<T, B: Buf> ReadPreface<T, B> {
1435    fn new(codec: Codec<T, B>) -> Self {
1436        ReadPreface {
1437            codec: Some(codec),
1438            pos: 0,
1439        }
1440    }
1441
1442    fn inner_mut(&mut self) -> &mut T {
1443        self.codec.as_mut().unwrap().get_mut()
1444    }
1445}
1446
1447impl<T, B> Future for ReadPreface<T, B>
1448where
1449    T: AsyncRead + Unpin,
1450    B: Buf,
1451{
1452    type Output = Result<Codec<T, B>, crate::Error>;
1453
1454    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1455        let mut buf = [0; 24];
1456        let mut rem = PREFACE.len() - self.pos;
1457
1458        while rem > 0 {
1459            let mut buf = ReadBuf::new(&mut buf[..rem]);
1460            ready!(Pin::new(self.inner_mut()).poll_read(cx, &mut buf))
1461                .map_err(crate::Error::from_io)?;
1462            let n = buf.filled().len();
1463            if n == 0 {
1464                return Poll::Ready(Err(crate::Error::from_io(io::Error::new(
1465                    io::ErrorKind::UnexpectedEof,
1466                    "connection closed before reading preface",
1467                ))));
1468            }
1469
1470            if &PREFACE[self.pos..self.pos + n] != buf.filled() {
1471                proto_err!(conn: "read_preface: invalid preface");
1472                // TODO: Should this just write the GO_AWAY frame directly?
1473                return Poll::Ready(Err(Error::library_go_away(Reason::PROTOCOL_ERROR).into()));
1474            }
1475
1476            self.pos += n;
1477            rem -= n; // TODO test
1478        }
1479
1480        Poll::Ready(Ok(self.codec.take().unwrap()))
1481    }
1482}
1483
1484// ===== impl Handshake =====
1485
1486impl<T, B: Buf> Future for Handshake<T, B>
1487where
1488    T: AsyncRead + AsyncWrite + Unpin,
1489    B: Buf,
1490{
1491    type Output = Result<Connection<T, B>, crate::Error>;
1492
1493    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1494        let span = self.span.clone(); // XXX(eliza): T_T
1495        let _e = span.enter();
1496        tracing::trace!(state = ?self.state);
1497
1498        loop {
1499            match &mut self.state {
1500                Handshaking::Flushing(flush) => {
1501                    // We're currently flushing a pending SETTINGS frame. Poll the
1502                    // flush future, and, if it's completed, advance our state to wait
1503                    // for the client preface.
1504                    let codec = match Pin::new(flush).poll(cx)? {
1505                        Poll::Pending => {
1506                            tracing::trace!(flush.poll = %"Pending");
1507                            return Poll::Pending;
1508                        }
1509                        Poll::Ready(flushed) => {
1510                            tracing::trace!(flush.poll = %"Ready");
1511                            flushed
1512                        }
1513                    };
1514                    self.state = Handshaking::ReadingPreface(
1515                        ReadPreface::new(codec).instrument(tracing::trace_span!("read_preface")),
1516                    );
1517                }
1518                Handshaking::ReadingPreface(read) => {
1519                    let codec = ready!(Pin::new(read).poll(cx)?);
1520
1521                    self.state = Handshaking::Done;
1522
1523                    let connection = proto::Connection::new(
1524                        codec,
1525                        Config {
1526                            next_stream_id: 2.into(),
1527                            // Server does not need to locally initiate any streams
1528                            initial_max_send_streams: 0,
1529                            max_send_buffer_size: self.builder.max_send_buffer_size,
1530                            reset_stream_duration: self.builder.reset_stream_duration,
1531                            reset_stream_max: self.builder.reset_stream_max,
1532                            remote_reset_stream_max: self.builder.pending_accept_reset_stream_max,
1533                            local_error_reset_streams_max: self
1534                                .builder
1535                                .local_max_error_reset_streams,
1536                            settings: self.builder.settings.clone(),
1537                            data_frame_budget: self.builder.data_frame_budget,
1538                        },
1539                    );
1540
1541                    tracing::trace!("connection established!");
1542                    let mut c = Connection { connection };
1543                    if let Some(sz) = self.builder.initial_target_connection_window_size {
1544                        c.set_target_window_size(sz);
1545                    }
1546
1547                    return Poll::Ready(Ok(c));
1548                }
1549                Handshaking::Done => {
1550                    panic!("Handshaking::poll() called again after handshaking was complete")
1551                }
1552            }
1553        }
1554    }
1555}
1556
1557impl<T, B> fmt::Debug for Handshake<T, B>
1558where
1559    T: AsyncRead + AsyncWrite + fmt::Debug,
1560    B: fmt::Debug + Buf,
1561{
1562    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1563        write!(fmt, "server::Handshake")
1564    }
1565}
1566
1567impl Peer {
1568    pub fn convert_send_message(
1569        id: StreamId,
1570        response: Response<()>,
1571        end_of_stream: bool,
1572    ) -> frame::Headers {
1573        use http::response::Parts;
1574
1575        // Extract the components of the HTTP request
1576        let (
1577            Parts {
1578                status, headers, ..
1579            },
1580            _,
1581        ) = response.into_parts();
1582
1583        // Build the set pseudo header set. All requests will include `method`
1584        // and `path`.
1585        let pseudo = Pseudo::response(status);
1586
1587        // Create the HEADERS frame
1588        let mut frame = frame::Headers::new(id, pseudo, headers);
1589
1590        if end_of_stream {
1591            frame.set_end_stream()
1592        }
1593
1594        frame
1595    }
1596
1597    pub fn convert_push_message(
1598        stream_id: StreamId,
1599        promised_id: StreamId,
1600        request: Request<()>,
1601    ) -> Result<frame::PushPromise, UserError> {
1602        use http::request::Parts;
1603
1604        if let Err(e) = frame::PushPromise::validate_request(&request) {
1605            use PushPromiseHeaderError::*;
1606            match e {
1607                NotSafeAndCacheable => tracing::debug!(
1608                    ?promised_id,
1609                    "convert_push_message: method {} is not safe and cacheable",
1610                    request.method(),
1611                ),
1612                InvalidContentLength(e) => tracing::debug!(
1613                    ?promised_id,
1614                    "convert_push_message; promised request has invalid content-length {:?}",
1615                    e,
1616                ),
1617            }
1618            return Err(UserError::MalformedHeaders);
1619        }
1620
1621        // Extract the components of the HTTP request
1622        let (
1623            Parts {
1624                method,
1625                uri,
1626                headers,
1627                ..
1628            },
1629            _,
1630        ) = request.into_parts();
1631
1632        let pseudo = Pseudo::request(method, uri, None);
1633
1634        Ok(frame::PushPromise::new(
1635            stream_id,
1636            promised_id,
1637            pseudo,
1638            headers,
1639        ))
1640    }
1641}
1642
1643impl proto::Peer for Peer {
1644    type Poll = Request<()>;
1645
1646    const NAME: &'static str = "Server";
1647
1648    /*
1649    fn is_server() -> bool {
1650        true
1651    }
1652    */
1653
1654    fn r#dyn() -> proto::DynPeer {
1655        proto::DynPeer::Server
1656    }
1657
1658    fn convert_poll_message(
1659        pseudo: Pseudo,
1660        fields: HeaderMap,
1661        stream_id: StreamId,
1662    ) -> Result<Self::Poll, Error> {
1663        use http::{uri, Version};
1664
1665        let mut b = Request::builder();
1666
1667        macro_rules! malformed {
1668            ($($arg:tt)*) => {{
1669                tracing::debug!($($arg)*);
1670                return Err(Error::library_reset(stream_id, Reason::PROTOCOL_ERROR));
1671            }}
1672        }
1673
1674        b = b.version(Version::HTTP_2);
1675
1676        let is_connect;
1677        if let Some(method) = pseudo.method {
1678            is_connect = method == Method::CONNECT;
1679            b = b.method(method);
1680        } else {
1681            malformed!("malformed headers: missing method");
1682        }
1683
1684        let has_protocol = pseudo.protocol.is_some();
1685        if has_protocol {
1686            if is_connect {
1687                // Assert that we have the right type.
1688                b = b.extension::<crate::ext::Protocol>(pseudo.protocol.unwrap());
1689            } else {
1690                malformed!("malformed headers: :protocol on non-CONNECT request");
1691            }
1692        }
1693
1694        if pseudo.status.is_some() {
1695            malformed!("malformed headers: :status field on request");
1696        }
1697
1698        // Convert the URI
1699        let mut parts = uri::Parts::default();
1700
1701        // A request translated from HTTP/1 must not include the :authority
1702        // header
1703        if let Some(authority) = pseudo.authority {
1704            let maybe_authority = uri::Authority::from_maybe_shared(authority.clone().into_inner());
1705            parts.authority = Some(maybe_authority.or_else(|why| {
1706                malformed!(
1707                    "malformed headers: malformed authority ({:?}): {}",
1708                    authority,
1709                    why,
1710                )
1711            })?);
1712        }
1713
1714        // A :scheme is required, except CONNECT.
1715        if let Some(scheme) = pseudo.scheme {
1716            if is_connect && !has_protocol {
1717                malformed!("malformed headers: :scheme in CONNECT");
1718            }
1719            let maybe_scheme = scheme.parse();
1720            let scheme = maybe_scheme.or_else(|why| {
1721                malformed!(
1722                    "malformed headers: malformed scheme ({:?}): {}",
1723                    scheme,
1724                    why,
1725                )
1726            })?;
1727
1728            // It's not possible to build an `Uri` from a scheme and path. So,
1729            // after validating is was a valid scheme, we just have to drop it
1730            // if there isn't an :authority.
1731            if parts.authority.is_some() {
1732                parts.scheme = Some(scheme);
1733            }
1734        } else if !is_connect || has_protocol {
1735            malformed!("malformed headers: missing scheme");
1736        }
1737
1738        if let Some(path) = pseudo.path {
1739            if is_connect && !has_protocol {
1740                malformed!("malformed headers: :path in CONNECT");
1741            }
1742
1743            // This cannot be empty
1744            if path.is_empty() {
1745                malformed!("malformed headers: missing path");
1746            }
1747
1748            let maybe_path = uri::PathAndQuery::from_maybe_shared(path.clone().into_inner());
1749            parts.path_and_query = Some(maybe_path.or_else(|why| {
1750                malformed!("malformed headers: malformed path ({:?}): {}", path, why,)
1751            })?);
1752        } else if is_connect && has_protocol {
1753            malformed!("malformed headers: missing path in extended CONNECT");
1754        }
1755
1756        b = b.uri(parts);
1757
1758        let mut request = match b.body(()) {
1759            Ok(request) => request,
1760            Err(e) => {
1761                // TODO: Should there be more specialized handling for different
1762                // kinds of errors
1763                proto_err!(stream: "error building request: {}; stream={:?}", e, stream_id);
1764                return Err(Error::library_reset(stream_id, Reason::PROTOCOL_ERROR));
1765            }
1766        };
1767
1768        *request.headers_mut() = fields;
1769
1770        Ok(request)
1771    }
1772}
1773
1774// ===== impl Handshaking =====
1775
1776impl<T, B> fmt::Debug for Handshaking<T, B>
1777where
1778    B: Buf,
1779{
1780    #[inline]
1781    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1782        match *self {
1783            Handshaking::Flushing(_) => f.write_str("Flushing(_)"),
1784            Handshaking::ReadingPreface(_) => f.write_str("ReadingPreface(_)"),
1785            Handshaking::Done => f.write_str("Done"),
1786        }
1787    }
1788}