Skip to main content

hyper/client/conn/
http1.rs

1//! HTTP/1 client connections.
2
3use std::error::Error as StdError;
4use std::fmt;
5use std::future::Future;
6use std::pin::Pin;
7use std::task::{Context, Poll};
8
9use crate::rt::{Read, Write};
10use bytes::Bytes;
11use futures_core::ready;
12use http::{Request, Response};
13use httparse::ParserConfig;
14
15use super::super::dispatch::{self, TrySendError};
16use crate::body::{Body, Incoming as IncomingBody};
17use crate::proto;
18
19type Dispatcher<T, B> =
20    proto::dispatch::Dispatcher<proto::dispatch::Client<B>, B, T, proto::h1::ClientTransaction>;
21
22/// The sender side of an established connection.
23pub struct SendRequest<B> {
24    dispatch: dispatch::Sender<Request<B>, Response<IncomingBody>>,
25}
26
27/// Deconstructed parts of a `Connection`.
28///
29/// This allows taking apart a `Connection` at a later time, in order to
30/// reclaim the IO object, and additional related pieces.
31#[derive(Debug)]
32#[non_exhaustive]
33pub struct Parts<T> {
34    /// The original IO object used in the handshake.
35    pub io: T,
36    /// A buffer of bytes that have been read but not processed as HTTP.
37    ///
38    /// For instance, if the `Connection` is used for an HTTP upgrade request,
39    /// it is possible the server sent back the first bytes of the new protocol
40    /// along with the response upgrade.
41    ///
42    /// You will want to check for any existing bytes if you plan to continue
43    /// communicating on the IO object.
44    pub read_buf: Bytes,
45}
46
47/// A future that processes all HTTP state for the IO object.
48///
49/// In most cases, this should just be spawned into an executor, so that it
50/// can process incoming and outgoing messages, notice hangups, and the like.
51///
52/// Instances of this type are typically created via the [`handshake`] function.
53///
54/// # Drop behavior
55///
56/// Dropping the `Connection` will close the underlying IO resource.
57/// Any in-flight requests that have not received a response will be
58/// interrupted. If graceful shutdown is desired, poll the connection
59/// until it completes instead of dropping.
60#[must_use = "futures do nothing unless polled"]
61pub struct Connection<T, B>
62where
63    T: Read + Write,
64    B: Body + 'static,
65{
66    inner: Dispatcher<T, B>,
67}
68
69impl<T, B> Connection<T, B>
70where
71    T: Read + Write + Unpin,
72    B: Body + 'static,
73    B::Error: Into<Box<dyn StdError + Send + Sync>>,
74{
75    /// Return the inner IO object, and additional information.
76    ///
77    /// Only works for HTTP/1 connections. HTTP/2 connections will panic.
78    pub fn into_parts(self) -> Parts<T> {
79        let (io, read_buf, _) = self.inner.into_inner();
80        Parts { io, read_buf }
81    }
82
83    /// Poll the connection for completion, but without calling `shutdown`
84    /// on the underlying IO.
85    ///
86    /// This is useful to allow running a connection while doing an HTTP
87    /// upgrade. Once the upgrade is completed, the connection would be "done",
88    /// but it is not desired to actually shutdown the IO object. Instead you
89    /// would take it back using `into_parts`.
90    ///
91    /// Use [`poll_fn`](https://docs.rs/futures/0.1.25/futures/future/fn.poll_fn.html)
92    /// and [`try_ready!`](https://docs.rs/futures/0.1.25/futures/macro.try_ready.html)
93    /// to work with this function; or use the `without_shutdown` wrapper.
94    pub fn poll_without_shutdown(&mut self, cx: &mut Context<'_>) -> Poll<crate::Result<()>> {
95        self.inner.poll_without_shutdown(cx)
96    }
97
98    /// Prevent shutdown of the underlying IO object at the end of service the request,
99    /// instead run `into_parts`. This is a convenience wrapper over `poll_without_shutdown`.
100    ///
101    /// # Errors
102    ///
103    /// Returns an error if the connection encounters an error while being polled to completion.
104    pub async fn without_shutdown(self) -> crate::Result<Parts<T>> {
105        let mut conn = Some(self);
106        crate::common::future::poll_fn(move |cx| -> Poll<crate::Result<Parts<T>>> {
107            ready!(conn
108                .as_mut()
109                .expect("client connection polled after completion")
110                .poll_without_shutdown(cx))?;
111            Poll::Ready(Ok(conn
112                .take()
113                .expect("client connection missing before completion")
114                .into_parts()))
115        })
116        .await
117    }
118}
119
120/// A builder to configure an HTTP connection.
121///
122/// After setting options, the builder is used to create a handshake future.
123///
124/// **Note**: The default values of options are *not considered stable*. They
125/// are subject to change at any time.
126#[derive(Clone, Debug)]
127pub struct Builder {
128    h09_responses: bool,
129    h1_parser_config: ParserConfig,
130    h1_writev: Option<bool>,
131    h1_title_case_headers: bool,
132    h1_preserve_header_case: bool,
133    h1_max_headers: Option<usize>,
134    #[cfg(feature = "ffi")]
135    h1_preserve_header_order: bool,
136    h1_read_buf_exact_size: Option<usize>,
137    h1_max_buf_size: Option<usize>,
138}
139
140/// Returns a handshake future over some IO.
141///
142/// This is a shortcut for `Builder::new().handshake(io)`.
143/// See [`client::conn`](crate::client::conn) for more.
144///
145/// # Errors
146///
147/// Returns an error if the HTTP/1 connection handshake fails.
148pub async fn handshake<T, B>(io: T) -> crate::Result<(SendRequest<B>, Connection<T, B>)>
149where
150    T: Read + Write + Unpin,
151    B: Body + 'static,
152    B::Data: Send,
153    B::Error: Into<Box<dyn StdError + Send + Sync>>,
154{
155    Builder::new().handshake(io).await
156}
157
158// ===== impl SendRequest
159
160impl<B> SendRequest<B> {
161    /// Polls to determine whether this sender can be used yet for a request.
162    ///
163    /// If the associated connection is closed, this returns an Error.
164    pub fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<crate::Result<()>> {
165        self.dispatch.poll_ready(cx)
166    }
167
168    /// Waits until the dispatcher is ready.
169    ///
170    /// # Errors
171    ///
172    /// If the associated connection is closed, this returns an Error.
173    pub async fn ready(&mut self) -> crate::Result<()> {
174        crate::common::future::poll_fn(|cx| self.poll_ready(cx)).await
175    }
176
177    /// Checks if the connection is currently ready to send a request.
178    ///
179    /// # Note
180    ///
181    /// This is mostly a hint. Due to inherent latency of networks, it is
182    /// possible that even after checking this is ready, sending a request
183    /// may still fail because the connection was closed in the meantime.
184    pub fn is_ready(&self) -> bool {
185        self.dispatch.is_ready()
186    }
187
188    /// Checks if the connection side has been closed.
189    pub fn is_closed(&self) -> bool {
190        self.dispatch.is_closed()
191    }
192}
193
194impl<B> SendRequest<B>
195where
196    B: Body + 'static,
197{
198    /// Sends a `Request` on the associated connection.
199    ///
200    /// Returns a future that if successful, yields the `Response`.
201    ///
202    /// `req` must have a `Host` header.
203    ///
204    /// # Uri
205    ///
206    /// The `Uri` of the request is serialized as-is.
207    ///
208    /// - Usually you want origin-form (`/path?query`).
209    /// - For sending to an HTTP proxy, you want to send in absolute-form
210    ///   (`https://hyper.rs/guides`).
211    ///
212    /// This is however not enforced or validated and it is up to the user
213    /// of this method to ensure the `Uri` is correct for their intended purpose.
214    ///
215    /// # Cancel safety
216    ///
217    /// Dropping the returned future is the supported way to cancel an
218    /// in-flight HTTP/1 request. Because HTTP/1 has no in-protocol way to
219    /// abort a single request without affecting the shared connection,
220    /// hyper closes the underlying connection when a request future is
221    /// dropped before completion. Any subsequent calls on the same
222    /// [`SendRequest`] will return a `canceled` error.
223    ///
224    /// # Errors
225    ///
226    /// Returns an error if the connection is not ready or if an error occurs while
227    /// processing the request.
228    pub fn send_request(
229        &mut self,
230        req: Request<B>,
231    ) -> impl Future<Output = crate::Result<Response<IncomingBody>>> {
232        let sent = self.dispatch.send(req);
233
234        async move {
235            match sent {
236                Ok(rx) => match rx.await {
237                    Ok(Ok(resp)) => Ok(resp),
238                    Ok(Err(err)) => Err(err),
239                    // this is definite bug if it happens, but it shouldn't happen!
240                    Err(_canceled) => panic!("dispatch dropped without returning error"),
241                },
242                Err(_req) => {
243                    debug!("connection was not ready");
244                    Err(crate::Error::new_canceled().with("connection was not ready"))
245                }
246            }
247        }
248    }
249
250    /// Sends a `Request` on the associated connection.
251    ///
252    /// Returns a future that if successful, yields the `Response`.
253    ///
254    /// # Errors
255    ///
256    /// If there was an error before trying to serialize the request to the
257    /// connection, the message will be returned as part of this error.
258    #[allow(clippy::result_large_err)]
259    pub fn try_send_request(
260        &mut self,
261        req: Request<B>,
262    ) -> impl Future<Output = Result<Response<IncomingBody>, TrySendError<Request<B>>>> {
263        let sent = self.dispatch.try_send(req);
264        async move {
265            match sent {
266                Ok(rx) => match rx.await {
267                    Ok(Ok(res)) => Ok(res),
268                    Ok(Err(err)) => Err(err),
269                    // this is definite bug if it happens, but it shouldn't happen!
270                    Err(_) => panic!("dispatch dropped without returning error"),
271                },
272                Err(req) => {
273                    debug!("connection was not ready");
274                    let error = crate::Error::new_canceled().with("connection was not ready");
275                    Err(TrySendError {
276                        error,
277                        message: Some(req),
278                    })
279                }
280            }
281        }
282    }
283}
284
285impl<B> fmt::Debug for SendRequest<B> {
286    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287        f.debug_struct("SendRequest").finish()
288    }
289}
290
291// ===== impl Connection
292
293impl<T, B> Connection<T, B>
294where
295    T: Read + Write + Unpin + Send,
296    B: Body + 'static,
297    B::Error: Into<Box<dyn StdError + Send + Sync>>,
298{
299    /// Enable this connection to support higher-level HTTP upgrades.
300    ///
301    /// See [the `upgrade` module](crate::upgrade) for more.
302    pub fn with_upgrades(self) -> upgrades::UpgradeableConnection<T, B> {
303        upgrades::UpgradeableConnection { inner: Some(self) }
304    }
305}
306
307impl<T, B> fmt::Debug for Connection<T, B>
308where
309    T: Read + Write + fmt::Debug,
310    B: Body + 'static,
311{
312    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313        f.debug_struct("Connection").finish()
314    }
315}
316
317impl<T, B> Future for Connection<T, B>
318where
319    T: Read + Write + Unpin,
320    B: Body + 'static,
321    B::Data: Send,
322    B::Error: Into<Box<dyn StdError + Send + Sync>>,
323{
324    type Output = crate::Result<()>;
325
326    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
327        match ready!(Pin::new(&mut self.inner).poll(cx))? {
328            proto::Dispatched::Shutdown => Poll::Ready(Ok(())),
329            proto::Dispatched::Upgrade(pending) => {
330                // With no `Send` bound on `I`, we can't try to do
331                // upgrades here. In case a user was trying to use
332                // `upgrade` with this API, send a special
333                // error letting them know about that.
334                pending.manual();
335                Poll::Ready(Ok(()))
336            }
337        }
338    }
339}
340
341// ===== impl Builder
342
343impl Builder {
344    /// Creates a new connection builder.
345    #[inline]
346    pub fn new() -> Builder {
347        Builder {
348            h09_responses: false,
349            h1_writev: None,
350            h1_read_buf_exact_size: None,
351            h1_parser_config: ParserConfig::default(),
352            h1_title_case_headers: false,
353            h1_preserve_header_case: false,
354            h1_max_headers: None,
355            #[cfg(feature = "ffi")]
356            h1_preserve_header_order: false,
357            h1_max_buf_size: None,
358        }
359    }
360
361    /// Set whether HTTP/0.9 responses should be tolerated.
362    ///
363    /// Default is false.
364    pub fn http09_responses(&mut self, enabled: bool) -> &mut Builder {
365        self.h09_responses = enabled;
366        self
367    }
368
369    /// Set whether HTTP/1 connections will accept spaces between header names
370    /// and the colon that follow them in responses.
371    ///
372    /// You probably don't need this, here is what [RFC 7230 Section 3.2.4.] has
373    /// to say about it:
374    ///
375    /// > No whitespace is allowed between the header field-name and colon. In
376    /// > the past, differences in the handling of such whitespace have led to
377    /// > security vulnerabilities in request routing and response handling. A
378    /// > server MUST reject any received request message that contains
379    /// > whitespace between a header field-name and colon with a response code
380    /// > of 400 (Bad Request). A proxy MUST remove any such whitespace from a
381    /// > response message before forwarding the message downstream.
382    ///
383    /// Default is false.
384    ///
385    /// [RFC 7230 Section 3.2.4.]: https://tools.ietf.org/html/rfc7230#section-3.2.4
386    pub fn allow_spaces_after_header_name_in_responses(&mut self, enabled: bool) -> &mut Builder {
387        self.h1_parser_config
388            .allow_spaces_after_header_name_in_responses(enabled);
389        self
390    }
391
392    /// Set whether HTTP/1 connections will accept obsolete line folding for
393    /// header values.
394    ///
395    /// Newline codepoints (`\r` and `\n`) will be transformed to spaces when
396    /// parsing.
397    ///
398    /// You probably don't need this, here is what [RFC 7230 Section 3.2.4.] has
399    /// to say about it:
400    ///
401    /// > A server that receives an obs-fold in a request message that is not
402    /// > within a message/http container MUST either reject the message by
403    /// > sending a 400 (Bad Request), preferably with a representation
404    /// > explaining that obsolete line folding is unacceptable, or replace
405    /// > each received obs-fold with one or more SP octets prior to
406    /// > interpreting the field value or forwarding the message downstream.
407    ///
408    /// > A proxy or gateway that receives an obs-fold in a response message
409    /// > that is not within a message/http container MUST either discard the
410    /// > message and replace it with a 502 (Bad Gateway) response, preferably
411    /// > with a representation explaining that unacceptable line folding was
412    /// > received, or replace each received obs-fold with one or more SP
413    /// > octets prior to interpreting the field value or forwarding the
414    /// > message downstream.
415    ///
416    /// > A user agent that receives an obs-fold in a response message that is
417    /// > not within a message/http container MUST replace each received
418    /// > obs-fold with one or more SP octets prior to interpreting the field
419    /// > value.
420    ///
421    /// Default is false.
422    ///
423    /// [RFC 7230 Section 3.2.4.]: https://tools.ietf.org/html/rfc7230#section-3.2.4
424    pub fn allow_obsolete_multiline_headers_in_responses(&mut self, enabled: bool) -> &mut Builder {
425        self.h1_parser_config
426            .allow_obsolete_multiline_headers_in_responses(enabled);
427        self
428    }
429
430    /// Set whether HTTP/1 connections will silently ignored malformed header lines.
431    ///
432    /// If this is enabled and a header line does not start with a valid header
433    /// name, or does not include a colon at all, the line will be silently ignored
434    /// and no error will be reported.
435    ///
436    /// Default is false.
437    pub fn ignore_invalid_headers_in_responses(&mut self, enabled: bool) -> &mut Builder {
438        self.h1_parser_config
439            .ignore_invalid_headers_in_responses(enabled);
440        self
441    }
442
443    /// Set whether HTTP/1 connections should try to use vectored writes,
444    /// or always flatten into a single buffer.
445    ///
446    /// Note that setting this to false may mean more copies of body data,
447    /// but may also improve performance when an IO transport doesn't
448    /// support vectored writes well, such as most TLS implementations.
449    ///
450    /// Setting this to true will force hyper to use queued strategy,
451    /// which may eliminate unnecessary cloning on some TLS backends.
452    ///
453    /// Default is `auto`. In this mode hyper will try to guess which
454    /// mode to use.
455    pub fn writev(&mut self, enabled: bool) -> &mut Builder {
456        self.h1_writev = Some(enabled);
457        self
458    }
459
460    /// Set whether HTTP/1 connections will write header names as title case at
461    /// the socket level.
462    ///
463    /// Default is false.
464    pub fn title_case_headers(&mut self, enabled: bool) -> &mut Builder {
465        self.h1_title_case_headers = enabled;
466        self
467    }
468
469    /// Set whether to support preserving original header cases.
470    ///
471    /// Currently, this will record the original cases received, and store them
472    /// in a private extension on the `Response`. It will also look for and use
473    /// such an extension in any provided `Request`.
474    ///
475    /// Since the relevant extension is still private, there is no way to
476    /// interact with the original cases. The only effect this can have now is
477    /// to forward the cases in a proxy-like fashion.
478    ///
479    /// Default is false.
480    pub fn preserve_header_case(&mut self, enabled: bool) -> &mut Builder {
481        self.h1_preserve_header_case = enabled;
482        self
483    }
484
485    /// Set the maximum number of headers.
486    ///
487    /// When a response is received, the parser will reserve a buffer to store headers for optimal
488    /// performance.
489    ///
490    /// If client receives more headers than the buffer size, the error "message header too large"
491    /// is returned.
492    ///
493    /// Note that headers is allocated on the stack by default, which has higher performance. After
494    /// setting this value, headers will be allocated in heap memory, that is, heap memory
495    /// allocation will occur for each response, and there will be a performance drop of about 5%.
496    ///
497    /// Default is 100.
498    pub fn max_headers(&mut self, val: usize) -> &mut Self {
499        self.h1_max_headers = Some(val);
500        self
501    }
502
503    /// Set whether to support preserving original header order.
504    ///
505    /// Currently, this will record the order in which headers are received, and store this
506    /// ordering in a private extension on the `Response`. It will also look for and use
507    /// such an extension in any provided `Request`.
508    ///
509    /// Default is false.
510    #[cfg(feature = "ffi")]
511    pub fn preserve_header_order(&mut self, enabled: bool) -> &mut Builder {
512        self.h1_preserve_header_order = enabled;
513        self
514    }
515
516    /// Sets the exact size of the read buffer to *always* use.
517    ///
518    /// Note that setting this option unsets the `max_buf_size` option.
519    ///
520    /// Default is an adaptive read buffer.
521    pub fn read_buf_exact_size(&mut self, sz: Option<usize>) -> &mut Builder {
522        self.h1_read_buf_exact_size = sz;
523        self.h1_max_buf_size = None;
524        self
525    }
526
527    /// Set the maximum buffer size for the connection.
528    ///
529    /// Default is ~400kb.
530    ///
531    /// Note that setting this option unsets the `read_exact_buf_size` option.
532    ///
533    /// # Panics
534    ///
535    /// The minimum value allowed is 8192. This method panics if the passed `max` is less than the minimum.
536    pub fn max_buf_size(&mut self, max: usize) -> &mut Self {
537        assert!(
538            max >= proto::h1::MINIMUM_MAX_BUFFER_SIZE,
539            "the max_buf_size cannot be smaller than the minimum that h1 specifies."
540        );
541
542        self.h1_max_buf_size = Some(max);
543        self.h1_read_buf_exact_size = None;
544        self
545    }
546
547    /// Constructs a connection with the configured options and IO.
548    /// See [`client::conn`](crate::client::conn) for more.
549    ///
550    /// Note, if [`Connection`] is not `await`-ed, [`SendRequest`] will
551    /// do nothing.
552    ///
553    /// # Errors
554    ///
555    /// Returns an error if the HTTP/1connection handshake fails.
556    pub fn handshake<T, B>(
557        &self,
558        io: T,
559    ) -> impl Future<Output = crate::Result<(SendRequest<B>, Connection<T, B>)>>
560    where
561        T: Read + Write + Unpin,
562        B: Body + 'static,
563        B::Data: Send,
564        B::Error: Into<Box<dyn StdError + Send + Sync>>,
565    {
566        let opts = self.clone();
567
568        async move {
569            trace!("client handshake HTTP/1");
570
571            let (tx, rx) = dispatch::channel();
572            let mut conn = proto::Conn::new(io);
573            conn.set_h1_parser_config(opts.h1_parser_config);
574            if let Some(writev) = opts.h1_writev {
575                if writev {
576                    conn.set_write_strategy_queue();
577                } else {
578                    conn.set_write_strategy_flatten();
579                }
580            }
581            if opts.h1_title_case_headers {
582                conn.set_title_case_headers();
583            }
584            if opts.h1_preserve_header_case {
585                conn.set_preserve_header_case();
586            }
587            if let Some(max_headers) = opts.h1_max_headers {
588                conn.set_http1_max_headers(max_headers);
589            }
590            #[cfg(feature = "ffi")]
591            if opts.h1_preserve_header_order {
592                conn.set_preserve_header_order();
593            }
594
595            if opts.h09_responses {
596                conn.set_h09_responses();
597            }
598
599            if let Some(sz) = opts.h1_read_buf_exact_size {
600                conn.set_read_buf_exact_size(sz);
601            }
602            if let Some(max) = opts.h1_max_buf_size {
603                conn.set_max_buf_size(max);
604            }
605            let cd = proto::h1::dispatch::Client::new(rx);
606            let proto = proto::h1::Dispatcher::new(cd, conn);
607
608            Ok((SendRequest { dispatch: tx }, Connection { inner: proto }))
609        }
610    }
611}
612
613mod upgrades {
614    use super::{Connection, Context, Future, Parts, Pin, Poll, Read, StdError, Write};
615    use crate::body::Body;
616    use crate::proto::Dispatched;
617    use crate::upgrade::Upgraded;
618    use futures_core::ready;
619    // A future binding a connection with a Service with Upgrade support.
620    //
621    // This type is unnameable outside the crate.
622    #[must_use = "futures do nothing unless polled"]
623    #[allow(missing_debug_implementations)]
624    pub struct UpgradeableConnection<T, B>
625    where
626        T: Read + Write + Unpin + Send + 'static,
627        B: Body + 'static,
628        B::Error: Into<Box<dyn StdError + Send + Sync>>,
629    {
630        pub(super) inner: Option<Connection<T, B>>,
631    }
632
633    impl<I, B> Future for UpgradeableConnection<I, B>
634    where
635        I: Read + Write + Unpin + Send + 'static,
636        B: Body + 'static,
637        B::Data: Send,
638        B::Error: Into<Box<dyn StdError + Send + Sync>>,
639    {
640        type Output = crate::Result<()>;
641
642        fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
643            match ready!(Pin::new(
644                &mut self
645                    .inner
646                    .as_mut()
647                    .expect("upgradeable client connection polled after upgrade")
648                    .inner,
649            )
650            .poll(cx))
651            {
652                Ok(Dispatched::Shutdown) => Poll::Ready(Ok(())),
653                Ok(Dispatched::Upgrade(pending)) => {
654                    let Parts { io, read_buf } = self
655                        .inner
656                        .take()
657                        .expect("upgradeable client connection missing after upgrade")
658                        .into_parts();
659                    pending.fulfill(Upgraded::new(io, read_buf));
660                    Poll::Ready(Ok(()))
661                }
662                Err(e) => Poll::Ready(Err(e)),
663            }
664        }
665    }
666}