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