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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
use crate::{Socks5Client, client::proxy_error::Socks5ProxyError};
use rama_core::error::BoxErrorExt as _;
use rama_core::{Layer, Service, error::BoxError, io::Io, telemetry::tracing};
#[cfg(feature = "dns")]
use rama_dns::client::{
GlobalDnsResolver,
resolver::{BoxDnsAddressResolver, DnsAddressResolver},
};
use rama_net::{
ConnectorTargetInputExt,
address::ProxyAddress,
client::{
ConnectionError, ConnectionErrorKind, ConnectorService, ConnectorTarget,
EstablishedClientConnection, ProxyRoute,
},
user::ProxyCredential,
};
#[cfg(feature = "dns")]
use rama_net::{Protocol, address::Host, mode::DnsResolveIpMode};
use rama_utils::macros::define_inner_service_accessors;
#[cfg(feature = "dns")]
use rama_utils::macros::generate_set_and_with;
#[cfg(feature = "dns")]
use std::net::IpAddr;
#[derive(Debug, Clone, Default)]
/// A [`Layer`] which wraps the given service with a [`Socks5ProxyConnector`].
///
/// See [`Socks5ProxyConnector`] for more information.
pub struct Socks5ProxyConnectorLayer {
required: bool,
#[cfg(feature = "dns")]
dns_resolver: Option<BoxDnsAddressResolver>,
}
impl Socks5ProxyConnectorLayer {
/// Create a new [`Socks5ProxyConnectorLayer`] which creates a [`Socks5ProxyConnector`]
/// which will only connect via a socks5 proxy when a proxied [`ProxyRoute`] is available
/// in the input [`Extensions`].
///
/// [`Extensions`]: rama_core::extensions::Extensions
/// [`ProxyRoute`]: rama_net::client::ProxyRoute
#[must_use]
pub fn optional() -> Self {
Self {
required: false,
#[cfg(feature = "dns")]
dns_resolver: None,
}
}
/// Create a new [`Socks5ProxyConnectorLayer`] which creates a [`Socks5ProxyConnector`]
/// which will always connect via a SOCKS5 proxy, but fail when a proxied [`ProxyRoute`] is
/// not available in the input [`Extensions`].
///
/// [`Extensions`]: rama_core::extensions::Extensions
/// [`ProxyRoute`]: rama_net::client::ProxyRoute
#[must_use]
pub fn required() -> Self {
Self {
required: true,
#[cfg(feature = "dns")]
dns_resolver: None,
}
}
}
#[cfg(feature = "dns")]
impl Socks5ProxyConnectorLayer {
generate_set_and_with! {
/// Attach the default [`DnsAddressResolver`] to this [`Socks5ProxyConnectorLayer`].
///
/// It will try to be used (best-effort) to resolve domain addresses
/// as IP addresses if the `socks5` protocol is used, but not for the `socks5h` protocol.
///
/// In case of an error with resolving the domain address the connector
/// will anyway use the domain instead of the ip.
pub fn default_dns_resolver(mut self) -> Self {
self.dns_resolver = Some(GlobalDnsResolver::new().into_box_dns_address_resolver());
self
}
}
/// Attach a [`DnsAddressResolver`] to this [`Socks5ProxyConnectorLayer`].
///
/// It will try to be used (best-effort) to resolve domain addresses
/// as IP addresses if the `socks5` protocol is used, but not for the `socks5h` protocol.
///
/// In case of an error with resolving the domain address the connector
/// will anyway use the domain instead of the ip.
#[must_use]
pub fn with_dns_address_resolver(mut self, resolver: impl DnsAddressResolver) -> Self {
self.dns_resolver = Some(resolver.into_box_dns_address_resolver());
self
}
/// Attach a [`DnsAddressResolver`] to this [`Socks5ProxyConnectorLayer`].
///
/// It will try to be used (best-effort) to resolve domain addresses
/// as IP addresses if the `socks5` protocol is used, but not for the `socks5h` protocol.
///
/// In case of an error with resolving the domain address the connector
/// will anyway use the domain instead of the ip.
pub fn set_dns_address_resolver(&mut self, resolver: impl DnsAddressResolver) -> &mut Self {
self.dns_resolver = Some(resolver.into_box_dns_address_resolver());
self
}
}
impl<S> Layer<S> for Socks5ProxyConnectorLayer {
type Service = Socks5ProxyConnector<S>;
fn layer(&self, inner: S) -> Self::Service {
Socks5ProxyConnector {
inner,
required: self.required,
#[cfg(feature = "dns")]
dns_resolver: self.dns_resolver.clone(),
}
}
fn into_layer(self, inner: S) -> Self::Service {
Socks5ProxyConnector {
inner,
required: self.required,
#[cfg(feature = "dns")]
dns_resolver: self.dns_resolver,
}
}
}
/// A connector which can be used to establish a connection over a SOCKS5 Proxy.
///
/// This behaviour is optional and only triggered in case there
/// is a proxied [`ProxyRoute`] found in the [`Extensions`].
///
/// [`Extensions`]: rama_core::extensions::Extensions
#[derive(Debug, Clone)]
pub struct Socks5ProxyConnector<S> {
inner: S,
required: bool,
#[cfg(feature = "dns")]
dns_resolver: Option<BoxDnsAddressResolver>,
}
impl<S> Socks5ProxyConnector<S> {
/// Creates a new [`Socks5ProxyConnector`].
fn new(inner: S, required: bool) -> Self {
Self {
inner,
required,
#[cfg(feature = "dns")]
dns_resolver: None,
}
}
/// Creates a new optional [`Socks5ProxyConnector`].
#[inline]
pub fn optional(inner: S) -> Self {
Self::new(inner, false)
}
/// Creates a new required [`Socks5ProxyConnector`].
#[inline]
pub fn required(inner: S) -> Self {
Self::new(inner, true)
}
define_inner_service_accessors!();
}
#[cfg(feature = "dns")]
impl<S> Socks5ProxyConnector<S> {
generate_set_and_with! {
/// Attach the default [`DnsAddressResolver`] to this [`Socks5ProxyConnector`].
///
/// It will try to be used (best-effort) to resolve domain addresses
/// as IP addresses if the `socks5` protocol is used, but not for the `socks5h` protocol.
///
/// In case of an error with resolving the domain address the connector
/// will anyway use the domain instead of the ip.
pub fn default_dns_resolver(mut self) -> Self {
self.dns_resolver = Some(GlobalDnsResolver::default().into_box_dns_address_resolver());
self
}
}
generate_set_and_with! {
/// Attach a [`DnsAddressResolver`] to this [`Socks5ProxyConnector`].
///
/// It will try to be used (best-effort) to resolve domain addresses
/// as IP addresses if the `socks5` protocol is used, but not for the `socks5h` protocol.
///
/// In case of an error with resolving the domain address the connector
/// will anyway use the domain instead of the ip.
pub fn dns_resolver(mut self, resolver: Option<BoxDnsAddressResolver>) -> Self {
self.dns_resolver = resolver;
self
}
}
/// Attach a [`DnsAddressResolver`] to this [`Socks5ProxyConnector`].
///
/// It will try to be used (best-effort) to resolve domain addresses
/// as IP addresses if the `socks5` protocol is used, but not for the `socks5h` protocol.
///
/// In case of an error with resolving the domain address the connector
/// will anyway use the domain instead of the ip.
#[must_use]
pub fn with_dns_address_resolver(mut self, resolver: impl DnsAddressResolver) -> Self {
self.dns_resolver = Some(resolver.into_box_dns_address_resolver());
self
}
/// Attach a [`DnsAddressResolver`] to this [`Socks5ProxyConnector`].
///
/// It will try to be used (best-effort) to resolve domain addresses
/// as IP addresses if the `socks5` protocol is used, but not for the `socks5h` protocol.
///
/// In case of an error with resolving the domain address the connector
/// will anyway use the domain instead of the ip.
pub fn set_dns_address_resolver(&mut self, resolver: impl DnsAddressResolver) -> &mut Self {
self.dns_resolver = Some(resolver.into_box_dns_address_resolver());
self
}
}
impl<S> Socks5ProxyConnector<S> {
#[cfg(feature = "dns")]
async fn normalize_socks5_proxy_addr(
&self,
dns_mode: DnsResolveIpMode,
addr: ProxyAddress,
) -> ProxyAddress {
if let Some(dns_resolver) = self.dns_resolver.as_ref()
&& addr.protocol == Some(Protocol::SOCKS5)
{
use rama_net::address::HostWithPort;
let ProxyAddress {
protocol,
address: HostWithPort { host, port },
credential,
} = addr;
let host = match host {
Host::Name(domain) => match dns_mode {
DnsResolveIpMode::SingleIpV4 => {
match dns_resolver.lookup_ipv4_rand(domain.clone()).await {
Some(Ok(addr)) => Host::Address(IpAddr::V4(addr)),
Some(Err(err)) => {
tracing::debug!(
"failed to lookup ipv4 addresses for domain: {err:?}"
);
Host::Name(domain)
}
None => {
tracing::debug!(
"failed to lookup ipv4 addresses for domain: no addresses found"
);
Host::Name(domain)
}
}
}
DnsResolveIpMode::SingleIpV6 => {
match dns_resolver.lookup_ipv6_rand(domain.clone()).await {
Some(Ok(addr)) => Host::Address(IpAddr::V6(addr)),
Some(Err(err)) => {
tracing::debug!(
"failed to lookup ipv6 addresses for domain: {err:?}"
);
Host::Name(domain)
}
None => {
tracing::debug!(
"failed to lookup ipv6 addresses for domain: no addresses found"
);
Host::Name(domain)
}
}
}
DnsResolveIpMode::Dual | DnsResolveIpMode::DualPreferIpV4 => {
crate::dns::race_resolve_dual(dns_resolver, domain.clone(), dns_mode)
.await
.map(Host::Address)
.unwrap_or(Host::Name(domain))
}
},
// IPs and any non-Domain shape pass through unchanged —
// there's nothing to resolve.
_ => host,
};
let address = HostWithPort::new(host, port);
return ProxyAddress {
protocol,
address,
credential,
};
}
addr
}
#[cfg(not(feature = "dns"))]
async fn normalize_socks5_proxy_addr(&self, addr: ProxyAddress) -> ProxyAddress {
addr
}
}
impl<S, Input> Service<Input> for Socks5ProxyConnector<S>
where
S: ConnectorService<Input, Connection: Io + Unpin>,
Input: ConnectorTargetInputExt + Send + 'static,
{
type Output = EstablishedClientConnection<S::Connection, Input>;
type Error = ConnectionError;
async fn serve(&self, input: Input) -> Result<Self::Output, Self::Error> {
let proxy_info = match input.extensions().get_ref::<ProxyRoute>() {
Some(ProxyRoute::Proxy(proxy_info)) => proxy_info.clone(),
None | Some(ProxyRoute::Direct) => {
return if self.required {
Err(ConnectionError::local(
BoxError::from_static_str("socks5 proxy required but none is defined"),
ConnectionErrorKind::InvalidInput,
))
} else {
tracing::trace!(
"socks5 proxy connector: no proxy required or set: proceed with direct connection"
);
self.inner.connect(input).await.map_err(|error| {
error.context(
"establish connection target (no socks5 proxy defined and neither required)",
)
})
};
}
};
if !proxy_info
.protocol
.as_ref()
.map(|p| p.is_socks5())
.unwrap_or(true)
{
return Err(ConnectionError::transport(
BoxError::from_static_str("socks5 proxy connector can only serve socks5 protocol"),
ConnectionErrorKind::Protocol,
)
.context_debug_field("protocol", proxy_info.protocol.clone()));
}
#[cfg(feature = "dns")]
let normalized_proxy_info = self
.normalize_socks5_proxy_addr(
input.extensions().get_ref().copied().unwrap_or_default(),
proxy_info,
)
.await;
#[cfg(not(feature = "dns"))]
let normalized_proxy_info = self.normalize_socks5_proxy_addr(proxy_info).await;
input
.extensions()
.insert(ProxyRoute::Proxy(normalized_proxy_info.clone()));
// insert target so that inner connector can use it instead of input's version
input
.extensions()
.insert(ConnectorTarget(normalized_proxy_info.address.clone()));
let EstablishedClientConnection { input, mut conn } =
self.inner.connect(input).await.map_err(|error| {
error
.context("establish connection to proxy")
.context_field("address", normalized_proxy_info.address.clone())
.context_debug_field("protocol", normalized_proxy_info.protocol.clone())
})?;
let authority = input.authority().ok_or_else(|| {
ConnectionError::local(
BoxError::from_static_str("socks5 proxy connector: authority missing from input"),
ConnectionErrorKind::InvalidInput,
)
})?;
tracing::trace!(
network.peer.address = %normalized_proxy_info.address.host,
network.peer.port = %normalized_proxy_info.address.port,
server.address = %authority.host,
server.port = authority.port_u16(),
"socks5 proxy connector: connected to proxy",
);
let mut client = Socks5Client::new();
match &normalized_proxy_info.credential {
Some(ProxyCredential::Basic(basic)) => {
tracing::trace!(
network.peer.address = %normalized_proxy_info.address.host,
network.peer.port = %normalized_proxy_info.address.port,
server.address = %authority.host,
server.port = authority.port_u16(),
"socks5 proxy connector: continue handshake with authorisation",
);
client.set_auth(basic.clone());
}
Some(ProxyCredential::Bearer(_)) => {
return Err(ConnectionError::local(
BoxError::from_static_str(
"socks5proxy does not support auth with bearer credential",
),
ConnectionErrorKind::InvalidInput,
));
}
None => {
tracing::trace!(
network.peer.address = %normalized_proxy_info.address.host,
network.peer.port = %normalized_proxy_info.address.port,
server.address = %authority.host,
server.port = authority.port_u16(),
"socks5 proxy connector: continue handshake without authorisation",
);
}
}
let Some(connect_authority) = authority
.clone()
.into_host_with_port(input.protocol_default_port())
else {
return Err(ConnectionError::local(
BoxError::from_static_str("failed to get port from transport context"),
ConnectionErrorKind::InvalidInput,
));
};
match client
.handshake_connect(&mut conn, &connect_authority)
.await
{
Ok(bind_addr) => {
tracing::trace!(
network.peer.address = %normalized_proxy_info.address.host,
network.peer.port = %normalized_proxy_info.address.port,
server.address = %authority.host,
server.port = authority.port_u16(),
%bind_addr,
"socks5 proxy connector: handshake complete",
)
}
Err(error) => {
return Err(ConnectionError::from(Socks5ProxyError::Handshake(error)));
}
}
Ok(EstablishedClientConnection { input, conn })
}
}