Skip to main content

trillium_client/proxy/
connect.rs

1use super::Proxy;
2use crate::{
3    Headers, KnownHeaderName, Status,
4    conn::{request_head, response_head},
5};
6use futures_lite::io::{AsyncRead, AsyncWrite, AsyncWriteExt};
7use std::{
8    borrow::Cow,
9    fmt,
10    io::{self, ErrorKind},
11    pin::Pin,
12    task::{Context, Poll},
13};
14use trillium_http::{Buffer, Error, HttpConfig, Result};
15use trillium_macros::{AsyncWrite, Transport};
16use trillium_server_common::{Connector, Destination, Transport, url};
17
18/// An error returned when an HTTP proxy rejects a `CONNECT` request.
19///
20/// Carried inside [`Error::Io`](crate::Error::Io) with [`io::ErrorKind::ConnectionRefused`]
21/// and recoverable via [`io::Error::get_ref`].
22#[derive(Clone, Debug)]
23pub struct ProxyConnectError {
24    code: u16,
25    headers: Headers,
26}
27
28impl ProxyConnectError {
29    /// The status returned by the proxy for the `CONNECT` request.
30    ///
31    /// A code that [`Status`] doesn't represent is reported as the `x00` status of its class, or
32    /// as [`Status::InternalServerError`] when it is outside 100–599.
33    #[must_use]
34    pub fn status(&self) -> Status {
35        Status::from_code_lossy(self.code)
36    }
37
38    /// The response headers returned by the proxy for the `CONNECT` request.
39    #[must_use]
40    pub const fn headers(&self) -> &Headers {
41        &self.headers
42    }
43}
44
45impl fmt::Display for ProxyConnectError {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        let status = self.status();
48        if status == self.code {
49            write!(f, "CONNECT proxy returned {status}")
50        } else {
51            write!(
52                f,
53                "CONNECT proxy returned {status} (status code {})",
54                self.code
55            )
56        }
57    }
58}
59
60impl std::error::Error for ProxyConnectError {}
61
62#[derive(Debug, AsyncWrite, Transport)]
63pub(crate) struct Tunnel<T = Box<dyn Transport>> {
64    #[async_write]
65    #[transport(except = negotiated_alpn)]
66    transport: T,
67    /// Bytes that arrived after the proxy's response head. They belong to the tunneled stream, so
68    /// they are read before anything further from `transport`.
69    leftover: Buffer,
70}
71
72impl<T: AsyncRead + Unpin> AsyncRead for Tunnel<T> {
73    fn poll_read(
74        mut self: Pin<&mut Self>,
75        cx: &mut Context<'_>,
76        buf: &mut [u8],
77    ) -> Poll<io::Result<usize>> {
78        let this = &mut *self;
79        if this.leftover.is_empty() {
80            return Pin::new(&mut this.transport).poll_read(cx, buf);
81        }
82        let len = buf.len().min(this.leftover.live_len());
83        buf[..len].copy_from_slice(&this.leftover[..len]);
84        this.leftover.ignore_front(len);
85        Poll::Ready(Ok(len))
86    }
87}
88
89impl<T> Tunnel<T> {
90    /// Any ALPN on `transport` was negotiated with the proxy, not with the tunneled origin.
91    const fn negotiated_alpn(&self) -> Option<Cow<'_, [u8]>> {
92        None
93    }
94}
95
96pub(crate) async fn open_tunnel<C: Connector + ?Sized>(
97    connector: &C,
98    proxy: &Proxy,
99    origin: &Destination,
100    config: &HttpConfig,
101) -> Result<Box<dyn Transport>> {
102    let request = build_connect_request(proxy, origin)?;
103    let mut transport = connector.connect_to(proxy.destination()?).await?;
104    let leftover = handshake(&mut transport, &request, config).await?;
105    Ok(Box::new(Tunnel {
106        transport,
107        leftover,
108    }))
109}
110
111/// The client writes `Host` itself, and a `CONNECT` request has no body and upgrades nothing.
112const RESERVED_CONNECT_HEADERS: [KnownHeaderName; 5] = [
113    KnownHeaderName::Host,
114    KnownHeaderName::ContentLength,
115    KnownHeaderName::TransferEncoding,
116    KnownHeaderName::Connection,
117    KnownHeaderName::Upgrade,
118];
119
120fn build_connect_request(proxy: &Proxy, origin: &Destination) -> Result<Vec<u8>> {
121    let authority = if let Some(host) = origin.host() {
122        let host =
123            url::Host::parse(host).map_err(|e| io::Error::new(ErrorKind::InvalidInput, e))?;
124        format!("{host}:{}", origin.port())
125    } else {
126        origin
127            .addrs()
128            .first()
129            .ok_or_else(|| {
130                io::Error::new(ErrorKind::InvalidInput, "missing tunnel origin address")
131            })?
132            .to_string()
133    };
134    if let Some((name, _)) = proxy.connect_headers().iter().find(|(name, _)| {
135        RESERVED_CONNECT_HEADERS
136            .iter()
137            .any(|reserved| name == *reserved)
138    }) {
139        return Err(Error::UnexpectedHeader(name.into_owned()));
140    }
141    let mut request = format!("CONNECT {authority} HTTP/1.1\r\nHost: {authority}\r\n").into_bytes();
142    request_head::write_headers(&mut request, proxy.connect_headers())?;
143    request.extend_from_slice(b"\r\n");
144    Ok(request)
145}
146
147/// Sends the CONNECT request and reads the proxy's response, returning any bytes that arrived
148/// after the final response head.
149async fn handshake<T>(transport: &mut T, request: &[u8], config: &HttpConfig) -> Result<Buffer>
150where
151    T: AsyncRead + AsyncWrite + Unpin,
152{
153    transport.write_all(request).await?;
154    transport.flush().await?;
155    let mut buffer = Buffer::default();
156    // `read_head` bounds each head; bounding them together also ends an endless run of interim
157    // responses.
158    let mut consumed = 0;
159    loop {
160        let head_len = response_head::read_head(transport, &mut buffer, config).await?;
161        consumed += head_len;
162        if consumed > config.head_max_len() {
163            return Err(Error::HeadersTooLong);
164        }
165        let head = response_head::parse_head(&buffer[..head_len])?;
166        buffer.ignore_front(head_len);
167        match head.code {
168            200..=299 => return Ok(buffer),
169            100..=199 if head.code != 101 => {}
170            code => {
171                let refusal = ProxyConnectError {
172                    code,
173                    headers: head.headers,
174                };
175                return Err(io::Error::new(ErrorKind::ConnectionRefused, refusal).into());
176            }
177        }
178    }
179}
180
181#[cfg(test)]
182mod tests;