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