hyper/server/conn/
http1.rs

1//! HTTP/1 Server Connections
2
3use std::error::Error as StdError;
4use std::fmt;
5use std::future::Future;
6use std::pin::Pin;
7use std::sync::Arc;
8use std::task::{Context, Poll};
9use std::time::Duration;
10
11use crate::rt::{Read, Write};
12use crate::upgrade::Upgraded;
13use bytes::Bytes;
14use futures_util::ready;
15
16use crate::body::{Body, Incoming as IncomingBody};
17use crate::proto;
18use crate::service::HttpService;
19use crate::{
20    common::time::{Dur, Time},
21    rt::Timer,
22};
23
24type Http1Dispatcher<T, B, S> = proto::h1::Dispatcher<
25    proto::h1::dispatch::Server<S, IncomingBody>,
26    B,
27    T,
28    proto::ServerTransaction,
29>;
30
31pin_project_lite::pin_project! {
32    /// A [`Future`](core::future::Future) representing an HTTP/1 connection, bound to a
33    /// [`Service`](crate::service::Service), returned from
34    /// [`Builder::serve_connection`](struct.Builder.html#method.serve_connection).
35    ///
36    /// To drive HTTP on this connection this future **must be polled**, typically with
37    /// `.await`. If it isn't polled, no progress will be made on this connection.
38    #[must_use = "futures do nothing unless polled"]
39    pub struct Connection<T, S>
40    where
41        S: HttpService<IncomingBody>,
42    {
43        conn: Http1Dispatcher<T, S::ResBody, S>,
44    }
45}
46
47/// A configuration builder for HTTP/1 server connections.
48///
49/// **Note**: The default values of options are *not considered stable*. They
50/// are subject to change at any time.
51///
52/// # Example
53///
54/// ```
55/// # use std::time::Duration;
56/// # use hyper::server::conn::http1::Builder;
57/// # fn main() {
58/// let mut http = Builder::new();
59/// // Set options one at a time
60/// http.half_close(false);
61///
62/// // Or, chain multiple options
63/// http.keep_alive(false).title_case_headers(true).max_buf_size(8192);
64///
65/// # }
66/// ```
67///
68/// Use [`Builder::serve_connection`](struct.Builder.html#method.serve_connection)
69/// to bind the built connection to a service.
70#[derive(Clone, Debug)]
71pub struct Builder {
72    h1_parser_config: httparse::ParserConfig,
73    timer: Time,
74    h1_half_close: bool,
75    h1_keep_alive: bool,
76    h1_title_case_headers: bool,
77    h1_preserve_header_case: bool,
78    h1_max_headers: Option<usize>,
79    h1_header_read_timeout: Dur,
80    h1_writev: Option<bool>,
81    max_buf_size: Option<usize>,
82    pipeline_flush: bool,
83    date_header: bool,
84}
85
86/// Deconstructed parts of a `Connection`.
87///
88/// This allows taking apart a `Connection` at a later time, in order to
89/// reclaim the IO object, and additional related pieces.
90#[derive(Debug)]
91#[non_exhaustive]
92pub struct Parts<T, S> {
93    /// The original IO object used in the handshake.
94    pub io: T,
95    /// A buffer of bytes that have been read but not processed as HTTP.
96    ///
97    /// If the client sent additional bytes after its last request, and
98    /// this connection "ended" with an upgrade, the read buffer will contain
99    /// those bytes.
100    ///
101    /// You will want to check for any existing bytes if you plan to continue
102    /// communicating on the IO object.
103    pub read_buf: Bytes,
104    /// The `Service` used to serve this connection.
105    pub service: S,
106}
107
108// ===== impl Connection =====
109
110impl<I, S> fmt::Debug for Connection<I, S>
111where
112    S: HttpService<IncomingBody>,
113{
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        f.debug_struct("Connection").finish()
116    }
117}
118
119impl<I, B, S> Connection<I, S>
120where
121    S: HttpService<IncomingBody, ResBody = B>,
122    S::Error: Into<Box<dyn StdError + Send + Sync>>,
123    I: Read + Write + Unpin,
124    B: Body + 'static,
125    B::Error: Into<Box<dyn StdError + Send + Sync>>,
126{
127    /// Start a graceful shutdown process for this connection.
128    ///
129    /// This `Connection` should continue to be polled until shutdown
130    /// can finish.
131    ///
132    /// # Note
133    ///
134    /// This should only be called while the `Connection` future is still
135    /// pending. If called after `Connection::poll` has resolved, this does
136    /// nothing.
137    pub fn graceful_shutdown(mut self: Pin<&mut Self>) {
138        self.conn.disable_keep_alive();
139    }
140
141    /// Return the inner IO object, and additional information.
142    ///
143    /// If the IO object has been "rewound" the io will not contain those bytes rewound.
144    /// This should only be called after `poll_without_shutdown` signals
145    /// that the connection is "done". Otherwise, it may not have finished
146    /// flushing all necessary HTTP bytes.
147    ///
148    /// # Panics
149    /// This method will panic if this connection is using an h2 protocol.
150    pub fn into_parts(self) -> Parts<I, S> {
151        let (io, read_buf, dispatch) = self.conn.into_inner();
152        Parts {
153            io,
154            read_buf,
155            service: dispatch.into_service(),
156        }
157    }
158
159    /// Poll the connection for completion, but without calling `shutdown`
160    /// on the underlying IO.
161    ///
162    /// This is useful to allow running a connection while doing an HTTP
163    /// upgrade. Once the upgrade is completed, the connection would be "done",
164    /// but it is not desired to actually shutdown the IO object. Instead you
165    /// would take it back using `into_parts`.
166    pub fn poll_without_shutdown(&mut self, cx: &mut Context<'_>) -> Poll<crate::Result<()>>
167    where
168        S: Unpin,
169        S::Future: Unpin,
170    {
171        self.conn.poll_without_shutdown(cx)
172    }
173
174    /// Prevent shutdown of the underlying IO object at the end of service the request,
175    /// instead run `into_parts`. This is a convenience wrapper over `poll_without_shutdown`.
176    ///
177    /// # Error
178    ///
179    /// This errors if the underlying connection protocol is not HTTP/1.
180    pub fn without_shutdown(self) -> impl Future<Output = crate::Result<Parts<I, S>>> {
181        let mut zelf = Some(self);
182        futures_util::future::poll_fn(move |cx| {
183            ready!(zelf.as_mut().unwrap().conn.poll_without_shutdown(cx))?;
184            Poll::Ready(Ok(zelf.take().unwrap().into_parts()))
185        })
186    }
187
188    /// Enable this connection to support higher-level HTTP upgrades.
189    ///
190    /// See [the `upgrade` module](crate::upgrade) for more.
191    pub fn with_upgrades(self) -> UpgradeableConnection<I, S>
192    where
193        I: Send,
194    {
195        UpgradeableConnection { inner: Some(self) }
196    }
197}
198
199impl<I, B, S> Future for Connection<I, S>
200where
201    S: HttpService<IncomingBody, ResBody = B>,
202    S::Error: Into<Box<dyn StdError + Send + Sync>>,
203    I: Read + Write + Unpin,
204    B: Body + 'static,
205    B::Error: Into<Box<dyn StdError + Send + Sync>>,
206{
207    type Output = crate::Result<()>;
208
209    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
210        match ready!(Pin::new(&mut self.conn).poll(cx)) {
211            Ok(done) => {
212                match done {
213                    proto::Dispatched::Shutdown => {}
214                    proto::Dispatched::Upgrade(pending) => {
215                        // With no `Send` bound on `I`, we can't try to do
216                        // upgrades here. In case a user was trying to use
217                        // `Body::on_upgrade` with this API, send a special
218                        // error letting them know about that.
219                        pending.manual();
220                    }
221                };
222                Poll::Ready(Ok(()))
223            }
224            Err(e) => Poll::Ready(Err(e)),
225        }
226    }
227}
228
229// ===== impl Builder =====
230
231impl Builder {
232    /// Create a new connection builder.
233    pub fn new() -> Self {
234        Self {
235            h1_parser_config: Default::default(),
236            timer: Time::Empty,
237            h1_half_close: false,
238            h1_keep_alive: true,
239            h1_title_case_headers: false,
240            h1_preserve_header_case: false,
241            h1_max_headers: None,
242            h1_header_read_timeout: Dur::Default(Some(Duration::from_secs(30))),
243            h1_writev: None,
244            max_buf_size: None,
245            pipeline_flush: false,
246            date_header: true,
247        }
248    }
249    /// Set whether HTTP/1 connections should support half-closures.
250    ///
251    /// Clients can chose to shutdown their write-side while waiting
252    /// for the server to respond. Setting this to `true` will
253    /// prevent closing the connection immediately if `read`
254    /// detects an EOF in the middle of a request.
255    ///
256    /// Default is `false`.
257    pub fn half_close(&mut self, val: bool) -> &mut Self {
258        self.h1_half_close = val;
259        self
260    }
261
262    /// Enables or disables HTTP/1 keep-alive.
263    ///
264    /// Default is true.
265    pub fn keep_alive(&mut self, val: bool) -> &mut Self {
266        self.h1_keep_alive = val;
267        self
268    }
269
270    /// Set whether HTTP/1 connections will write header names as title case at
271    /// the socket level.
272    ///
273    /// Default is false.
274    pub fn title_case_headers(&mut self, enabled: bool) -> &mut Self {
275        self.h1_title_case_headers = enabled;
276        self
277    }
278
279    /// Set whether HTTP/1 connections will silently ignored malformed header lines.
280    ///
281    /// If this is enabled and a header line does not start with a valid header
282    /// name, or does not include a colon at all, the line will be silently ignored
283    /// and no error will be reported.
284    ///
285    /// Default is false.
286    pub fn ignore_invalid_headers(&mut self, enabled: bool) -> &mut Builder {
287        self.h1_parser_config
288            .ignore_invalid_headers_in_requests(enabled);
289        self
290    }
291
292    /// Set whether to support preserving original header cases.
293    ///
294    /// Currently, this will record the original cases received, and store them
295    /// in a private extension on the `Request`. It will also look for and use
296    /// such an extension in any provided `Response`.
297    ///
298    /// Since the relevant extension is still private, there is no way to
299    /// interact with the original cases. The only effect this can have now is
300    /// to forward the cases in a proxy-like fashion.
301    ///
302    /// Default is false.
303    pub fn preserve_header_case(&mut self, enabled: bool) -> &mut Self {
304        self.h1_preserve_header_case = enabled;
305        self
306    }
307
308    /// Set the maximum number of headers.
309    ///
310    /// When a request is received, the parser will reserve a buffer to store headers for optimal
311    /// performance.
312    ///
313    /// If server receives more headers than the buffer size, it responds to the client with
314    /// "431 Request Header Fields Too Large".
315    ///
316    /// Note that headers is allocated on the stack by default, which has higher performance. After
317    /// setting this value, headers will be allocated in heap memory, that is, heap memory
318    /// allocation will occur for each request, and there will be a performance drop of about 5%.
319    ///
320    /// Default is 100.
321    pub fn max_headers(&mut self, val: usize) -> &mut Self {
322        self.h1_max_headers = Some(val);
323        self
324    }
325
326    /// Set a timeout for reading client request headers. If a client does not
327    /// transmit the entire header within this time, the connection is closed.
328    ///
329    /// Requires a [`Timer`] set by [`Builder::timer`] to take effect. Panics if `header_read_timeout` is configured
330    /// without a [`Timer`].
331    ///
332    /// Pass `None` to disable.
333    ///
334    /// Default is 30 seconds.
335    pub fn header_read_timeout(&mut self, read_timeout: impl Into<Option<Duration>>) -> &mut Self {
336        self.h1_header_read_timeout = Dur::Configured(read_timeout.into());
337        self
338    }
339
340    /// Set whether HTTP/1 connections should try to use vectored writes,
341    /// or always flatten into a single buffer.
342    ///
343    /// Note that setting this to false may mean more copies of body data,
344    /// but may also improve performance when an IO transport doesn't
345    /// support vectored writes well, such as most TLS implementations.
346    ///
347    /// Setting this to true will force hyper to use queued strategy
348    /// which may eliminate unnecessary cloning on some TLS backends
349    ///
350    /// Default is `auto`. In this mode hyper will try to guess which
351    /// mode to use
352    pub fn writev(&mut self, val: bool) -> &mut Self {
353        self.h1_writev = Some(val);
354        self
355    }
356
357    /// Set the maximum buffer size for the connection.
358    ///
359    /// Default is ~400kb.
360    ///
361    /// # Panics
362    ///
363    /// The minimum value allowed is 8192. This method panics if the passed `max` is less than the minimum.
364    pub fn max_buf_size(&mut self, max: usize) -> &mut Self {
365        assert!(
366            max >= proto::h1::MINIMUM_MAX_BUFFER_SIZE,
367            "the max_buf_size cannot be smaller than the minimum that h1 specifies."
368        );
369        self.max_buf_size = Some(max);
370        self
371    }
372
373    /// Set whether the `date` header should be included in HTTP responses.
374    ///
375    /// Note that including the `date` header is recommended by RFC 7231.
376    ///
377    /// Default is true.
378    pub fn auto_date_header(&mut self, enabled: bool) -> &mut Self {
379        self.date_header = enabled;
380        self
381    }
382
383    /// Aggregates flushes to better support pipelined responses.
384    ///
385    /// Experimental, may have bugs.
386    ///
387    /// Default is false.
388    pub fn pipeline_flush(&mut self, enabled: bool) -> &mut Self {
389        self.pipeline_flush = enabled;
390        self
391    }
392
393    /// Set the timer used in background tasks.
394    pub fn timer<M>(&mut self, timer: M) -> &mut Self
395    where
396        M: Timer + Send + Sync + 'static,
397    {
398        self.timer = Time::Timer(Arc::new(timer));
399        self
400    }
401
402    /// Bind a connection together with a [`Service`](crate::service::Service).
403    ///
404    /// This returns a Future that must be polled in order for HTTP to be
405    /// driven on the connection.
406    ///
407    /// # Panics
408    ///
409    /// If a timeout option has been configured, but a `timer` has not been
410    /// provided, calling `serve_connection` will panic.
411    ///
412    /// # Example
413    ///
414    /// ```
415    /// # use hyper::{body::Incoming, Request, Response};
416    /// # use hyper::service::Service;
417    /// # use hyper::server::conn::http1::Builder;
418    /// # use hyper::rt::{Read, Write};
419    /// # async fn run<I, S>(some_io: I, some_service: S)
420    /// # where
421    /// #     I: Read + Write + Unpin + Send + 'static,
422    /// #     S: Service<hyper::Request<Incoming>, Response=hyper::Response<Incoming>> + Send + 'static,
423    /// #     S::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
424    /// #     S::Future: Send,
425    /// # {
426    /// let http = Builder::new();
427    /// let conn = http.serve_connection(some_io, some_service);
428    ///
429    /// if let Err(e) = conn.await {
430    ///     eprintln!("server connection error: {}", e);
431    /// }
432    /// # }
433    /// # fn main() {}
434    /// ```
435    pub fn serve_connection<I, S>(&self, io: I, service: S) -> Connection<I, S>
436    where
437        S: HttpService<IncomingBody>,
438        S::Error: Into<Box<dyn StdError + Send + Sync>>,
439        S::ResBody: 'static,
440        <S::ResBody as Body>::Error: Into<Box<dyn StdError + Send + Sync>>,
441        I: Read + Write + Unpin,
442    {
443        let mut conn = proto::Conn::new(io);
444        conn.set_h1_parser_config(self.h1_parser_config.clone());
445        conn.set_timer(self.timer.clone());
446        if !self.h1_keep_alive {
447            conn.disable_keep_alive();
448        }
449        if self.h1_half_close {
450            conn.set_allow_half_close();
451        }
452        if self.h1_title_case_headers {
453            conn.set_title_case_headers();
454        }
455        if self.h1_preserve_header_case {
456            conn.set_preserve_header_case();
457        }
458        if let Some(max_headers) = self.h1_max_headers {
459            conn.set_http1_max_headers(max_headers);
460        }
461        if let Some(dur) = self
462            .timer
463            .check(self.h1_header_read_timeout, "header_read_timeout")
464        {
465            conn.set_http1_header_read_timeout(dur);
466        };
467        if let Some(writev) = self.h1_writev {
468            if writev {
469                conn.set_write_strategy_queue();
470            } else {
471                conn.set_write_strategy_flatten();
472            }
473        }
474        conn.set_flush_pipeline(self.pipeline_flush);
475        if let Some(max) = self.max_buf_size {
476            conn.set_max_buf_size(max);
477        }
478        if !self.date_header {
479            conn.disable_date_header();
480        }
481        let sd = proto::h1::dispatch::Server::new(service);
482        let proto = proto::h1::Dispatcher::new(sd, conn);
483        Connection { conn: proto }
484    }
485}
486
487/// A future binding a connection with a Service with Upgrade support.
488#[must_use = "futures do nothing unless polled"]
489#[allow(missing_debug_implementations)]
490pub struct UpgradeableConnection<T, S>
491where
492    S: HttpService<IncomingBody>,
493{
494    pub(super) inner: Option<Connection<T, S>>,
495}
496
497impl<I, B, S> UpgradeableConnection<I, S>
498where
499    S: HttpService<IncomingBody, ResBody = B>,
500    S::Error: Into<Box<dyn StdError + Send + Sync>>,
501    I: Read + Write + Unpin,
502    B: Body + 'static,
503    B::Error: Into<Box<dyn StdError + Send + Sync>>,
504{
505    /// Start a graceful shutdown process for this connection.
506    ///
507    /// This `Connection` should continue to be polled until shutdown
508    /// can finish.
509    pub fn graceful_shutdown(mut self: Pin<&mut Self>) {
510        // Connection (`inner`) is `None` if it was upgraded (and `poll` is `Ready`).
511        // In that case, we don't need to call `graceful_shutdown`.
512        if let Some(conn) = self.inner.as_mut() {
513            Pin::new(conn).graceful_shutdown()
514        }
515    }
516}
517
518impl<I, B, S> Future for UpgradeableConnection<I, S>
519where
520    S: HttpService<IncomingBody, ResBody = B>,
521    S::Error: Into<Box<dyn StdError + Send + Sync>>,
522    I: Read + Write + Unpin + Send + 'static,
523    B: Body + 'static,
524    B::Error: Into<Box<dyn StdError + Send + Sync>>,
525{
526    type Output = crate::Result<()>;
527
528    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
529        if let Some(conn) = self.inner.as_mut() {
530            match ready!(Pin::new(&mut conn.conn).poll(cx)) {
531                Ok(proto::Dispatched::Shutdown) => Poll::Ready(Ok(())),
532                Ok(proto::Dispatched::Upgrade(pending)) => {
533                    let (io, buf, _) = self.inner.take().unwrap().conn.into_inner();
534                    pending.fulfill(Upgraded::new(io, buf));
535                    Poll::Ready(Ok(()))
536                }
537                Err(e) => Poll::Ready(Err(e)),
538            }
539        } else {
540            // inner is `None`, meaning the connection was upgraded, thus it's `Poll::Ready(Ok(()))`
541            Poll::Ready(Ok(()))
542        }
543    }
544}