1use crate::{
2 Service,
3 error::{BoxError, BoxErrorExt as _},
4 extensions::{Extensions, ExtensionsRef},
5 http::io::upgrade::Upgraded,
6 net::client::{
7 ConnectionError, ConnectionErrorKind, ConnectorService, EstablishedClientConnection,
8 ProxyRoute,
9 },
10 telemetry::tracing,
11};
12use pin_project_lite::pin_project;
13use std::{
14 fmt,
15 pin::Pin,
16 task::{self, Poll},
17};
18use tokio::io::{AsyncRead, AsyncWrite};
19
20#[derive(Debug, Clone)]
30pub struct ProxyStreamConnector<S, C> {
31 socks: S,
32 connect: C,
33}
34
35impl<S, C> ProxyStreamConnector<S, C> {
36 pub const fn new(socks: S, connect: C) -> Self {
39 Self { socks, connect }
40 }
41}
42
43impl<S, C, Input, Socks> Service<Input> for ProxyStreamConnector<S, C>
44where
45 S: ConnectorService<Input, Connection = Socks>,
46 C: ConnectorService<Input, Connection: Into<Upgraded>>,
47 Socks: Send + ExtensionsRef + 'static,
48 Input: ExtensionsRef + Send + 'static,
49{
50 type Output = EstablishedClientConnection<ProxyStream<Socks>, Input>;
51 type Error = ConnectionError;
52
53 async fn serve(&self, input: Input) -> Result<Self::Output, Self::Error> {
54 let Some(ProxyRoute::Proxy(proxy)) = input.extensions().get_ref::<ProxyRoute>() else {
55 return Err(ConnectionError::local(
56 BoxError::from_static_str("proxy stream connector: no proxied route is requested"),
57 ConnectionErrorKind::InvalidInput,
58 ));
59 };
60 let protocol = proxy.protocol.clone();
61 if protocol.is_socks5() {
62 tracing::trace!(?protocol, "proxy stream connector: socks5 proxy");
63 let EstablishedClientConnection { input, conn } = self.socks.connect(input).await?;
64 return Ok(EstablishedClientConnection {
65 input,
66 conn: ProxyStream::Socks { conn },
67 });
68 }
69 if protocol.is_http() {
70 tracing::trace!(?protocol, "proxy stream connector: connect tunnel");
71 let EstablishedClientConnection { input, conn } = self.connect.connect(input).await?;
72 return Ok(EstablishedClientConnection {
73 input,
74 conn: ProxyStream::Connect { conn: conn.into() },
75 });
76 }
77 Err(ConnectionError::transport(
78 BoxError::from_static_str("received unsupported proxy protocol"),
79 ConnectionErrorKind::Protocol,
80 )
81 .context_debug_field("protocol", protocol))
82 }
83}
84
85pin_project! {
86 #[project = ProxyStreamProj]
88 pub enum ProxyStream<S> {
89 Socks { #[pin] conn: S },
91 Connect { #[pin] conn: Upgraded },
93 }
94}
95
96impl<S: fmt::Debug> fmt::Debug for ProxyStream<S> {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 match self {
99 Self::Socks { conn } => f.debug_struct("Socks").field("conn", conn).finish(),
100 Self::Connect { conn } => f.debug_struct("Connect").field("conn", conn).finish(),
101 }
102 }
103}
104
105impl<S: ExtensionsRef> ExtensionsRef for ProxyStream<S> {
106 fn extensions(&self) -> &Extensions {
107 match self {
108 Self::Socks { conn } => conn.extensions(),
109 Self::Connect { conn } => conn.extensions(),
110 }
111 }
112}
113
114#[warn(clippy::missing_trait_methods)]
115impl<S: AsyncRead> AsyncRead for ProxyStream<S> {
116 fn poll_read(
117 self: Pin<&mut Self>,
118 cx: &mut task::Context<'_>,
119 buf: &mut tokio::io::ReadBuf<'_>,
120 ) -> Poll<std::io::Result<()>> {
121 match self.project() {
122 ProxyStreamProj::Socks { conn } => conn.poll_read(cx, buf),
123 ProxyStreamProj::Connect { conn } => conn.poll_read(cx, buf),
124 }
125 }
126}
127
128#[warn(clippy::missing_trait_methods)]
129impl<S: AsyncWrite> AsyncWrite for ProxyStream<S> {
130 fn poll_write(
131 self: Pin<&mut Self>,
132 cx: &mut task::Context<'_>,
133 buf: &[u8],
134 ) -> Poll<Result<usize, std::io::Error>> {
135 match self.project() {
136 ProxyStreamProj::Socks { conn } => conn.poll_write(cx, buf),
137 ProxyStreamProj::Connect { conn } => conn.poll_write(cx, buf),
138 }
139 }
140
141 fn poll_flush(
142 self: Pin<&mut Self>,
143 cx: &mut task::Context<'_>,
144 ) -> Poll<Result<(), std::io::Error>> {
145 match self.project() {
146 ProxyStreamProj::Socks { conn } => conn.poll_flush(cx),
147 ProxyStreamProj::Connect { conn } => conn.poll_flush(cx),
148 }
149 }
150
151 fn poll_shutdown(
152 self: Pin<&mut Self>,
153 cx: &mut task::Context<'_>,
154 ) -> Poll<Result<(), std::io::Error>> {
155 match self.project() {
156 ProxyStreamProj::Socks { conn } => conn.poll_shutdown(cx),
157 ProxyStreamProj::Connect { conn } => conn.poll_shutdown(cx),
158 }
159 }
160
161 fn is_write_vectored(&self) -> bool {
162 match self {
163 Self::Socks { conn } => conn.is_write_vectored(),
164 Self::Connect { conn } => conn.is_write_vectored(),
165 }
166 }
167
168 fn poll_write_vectored(
169 self: Pin<&mut Self>,
170 cx: &mut task::Context<'_>,
171 bufs: &[std::io::IoSlice<'_>],
172 ) -> Poll<Result<usize, std::io::Error>> {
173 match self.project() {
174 ProxyStreamProj::Socks { conn } => conn.poll_write_vectored(cx, bufs),
175 ProxyStreamProj::Connect { conn } => conn.poll_write_vectored(cx, bufs),
176 }
177 }
178}
179
180#[cfg(test)]
181mod tests {
182 use super::*;
183 use crate::http::client::proxy::HttpTunnelRoute;
184 use crate::net::client::{EstablishedProxyRoute, MaybeProxied, MaybeProxiedConnector};
185 use crate::{
186 ServiceInput,
187 http::proxy::PlaintextHttpProxyMode,
188 net::{Protocol, address::HostWithPort, client::ConnectRequest},
189 service::service_fn,
190 };
191
192 fn stream() -> ServiceInput<tokio::io::DuplexStream> {
193 let (io, _peer) = tokio::io::duplex(64);
194 ServiceInput::new(io)
195 }
196
197 fn streams<Input: Send + 'static>()
198 -> impl ConnectorService<Input, Connection = ServiceInput<tokio::io::DuplexStream>> {
199 service_fn(|input: Input| async move {
200 Ok::<_, ConnectionError>(EstablishedClientConnection {
201 input,
202 conn: stream(),
203 })
204 })
205 }
206
207 fn tunnels<Input: Send + 'static>() -> impl ConnectorService<Input, Connection = Upgraded> {
208 service_fn(|input: Input| async move {
209 Ok::<_, ConnectionError>(EstablishedClientConnection {
210 input,
211 conn: Upgraded::new(stream(), Default::default()),
212 })
213 })
214 }
215
216 fn no_stream<Input: Send + 'static>()
217 -> impl ConnectorService<Input, Connection = ServiceInput<tokio::io::DuplexStream>> {
218 unreachable()
219 }
220
221 fn no_tunnel<Input: Send + 'static>() -> impl ConnectorService<Input, Connection = Upgraded> {
222 unreachable()
223 }
224
225 fn unreachable<Input: Send + 'static, Conn: Send + ExtensionsRef + 'static>()
226 -> impl ConnectorService<Input, Connection = Conn> {
227 service_fn(|_: Input| async move {
228 Err::<EstablishedClientConnection<Conn, Input>, _>(ConnectionError::local(
229 BoxError::from_static_str("connector must not be used"),
230 ConnectionErrorKind::Unavailable,
231 ))
232 })
233 }
234
235 fn transport<D, S, C>(
236 direct: D,
237 socks: S,
238 connect: C,
239 ) -> MaybeProxiedConnector<D, ProxyStreamConnector<S, C>, HttpTunnelRoute> {
240 MaybeProxiedConnector::new(
241 direct,
242 ProxyStreamConnector::new(socks, connect),
243 HttpTunnelRoute::new(),
244 )
245 }
246
247 fn plaintext(route: Option<&str>, mode: Option<PlaintextHttpProxyMode>) -> ConnectRequest {
248 let input = ConnectRequest::new(HostWithPort::try_from("origin.example:80").unwrap())
249 .with_application_protocol(Protocol::HTTP);
250 if let Some(route) = route {
251 input
252 .extensions
253 .insert(ProxyRoute::Proxy(route.parse().unwrap()));
254 }
255 if let Some(mode) = mode {
256 input.extensions.insert(mode);
257 }
258 input
259 }
260
261 #[tokio::test]
262 async fn a_request_without_a_route_takes_a_stream_of_its_own() {
263 let connector = transport(streams(), no_stream(), no_tunnel());
264 let established = connector.connect(plaintext(None, None)).await.unwrap();
265
266 assert!(matches!(established.conn, MaybeProxied::Direct { .. }));
267 assert!(
268 !established
269 .conn
270 .extensions()
271 .contains::<EstablishedProxyRoute>(),
272 "no route was requested",
273 );
274 }
275
276 #[tokio::test]
277 async fn a_socks5_route_reaches_the_socks_connector() {
278 let connector = transport(no_stream(), streams(), no_tunnel());
279 let established = connector
280 .connect(plaintext(Some("socks5://proxy.example:1080"), None))
281 .await
282 .unwrap();
283
284 assert!(matches!(
285 established.conn,
286 MaybeProxied::Proxied {
287 conn: ProxyStream::Socks { .. }
288 }
289 ));
290 }
291
292 #[tokio::test]
293 async fn a_tunneled_http_route_reaches_the_connect_connector() {
294 let connector = transport(no_stream(), no_stream(), tunnels());
295 for input in [
296 plaintext(
297 Some("http://proxy.example:8080"),
298 Some(PlaintextHttpProxyMode::Tunnel),
299 ),
300 ConnectRequest::new(HostWithPort::try_from("origin.example:443").unwrap())
301 .with_application_protocol(Protocol::HTTPS),
302 ] {
303 input.extensions.insert(ProxyRoute::Proxy(
304 "http://proxy.example:8080".parse().unwrap(),
305 ));
306 let established = connector.connect(input).await.unwrap();
307 assert!(matches!(
308 established.conn,
309 MaybeProxied::Proxied {
310 conn: ProxyStream::Connect { .. }
311 }
312 ));
313 }
314 }
315
316 #[tokio::test]
317 async fn a_forwarded_request_keeps_the_stream_to_its_proxy_unclaimed() {
318 let connector = transport(streams(), no_stream(), no_tunnel());
319 let established = connector
320 .connect(plaintext(Some("http://proxy.example:8080"), None))
321 .await
322 .unwrap();
323
324 assert!(matches!(established.conn, MaybeProxied::Direct { .. }));
325 assert!(
326 !established
327 .conn
328 .extensions()
329 .contains::<EstablishedProxyRoute>(),
330 "the forward connector publishes the route of this connection",
331 );
332 }
333
334 #[cfg(feature = "socks5")]
335 #[test]
336 fn eager_socks5_accepts_combined_proxy_connection() {
337 use crate::{
338 graceful::WeakScope,
339 http::{
340 Body,
341 client::{ProxyConnector, ProxyConnectorParts},
342 },
343 net::{proxy::IoForwardService, test_utils::client::MockSocket},
344 proxy::socks5::server::{Connector as EagerSocks5Connector, Socks5Connector},
345 };
346
347 fn assert_socks5_connector<S, C: Socks5Connector<S>>(_: &C) {}
348
349 let scope = WeakScope::detached();
350 let ProxyConnectorParts { socks, connect, .. } = ProxyConnector::builder(scope.clone())
351 .with_default_tcp_connector()
352 .without_dns_connector()
353 .without_tls_support()
354 .with_default_http_connector::<Body>()
355 .without_connection_pool()
356 .with_socks5()
357 .with_http_connect()
358 .build()
359 .into_parts();
360 let connector = EagerSocks5Connector::new(
361 ProxyStreamConnector::new(socks, connect),
362 IoForwardService::new(scope),
363 );
364
365 assert_socks5_connector::<MockSocket, _>(&connector);
366 }
367
368 #[tokio::test]
369 async fn a_proxy_protocol_without_a_transport_is_refused() {
370 let connector = transport(no_stream(), no_stream(), no_tunnel());
371 let error = connector
372 .connect(plaintext(Some("ftp://proxy.example:21"), None))
373 .await
374 .unwrap_err();
375
376 assert!(
377 format!("{error:?}").contains("unsupported proxy protocol"),
378 "{error:?}"
379 );
380 }
381}