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