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