1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
use crate::bytes;
use full_duplex_async_copy::full_duplex_copy;
use std::fmt::Debug;
use trillium::{async_trait, Conn, Handler, Upgrade};
use trillium_client::{Connector, ObjectSafeConnector};
use trillium_http::{Method, Status};
use url::Url;

#[derive(Debug)]
/// trillium handler to implement Connect proxying
pub struct ForwardProxyConnect(Box<dyn ObjectSafeConnector>);

#[derive(Debug)]
struct ForwardUpgrade(trillium_http::transport::BoxedTransport);

impl ForwardProxyConnect {
    /// construct a new ForwardProxyConnect
    pub fn new(connector: impl Connector) -> Self {
        Self(connector.boxed())
    }
}
#[async_trait]
impl Handler for ForwardProxyConnect {
    async fn run(&self, conn: Conn) -> Conn {
        if conn.method() == Method::Connect {
            let Ok(url) = Url::parse(&format!("http://{}", conn.path())) else {
                return conn.with_status(Status::BadRequest).halt();
            };

            if url.cannot_be_a_base() {
                return conn.with_status(Status::BadRequest).halt();
            }

            let Ok(tcp) = Connector::connect(&self.0, &url).await else {
                return conn.with_status(Status::BadGateway).halt();
            };

            conn.with_status(Status::Ok)
                .with_state(ForwardUpgrade(tcp))
                .halt()
        } else {
            conn
        }
    }

    fn has_upgrade(&self, upgrade: &Upgrade) -> bool {
        upgrade.state.contains::<ForwardUpgrade>()
    }

    async fn upgrade(&self, mut upgrade: Upgrade) {
        let Some(ForwardUpgrade(upstream)) = upgrade.state.take() else {
            return;
        };
        let downstream = upgrade;
        match full_duplex_copy(upstream, downstream).await {
            Err(e) => log::error!("upgrade stream error: {:?}", e),
            Ok((up, down)) => {
                log::debug!("streamed upgrade {} up and {} down", bytes(up), bytes(down))
            }
        }
    }
}