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_core::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        crate::common::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 multiple spaces are allowed as delimiters in request lines.
280    ///
281    /// Default is `false`.
282    pub fn allow_multiple_spaces_in_request_line_delimiters(&mut self, enabled: bool) -> &mut Self {
283        self.h1_parser_config
284            .allow_multiple_spaces_in_request_line_delimiters(enabled);
285        self
286    }
287
288    /// Set whether HTTP/1 connections will silently ignored malformed header lines.
289    ///
290    /// If this is enabled and a header line does not start with a valid header
291    /// name, or does not include a colon at all, the line will be silently ignored
292    /// and no error will be reported.
293    ///
294    /// Default is `false`.
295    pub fn ignore_invalid_headers(&mut self, enabled: bool) -> &mut Builder {
296        self.h1_parser_config
297            .ignore_invalid_headers_in_requests(enabled);
298        self
299    }
300
301    /// Set whether to support preserving original header cases.
302    ///
303    /// Currently, this will record the original cases received, and store them
304    /// in a private extension on the `Request`. It will also look for and use
305    /// such an extension in any provided `Response`.
306    ///
307    /// Since the relevant extension is still private, there is no way to
308    /// interact with the original cases. The only effect this can have now is
309    /// to forward the cases in a proxy-like fashion.
310    ///
311    /// Default is `false`.
312    pub fn preserve_header_case(&mut self, enabled: bool) -> &mut Self {
313        self.h1_preserve_header_case = enabled;
314        self
315    }
316
317    /// Set the maximum number of headers.
318    ///
319    /// When a request is received, the parser will reserve a buffer to store headers for optimal
320    /// performance.
321    ///
322    /// If server receives more headers than the buffer size, it responds to the client with
323    /// "431 Request Header Fields Too Large".
324    ///
325    /// Note that headers is allocated on the stack by default, which has higher performance. After
326    /// setting this value, headers will be allocated in heap memory, that is, heap memory
327    /// allocation will occur for each request, and there will be a performance drop of about 5%.
328    ///
329    /// Default is 100.
330    pub fn max_headers(&mut self, val: usize) -> &mut Self {
331        self.h1_max_headers = Some(val);
332        self
333    }
334
335    /// Set a timeout for reading client request headers. If a client does not
336    /// transmit the entire header within this time, the connection is closed.
337    ///
338    /// Requires a [`Timer`] set by [`Builder::timer`] to take effect. Panics if `header_read_timeout` is configured
339    /// without a [`Timer`].
340    ///
341    /// Pass `None` to disable.
342    ///
343    /// Default is 30 seconds.
344    pub fn header_read_timeout(&mut self, read_timeout: impl Into<Option<Duration>>) -> &mut Self {
345        self.h1_header_read_timeout = Dur::Configured(read_timeout.into());
346        self
347    }
348
349    /// Set whether HTTP/1 connections should try to use vectored writes,
350    /// or always flatten into a single buffer.
351    ///
352    /// Note that setting this to false may mean more copies of body data,
353    /// but may also improve performance when an IO transport doesn't
354    /// support vectored writes well, such as most TLS implementations.
355    ///
356    /// Setting this to true will force hyper to use queued strategy
357    /// which may eliminate unnecessary cloning on some TLS backends
358    ///
359    /// Default is `auto`. In this mode hyper will try to guess which
360    /// mode to use
361    pub fn writev(&mut self, val: bool) -> &mut Self {
362        self.h1_writev = Some(val);
363        self
364    }
365
366    /// Set the maximum buffer size for the connection.
367    ///
368    /// Default is ~400kb.
369    ///
370    /// # Panics
371    ///
372    /// The minimum value allowed is 8192. This method panics if the passed `max` is less than the minimum.
373    pub fn max_buf_size(&mut self, max: usize) -> &mut Self {
374        assert!(
375            max >= proto::h1::MINIMUM_MAX_BUFFER_SIZE,
376            "the max_buf_size cannot be smaller than the minimum that h1 specifies."
377        );
378        self.max_buf_size = Some(max);
379        self
380    }
381
382    /// Set whether the `date` header should be included in HTTP responses.
383    ///
384    /// Note that including the `date` header is recommended by RFC 7231.
385    ///
386    /// Default is `true`.
387    pub fn auto_date_header(&mut self, enabled: bool) -> &mut Self {
388        self.date_header = enabled;
389        self
390    }
391
392    /// Aggregates flushes to better support pipelined responses.
393    ///
394    /// Experimental, may have bugs.
395    ///
396    /// Default is `false`.
397    pub fn pipeline_flush(&mut self, enabled: bool) -> &mut Self {
398        self.pipeline_flush = enabled;
399        self
400    }
401
402    /// Set the timer used in background tasks.
403    pub fn timer<M>(&mut self, timer: M) -> &mut Self
404    where
405        M: Timer + Send + Sync + 'static,
406    {
407        self.timer = Time::Timer(Arc::new(timer));
408        self
409    }
410
411    /// Bind a connection together with a [`Service`](crate::service::Service).
412    ///
413    /// This returns a Future that must be polled in order for HTTP to be
414    /// driven on the connection.
415    ///
416    /// # Panics
417    ///
418    /// If a timeout option has been configured, but a `timer` has not been
419    /// provided, calling `serve_connection` will panic.
420    ///
421    /// # Example
422    ///
423    /// ```
424    /// # use hyper::{body::Incoming, Request, Response};
425    /// # use hyper::service::Service;
426    /// # use hyper::server::conn::http1::Builder;
427    /// # use hyper::rt::{Read, Write};
428    /// # async fn run<I, S>(some_io: I, some_service: S)
429    /// # where
430    /// #     I: Read + Write + Unpin + Send + 'static,
431    /// #     S: Service<hyper::Request<Incoming>, Response=hyper::Response<Incoming>> + Send + 'static,
432    /// #     S::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
433    /// #     S::Future: Send,
434    /// # {
435    /// let http = Builder::new();
436    /// let conn = http.serve_connection(some_io, some_service);
437    ///
438    /// if let Err(e) = conn.await {
439    ///     eprintln!("server connection error: {}", e);
440    /// }
441    /// # }
442    /// # fn main() {}
443    /// ```
444    pub fn serve_connection<I, S>(&self, io: I, service: S) -> Connection<I, S>
445    where
446        S: HttpService<IncomingBody>,
447        S::Error: Into<Box<dyn StdError + Send + Sync>>,
448        S::ResBody: 'static,
449        <S::ResBody as Body>::Error: Into<Box<dyn StdError + Send + Sync>>,
450        I: Read + Write + Unpin,
451    {
452        let mut conn = proto::Conn::new(io);
453        conn.set_h1_parser_config(self.h1_parser_config.clone());
454        conn.set_timer(self.timer.clone());
455        if !self.h1_keep_alive {
456            conn.disable_keep_alive();
457        }
458        if self.h1_half_close {
459            conn.set_allow_half_close();
460        }
461        if self.h1_title_case_headers {
462            conn.set_title_case_headers();
463        }
464        if self.h1_preserve_header_case {
465            conn.set_preserve_header_case();
466        }
467        if let Some(max_headers) = self.h1_max_headers {
468            conn.set_http1_max_headers(max_headers);
469        }
470        if let Some(dur) = self
471            .timer
472            .check(self.h1_header_read_timeout, "header_read_timeout")
473        {
474            conn.set_http1_header_read_timeout(dur);
475        };
476        if let Some(writev) = self.h1_writev {
477            if writev {
478                conn.set_write_strategy_queue();
479            } else {
480                conn.set_write_strategy_flatten();
481            }
482        }
483        conn.set_flush_pipeline(self.pipeline_flush);
484        if let Some(max) = self.max_buf_size {
485            conn.set_max_buf_size(max);
486        }
487        if !self.date_header {
488            conn.disable_date_header();
489        }
490        let sd = proto::h1::dispatch::Server::new(service);
491        let proto = proto::h1::Dispatcher::new(sd, conn);
492        Connection { conn: proto }
493    }
494}
495
496/// A future binding a connection with a Service with Upgrade support.
497#[must_use = "futures do nothing unless polled"]
498#[allow(missing_debug_implementations)]
499pub struct UpgradeableConnection<T, S>
500where
501    S: HttpService<IncomingBody>,
502{
503    pub(super) inner: Option<Connection<T, S>>,
504}
505
506impl<I, B, S> UpgradeableConnection<I, S>
507where
508    S: HttpService<IncomingBody, ResBody = B>,
509    S::Error: Into<Box<dyn StdError + Send + Sync>>,
510    I: Read + Write + Unpin,
511    B: Body + 'static,
512    B::Error: Into<Box<dyn StdError + Send + Sync>>,
513{
514    /// Start a graceful shutdown process for this connection.
515    ///
516    /// This `Connection` should continue to be polled until shutdown
517    /// can finish.
518    pub fn graceful_shutdown(mut self: Pin<&mut Self>) {
519        // Connection (`inner`) is `None` if it was upgraded (and `poll` is `Ready`).
520        // In that case, we don't need to call `graceful_shutdown`.
521        if let Some(conn) = self.inner.as_mut() {
522            Pin::new(conn).graceful_shutdown()
523        }
524    }
525}
526
527impl<I, B, S> Future for UpgradeableConnection<I, S>
528where
529    S: HttpService<IncomingBody, ResBody = B>,
530    S::Error: Into<Box<dyn StdError + Send + Sync>>,
531    I: Read + Write + Unpin + Send + 'static,
532    B: Body + 'static,
533    B::Error: Into<Box<dyn StdError + Send + Sync>>,
534{
535    type Output = crate::Result<()>;
536
537    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
538        if let Some(conn) = self.inner.as_mut() {
539            match ready!(Pin::new(&mut conn.conn).poll(cx)) {
540                Ok(proto::Dispatched::Shutdown) => Poll::Ready(Ok(())),
541                Ok(proto::Dispatched::Upgrade(pending)) => {
542                    let (io, buf, _) = self.inner.take().unwrap().conn.into_inner();
543                    pending.fulfill(Upgraded::new(io, buf));
544                    Poll::Ready(Ok(()))
545                }
546                Err(e) => Poll::Ready(Err(e)),
547            }
548        } else {
549            // inner is `None`, meaning the connection was upgraded, thus it's `Poll::Ready(Ok(()))`
550            Poll::Ready(Ok(()))
551        }
552    }
553}