Skip to main content

rama/http/client/proxy_connector/
builder.rs

1use super::{ProxyConnector, ProxyMethodNotEnabled};
2use crate::{
3    Layer,
4    dns::client::{
5        DnsConnector, DnsConnectorLayer, GlobalDnsResolver, resolver::DnsAddressResolver,
6    },
7    extensions::{ExtensionsTransfer, SharedExtensionsTransfer},
8    graceful::WeakScope,
9    http::{
10        Body as ResponseBody, HeaderValue,
11        client::{
12            HttpConnector, HttpPooledConnector, HttpPooledConnectorConfig,
13            builder::{AltSvcConnectionLayer, DnsStage, HttpsDiscovery, TlsStage, TransportStage},
14            proxy::{HttpForwardProxyConnector, layer::HttpConnectProxyConnector},
15        },
16        header::IntoHeaderName,
17        layer::{
18            alt_svc::{AltSvc, AltSvcBody, AltSvcCache},
19            http_service::HttpServiceConnector,
20            map_response_body::MapResponseBody,
21        },
22        proxy::ProxyRequestBody,
23    },
24    net::{
25        client::{
26            ConnectRequest, ConnectorService, MapEstablishedConnection, PlaintextProxyOnly,
27            PlaintextProxyOnlyLayer, ProxyDialer,
28        },
29        stream::DefaultExtensionsTransfer,
30    },
31    tcp::client::service::TcpConnector,
32};
33use rama_utils::macros::generate_set_and_with;
34use std::marker::PhantomData;
35
36#[cfg(feature = "quic")]
37use crate::{
38    dns::client::resolver::{BoxDnsResolver, DnsResolver},
39    http::layer::https_service::{HttpsService, HttpsServiceLayer},
40};
41
42#[cfg(feature = "socks5")]
43use crate::proxy::socks5::{Socks5ConnectProxyConnector, Socks5ConnectProxyConnectorLayer};
44
45#[cfg(any(feature = "rustls", feature = "boring"))]
46use rama_tls::client::TlsClientConfig;
47
48#[cfg(feature = "boring")]
49use crate::tls::boring::client as boring_client;
50#[cfg(feature = "rustls")]
51use crate::tls::rustls::client as rustls_client;
52
53#[cfg(all(
54    feature = "masque",
55    feature = "quic",
56    any(feature = "boring", feature = "rustls")
57))]
58use crate::http::client::masque_quic_transport;
59#[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
60use crate::{
61    http::client::builder::{NoTcpConnector, QuicLeg, quic_tls_provider_or_unavailable},
62    quic::{
63        TransportConfig,
64        client::{ClientEndpoint, SharedQuicEndpoint},
65    },
66};
67
68#[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
69use {
70    crate::{
71        Service,
72        http::client::{
73            Http3Connector, Http3Transport, HttpTransportConnector, default_http3_builder,
74        },
75        net::client::{ConnectionError, EstablishedClientConnection},
76        quic::tls::QuicClientConfigProvider,
77    },
78    std::sync::Arc,
79};
80
81#[cfg(all(feature = "masque", feature = "quic"))]
82use crate::{
83    net::client::{MaybeProxiedConnector, ProxiedRoute},
84    proxy::masque::connect_udp::HttpConnectUdpProxyConnector,
85    udp::proxy::UdpConnector,
86};
87
88/// Builds the connections towards proxies of a client, which are client connections of
89/// their own and share nothing with the connections to origins.
90///
91/// Its stages are those of [`EasyHttpConnectorBuilder`] up to the HTTP connections, which
92/// is all a proxy needs: a proxy is never reached through another proxy. The proxy methods
93/// spoken on those connections follow, see [`ProxyMethodBuilder`].
94///
95/// [`EasyHttpConnectorBuilder`]: super::super::EasyHttpConnectorBuilder
96#[derive(Debug)]
97pub struct ProxyConnectorBuilder<C = (), S = (), D = ()> {
98    connector: C,
99    stage: S,
100    dns: D,
101    scope: WeakScope,
102}
103
104/// The stage of a [`ProxyConnectorBuilder`] which speaks HTTP to a proxy, in the body
105/// type `B` its connections send. It keeps the stream connector `T` towards proxies, which
106/// SOCKS5 dials over.
107#[derive(Debug)]
108pub struct ProxyHttpStage<T, B = ResponseBody> {
109    stream: T,
110    discovery: HttpsDiscovery,
111    _phantom: PhantomData<fn() -> B>,
112}
113
114impl<T, B> ProxyHttpStage<T, B> {
115    const fn new(stream: T, discovery: HttpsDiscovery) -> Self {
116        Self {
117            stream,
118            discovery,
119            _phantom: PhantomData,
120        }
121    }
122}
123
124impl ProxyConnectorBuilder {
125    /// Create a new [`ProxyConnectorBuilder`] whose connections and tunnels run in
126    /// `scope`; see [`ProxyConnector::builder`].
127    #[must_use]
128    pub fn new(scope: impl Into<WeakScope>) -> Self {
129        Self {
130            connector: (),
131            stage: (),
132            dns: (),
133            scope: scope.into(),
134        }
135    }
136}
137
138impl<C, S, D> ProxyConnectorBuilder<C, S, D> {
139    /// Add a custom connector around the connector built so far, keeping the stage.
140    ///
141    /// Before the HTTP stage, that is the stream connector of the TCP-based proxy
142    /// connections, SOCKS5 included. HTTP/3 proxies use the separate QUIC connector.
143    ///
144    /// After the HTTP stage, the layer wraps the HTTP connector towards proxies.
145    /// A pool added later sits above it, so the layer only runs when the pool
146    /// opens a new connection. SOCKS5 keeps the stream connector from before
147    /// and does not see this layer.
148    pub fn with_custom_connector<L: Layer<C>>(
149        self,
150        connector_layer: L,
151    ) -> ProxyConnectorBuilder<L::Service, S, D> {
152        self.map_connector(|connector| connector_layer.into_layer(connector))
153    }
154
155    /// Map the connector built so far, keeping the stage; see
156    /// [`Self::with_custom_connector`].
157    ///
158    /// Right after the TLS stage, before HTTP, this is how every connection to a proxy is
159    /// secured, also one whose address does not ask for TLS:
160    /// `.map_connector(|tls| tls.into_secure())`.
161    pub fn map_connector<C2>(
162        self,
163        map_fn: impl FnOnce(C) -> C2,
164    ) -> ProxyConnectorBuilder<C2, S, D> {
165        ProxyConnectorBuilder {
166            connector: map_fn(self.connector),
167            stage: self.stage,
168            dns: self.dns,
169            scope: self.scope,
170        }
171    }
172}
173
174impl<D> ProxyConnectorBuilder<(), (), D> {
175    /// Dial proxies over TCP, and over QUIC for an `h3://` proxy where this build has a
176    /// QUIC TLS backend.
177    #[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
178    #[must_use]
179    pub fn with_default_transport_connector(
180        self,
181    ) -> ProxyConnectorBuilder<TcpConnector, TransportStage<QuicLeg<SharedQuicEndpoint>>, D> {
182        let quic = QuicLeg::new(SharedQuicEndpoint::managed(self.scope.clone()));
183        self.with_transport(TcpConnector::new(), quic)
184    }
185
186    /// Dial proxies over TCP.
187    #[cfg(not(all(feature = "quic", any(feature = "boring", feature = "rustls"))))]
188    #[must_use]
189    pub fn with_default_transport_connector(
190        self,
191    ) -> ProxyConnectorBuilder<TcpConnector, TransportStage, D> {
192        self.with_default_tcp_connector()
193    }
194
195    /// Dial proxies over QUIC only, which makes every proxy but an `h3://` one unreachable.
196    #[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
197    #[must_use]
198    pub fn with_default_quic_connector(
199        self,
200    ) -> ProxyConnectorBuilder<NoTcpConnector, TransportStage<QuicLeg<SharedQuicEndpoint>>, D> {
201        let quic = QuicLeg::new(SharedQuicEndpoint::managed(self.scope.clone()));
202        self.with_transport(NoTcpConnector, quic)
203    }
204
205    /// Dial proxies over TCP only, which makes an `h3://` proxy unreachable.
206    #[must_use]
207    pub fn with_default_tcp_connector(
208        self,
209    ) -> ProxyConnectorBuilder<TcpConnector, TransportStage, D> {
210        self.with_transport(TcpConnector::new(), ())
211    }
212
213    /// Dial proxies over `connector` only: this first call is the only transport leg, so
214    /// no `h3://` proxy is reachable unless a QUIC leg is added with
215    /// [`ProxyConnectorBuilder::with_custom_quic_connector`].
216    pub fn with_custom_tcp_connector<T>(
217        self,
218        connector: T,
219    ) -> ProxyConnectorBuilder<T, TransportStage, D> {
220        self.with_transport(connector, ())
221    }
222
223    /// Dial proxies over the QUIC endpoints `endpoints` hands out only: this first call is
224    /// the only transport leg, which makes every proxy but an `h3://` one unreachable
225    /// unless a TCP leg is added with
226    /// [`ProxyConnectorBuilder::with_custom_tcp_connector`].
227    #[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
228    pub fn with_custom_quic_connector<E>(
229        self,
230        endpoints: E,
231    ) -> ProxyConnectorBuilder<NoTcpConnector, TransportStage<QuicLeg<E>>, D>
232    where
233        E: ConnectorService<ConnectRequest, Connection = ClientEndpoint>,
234    {
235        self.with_transport(NoTcpConnector, QuicLeg::new(endpoints))
236    }
237
238    fn with_transport<T, Q>(
239        self,
240        connector: T,
241        quic: Q,
242    ) -> ProxyConnectorBuilder<T, TransportStage<Q>, D> {
243        ProxyConnectorBuilder {
244            connector,
245            stage: TransportStage { quic },
246            dns: self.dns,
247            scope: self.scope,
248        }
249    }
250}
251
252#[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
253impl<T, E, D> ProxyConnectorBuilder<T, TransportStage<QuicLeg<E>>, D> {
254    /// Configure the QUIC transport of the connections to `h3://` proxies, replacing the
255    /// default one, which leaves a MASQUE proxy room for tunneled QUIC packets.
256    #[must_use]
257    pub fn with_quic_transport_config(mut self, transport: TransportConfig) -> Self {
258        self.stage.quic.transport = Some(transport);
259        self
260    }
261}
262
263#[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
264impl<T, Q, D> ProxyConnectorBuilder<T, TransportStage<Q>, D> {
265    /// Reach an `h3://` proxy over the QUIC endpoints `endpoints` hands out, instead of the
266    /// built-in ones or none: on a builder which already has a transport this swaps the
267    /// QUIC leg and keeps the TCP leg.
268    pub fn with_custom_quic_connector<E>(
269        self,
270        endpoints: E,
271    ) -> ProxyConnectorBuilder<T, TransportStage<QuicLeg<E>>, D>
272    where
273        E: ConnectorService<ConnectRequest, Connection = ClientEndpoint>,
274    {
275        ProxyConnectorBuilder {
276            connector: self.connector,
277            stage: TransportStage {
278                quic: QuicLeg::new(endpoints),
279            },
280            dns: self.dns,
281            scope: self.scope,
282        }
283    }
284
285    /// Reach an `h3://` proxy over the built-in QUIC endpoints, keeping the TCP leg chosen
286    /// before, such as a custom one.
287    #[must_use]
288    pub fn with_default_quic_connector(
289        self,
290    ) -> ProxyConnectorBuilder<T, TransportStage<QuicLeg<SharedQuicEndpoint>>, D> {
291        let endpoints = SharedQuicEndpoint::managed(self.scope.clone());
292        self.with_custom_quic_connector(endpoints)
293    }
294}
295
296impl<T, Q, D> ProxyConnectorBuilder<T, TransportStage<Q>, D> {
297    /// Dial proxies over `connector` instead of the TCP leg chosen before, keeping the
298    /// QUIC leg: `with_default_transport_connector().with_custom_tcp_connector(c)` dials
299    /// every proxy over `c` and keeps rama's default QUIC endpoints for an `h3://` one.
300    pub fn with_custom_tcp_connector<T2>(
301        self,
302        connector: T2,
303    ) -> ProxyConnectorBuilder<T2, TransportStage<Q>, D> {
304        ProxyConnectorBuilder {
305            connector,
306            stage: self.stage,
307            dns: self.dns,
308            scope: self.scope,
309        }
310    }
311
312    /// Resolve the addresses of proxies with the default resolver.
313    pub fn with_default_dns_connector(
314        self,
315    ) -> ProxyConnectorBuilder<DnsConnector<T>, DnsStage<Q>, DnsConnectorLayer> {
316        self.with_dns_address_resolver(GlobalDnsResolver::new())
317    }
318
319    /// Resolve the addresses of proxies with `resolver`, on both legs.
320    pub fn with_dns_address_resolver<R: DnsAddressResolver + Clone>(
321        self,
322        resolver: R,
323    ) -> ProxyConnectorBuilder<DnsConnector<T, R>, DnsStage<Q>, DnsConnectorLayer<R>> {
324        let layer = DnsConnectorLayer::with_resolver(resolver);
325        ProxyConnectorBuilder {
326            connector: layer.layer(self.connector),
327            stage: DnsStage {
328                quic: self.stage.quic,
329            },
330            dns: layer,
331            scope: self.scope,
332        }
333    }
334
335    /// Leave resolving the addresses of proxies to the transport connectors.
336    pub fn without_dns_connector(self) -> ProxyConnectorBuilder<T, DnsStage<Q>, ()> {
337        ProxyConnectorBuilder {
338            connector: self.connector,
339            stage: DnsStage {
340                quic: self.stage.quic,
341            },
342            dns: (),
343            scope: self.scope,
344        }
345    }
346}
347
348impl<T, Q, D> ProxyConnectorBuilder<T, DnsStage<Q>, D> {
349    #[cfg(feature = "boring")]
350    #[cfg_attr(docsrs, doc(cfg(feature = "boring")))]
351    /// Secure the connection to a proxy whose address asks for TLS, using boringssl.
352    ///
353    /// `config` secures both legs, but its ALPN only applies to TCP: the QUIC leg always
354    /// offers `h3`.
355    pub fn with_tls_support_using_boringssl(
356        self,
357        config: TlsClientConfig,
358    ) -> ProxyConnectorBuilder<boring_client::TlsConnector<T>, TlsStage<false, TlsClientConfig, Q>, D>
359    {
360        ProxyConnectorBuilder {
361            connector: boring_client::TlsConnector::auto(self.connector)
362                .with_base_config(config.clone()),
363            stage: TlsStage::using_boring(config, self.stage.quic),
364            dns: self.dns,
365            scope: self.scope,
366        }
367    }
368
369    #[cfg(feature = "rustls")]
370    #[cfg_attr(docsrs, doc(cfg(feature = "rustls")))]
371    /// Secure the connection to a proxy whose address asks for TLS, using rustls.
372    ///
373    /// `config` secures both legs, but its ALPN only applies to TCP: the QUIC leg always
374    /// offers `h3`.
375    pub fn with_tls_support_using_rustls(
376        self,
377        config: TlsClientConfig,
378    ) -> ProxyConnectorBuilder<rustls_client::TlsConnector<T>, TlsStage<false, TlsClientConfig, Q>, D>
379    {
380        ProxyConnectorBuilder {
381            connector: rustls_client::TlsConnector::auto(self.connector)
382                .with_base_config(config.clone()),
383            stage: TlsStage::using_rustls(config, self.stage.quic),
384            dns: self.dns,
385            scope: self.scope,
386        }
387    }
388
389    /// Secure the connection to a proxy with the given TLS connector; the QUIC leg gets no
390    /// TLS from it, so no `h3://` proxy is reachable.
391    ///
392    /// It must attach `rama_tls::client::NegotiatedTlsParameters` to the connections it
393    /// secures: rama uses this as positive proof that TLS was negotiated, and sends nothing
394    /// to an `https://` proxy without it.
395    pub fn with_custom_tls_connector<L: Layer<T>>(
396        self,
397        connector_layer: L,
398    ) -> ProxyConnectorBuilder<L::Service, TlsStage<false, (), Q>, D> {
399        ProxyConnectorBuilder {
400            connector: connector_layer.into_layer(self.connector),
401            stage: TlsStage::without_tls(self.stage.quic),
402            dns: self.dns,
403            scope: self.scope,
404        }
405    }
406
407    core::cfg_select! {
408        feature = "boring" => {
409            /// Secure the connection to a proxy whose address asks for TLS, with the TLS
410            /// implementation this build of rama prefers.
411            pub fn with_default_tls_support(
412                self,
413                config: TlsClientConfig,
414            ) -> ProxyConnectorBuilder<
415                boring_client::TlsConnector<T>,
416                TlsStage<false, TlsClientConfig, Q>,
417                D,
418            > {
419                self.with_tls_support_using_boringssl(config)
420            }
421        }
422        feature = "rustls" => {
423            /// Secure the connection to a proxy whose address asks for TLS, with the TLS
424            /// implementation this build of rama prefers.
425            pub fn with_default_tls_support(
426                self,
427                config: TlsClientConfig,
428            ) -> ProxyConnectorBuilder<
429                rustls_client::TlsConnector<T>,
430                TlsStage<false, TlsClientConfig, Q>,
431                D,
432            > {
433                self.with_tls_support_using_rustls(config)
434            }
435        }
436        _ => {}
437    }
438
439    /// Reach proxies in plaintext only: an `https://` or `h3://` proxy is refused before
440    /// it is dialed.
441    pub fn without_tls_support(
442        self,
443    ) -> ProxyConnectorBuilder<PlaintextProxyOnly<T>, TlsStage<false, (), Q>, D> {
444        ProxyConnectorBuilder {
445            connector: PlaintextProxyOnlyLayer::new().into_layer(self.connector),
446            stage: TlsStage::without_tls(self.stage.quic),
447            dns: self.dns,
448            scope: self.scope,
449        }
450    }
451}
452
453impl<T: Clone, Tls, Q, D> ProxyConnectorBuilder<T, TlsStage<false, Tls, Q>, D> {
454    fn into_http_stage<C, B>(
455        self,
456        discovery: HttpsDiscovery,
457        http: impl FnOnce(T) -> C,
458    ) -> ProxyConnectorBuilder<C, ProxyHttpStage<T, B>, D> {
459        ProxyConnectorBuilder {
460            connector: http(self.connector.clone()),
461            stage: ProxyHttpStage::new(self.connector, discovery),
462            dns: self.dns,
463            scope: self.scope,
464        }
465    }
466
467    fn http_connector<B>(
468        self,
469        discovery: HttpsDiscovery,
470    ) -> ProxyConnectorBuilder<HttpConnector<T, ProxyRequestBody<B>>, ProxyHttpStage<T, B>, D> {
471        let scope = self.scope.clone();
472        self.into_http_stage(discovery, |stream| HttpConnector::new(stream, scope))
473    }
474
475    /// Speak HTTP to a proxy over a connector of your own, built on the connections dialed
476    /// so far, instead of the one [`Self::with_default_http_connector`] builds; the QUIC leg
477    /// is left out.
478    ///
479    /// `B` is the body type sent to a proxy, which is the one the client serves origins with.
480    /// Its connections report the HTTP version they speak in a `TargetHttpVersion`, as
481    /// `HttpConnector` does: a proxy address that names a version is checked against it.
482    pub fn with_custom_http_connector<B, L: Layer<T>>(
483        self,
484        connector_layer: L,
485    ) -> ProxyConnectorBuilder<L::Service, ProxyHttpStage<T, B>, D> {
486        self.into_http_stage(HttpsDiscovery::default(), |stream| {
487            connector_layer.into_layer(stream)
488        })
489    }
490}
491
492impl<T: Clone, Q, D> ProxyConnectorBuilder<T, TlsStage<false, (), Q>, D> {
493    /// Speak HTTP to a proxy over the TCP leg, in the version its [`ProxyAddress`] asks for.
494    /// Without TLS there is no HTTP/3 proxy: that runs over QUIC, which is always secure.
495    ///
496    /// `B` is the body type sent to a proxy, which is the one the client serves origins with.
497    ///
498    /// [`ProxyAddress`]: rama_net::address::ProxyAddress
499    pub fn with_default_http_connector<B>(
500        self,
501    ) -> ProxyConnectorBuilder<HttpConnector<T, ProxyRequestBody<B>>, ProxyHttpStage<T, B>, D> {
502        self.http_connector(HttpsDiscovery::default())
503    }
504}
505
506#[cfg(any(feature = "boring", feature = "rustls"))]
507impl<T: Clone, D> ProxyConnectorBuilder<T, TlsStage<false, TlsClientConfig, ()>, D> {
508    /// Speak HTTP to a proxy over the TCP leg, in the version its [`ProxyAddress`] asks for;
509    /// there is no QUIC leg for an `h3://` proxy.
510    ///
511    /// `B` is the body type sent to a proxy, which is the one the client serves origins with.
512    ///
513    /// [`ProxyAddress`]: rama_net::address::ProxyAddress
514    pub fn with_default_http_connector<B>(
515        self,
516    ) -> ProxyConnectorBuilder<HttpConnector<T, ProxyRequestBody<B>>, ProxyHttpStage<T, B>, D> {
517        let discovery = HttpsDiscovery::default().with_tls(&self.stage.tls, false);
518        self.http_connector(discovery)
519    }
520}
521
522#[cfg(all(feature = "quic", any(feature = "boring", feature = "rustls")))]
523#[cfg_attr(docsrs, doc(cfg(feature = "quic")))]
524impl<T: Clone, D, E> ProxyConnectorBuilder<T, TlsStage<false, TlsClientConfig, QuicLeg<E>>, D> {
525    /// Build the QUIC TLS configurations through `provider` instead of the backend the
526    /// TLS stage selected, so the QUIC leg can use another backend than the TCP leg.
527    #[must_use]
528    pub fn with_quic_tls_provider(mut self, provider: Arc<dyn QuicClientConfigProvider>) -> Self {
529        self.stage.quic_tls = Some(provider);
530        self
531    }
532
533    /// Speak HTTP to a proxy in the version its [`ProxyAddress`] asks for: over the TCP leg,
534    /// or over the QUIC leg for an `h3://` proxy, on the TLS of the stage before this one
535    /// and the same DNS policy for both.
536    ///
537    /// `B` is the body type sent to a proxy, which is the one the client serves origins with.
538    ///
539    /// [`ProxyAddress`]: rama_net::address::ProxyAddress
540    pub fn with_default_http_connector<B>(
541        self,
542    ) -> ProxyConnectorBuilder<
543        HttpConnector<HttpTransportConnector<T, D::Service>, ProxyRequestBody<B>>,
544        ProxyHttpStage<T, B>,
545        D,
546    >
547    where
548        E: ConnectorService<ConnectRequest, Connection = ClientEndpoint> + Clone,
549        D: Layer<Http3Connector<E>>,
550        D::Service: Service<
551                ConnectRequest,
552                Output = EstablishedClientConnection<Http3Transport, ConnectRequest>,
553                Error = ConnectionError,
554            > + Send
555            + Sync
556            + 'static,
557    {
558        // A MASQUE proxy carries tunneled QUIC packets on its own HTTP/3 connection, which
559        // needs room for them.
560        #[cfg(feature = "masque")]
561        let transport = Some(
562            self.stage
563                .quic
564                .transport
565                .clone()
566                .unwrap_or_else(masque_quic_transport),
567        );
568        #[cfg(not(feature = "masque"))]
569        let transport = self.stage.quic.transport.clone();
570        let provider = quic_tls_provider_or_unavailable(self.stage.quic_tls.clone());
571        #[expect(
572            clippy::expect_used,
573            reason = "the built-in HTTP/3 configuration is always valid"
574        )]
575        let quic = default_http3_builder(self.scope.clone(), self.stage.tls.clone(), provider)
576            .with_endpoints(self.stage.quic.endpoints.clone())
577            .maybe_with_transport(transport)
578            .build_lazy()
579            .expect("built-in HTTP/3 configuration");
580        let quic = self.dns.layer(quic);
581        let discovery = HttpsDiscovery::default().with_tls(&self.stage.tls, false);
582        let scope = self.scope.clone();
583        self.into_http_stage(discovery, |stream| {
584            HttpConnector::new(stream, scope).with_http3_connector(quic)
585        })
586    }
587}
588
589impl<T, C, B, D> ProxyConnectorBuilder<C, ProxyHttpStage<T, B>, D>
590where
591    C: ConnectorService<ConnectRequest>,
592{
593    /// Pool the HTTP connections to a proxy with rama's defaults, so the tunnels and
594    /// forwarded requests through one proxy share its HTTP/2 and HTTP/3 connections.
595    ///
596    /// Outside the pool sit HTTPS-record discovery and Alt-Svc, as on an origin, so an
597    /// `https://` proxy without a version is reached over HTTP/3 when it advertises it.
598    pub fn with_default_connection_pool(
599        self,
600    ) -> ProxyMethodBuilder<T, ProxyServiceConnector<HttpPooledConnector<C>>, B> {
601        self.with_connection_pool(HttpPooledConnectorConfig::default())
602    }
603
604    /// [`Self::with_default_connection_pool`], with the given pool configuration.
605    pub fn with_connection_pool(
606        self,
607        config: HttpPooledConnectorConfig,
608    ) -> ProxyMethodBuilder<T, ProxyServiceConnector<HttpPooledConnector<C>>, B> {
609        let http = config.build_connector(self.connector);
610        let http = proxy_service_connector(http, self.stage.discovery);
611        ProxyMethodBuilder::new(self.stage.stream, http, self.scope)
612    }
613
614    /// Give every tunnel and forwarded request a connection to the proxy of its own, with
615    /// the discovery and Alt-Svc of [`Self::with_default_connection_pool`].
616    pub fn without_connection_pool(self) -> ProxyMethodBuilder<T, ProxyServiceConnector<C>, B> {
617        let http = proxy_service_connector(self.connector, self.stage.discovery);
618        ProxyMethodBuilder::new(self.stage.stream, http, self.scope)
619    }
620}
621
622#[cfg(feature = "quic")]
623type ProxyServiceSelector<C> = HttpsService<HttpServiceConnector<C>, BoxDnsResolver>;
624#[cfg(not(feature = "quic"))]
625type ProxyServiceSelector<C> = HttpServiceConnector<C>;
626
627/// The HTTP connector towards proxies the pool stage of a [`ProxyConnectorBuilder`] builds:
628/// `C` with HTTPS-record discovery and Alt-Svc around it.
629pub type ProxyServiceConnector<C> =
630    MapEstablishedConnection<ProxyServiceSelector<C>, ProxyAltSvcConnectionLayer>;
631
632fn proxy_service_connector<C>(connector: C, discovery: HttpsDiscovery) -> ProxyServiceConnector<C> {
633    let cache = AltSvcCache::default();
634    let connector = HttpServiceConnector::new(connector).with_cache(cache.clone());
635    #[cfg(feature = "quic")]
636    let connector = discovery.layer.with_cache(cache.clone()).layer(connector);
637    #[cfg(not(feature = "quic"))]
638    let _ = discovery;
639    MapEstablishedConnection::new(
640        connector,
641        ProxyAltSvcConnectionLayer {
642            alt_svc: AltSvcConnectionLayer { cache: Some(cache) },
643        },
644    )
645}
646
647/// [`AltSvcConnectionLayer`] for a connection to a proxy, whose responses the proxy
648/// methods read as plain [`ResponseBody`]s.
649#[doc(hidden)]
650#[derive(Clone, Debug)]
651pub struct ProxyAltSvcConnectionLayer {
652    alt_svc: AltSvcConnectionLayer,
653}
654
655impl<S> Layer<S> for ProxyAltSvcConnectionLayer {
656    type Service = MapResponseBody<AltSvc<S>, fn(AltSvcBody<ResponseBody>) -> ResponseBody>;
657
658    fn layer(&self, inner: S) -> Self::Service {
659        MapResponseBody::into_boxed_streaming_body(self.alt_svc.layer(inner))
660    }
661}
662
663/// The proxy methods of a [`ProxyConnector`], over the connections towards proxies an
664/// [`ProxyConnectorBuilder`] built: `T` dials a stream to a proxy, `C` speaks HTTP to
665/// one in the body type `B`.
666///
667/// A method which is not enabled refuses the routes asking for it.
668#[derive(Debug)]
669pub struct ProxyMethodBuilder<
670    T,
671    C,
672    B = ResponseBody,
673    Socks = ProxyMethodNotEnabled<T>,
674    Connect = ProxyMethodNotEnabled<C>,
675    ConnectUdp = ProxyConnectUdpNotEnabled<C, B>,
676    Forward = ProxyMethodNotEnabled<C>,
677> {
678    stream: T,
679    http: C,
680    scope: WeakScope,
681    socks: Socks,
682    connect: Connect,
683    connect_udp: ConnectUdp,
684    forward: Forward,
685    extensions_transfer: SharedExtensionsTransfer,
686    _phantom: PhantomData<fn() -> B>,
687}
688
689impl<T, C, B> ProxyMethodBuilder<T, ProxyServiceConnector<C>, B> {
690    fn service_selector_mut(&mut self) -> &mut HttpServiceConnector<C> {
691        let connector = self.http.get_mut();
692        #[cfg(feature = "quic")]
693        let connector = connector.get_mut();
694        connector
695    }
696
697    /// Configure HTTP service selection towards proxies, including attempt timeouts and
698    /// budgets.
699    #[must_use]
700    pub fn configure_http_service(
701        mut self,
702        configure: impl FnOnce(&mut HttpServiceConnector<C>),
703    ) -> Self {
704        configure(self.service_selector_mut());
705        self
706    }
707
708    #[cfg(feature = "quic")]
709    /// Disable HTTPS discovery of proxies while retaining independently configured Alt-Svc.
710    #[must_use]
711    pub fn without_https_discovery(mut self) -> Self {
712        self.http.get_mut().config_mut().set_enabled(false);
713        self
714    }
715
716    #[cfg(feature = "quic")]
717    /// Enable HTTPS discovery of proxies with this resolver for HTTPS and A/AAAA records.
718    #[must_use]
719    pub fn with_https_resolver<R: DnsResolver>(mut self, resolver: R) -> Self {
720        let config = self.http.get_mut().config_mut();
721        *config = config
722            .clone()
723            .with_resolver(BoxDnsResolver::new(resolver))
724            .with_enabled(true);
725        self
726    }
727
728    #[cfg(feature = "quic")]
729    /// Configure the HTTPS discovery layer towards proxies.
730    #[must_use]
731    pub fn configure_https_discovery(
732        mut self,
733        configure: impl FnOnce(&mut HttpsServiceLayer<BoxDnsResolver>),
734    ) -> Self {
735        configure(self.http.get_mut().config_mut());
736        self
737    }
738
739    /// Disable advertised alternatives and response learning towards proxies.
740    #[must_use]
741    pub fn without_alt_svc(self) -> Self {
742        self.maybe_with_alt_svc_cache(None)
743    }
744
745    generate_set_and_with! {
746        /// The Alt-Svc cache of the connections towards proxies; `None` disables Alt-Svc
747        /// only. HTTPS-record discovery is configured separately.
748        pub fn alt_svc_cache(mut self, cache: Option<AltSvcCache>) -> Self {
749            self.service_selector_mut().maybe_set_cache(cache.clone());
750            #[cfg(feature = "quic")]
751            self.http.get_mut().config_mut().maybe_set_cache(cache.clone());
752            self.http.layer_mut().alt_svc.cache = cache;
753            self
754        }
755    }
756}
757
758impl<T, C, B> ProxyMethodBuilder<T, C, B> {
759    /// Add a custom connector around the HTTP connector towards proxies that the HTTP proxy
760    /// methods added next share: above the pool when there is one.
761    ///
762    /// It runs for every dial, so a layer that sets a
763    /// [`ConnectorTarget`](crate::net::client::ConnectorTarget), such as a load balancer,
764    /// decides which pooled connection a dial gets: the pool keys on it. Such a target is an
765    /// explicit endpoint, so HTTPS discovery and Alt-Svc are skipped for it.
766    ///
767    /// Configure HTTP service selection, HTTPS discovery and Alt-Svc
768    /// (`configure_http_service`, `without_https_discovery`, `alt_svc_cache` and the like)
769    /// before this call: they are not available after it.
770    pub fn with_custom_connector<L: Layer<C>>(
771        self,
772        connector_layer: L,
773    ) -> ProxyMethodBuilder<T, L::Service, B> {
774        self.map_connector(|connector| connector_layer.into_layer(connector))
775    }
776
777    /// Map the HTTP connector towards proxies; see [`Self::with_custom_connector`].
778    pub fn map_connector<C2>(self, map_fn: impl FnOnce(C) -> C2) -> ProxyMethodBuilder<T, C2, B> {
779        let mut builder = ProxyMethodBuilder::new(self.stream, map_fn(self.http), self.scope);
780        builder.extensions_transfer = self.extensions_transfer;
781        builder
782    }
783
784    fn new(stream: T, http: C, scope: WeakScope) -> Self {
785        Self {
786            connect_udp: connect_udp_not_enabled(&scope),
787            stream,
788            http,
789            scope,
790            socks: ProxyMethodNotEnabled::SOCKS5,
791            connect: ProxyMethodNotEnabled::HTTP_CONNECT,
792            forward: ProxyMethodNotEnabled::HTTP_FORWARD,
793            extensions_transfer: DefaultExtensionsTransfer::new().into_shared(),
794            _phantom: PhantomData,
795        }
796    }
797
798    generate_set_and_with! {
799        /// Set what a tunnel opened by any of the methods added next keeps from the proxy
800        /// connection it is nested on.
801        ///
802        /// Defaults to [`DefaultExtensionsTransfer`]. Chain transfers with
803        /// [`ExtensionsTransfer::and`] to also carry your own connection-scoped
804        /// extension types across every tunnel.
805        pub fn extensions_transfer(mut self, transfer: impl ExtensionsTransfer) -> Self {
806            self.extensions_transfer = transfer.into_shared();
807            self
808        }
809    }
810
811    /// Support every proxy protocol this build of rama has, with its defaults: SOCKS5
812    /// (`socks5` feature), HTTP CONNECT and forwarding, and CONNECT-UDP (`masque` and
813    /// `quic` features). Pick a subset with `with_socks5`, `with_http_connect`,
814    /// `with_http_forward` and `with_http_connect_udp`.
815    pub fn with_all_proxy_protocols(
816        self,
817    ) -> ProxyMethodBuilder<
818        T,
819        C,
820        B,
821        ProxySocksMethod<T>,
822        HttpConnectProxyConnector<ProxyDialer<C>, ProxyRequestBody<B>>,
823        ProxyConnectUdpMethod<C, B>,
824        HttpForwardProxyConnector<ProxyDialer<C>>,
825    >
826    where
827        T: Clone,
828        C: Clone,
829    {
830        #[cfg(feature = "socks5")]
831        let builder = self.with_socks5();
832        #[cfg(not(feature = "socks5"))]
833        let builder = self;
834        let builder = builder.with_http_connect();
835        #[cfg(all(feature = "masque", feature = "quic"))]
836        let builder = builder.with_http_connect_udp();
837        builder.with_http_forward()
838    }
839}
840
841impl<T, C, B, Socks, Connect, ConnectUdp, Forward>
842    ProxyMethodBuilder<T, C, B, Socks, Connect, ConnectUdp, Forward>
843{
844    #[cfg(feature = "socks5")]
845    #[cfg_attr(docsrs, doc(cfg(feature = "socks5")))]
846    /// Reach the origin of a `socks5://` or `socks5h://` route over a stream its proxy
847    /// opens for it.
848    pub fn with_socks5(
849        self,
850    ) -> ProxyMethodBuilder<
851        T,
852        C,
853        B,
854        Socks5ConnectProxyConnector<ProxyDialer<T>>,
855        Connect,
856        ConnectUdp,
857        Forward,
858    >
859    where
860        T: Clone,
861    {
862        let socks = Socks5ConnectProxyConnectorLayer::default()
863            .with_extensions_transfer(self.extensions_transfer.clone())
864            .into_layer(self.stream.clone());
865        self.with_socks(socks)
866    }
867
868    /// Open a tunnel to the origin over an HTTP proxy with CONNECT.
869    pub fn with_http_connect(
870        self,
871    ) -> ProxyMethodBuilder<
872        T,
873        C,
874        B,
875        Socks,
876        HttpConnectProxyConnector<ProxyDialer<C>, ProxyRequestBody<B>>,
877        ConnectUdp,
878        Forward,
879    >
880    where
881        C: Clone,
882    {
883        let connect = HttpConnectProxyConnector::new(self.http.clone())
884            .with_extensions_transfer(self.extensions_transfer.clone());
885        self.with_connect(connect)
886    }
887
888    #[cfg(all(feature = "masque", feature = "quic"))]
889    #[cfg_attr(docsrs, doc(cfg(all(feature = "masque", feature = "quic"))))]
890    /// Open a datagram tunnel to the origin over an HTTP proxy with CONNECT-UDP
891    /// ([RFC 9298]), for the QUIC endpoint of an HTTP/3 origin reached through one. Every
892    /// other datagram request takes a UDP socket of its own.
893    ///
894    /// [RFC 9298]: https://datatracker.ietf.org/doc/html/rfc9298
895    pub fn with_http_connect_udp(
896        self,
897    ) -> ProxyMethodBuilder<T, C, B, Socks, Connect, ProxyConnectUdpMethod<C, B>, Forward>
898    where
899        C: Clone,
900    {
901        let connect_udp = HttpConnectUdpProxyConnector::new(self.http.clone(), self.scope.clone())
902            .with_extensions_transfer(self.extensions_transfer.clone());
903        self.with_connect_udp(MaybeProxiedConnector::new(
904            UdpConnector::new(),
905            connect_udp,
906            ProxiedRoute::new(),
907        ))
908    }
909
910    /// Have an HTTP proxy forward a plaintext request to its origin, over the HTTP
911    /// connection to that proxy.
912    pub fn with_http_forward(
913        self,
914    ) -> ProxyMethodBuilder<
915        T,
916        C,
917        B,
918        Socks,
919        Connect,
920        ConnectUdp,
921        HttpForwardProxyConnector<ProxyDialer<C>>,
922    >
923    where
924        C: Clone,
925    {
926        let forward = HttpForwardProxyConnector::new(self.http.clone());
927        self.with_forward(forward)
928    }
929
930    /// The [`ProxyConnector`] of the methods enabled so far.
931    pub fn build(self) -> ProxyConnector<Socks, Connect, ConnectUdp, Forward> {
932        ProxyConnector::from_methods(self.socks, self.connect, self.connect_udp, self.forward)
933    }
934
935    #[cfg(feature = "socks5")]
936    fn with_socks<S2>(
937        self,
938        socks: S2,
939    ) -> ProxyMethodBuilder<T, C, B, S2, Connect, ConnectUdp, Forward> {
940        ProxyMethodBuilder {
941            stream: self.stream,
942            http: self.http,
943            scope: self.scope,
944            socks,
945            connect: self.connect,
946            connect_udp: self.connect_udp,
947            forward: self.forward,
948            extensions_transfer: self.extensions_transfer,
949            _phantom: PhantomData,
950        }
951    }
952
953    fn with_connect<C2>(
954        self,
955        connect: C2,
956    ) -> ProxyMethodBuilder<T, C, B, Socks, C2, ConnectUdp, Forward> {
957        ProxyMethodBuilder {
958            stream: self.stream,
959            http: self.http,
960            scope: self.scope,
961            socks: self.socks,
962            connect,
963            connect_udp: self.connect_udp,
964            forward: self.forward,
965            extensions_transfer: self.extensions_transfer,
966            _phantom: PhantomData,
967        }
968    }
969
970    #[cfg(all(feature = "masque", feature = "quic"))]
971    fn with_connect_udp<U2>(
972        self,
973        connect_udp: U2,
974    ) -> ProxyMethodBuilder<T, C, B, Socks, Connect, U2, Forward> {
975        ProxyMethodBuilder {
976            stream: self.stream,
977            http: self.http,
978            scope: self.scope,
979            socks: self.socks,
980            connect: self.connect,
981            connect_udp,
982            forward: self.forward,
983            extensions_transfer: self.extensions_transfer,
984            _phantom: PhantomData,
985        }
986    }
987
988    fn with_forward<F2>(
989        self,
990        forward: F2,
991    ) -> ProxyMethodBuilder<T, C, B, Socks, Connect, ConnectUdp, F2> {
992        ProxyMethodBuilder {
993            stream: self.stream,
994            http: self.http,
995            scope: self.scope,
996            socks: self.socks,
997            connect: self.connect,
998            connect_udp: self.connect_udp,
999            forward,
1000            extensions_transfer: self.extensions_transfer,
1001            _phantom: PhantomData,
1002        }
1003    }
1004}
1005
1006impl<T, C, B, Socks, ConnectUdp, Forward>
1007    ProxyMethodBuilder<
1008        T,
1009        C,
1010        B,
1011        Socks,
1012        HttpConnectProxyConnector<ProxyDialer<C>, ProxyRequestBody<B>>,
1013        ConnectUdp,
1014        Forward,
1015    >
1016{
1017    /// See [`HttpConnectProxyConnector::with_custom_header`].
1018    #[must_use]
1019    pub fn with_connect_custom_header(
1020        mut self,
1021        name: impl IntoHeaderName,
1022        value: HeaderValue,
1023    ) -> Self {
1024        self.connect.set_custom_header(name, value);
1025        self
1026    }
1027}
1028
1029core::cfg_select! {
1030    feature = "socks5" => {
1031        /// The SOCKS5 method of a [`ProxyConnector`] over the streams `T` dials.
1032        pub type ProxySocksMethod<T> = Socks5ConnectProxyConnector<ProxyDialer<T>>;
1033    }
1034    _ => {
1035        /// SOCKS5 is not compiled into this build of rama.
1036        pub type ProxySocksMethod<T> = ProxyMethodNotEnabled<T>;
1037    }
1038}
1039
1040core::cfg_select! {
1041    all(feature = "masque", feature = "quic") => {
1042        /// The CONNECT-UDP method of a [`ProxyConnector`] over the HTTP connections `C`
1043        /// makes to a proxy in the body type `B`.
1044        ///
1045        /// Built on a method which is not enabled it refuses a MASQUE route, while every
1046        /// other datagram request still takes a UDP socket of its own, as an HTTP/3 origin
1047        /// reached without a proxy needs.
1048        pub type ProxyConnectUdpMethod<C, B = ResponseBody> = MaybeProxiedConnector<
1049            UdpConnector,
1050            HttpConnectUdpProxyConnector<ProxyDialer<C>, ProxyRequestBody<B>>,
1051            ProxiedRoute,
1052        >;
1053
1054        /// The CONNECT-UDP slot of a [`ProxyConnector`] whose method is not enabled.
1055        pub type ProxyConnectUdpNotEnabled<C, B = ResponseBody> =
1056            ProxyConnectUdpMethod<ProxyMethodNotEnabled<C>, B>;
1057
1058        pub(super) fn connect_udp_not_enabled<C, B>(scope: &WeakScope) -> ProxyConnectUdpNotEnabled<C, B> {
1059            MaybeProxiedConnector::new(
1060                UdpConnector::new(),
1061                HttpConnectUdpProxyConnector::new(
1062                    ProxyMethodNotEnabled::HTTP_CONNECT_UDP,
1063                    scope.clone(),
1064                ),
1065                ProxiedRoute::new(),
1066            )
1067        }
1068    }
1069    _ => {
1070        /// MASQUE over QUIC is not compiled into this build of rama.
1071        pub type ProxyConnectUdpMethod<C, B = ResponseBody> = ProxyMethodNotEnabled<(C, B)>;
1072
1073        /// The CONNECT-UDP slot of a [`ProxyConnector`] whose method is not enabled, which in
1074        /// this build is the only one it has.
1075        pub type ProxyConnectUdpNotEnabled<C, B = ResponseBody> = ProxyConnectUdpMethod<C, B>;
1076
1077        pub(super) fn connect_udp_not_enabled<C, B>(_scope: &WeakScope) -> ProxyConnectUdpNotEnabled<C, B> {
1078            ProxyMethodNotEnabled::HTTP_CONNECT_UDP
1079        }
1080    }
1081}
1082
1083core::cfg_select! {
1084    feature = "boring" => {
1085        type DefaultProxyStream<T> = boring_client::TlsConnector<DnsConnector<T>>;
1086    }
1087    feature = "rustls" => {
1088        type DefaultProxyStream<T> = rustls_client::TlsConnector<DnsConnector<T>>;
1089    }
1090    _ => {
1091        type DefaultProxyStream<T> = PlaintextProxyOnly<DnsConnector<T>>;
1092    }
1093}
1094
1095core::cfg_select! {
1096    all(feature = "quic", any(feature = "boring", feature = "rustls")) => {
1097        type DefaultProxyTransport<T> = HttpTransportConnector<
1098            DefaultProxyStream<T>,
1099            DnsConnector<Http3Connector<SharedQuicEndpoint>>,
1100        >;
1101    }
1102    _ => {
1103        type DefaultProxyTransport<T> = DefaultProxyStream<T>;
1104    }
1105}
1106
1107pub(crate) type DefaultProxyHttpConnector<T, B> = ProxyServiceConnector<
1108    HttpPooledConnector<HttpConnector<DefaultProxyTransport<T>, ProxyRequestBody<B>>>,
1109>;
1110
1111pub(crate) type DefaultProxySocksMethod<T = TcpConnector> = ProxySocksMethod<DefaultProxyStream<T>>;
1112
1113pub(crate) type DefaultProxyConnectMethod<T = TcpConnector, B = ResponseBody> =
1114    HttpConnectProxyConnector<ProxyDialer<DefaultProxyHttpConnector<T, B>>, ProxyRequestBody<B>>;
1115
1116pub(crate) type DefaultProxyConnectUdpMethod<T = TcpConnector, B = ResponseBody> =
1117    ProxyConnectUdpMethod<DefaultProxyHttpConnector<T, B>, B>;
1118
1119pub(crate) type DefaultProxyForwardMethod<T = TcpConnector, B = ResponseBody> =
1120    HttpForwardProxyConnector<ProxyDialer<DefaultProxyHttpConnector<T, B>>>;
1121
1122/// Rama's default connector towards proxies, as [`ProxyConnector::default_with_scope`]
1123/// builds it: every proxy method this build of rama has, over the streams `T` dials to a
1124/// proxy and the pooled HTTP connections it makes to one in the body type `B`.
1125pub type DefaultProxyConnector<T = TcpConnector, B = ResponseBody> = ProxyConnector<
1126    DefaultProxySocksMethod<T>,
1127    DefaultProxyConnectMethod<T, B>,
1128    DefaultProxyConnectUdpMethod<T, B>,
1129    DefaultProxyForwardMethod<T, B>,
1130>;