Skip to main content

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
184                .as_mut()
185                .expect("server connection polled after completion")
186                .conn
187                .poll_without_shutdown(cx))?;
188            Poll::Ready(Ok(zelf
189                .take()
190                .expect("server connection missing before completion")
191                .into_parts()))
192        })
193    }
194
195    /// Enable this connection to support higher-level HTTP upgrades.
196    ///
197    /// See [the `upgrade` module](crate::upgrade) for more.
198    pub fn with_upgrades(self) -> UpgradeableConnection<I, S>
199    where
200        I: Send,
201    {
202        UpgradeableConnection { inner: Some(self) }
203    }
204}
205
206impl<I, B, S> Future for Connection<I, S>
207where
208    S: HttpService<IncomingBody, ResBody = B>,
209    S::Error: Into<Box<dyn StdError + Send + Sync>>,
210    I: Read + Write + Unpin,
211    B: Body + 'static,
212    B::Error: Into<Box<dyn StdError + Send + Sync>>,
213{
214    type Output = crate::Result<()>;
215
216    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
217        match ready!(Pin::new(&mut self.conn).poll(cx)) {
218            Ok(done) => {
219                match done {
220                    proto::Dispatched::Shutdown => {}
221                    proto::Dispatched::Upgrade(pending) => {
222                        // With no `Send` bound on `I`, we can't try to do
223                        // upgrades here. In case a user was trying to use
224                        // `Body::on_upgrade` with this API, send a special
225                        // error letting them know about that.
226                        pending.manual();
227                    }
228                };
229                Poll::Ready(Ok(()))
230            }
231            Err(e) => Poll::Ready(Err(e)),
232        }
233    }
234}
235
236// ===== impl Builder =====
237
238impl Builder {
239    /// Create a new connection builder.
240    pub fn new() -> Self {
241        Self {
242            h1_parser_config: Default::default(),
243            timer: Time::Empty,
244            h1_half_close: false,
245            h1_keep_alive: true,
246            h1_title_case_headers: false,
247            h1_preserve_header_case: false,
248            h1_max_headers: None,
249            h1_header_read_timeout: Dur::Default(Some(Duration::from_secs(30))),
250            h1_writev: None,
251            max_buf_size: None,
252            pipeline_flush: false,
253            date_header: true,
254        }
255    }
256    /// Set whether HTTP/1 connections should support half-closures.
257    ///
258    /// Clients can chose to shutdown their write-side while waiting
259    /// for the server to respond. Setting this to `true` will
260    /// prevent closing the connection immediately if `read`
261    /// detects an EOF in the middle of a request.
262    ///
263    /// Default is `false`.
264    pub fn half_close(&mut self, val: bool) -> &mut Self {
265        self.h1_half_close = val;
266        self
267    }
268
269    /// Enables or disables HTTP/1 keep-alive.
270    ///
271    /// Default is `true`.
272    pub fn keep_alive(&mut self, val: bool) -> &mut Self {
273        self.h1_keep_alive = val;
274        self
275    }
276
277    /// Set whether HTTP/1 connections will write header names as title case at
278    /// the socket level.
279    ///
280    /// Default is `false`.
281    pub fn title_case_headers(&mut self, enabled: bool) -> &mut Self {
282        self.h1_title_case_headers = enabled;
283        self
284    }
285
286    /// Set whether multiple spaces are allowed as delimiters in request lines.
287    ///
288    /// Default is `false`.
289    pub fn allow_multiple_spaces_in_request_line_delimiters(&mut self, enabled: bool) -> &mut Self {
290        self.h1_parser_config
291            .allow_multiple_spaces_in_request_line_delimiters(enabled);
292        self
293    }
294
295    /// Set whether HTTP/1 connections will silently ignored malformed header lines.
296    ///
297    /// If this is enabled and a header line does not start with a valid header
298    /// name, or does not include a colon at all, the line will be silently ignored
299    /// and no error will be reported.
300    ///
301    /// Default is `false`.
302    pub fn ignore_invalid_headers(&mut self, enabled: bool) -> &mut Builder {
303        self.h1_parser_config
304            .ignore_invalid_headers_in_requests(enabled);
305        self
306    }
307
308    /// Set whether to support preserving original header cases.
309    ///
310    /// Currently, this will record the original cases received, and store them
311    /// in a private extension on the `Request`. It will also look for and use
312    /// such an extension in any provided `Response`.
313    ///
314    /// Since the relevant extension is still private, there is no way to
315    /// interact with the original cases. The only effect this can have now is
316    /// to forward the cases in a proxy-like fashion.
317    ///
318    /// Default is `false`.
319    pub fn preserve_header_case(&mut self, enabled: bool) -> &mut Self {
320        self.h1_preserve_header_case = enabled;
321        self
322    }
323
324    /// Set the maximum number of headers.
325    ///
326    /// When a request is received, the parser will reserve a buffer to store headers for optimal
327    /// performance.
328    ///
329    /// If server receives more headers than the buffer size, it responds to the client with
330    /// "431 Request Header Fields Too Large".
331    ///
332    /// Note that headers is allocated on the stack by default, which has higher performance. After
333    /// setting this value, headers will be allocated in heap memory, that is, heap memory
334    /// allocation will occur for each request, and there will be a performance drop of about 5%.
335    ///
336    /// Default is 100.
337    pub fn max_headers(&mut self, val: usize) -> &mut Self {
338        self.h1_max_headers = Some(val);
339        self
340    }
341
342    /// Set a timeout for reading client request headers. If a client does not
343    /// transmit the entire header within this time, the connection is closed.
344    ///
345    /// Requires a [`Timer`] set by [`Builder::timer`] to take effect. Panics if `header_read_timeout` is configured
346    /// without a [`Timer`].
347    ///
348    /// Pass `None` to disable.
349    ///
350    /// Default is 30 seconds.
351    pub fn header_read_timeout(&mut self, read_timeout: impl Into<Option<Duration>>) -> &mut Self {
352        self.h1_header_read_timeout = Dur::Configured(read_timeout.into());
353        self
354    }
355
356    /// Set whether HTTP/1 connections should try to use vectored writes,
357    /// or always flatten into a single buffer.
358    ///
359    /// Note that setting this to false may mean more copies of body data,
360    /// but may also improve performance when an IO transport doesn't
361    /// support vectored writes well, such as most TLS implementations.
362    ///
363    /// Setting this to true will force hyper to use queued strategy,
364    /// which may eliminate unnecessary cloning on some TLS backends.
365    ///
366    /// Default is `auto`. In this mode hyper will try to guess which
367    /// mode to use.
368    pub fn writev(&mut self, val: bool) -> &mut Self {
369        self.h1_writev = Some(val);
370        self
371    }
372
373    /// Set the maximum buffer size for the connection.
374    ///
375    /// Default is ~400kb.
376    ///
377    /// # Panics
378    ///
379    /// The minimum value allowed is 8192. This method panics if the passed `max` is less than the minimum.
380    pub fn max_buf_size(&mut self, max: usize) -> &mut Self {
381        assert!(
382            max >= proto::h1::MINIMUM_MAX_BUFFER_SIZE,
383            "the max_buf_size cannot be smaller than the minimum that h1 specifies."
384        );
385        self.max_buf_size = Some(max);
386        self
387    }
388
389    /// Set whether the `date` header should be included in HTTP responses.
390    ///
391    /// Note that including the `date` header is recommended by RFC 7231.
392    ///
393    /// Default is `true`.
394    pub fn auto_date_header(&mut self, enabled: bool) -> &mut Self {
395        self.date_header = enabled;
396        self
397    }
398
399    /// Aggregates flushes to better support pipelined responses.
400    ///
401    /// Experimental, may have bugs.
402    ///
403    /// Default is `false`.
404    pub fn pipeline_flush(&mut self, enabled: bool) -> &mut Self {
405        self.pipeline_flush = enabled;
406        self
407    }
408
409    /// Set the timer used in background tasks.
410    pub fn timer<M>(&mut self, timer: M) -> &mut Self
411    where
412        M: Timer + Send + Sync + 'static,
413    {
414        self.timer = Time::Timer(Arc::new(timer));
415        self
416    }
417
418    /// Bind a connection together with a [`Service`](crate::service::Service).
419    ///
420    /// This returns a Future that must be polled in order for HTTP to be
421    /// driven on the connection.
422    ///
423    /// # Panics
424    ///
425    /// If a timeout option has been configured, but a `timer` has not been
426    /// provided, calling `serve_connection` will panic.
427    ///
428    /// # Example
429    ///
430    /// ```
431    /// # use hyper::{body::Incoming, Request, Response};
432    /// # use hyper::service::Service;
433    /// # use hyper::server::conn::http1::Builder;
434    /// # use hyper::rt::{Read, Write};
435    /// # async fn run<I, S>(some_io: I, some_service: S)
436    /// # where
437    /// #     I: Read + Write + Unpin + Send + 'static,
438    /// #     S: Service<hyper::Request<Incoming>, Response=hyper::Response<Incoming>> + Send + 'static,
439    /// #     S::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
440    /// #     S::Future: Send,
441    /// # {
442    /// let http = Builder::new();
443    /// let conn = http.serve_connection(some_io, some_service);
444    ///
445    /// if let Err(e) = conn.await {
446    ///     eprintln!("server connection error: {}", e);
447    /// }
448    /// # }
449    /// # fn main() {}
450    /// ```
451    pub fn serve_connection<I, S>(&self, io: I, service: S) -> Connection<I, S>
452    where
453        S: HttpService<IncomingBody>,
454        S::Error: Into<Box<dyn StdError + Send + Sync>>,
455        S::ResBody: 'static,
456        <S::ResBody as Body>::Error: Into<Box<dyn StdError + Send + Sync>>,
457        I: Read + Write + Unpin,
458    {
459        let mut conn = proto::Conn::new(io);
460        conn.set_h1_parser_config(self.h1_parser_config.clone());
461        conn.set_timer(self.timer.clone());
462        if !self.h1_keep_alive {
463            conn.disable_keep_alive();
464        }
465        if self.h1_half_close {
466            conn.set_allow_half_close();
467        }
468        if self.h1_title_case_headers {
469            conn.set_title_case_headers();
470        }
471        if self.h1_preserve_header_case {
472            conn.set_preserve_header_case();
473        }
474        if let Some(max_headers) = self.h1_max_headers {
475            conn.set_http1_max_headers(max_headers);
476        }
477        if let Some(dur) = self
478            .timer
479            .check(self.h1_header_read_timeout, "header_read_timeout")
480        {
481            conn.set_http1_header_read_timeout(dur);
482        };
483        if let Some(writev) = self.h1_writev {
484            if writev {
485                conn.set_write_strategy_queue();
486            } else {
487                conn.set_write_strategy_flatten();
488            }
489        }
490        conn.set_flush_pipeline(self.pipeline_flush);
491        if let Some(max) = self.max_buf_size {
492            conn.set_max_buf_size(max);
493        }
494        if !self.date_header {
495            conn.disable_date_header();
496        }
497        let sd = proto::h1::dispatch::Server::new(service);
498        let proto = proto::h1::Dispatcher::new(sd, conn);
499        Connection { conn: proto }
500    }
501}
502
503/// A future binding a connection with a Service with Upgrade support.
504#[must_use = "futures do nothing unless polled"]
505#[allow(missing_debug_implementations)]
506pub struct UpgradeableConnection<T, S>
507where
508    S: HttpService<IncomingBody>,
509{
510    pub(super) inner: Option<Connection<T, S>>,
511}
512
513impl<I, B, S> UpgradeableConnection<I, S>
514where
515    S: HttpService<IncomingBody, ResBody = B>,
516    S::Error: Into<Box<dyn StdError + Send + Sync>>,
517    I: Read + Write + Unpin,
518    B: Body + 'static,
519    B::Error: Into<Box<dyn StdError + Send + Sync>>,
520{
521    /// Start a graceful shutdown process for this connection.
522    ///
523    /// This `Connection` should continue to be polled until shutdown
524    /// can finish.
525    pub fn graceful_shutdown(mut self: Pin<&mut Self>) {
526        // Connection (`inner`) is `None` if it was upgraded (and `poll` is `Ready`).
527        // In that case, we don't need to call `graceful_shutdown`.
528        if let Some(conn) = self.inner.as_mut() {
529            Pin::new(conn).graceful_shutdown()
530        }
531    }
532
533    /// Return the inner IO object, and additional information provided the connection
534    /// has not yet been upgraded.
535    pub fn into_parts(self) -> Option<Parts<I, S>> {
536        self.inner.map(|conn| conn.into_parts())
537    }
538}
539
540impl<I, B, S> Future for UpgradeableConnection<I, S>
541where
542    S: HttpService<IncomingBody, ResBody = B>,
543    S::Error: Into<Box<dyn StdError + Send + Sync>>,
544    I: Read + Write + Unpin + Send + 'static,
545    B: Body + 'static,
546    B::Error: Into<Box<dyn StdError + Send + Sync>>,
547{
548    type Output = crate::Result<()>;
549
550    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
551        if let Some(conn) = self.inner.as_mut() {
552            match ready!(Pin::new(&mut conn.conn).poll(cx)) {
553                Ok(proto::Dispatched::Shutdown) => Poll::Ready(Ok(())),
554                Ok(proto::Dispatched::Upgrade(pending)) => {
555                    let (io, buf, _) = self
556                        .inner
557                        .take()
558                        .expect("upgradeable server connection missing after upgrade")
559                        .conn
560                        .into_inner();
561                    pending.fulfill(Upgraded::new(io, buf));
562                    Poll::Ready(Ok(()))
563                }
564                Err(e) => Poll::Ready(Err(e)),
565            }
566        } else {
567            // inner is `None`, meaning the connection was upgraded, thus it's `Poll::Ready(Ok(()))`
568            Poll::Ready(Ok(()))
569        }
570    }
571}