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.
463 ///
464 /// See [`FlowControl`] documentation for more details.
465 ///
466 /// [`FlowControl`]: ../struct.FlowControl.html
467 /// [library level]: ../index.html#flow-control
468 pub fn set_target_window_size(&mut self, size: u32) {
469 assert!(size <= proto::MAX_WINDOW_SIZE);
470 self.connection.set_target_window_size(size);
471 }
472
473 /// Set a new `INITIAL_WINDOW_SIZE` setting (in octets) for stream-level
474 /// flow control for received data.
475 ///
476 /// The `SETTINGS` will be sent to the remote, and only applied once the
477 /// remote acknowledges the change.
478 ///
479 /// This can be used to increase or decrease the window size for existing
480 /// streams.
481 ///
482 /// # Errors
483 ///
484 /// Returns an error if a previous call is still pending acknowledgement
485 /// from the remote endpoint.
486 pub fn set_initial_window_size(&mut self, size: u32) -> Result<(), crate::Error> {
487 assert!(size <= proto::MAX_WINDOW_SIZE);
488 self.connection.set_initial_window_size(size)?;
489 Ok(())
490 }
491
492 /// Enables the [extended CONNECT protocol].
493 ///
494 /// [extended CONNECT protocol]: https://datatracker.ietf.org/doc/html/rfc8441#section-4
495 ///
496 /// # Errors
497 ///
498 /// Returns an error if a previous call is still pending acknowledgement
499 /// from the remote endpoint.
500 pub fn enable_connect_protocol(&mut self) -> Result<(), crate::Error> {
501 self.connection.set_enable_connect_protocol()?;
502 Ok(())
503 }
504
505 /// Returns `Ready` when the underlying connection has closed.
506 ///
507 /// If any new inbound streams are received during a call to `poll_closed`,
508 /// they will be queued and returned on the next call to [`poll_accept`].
509 ///
510 /// This function will advance the internal connection state, driving
511 /// progress on all the other handles (e.g. [`RecvStream`] and [`SendStream`]).
512 ///
513 /// See [here](index.html#managing-the-connection) for more details.
514 ///
515 /// [`poll_accept`]: struct.Connection.html#method.poll_accept
516 /// [`RecvStream`]: ../struct.RecvStream.html
517 /// [`SendStream`]: ../struct.SendStream.html
518 pub fn poll_closed(&mut self, cx: &mut Context) -> Poll<Result<(), crate::Error>> {
519 self.connection.poll(cx).map_err(Into::into)
520 }
521
522 /// Sets the connection to a GOAWAY state.
523 ///
524 /// Does not terminate the connection. Must continue being polled to close
525 /// connection.
526 ///
527 /// After flushing the GOAWAY frame, the connection is closed. Any
528 /// outstanding streams do not prevent the connection from closing. This
529 /// should usually be reserved for shutting down when something bad
530 /// external to `h2` has happened, and open streams cannot be properly
531 /// handled.
532 ///
533 /// For graceful shutdowns, see [`graceful_shutdown`](Connection::graceful_shutdown).
534 pub fn abrupt_shutdown(&mut self, reason: Reason) {
535 self.connection.go_away_from_user(reason);
536 }
537
538 /// Starts a [graceful shutdown][1] process.
539 ///
540 /// Must continue being polled to close connection.
541 ///
542 /// It's possible to receive more requests after calling this method, since
543 /// they might have been in-flight from the client already. After about
544 /// 1 RTT, no new requests should be accepted. Once all active streams
545 /// have completed, the connection is closed.
546 ///
547 /// [1]: http://httpwg.org/specs/rfc7540.html#GOAWAY
548 pub fn graceful_shutdown(&mut self) {
549 self.connection.go_away_gracefully();
550 }
551
552 /// Takes a `PingPong` instance from the connection.
553 ///
554 /// # Note
555 ///
556 /// This may only be called once. Calling multiple times will return `None`.
557 pub fn ping_pong(&mut self) -> Option<PingPong> {
558 self.connection.take_user_pings().map(PingPong::new)
559 }
560
561 /// Checks if there are any streams
562 pub fn has_streams(&self) -> bool {
563 self.connection.has_streams()
564 }
565
566 /// Returns the maximum number of concurrent streams that may be initiated
567 /// by the server on this connection.
568 ///
569 /// This limit is configured by the client peer by sending the
570 /// [`SETTINGS_MAX_CONCURRENT_STREAMS` parameter][1] in a `SETTINGS` frame.
571 /// This method returns the currently acknowledged value received from the
572 /// remote.
573 ///
574 /// [1]: https://tools.ietf.org/html/rfc7540#section-5.1.2
575 pub fn max_concurrent_send_streams(&self) -> usize {
576 self.connection.max_send_streams()
577 }
578
579 /// Returns the maximum number of concurrent streams that may be initiated
580 /// by the client on this connection.
581 ///
582 /// This returns the value of the [`SETTINGS_MAX_CONCURRENT_STREAMS`
583 /// parameter][1] sent in a `SETTINGS` frame that has been
584 /// acknowledged by the remote peer. The value to be sent is configured by
585 /// the [`Builder::max_concurrent_streams`][2] method before handshaking
586 /// with the remote peer.
587 ///
588 /// [1]: https://tools.ietf.org/html/rfc7540#section-5.1.2
589 /// [2]: ../struct.Builder.html#method.max_concurrent_streams
590 pub fn max_concurrent_recv_streams(&self) -> usize {
591 self.connection.max_recv_streams()
592 }
593
594 // Could disappear at anytime.
595 #[doc(hidden)]
596 #[cfg(feature = "unstable")]
597 pub fn num_wired_streams(&self) -> usize {
598 self.connection.num_wired_streams()
599 }
600}
601
602#[cfg(feature = "stream")]
603impl<T, B> futures_core::Stream for Connection<T, B>
604where
605 T: AsyncRead + AsyncWrite + Unpin,
606 B: Buf,
607{
608 type Item = Result<(Request<RecvStream>, SendResponse<B>), crate::Error>;
609
610 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
611 self.poll_accept(cx)
612 }
613}
614
615impl<T, B> fmt::Debug for Connection<T, B>
616where
617 T: fmt::Debug,
618 B: fmt::Debug + Buf,
619{
620 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
621 fmt.debug_struct("Connection")
622 .field("connection", &self.connection)
623 .finish()
624 }
625}
626
627// ===== impl Builder =====
628
629impl Builder {
630 /// Returns a new server builder instance initialized with default
631 /// configuration values.
632 ///
633 /// Configuration methods can be chained on the return value.
634 ///
635 /// # Examples
636 ///
637 /// ```
638 /// # use tokio::io::{AsyncRead, AsyncWrite};
639 /// # use h2::server::*;
640 /// #
641 /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
642 /// # -> Handshake<T>
643 /// # {
644 /// // `server_fut` is a future representing the completion of the HTTP/2
645 /// // handshake.
646 /// let server_fut = Builder::new()
647 /// .initial_window_size(1_000_000)
648 /// .max_concurrent_streams(1000)
649 /// .handshake(my_io);
650 /// # server_fut
651 /// # }
652 /// #
653 /// # pub fn main() {}
654 /// ```
655 pub fn new() -> Builder {
656 Builder {
657 reset_stream_duration: Duration::from_secs(proto::DEFAULT_RESET_STREAM_SECS),
658 reset_stream_max: proto::DEFAULT_RESET_STREAM_MAX,
659 pending_accept_reset_stream_max: proto::DEFAULT_REMOTE_RESET_STREAM_MAX,
660 settings: Settings::default(),
661 initial_target_connection_window_size: None,
662 max_send_buffer_size: proto::DEFAULT_MAX_SEND_BUFFER_SIZE,
663 local_max_error_reset_streams: Some(proto::DEFAULT_LOCAL_RESET_COUNT_MAX),
664 data_frame_budget: proto::DataFrameBudget::Auto,
665 }
666 }
667
668 /// Indicates the initial window size (in octets) for stream-level
669 /// flow control for received data.
670 ///
671 /// The initial window of a stream is used as part of flow control. For more
672 /// details, see [`FlowControl`].
673 ///
674 /// The default value is 65,535.
675 ///
676 /// [`FlowControl`]: ../struct.FlowControl.html
677 ///
678 /// # Examples
679 ///
680 /// ```
681 /// # use tokio::io::{AsyncRead, AsyncWrite};
682 /// # use h2::server::*;
683 /// #
684 /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
685 /// # -> Handshake<T>
686 /// # {
687 /// // `server_fut` is a future representing the completion of the HTTP/2
688 /// // handshake.
689 /// let server_fut = Builder::new()
690 /// .initial_window_size(1_000_000)
691 /// .handshake(my_io);
692 /// # server_fut
693 /// # }
694 /// #
695 /// # pub fn main() {}
696 /// ```
697 pub fn initial_window_size(&mut self, size: u32) -> &mut Self {
698 self.settings.set_initial_window_size(Some(size));
699 self
700 }
701
702 /// Indicates the initial window size (in octets) for connection-level flow control
703 /// for received data.
704 ///
705 /// The initial window of a connection is used as part of flow control. For more details,
706 /// see [`FlowControl`].
707 ///
708 /// The default value is 65,535.
709 ///
710 /// [`FlowControl`]: ../struct.FlowControl.html
711 ///
712 /// # Examples
713 ///
714 /// ```
715 /// # use tokio::io::{AsyncRead, AsyncWrite};
716 /// # use h2::server::*;
717 /// #
718 /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
719 /// # -> Handshake<T>
720 /// # {
721 /// // `server_fut` is a future representing the completion of the HTTP/2
722 /// // handshake.
723 /// let server_fut = Builder::new()
724 /// .initial_connection_window_size(1_000_000)
725 /// .handshake(my_io);
726 /// # server_fut
727 /// # }
728 /// #
729 /// # pub fn main() {}
730 /// ```
731 pub fn initial_connection_window_size(&mut self, size: u32) -> &mut Self {
732 self.initial_target_connection_window_size = Some(size);
733 self
734 }
735
736 /// Indicates the size (in octets) of the largest HTTP/2 frame payload that the
737 /// configured server is able to accept.
738 ///
739 /// The sender may send data frames that are **smaller** than this value,
740 /// but any data larger than `max` will be broken up into multiple `DATA`
741 /// frames.
742 ///
743 /// The value **must** be between 16,384 and 16,777,215. The default value is 16,384.
744 ///
745 /// # Examples
746 ///
747 /// ```
748 /// # use tokio::io::{AsyncRead, AsyncWrite};
749 /// # use h2::server::*;
750 /// #
751 /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
752 /// # -> Handshake<T>
753 /// # {
754 /// // `server_fut` is a future representing the completion of the HTTP/2
755 /// // handshake.
756 /// let server_fut = Builder::new()
757 /// .max_frame_size(1_000_000)
758 /// .handshake(my_io);
759 /// # server_fut
760 /// # }
761 /// #
762 /// # pub fn main() {}
763 /// ```
764 ///
765 /// # Panics
766 ///
767 /// This function panics if `max` is not within the legal range specified
768 /// above.
769 pub fn max_frame_size(&mut self, max: u32) -> &mut Self {
770 self.settings.set_max_frame_size(Some(max));
771 self
772 }
773
774 /// Sets the max size of received header frames.
775 ///
776 /// This advisory setting informs a peer of the maximum size of header list
777 /// that the sender is prepared to accept, in octets. The value is based on
778 /// the uncompressed size of header fields, including the length of the name
779 /// and value in octets plus an overhead of 32 octets for each header field.
780 ///
781 /// This setting is also used to limit the maximum amount of data that is
782 /// buffered to decode HEADERS frames.
783 ///
784 /// # Examples
785 ///
786 /// ```
787 /// # use tokio::io::{AsyncRead, AsyncWrite};
788 /// # use h2::server::*;
789 /// #
790 /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
791 /// # -> Handshake<T>
792 /// # {
793 /// // `server_fut` is a future representing the completion of the HTTP/2
794 /// // handshake.
795 /// let server_fut = Builder::new()
796 /// .max_header_list_size(16 * 1024)
797 /// .handshake(my_io);
798 /// # server_fut
799 /// # }
800 /// #
801 /// # pub fn main() {}
802 /// ```
803 pub fn max_header_list_size(&mut self, max: u32) -> &mut Self {
804 self.settings.set_max_header_list_size(Some(max));
805 self
806 }
807
808 /// Sets the header table size.
809 ///
810 /// This setting informs the peer of the maximum size of the header compression
811 /// table used to encode header blocks, in octets. The encoder may select any value
812 /// equal to or less than the header table size specified by the sender.
813 ///
814 /// The default value is 4,096.
815 pub fn header_table_size(&mut self, size: u32) -> &mut Self {
816 self.settings.set_header_table_size(Some(size));
817 self
818 }
819
820 /// Sets the maximum number of concurrent streams.
821 ///
822 /// The maximum concurrent streams setting only controls the maximum number
823 /// of streams that can be initiated by the remote peer. In other words,
824 /// when this setting is set to 100, this does not limit the number of
825 /// concurrent streams that can be created by the caller.
826 ///
827 /// It is recommended that this value be no smaller than 100, so as to not
828 /// unnecessarily limit parallelism. However, any value is legal, including
829 /// 0. If `max` is set to 0, then the remote will not be permitted to
830 /// initiate streams.
831 ///
832 /// Note that streams in the reserved state, i.e., push promises that have
833 /// been reserved but the stream has not started, do not count against this
834 /// setting.
835 ///
836 /// Also note that if the remote *does* exceed the value set here, it is not
837 /// a protocol level error. Instead, the `h2` library will immediately reset
838 /// the stream.
839 ///
840 /// See [Section 5.1.2] in the HTTP/2 spec for more details.
841 ///
842 /// [Section 5.1.2]: https://http2.github.io/http2-spec/#rfc.section.5.1.2
843 ///
844 /// # Examples
845 ///
846 /// ```
847 /// # use tokio::io::{AsyncRead, AsyncWrite};
848 /// # use h2::server::*;
849 /// #
850 /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
851 /// # -> Handshake<T>
852 /// # {
853 /// // `server_fut` is a future representing the completion of the HTTP/2
854 /// // handshake.
855 /// let server_fut = Builder::new()
856 /// .max_concurrent_streams(1000)
857 /// .handshake(my_io);
858 /// # server_fut
859 /// # }
860 /// #
861 /// # pub fn main() {}
862 /// ```
863 pub fn max_concurrent_streams(&mut self, max: u32) -> &mut Self {
864 self.settings.set_max_concurrent_streams(Some(max));
865 self
866 }
867
868 /// Sets the maximum number of concurrent locally reset streams.
869 ///
870 /// When a stream is explicitly reset by either calling
871 /// [`SendResponse::send_reset`] or by dropping a [`SendResponse`] instance
872 /// before completing the stream, the HTTP/2 specification requires that
873 /// any further frames received for that stream must be ignored for "some
874 /// time".
875 ///
876 /// In order to satisfy the specification, internal state must be maintained
877 /// to implement the behavior. This state grows linearly with the number of
878 /// streams that are locally reset.
879 ///
880 /// The `max_concurrent_reset_streams` setting configures sets an upper
881 /// bound on the amount of state that is maintained. When this max value is
882 /// reached, the oldest reset stream is purged from memory.
883 ///
884 /// Once the stream has been fully purged from memory, any additional frames
885 /// received for that stream will result in a connection level protocol
886 /// error, forcing the connection to terminate.
887 ///
888 /// The default value is currently 50.
889 ///
890 /// # Examples
891 ///
892 /// ```
893 /// # use tokio::io::{AsyncRead, AsyncWrite};
894 /// # use h2::server::*;
895 /// #
896 /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
897 /// # -> Handshake<T>
898 /// # {
899 /// // `server_fut` is a future representing the completion of the HTTP/2
900 /// // handshake.
901 /// let server_fut = Builder::new()
902 /// .max_concurrent_reset_streams(1000)
903 /// .handshake(my_io);
904 /// # server_fut
905 /// # }
906 /// #
907 /// # pub fn main() {}
908 /// ```
909 pub fn max_concurrent_reset_streams(&mut self, max: usize) -> &mut Self {
910 self.reset_stream_max = max;
911 self
912 }
913
914 /// Sets the maximum number of local resets due to protocol errors made by the remote end.
915 ///
916 /// Invalid frames and many other protocol errors will lead to resets being generated for those streams.
917 /// Too many of these often indicate a malicious client, and there are attacks which can abuse this to DOS servers.
918 /// This limit protects against these DOS attacks by limiting the amount of resets we can be forced to generate.
919 ///
920 /// When the number of local resets exceeds this threshold, the server will issue GOAWAYs with an error code of
921 /// `ENHANCE_YOUR_CALM` to the client.
922 ///
923 /// If you really want to disable this, supply [`Option::None`] here.
924 /// Disabling this is not recommended and may expose you to DOS attacks.
925 ///
926 /// The default value is currently 1024, but could change.
927 pub fn max_local_error_reset_streams(&mut self, max: Option<usize>) -> &mut Self {
928 self.local_max_error_reset_streams = max;
929 self
930 }
931
932 /// Sets the maximum number of pending-accept remotely-reset streams.
933 ///
934 /// Streams that have been received by the peer, but not accepted by the
935 /// user, can also receive a RST_STREAM. This is a legitimate pattern: one
936 /// could send a request and then shortly after, realize it is not needed,
937 /// sending a CANCEL.
938 ///
939 /// However, since those streams are now "closed", they don't count towards
940 /// the max concurrent streams. So, they will sit in the accept queue,
941 /// using memory.
942 ///
943 /// When the number of remotely-reset streams sitting in the pending-accept
944 /// queue reaches this maximum value, a connection error with the code of
945 /// `ENHANCE_YOUR_CALM` will be sent to the peer, and returned by the
946 /// `Future`.
947 ///
948 /// The default value is currently 20, but could change.
949 ///
950 /// # Examples
951 ///
952 ///
953 /// ```
954 /// # use tokio::io::{AsyncRead, AsyncWrite};
955 /// # use h2::server::*;
956 /// #
957 /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
958 /// # -> Handshake<T>
959 /// # {
960 /// // `server_fut` is a future representing the completion of the HTTP/2
961 /// // handshake.
962 /// let server_fut = Builder::new()
963 /// .max_pending_accept_reset_streams(100)
964 /// .handshake(my_io);
965 /// # server_fut
966 /// # }
967 /// #
968 /// # pub fn main() {}
969 /// ```
970 pub fn max_pending_accept_reset_streams(&mut self, max: usize) -> &mut Self {
971 self.pending_accept_reset_stream_max = max;
972 self
973 }
974
975 /// Sets the maximum send buffer size per stream.
976 ///
977 /// Once a stream has buffered up to (or over) the maximum, the stream's
978 /// flow control will not "poll" additional capacity. Once bytes for the
979 /// stream have been written to the connection, the send buffer capacity
980 /// will be freed up again.
981 ///
982 /// The default is currently ~400KB, but may change.
983 ///
984 /// # Panics
985 ///
986 /// This function panics if `max` is larger than `u32::MAX`.
987 pub fn max_send_buffer_size(&mut self, max: usize) -> &mut Self {
988 assert!(max <= u32::MAX as usize);
989 self.max_send_buffer_size = max;
990 self
991 }
992
993 /// Sets the maximum number of concurrent locally reset streams.
994 ///
995 /// When a stream is explicitly reset by either calling
996 /// [`SendResponse::send_reset`] or by dropping a [`SendResponse`] instance
997 /// before completing the stream, the HTTP/2 specification requires that
998 /// any further frames received for that stream must be ignored for "some
999 /// time".
1000 ///
1001 /// In order to satisfy the specification, internal state must be maintained
1002 /// to implement the behavior. This state grows linearly with the number of
1003 /// streams that are locally reset.
1004 ///
1005 /// The `reset_stream_duration` setting configures the max amount of time
1006 /// this state will be maintained in memory. Once the duration elapses, the
1007 /// stream state is purged from memory.
1008 ///
1009 /// Once the stream has been fully purged from memory, any additional frames
1010 /// received for that stream will result in a connection level protocol
1011 /// error, forcing the connection to terminate.
1012 ///
1013 /// The default value is currently 1 second.
1014 ///
1015 /// # Examples
1016 ///
1017 /// ```
1018 /// # use tokio::io::{AsyncRead, AsyncWrite};
1019 /// # use h2::server::*;
1020 /// # use std::time::Duration;
1021 /// #
1022 /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
1023 /// # -> Handshake<T>
1024 /// # {
1025 /// // `server_fut` is a future representing the completion of the HTTP/2
1026 /// // handshake.
1027 /// let server_fut = Builder::new()
1028 /// .reset_stream_duration(Duration::from_secs(10))
1029 /// .handshake(my_io);
1030 /// # server_fut
1031 /// # }
1032 /// #
1033 /// # pub fn main() {}
1034 /// ```
1035 pub fn reset_stream_duration(&mut self, dur: Duration) -> &mut Self {
1036 self.reset_stream_duration = dur;
1037 self
1038 }
1039
1040 /// Enables the [extended CONNECT protocol].
1041 ///
1042 /// [extended CONNECT protocol]: https://datatracker.ietf.org/doc/html/rfc8441#section-4
1043 pub fn enable_connect_protocol(&mut self) -> &mut Self {
1044 self.settings.set_enable_connect_protocol(Some(1));
1045 self
1046 }
1047
1048 /// Sets a connection-level budget for limiting memory overhead from
1049 /// received small DATA frames.
1050 ///
1051 /// HTTP/2 flow control accounts for DATA payload bytes, but not the
1052 /// additional memory required to buffer each DATA frame. An excessive
1053 /// number of small frames may therefore consume disproportionate memory.
1054 ///
1055 /// Small DATA frames consume this budget. The budget is restored when
1056 /// buffered frames are consumed by the application, while sufficiently
1057 /// large frames may also restore budget. Empty DATA frames are limited
1058 /// separately and do not consume this budget.
1059 ///
1060 /// When this budget is exhausted, the connection is closed with
1061 /// `ENHANCE_YOUR_CALM`.
1062 ///
1063 /// By default, the budget is half the initial connection window, with a
1064 /// minimum of 25,600 bytes. Increasing the connection window therefore
1065 /// also increases the permitted framing overhead.
1066 pub fn data_frame_budget(&mut self, budget: usize) -> &mut Self {
1067 self.data_frame_budget = proto::DataFrameBudget::Configured(budget);
1068 self
1069 }
1070
1071 /// Creates a new configured HTTP/2 server backed by `io`.
1072 ///
1073 /// It is expected that `io` already be in an appropriate state to commence
1074 /// the [HTTP/2 handshake]. See [Handshake] for more details.
1075 ///
1076 /// Returns a future which resolves to the [`Connection`] instance once the
1077 /// HTTP/2 handshake has been completed.
1078 ///
1079 /// This function also allows the caller to configure the send payload data
1080 /// type. See [Outbound data type] for more details.
1081 ///
1082 /// [HTTP/2 handshake]: http://httpwg.org/specs/rfc7540.html#ConnectionHeader
1083 /// [Handshake]: ../index.html#handshake
1084 /// [`Connection`]: struct.Connection.html
1085 /// [Outbound data type]: ../index.html#outbound-data-type.
1086 ///
1087 /// # Examples
1088 ///
1089 /// Basic usage:
1090 ///
1091 /// ```
1092 /// # use tokio::io::{AsyncRead, AsyncWrite};
1093 /// # use h2::server::*;
1094 /// #
1095 /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
1096 /// # -> Handshake<T>
1097 /// # {
1098 /// // `server_fut` is a future representing the completion of the HTTP/2
1099 /// // handshake.
1100 /// let server_fut = Builder::new()
1101 /// .handshake(my_io);
1102 /// # server_fut
1103 /// # }
1104 /// #
1105 /// # pub fn main() {}
1106 /// ```
1107 ///
1108 /// Configures the send-payload data type. In this case, the outbound data
1109 /// type will be `&'static [u8]`.
1110 ///
1111 /// ```
1112 /// # use tokio::io::{AsyncRead, AsyncWrite};
1113 /// # use h2::server::*;
1114 /// #
1115 /// # fn doc<T: AsyncRead + AsyncWrite + Unpin>(my_io: T)
1116 /// # -> Handshake<T, &'static [u8]>
1117 /// # {
1118 /// // `server_fut` is a future representing the completion of the HTTP/2
1119 /// // handshake.
1120 /// let server_fut: Handshake<_, &'static [u8]> = Builder::new()
1121 /// .handshake(my_io);
1122 /// # server_fut
1123 /// # }
1124 /// #
1125 /// # pub fn main() {}
1126 /// ```
1127 pub fn handshake<T, B>(&self, io: T) -> Handshake<T, B>
1128 where
1129 T: AsyncRead + AsyncWrite + Unpin,
1130 B: Buf,
1131 {
1132 Connection::handshake2(io, self.clone())
1133 }
1134}
1135
1136impl Default for Builder {
1137 fn default() -> Builder {
1138 Builder::new()
1139 }
1140}
1141
1142// ===== impl SendResponse =====
1143
1144impl<B: Buf> SendResponse<B> {
1145 /// Send an interim informational response (1xx status codes)
1146 ///
1147 /// This method can be called multiple times before calling `send_response()`
1148 /// to send the final response. Only 1xx status codes are allowed.
1149 ///
1150 /// Interim informational responses are used to provide early feedback to the client
1151 /// before the final response is ready. Common examples include:
1152 /// - 100 Continue: Indicates the client should continue with the request
1153 /// - 103 Early Hints: Provides early hints about resources to preload
1154 ///
1155 /// # Arguments
1156 /// * `response` - HTTP response with 1xx status code and headers
1157 ///
1158 /// # Returns
1159 /// * `Ok(())` - Interim Informational response sent successfully
1160 /// * `Err(Error)` - Failed to send (invalid status code, connection error, etc.)
1161 ///
1162 /// # Examples
1163 /// ```rust
1164 /// use h2::server;
1165 /// use http::{Response, StatusCode};
1166 ///
1167 /// # async fn example(mut send_response: h2::server::SendResponse<bytes::Bytes>) -> Result<(), h2::Error> {
1168 /// // Send 100 Continue before processing request body
1169 /// let continue_response = Response::builder()
1170 /// .status(StatusCode::CONTINUE)
1171 /// .body(())
1172 /// .unwrap();
1173 /// send_response.send_informational(continue_response)?;
1174 ///
1175 /// // Later send the final response
1176 /// let final_response = Response::builder()
1177 /// .status(StatusCode::OK)
1178 /// .body(())
1179 /// .unwrap();
1180 /// let _stream = send_response.send_response(final_response, false)?;
1181 /// # Ok(())
1182 /// # }
1183 /// ```
1184 ///
1185 /// # Errors
1186 /// This method will return an error if:
1187 /// - The response status code is not in the 1xx range
1188 /// - The final response has already been sent
1189 /// - There is a connection-level error
1190 pub fn send_informational(&mut self, response: Response<()>) -> Result<(), crate::Error> {
1191 let stream_id = self.inner.stream_id();
1192 let status = response.status();
1193
1194 tracing::trace!(
1195 "send_informational called with status: {} on stream: {:?}",
1196 status,
1197 stream_id
1198 );
1199
1200 // Validate that this is an informational response (1xx status code)
1201 if !response.status().is_informational() {
1202 tracing::trace!(
1203 "invalid informational status code: {} on stream: {:?}",
1204 status,
1205 stream_id
1206 );
1207 return Err(crate::Error::from(
1208 UserError::InvalidInformationalStatusCode,
1209 ));
1210 }
1211
1212 tracing::trace!(
1213 "converting informational response to HEADERS frame without END_STREAM flag for stream: {:?}",
1214 stream_id
1215 );
1216
1217 let frame = Peer::convert_send_message(
1218 stream_id, response, false, // NOT end_of_stream for informational responses
1219 );
1220
1221 tracing::trace!(
1222 "sending interim informational headers frame for stream: {:?}",
1223 stream_id
1224 );
1225
1226 // Use the proper H2 streams API for sending interim informational headers
1227 // This bypasses the normal response flow and allows multiple informational responses
1228 let result = self
1229 .inner
1230 .send_informational_headers(frame)
1231 .map_err(Into::into);
1232
1233 match &result {
1234 Ok(()) => tracing::trace!(
1235 "Successfully sent informational headers for stream: {:?}",
1236 stream_id
1237 ),
1238 Err(e) => tracing::trace!(
1239 "Failed to send informational headers for stream: {:?}: {:?}",
1240 stream_id,
1241 e
1242 ),
1243 }
1244
1245 result
1246 }
1247
1248 /// Send a response to a client request.
1249 ///
1250 /// On success, a [`SendStream`] instance is returned. This instance can be
1251 /// used to stream the response body and send trailers.
1252 ///
1253 /// If a body or trailers will be sent on the returned [`SendStream`]
1254 /// instance, then `end_of_stream` must be set to `false` when calling this
1255 /// function.
1256 ///
1257 /// The [`SendResponse`] instance is already associated with a received
1258 /// request. This function may only be called once per instance and only if
1259 /// [`send_reset`] has not been previously called.
1260 ///
1261 /// [`SendResponse`]: #
1262 /// [`SendStream`]: ../struct.SendStream.html
1263 /// [`send_reset`]: #method.send_reset
1264 pub fn send_response(
1265 &mut self,
1266 response: Response<()>,
1267 end_of_stream: bool,
1268 ) -> Result<SendStream<B>, crate::Error> {
1269 self.inner
1270 .send_response(response, end_of_stream)
1271 .map(|_| SendStream::new(self.inner.clone()))
1272 .map_err(Into::into)
1273 }
1274
1275 /// Push a request and response to the client
1276 ///
1277 /// On success, a [`SendResponse`] instance is returned.
1278 ///
1279 /// [`SendResponse`]: #
1280 pub fn push_request(
1281 &mut self,
1282 request: Request<()>,
1283 ) -> Result<SendPushedResponse<B>, crate::Error> {
1284 self.inner
1285 .send_push_promise(request)
1286 .map(|inner| SendPushedResponse {
1287 inner: SendResponse { inner },
1288 })
1289 .map_err(Into::into)
1290 }
1291
1292 /// Send a stream reset to the peer.
1293 ///
1294 /// This essentially cancels the stream, including any inbound or outbound
1295 /// data streams.
1296 ///
1297 /// If this function is called before [`send_response`], a call to
1298 /// [`send_response`] will result in an error.
1299 ///
1300 /// If this function is called while a [`SendStream`] instance is active,
1301 /// any further use of the instance will result in an error.
1302 ///
1303 /// This function should only be called once.
1304 ///
1305 /// [`send_response`]: #method.send_response
1306 /// [`SendStream`]: ../struct.SendStream.html
1307 pub fn send_reset(&mut self, reason: Reason) {
1308 self.inner.send_reset(reason)
1309 }
1310
1311 /// Polls to be notified when the client resets this stream.
1312 ///
1313 /// If stream is still open, this returns `Poll::Pending`, and
1314 /// registers the task to be notified if a `RST_STREAM` is received.
1315 ///
1316 /// If a `RST_STREAM` frame is received for this stream, calling this
1317 /// method will yield the `Reason` for the reset.
1318 ///
1319 /// # Error
1320 ///
1321 /// Calling this method after having called `send_response` will return
1322 /// a user error.
1323 pub fn poll_reset(&mut self, cx: &mut Context) -> Poll<Result<Reason, crate::Error>> {
1324 self.inner.poll_reset(cx, proto::PollReset::AwaitingHeaders)
1325 }
1326
1327 /// Returns the stream ID of the response stream.
1328 ///
1329 /// # Panics
1330 ///
1331 /// If the lock on the stream store has been poisoned.
1332 pub fn stream_id(&self) -> crate::StreamId {
1333 crate::StreamId::from_internal(self.inner.stream_id())
1334 }
1335}
1336
1337// ===== impl SendPushedResponse =====
1338
1339impl<B: Buf> SendPushedResponse<B> {
1340 /// Send a response to a promised request.
1341 ///
1342 /// On success, a [`SendStream`] instance is returned. This instance can be
1343 /// used to stream the response body and send trailers.
1344 ///
1345 /// If a body or trailers will be sent on the returned [`SendStream`]
1346 /// instance, then `end_of_stream` must be set to `false` when calling this
1347 /// function.
1348 ///
1349 /// The [`SendPushedResponse`] instance is associated with a promised
1350 /// request. This function may only be called once per instance and only if
1351 /// [`send_reset`] has not been previously called.
1352 ///
1353 /// [`SendPushedResponse`]: #
1354 /// [`SendStream`]: ../struct.SendStream.html
1355 /// [`send_reset`]: #method.send_reset
1356 pub fn send_response(
1357 &mut self,
1358 response: Response<()>,
1359 end_of_stream: bool,
1360 ) -> Result<SendStream<B>, crate::Error> {
1361 self.inner.send_response(response, end_of_stream)
1362 }
1363
1364 /// Send a stream reset to the peer.
1365 ///
1366 /// This essentially cancels the stream, including any inbound or outbound
1367 /// data streams.
1368 ///
1369 /// If this function is called before [`send_response`], a call to
1370 /// [`send_response`] will result in an error.
1371 ///
1372 /// If this function is called while a [`SendStream`] instance is active,
1373 /// any further use of the instance will result in an error.
1374 ///
1375 /// This function should only be called once.
1376 ///
1377 /// [`send_response`]: #method.send_response
1378 /// [`SendStream`]: ../struct.SendStream.html
1379 pub fn send_reset(&mut self, reason: Reason) {
1380 self.inner.send_reset(reason)
1381 }
1382
1383 /// Polls to be notified when the client resets this stream.
1384 ///
1385 /// If stream is still open, this returns `Poll::Pending`, and
1386 /// registers the task to be notified if a `RST_STREAM` is received.
1387 ///
1388 /// If a `RST_STREAM` frame is received for this stream, calling this
1389 /// method will yield the `Reason` for the reset.
1390 ///
1391 /// # Error
1392 ///
1393 /// Calling this method after having called `send_response` will return
1394 /// a user error.
1395 pub fn poll_reset(&mut self, cx: &mut Context) -> Poll<Result<Reason, crate::Error>> {
1396 self.inner.poll_reset(cx)
1397 }
1398
1399 /// Returns the stream ID of the response stream.
1400 ///
1401 /// # Panics
1402 ///
1403 /// If the lock on the stream store has been poisoned.
1404 pub fn stream_id(&self) -> crate::StreamId {
1405 self.inner.stream_id()
1406 }
1407}
1408
1409// ===== impl Flush =====
1410
1411impl<T, B: Buf> Flush<T, B> {
1412 fn new(codec: Codec<T, B>) -> Self {
1413 Flush { codec: Some(codec) }
1414 }
1415}
1416
1417impl<T, B> Future for Flush<T, B>
1418where
1419 T: AsyncWrite + Unpin,
1420 B: Buf,
1421{
1422 type Output = Result<Codec<T, B>, crate::Error>;
1423
1424 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1425 // Flush the codec
1426 ready!(self.codec.as_mut().unwrap().flush(cx)).map_err(crate::Error::from_io)?;
1427
1428 // Return the codec
1429 Poll::Ready(Ok(self.codec.take().unwrap()))
1430 }
1431}
1432
1433impl<T, B: Buf> ReadPreface<T, B> {
1434 fn new(codec: Codec<T, B>) -> Self {
1435 ReadPreface {
1436 codec: Some(codec),
1437 pos: 0,
1438 }
1439 }
1440
1441 fn inner_mut(&mut self) -> &mut T {
1442 self.codec.as_mut().unwrap().get_mut()
1443 }
1444}
1445
1446impl<T, B> Future for ReadPreface<T, B>
1447where
1448 T: AsyncRead + Unpin,
1449 B: Buf,
1450{
1451 type Output = Result<Codec<T, B>, crate::Error>;
1452
1453 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1454 let mut buf = [0; 24];
1455 let mut rem = PREFACE.len() - self.pos;
1456
1457 while rem > 0 {
1458 let mut buf = ReadBuf::new(&mut buf[..rem]);
1459 ready!(Pin::new(self.inner_mut()).poll_read(cx, &mut buf))
1460 .map_err(crate::Error::from_io)?;
1461 let n = buf.filled().len();
1462 if n == 0 {
1463 return Poll::Ready(Err(crate::Error::from_io(io::Error::new(
1464 io::ErrorKind::UnexpectedEof,
1465 "connection closed before reading preface",
1466 ))));
1467 }
1468
1469 if &PREFACE[self.pos..self.pos + n] != buf.filled() {
1470 proto_err!(conn: "read_preface: invalid preface");
1471 // TODO: Should this just write the GO_AWAY frame directly?
1472 return Poll::Ready(Err(Error::library_go_away(Reason::PROTOCOL_ERROR).into()));
1473 }
1474
1475 self.pos += n;
1476 rem -= n; // TODO test
1477 }
1478
1479 Poll::Ready(Ok(self.codec.take().unwrap()))
1480 }
1481}
1482
1483// ===== impl Handshake =====
1484
1485impl<T, B: Buf> Future for Handshake<T, B>
1486where
1487 T: AsyncRead + AsyncWrite + Unpin,
1488 B: Buf,
1489{
1490 type Output = Result<Connection<T, B>, crate::Error>;
1491
1492 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1493 let span = self.span.clone(); // XXX(eliza): T_T
1494 let _e = span.enter();
1495 tracing::trace!(state = ?self.state);
1496
1497 loop {
1498 match &mut self.state {
1499 Handshaking::Flushing(flush) => {
1500 // We're currently flushing a pending SETTINGS frame. Poll the
1501 // flush future, and, if it's completed, advance our state to wait
1502 // for the client preface.
1503 let codec = match Pin::new(flush).poll(cx)? {
1504 Poll::Pending => {
1505 tracing::trace!(flush.poll = %"Pending");
1506 return Poll::Pending;
1507 }
1508 Poll::Ready(flushed) => {
1509 tracing::trace!(flush.poll = %"Ready");
1510 flushed
1511 }
1512 };
1513 self.state = Handshaking::ReadingPreface(
1514 ReadPreface::new(codec).instrument(tracing::trace_span!("read_preface")),
1515 );
1516 }
1517 Handshaking::ReadingPreface(read) => {
1518 let codec = ready!(Pin::new(read).poll(cx)?);
1519
1520 self.state = Handshaking::Done;
1521
1522 let connection = proto::Connection::new(
1523 codec,
1524 Config {
1525 next_stream_id: 2.into(),
1526 // Server does not need to locally initiate any streams
1527 initial_max_send_streams: 0,
1528 max_send_buffer_size: self.builder.max_send_buffer_size,
1529 reset_stream_duration: self.builder.reset_stream_duration,
1530 reset_stream_max: self.builder.reset_stream_max,
1531 remote_reset_stream_max: self.builder.pending_accept_reset_stream_max,
1532 local_error_reset_streams_max: self
1533 .builder
1534 .local_max_error_reset_streams,
1535 settings: self.builder.settings.clone(),
1536 data_frame_budget: self
1537 .builder
1538 .data_frame_budget
1539 .resolve(self.builder.initial_target_connection_window_size),
1540 },
1541 );
1542
1543 tracing::trace!("connection established!");
1544 let mut c = Connection { connection };
1545 if let Some(sz) = self.builder.initial_target_connection_window_size {
1546 c.set_target_window_size(sz);
1547 }
1548
1549 return Poll::Ready(Ok(c));
1550 }
1551 Handshaking::Done => {
1552 panic!("Handshaking::poll() called again after handshaking was complete")
1553 }
1554 }
1555 }
1556 }
1557}
1558
1559impl<T, B> fmt::Debug for Handshake<T, B>
1560where
1561 T: AsyncRead + AsyncWrite + fmt::Debug,
1562 B: fmt::Debug + Buf,
1563{
1564 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1565 write!(fmt, "server::Handshake")
1566 }
1567}
1568
1569impl Peer {
1570 pub fn convert_send_message(
1571 id: StreamId,
1572 response: Response<()>,
1573 end_of_stream: bool,
1574 ) -> frame::Headers {
1575 use http::response::Parts;
1576
1577 // Extract the components of the HTTP request
1578 let (
1579 Parts {
1580 status, headers, ..
1581 },
1582 _,
1583 ) = response.into_parts();
1584
1585 // Build the set pseudo header set. All requests will include `method`
1586 // and `path`.
1587 let pseudo = Pseudo::response(status);
1588
1589 // Create the HEADERS frame
1590 let mut frame = frame::Headers::new(id, pseudo, headers);
1591
1592 if end_of_stream {
1593 frame.set_end_stream()
1594 }
1595
1596 frame
1597 }
1598
1599 pub fn convert_push_message(
1600 stream_id: StreamId,
1601 promised_id: StreamId,
1602 request: Request<()>,
1603 ) -> Result<frame::PushPromise, UserError> {
1604 use http::request::Parts;
1605
1606 if let Err(e) = frame::PushPromise::validate_request(&request) {
1607 use PushPromiseHeaderError::*;
1608 match e {
1609 NotSafeAndCacheable => tracing::debug!(
1610 ?promised_id,
1611 "convert_push_message: method {} is not safe and cacheable",
1612 request.method(),
1613 ),
1614 InvalidContentLength(e) => tracing::debug!(
1615 ?promised_id,
1616 "convert_push_message; promised request has invalid content-length {:?}",
1617 e,
1618 ),
1619 }
1620 return Err(UserError::MalformedHeaders);
1621 }
1622
1623 // Extract the components of the HTTP request
1624 let (
1625 Parts {
1626 method,
1627 uri,
1628 headers,
1629 ..
1630 },
1631 _,
1632 ) = request.into_parts();
1633
1634 let pseudo = Pseudo::request(method, uri, None);
1635
1636 Ok(frame::PushPromise::new(
1637 stream_id,
1638 promised_id,
1639 pseudo,
1640 headers,
1641 ))
1642 }
1643}
1644
1645impl proto::Peer for Peer {
1646 type Poll = Request<()>;
1647
1648 const NAME: &'static str = "Server";
1649
1650 /*
1651 fn is_server() -> bool {
1652 true
1653 }
1654 */
1655
1656 fn r#dyn() -> proto::DynPeer {
1657 proto::DynPeer::Server
1658 }
1659
1660 fn convert_poll_message(
1661 pseudo: Pseudo,
1662 fields: HeaderMap,
1663 stream_id: StreamId,
1664 ) -> Result<Self::Poll, Error> {
1665 use http::{uri, Version};
1666
1667 let mut b = Request::builder();
1668
1669 macro_rules! malformed {
1670 ($($arg:tt)*) => {{
1671 tracing::debug!($($arg)*);
1672 return Err(Error::library_reset(stream_id, Reason::PROTOCOL_ERROR));
1673 }}
1674 }
1675
1676 b = b.version(Version::HTTP_2);
1677
1678 let is_connect;
1679 if let Some(method) = pseudo.method {
1680 is_connect = method == Method::CONNECT;
1681 b = b.method(method);
1682 } else {
1683 malformed!("malformed headers: missing method");
1684 }
1685
1686 let has_protocol = pseudo.protocol.is_some();
1687 if has_protocol {
1688 if is_connect {
1689 // Assert that we have the right type.
1690 b = b.extension::<crate::ext::Protocol>(pseudo.protocol.unwrap());
1691 } else {
1692 malformed!("malformed headers: :protocol on non-CONNECT request");
1693 }
1694 }
1695
1696 if pseudo.status.is_some() {
1697 malformed!("malformed headers: :status field on request");
1698 }
1699
1700 // Convert the URI
1701 let mut parts = uri::Parts::default();
1702
1703 // A request translated from HTTP/1 must not include the :authority
1704 // header
1705 if let Some(authority) = pseudo.authority {
1706 let maybe_authority = uri::Authority::from_maybe_shared(authority.clone().into_inner());
1707 parts.authority = Some(maybe_authority.or_else(|why| {
1708 malformed!(
1709 "malformed headers: malformed authority ({:?}): {}",
1710 authority,
1711 why,
1712 )
1713 })?);
1714 }
1715
1716 // A :scheme is required, except CONNECT.
1717 if let Some(scheme) = pseudo.scheme {
1718 if is_connect && !has_protocol {
1719 malformed!("malformed headers: :scheme in CONNECT");
1720 }
1721 let maybe_scheme = scheme.parse();
1722 let scheme = maybe_scheme.or_else(|why| {
1723 malformed!(
1724 "malformed headers: malformed scheme ({:?}): {}",
1725 scheme,
1726 why,
1727 )
1728 })?;
1729
1730 // It's not possible to build an `Uri` from a scheme and path. So,
1731 // after validating is was a valid scheme, we just have to drop it
1732 // if there isn't an :authority.
1733 if parts.authority.is_some() {
1734 parts.scheme = Some(scheme);
1735 }
1736 } else if !is_connect || has_protocol {
1737 malformed!("malformed headers: missing scheme");
1738 }
1739
1740 if let Some(path) = pseudo.path {
1741 if is_connect && !has_protocol {
1742 malformed!("malformed headers: :path in CONNECT");
1743 }
1744
1745 // This cannot be empty
1746 if path.is_empty() {
1747 malformed!("malformed headers: missing path");
1748 }
1749
1750 let maybe_path = uri::PathAndQuery::from_maybe_shared(path.clone().into_inner());
1751 parts.path_and_query = Some(maybe_path.or_else(|why| {
1752 malformed!("malformed headers: malformed path ({:?}): {}", path, why,)
1753 })?);
1754 } else if is_connect && has_protocol {
1755 malformed!("malformed headers: missing path in extended CONNECT");
1756 }
1757
1758 b = b.uri(parts);
1759
1760 let mut request = match b.body(()) {
1761 Ok(request) => request,
1762 Err(e) => {
1763 // TODO: Should there be more specialized handling for different
1764 // kinds of errors
1765 proto_err!(stream: "error building request: {}; stream={:?}", e, stream_id);
1766 return Err(Error::library_reset(stream_id, Reason::PROTOCOL_ERROR));
1767 }
1768 };
1769
1770 *request.headers_mut() = fields;
1771
1772 Ok(request)
1773 }
1774}
1775
1776// ===== impl Handshaking =====
1777
1778impl<T, B> fmt::Debug for Handshaking<T, B>
1779where
1780 B: Buf,
1781{
1782 #[inline]
1783 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1784 match *self {
1785 Handshaking::Flushing(_) => f.write_str("Flushing(_)"),
1786 Handshaking::ReadingPreface(_) => f.write_str("ReadingPreface(_)"),
1787 Handshaking::Done => f.write_str("Done"),
1788 }
1789 }
1790}