rama-socks5 0.4.0

SOCKS5 support for rama
Documentation
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
use std::{io, time::Duration};

use rama_core::io::BridgeIo;
use rama_core::rt::Executor;
use rama_core::telemetry::tracing::{self, Instrument};
use rama_core::{Service, error::BoxError, io::Io, layer::timeout::DefaultTimeout};
use rama_net::address::HostWithPort;
use rama_net::{address::SocketAddress, proxy::IoForwardService, socket::SocketService};
use rama_tcp::{TcpStream, server::TcpListener};
use rama_utils::macros::generate_set_and_with;

use super::Error;
use crate::proto::{ReplyKind, server::Reply};

/// Types which can be used as socks5 [`Command::Bind`] drivers on the server side.
///
/// Typically used as a component part of a [`Socks5Acceptor`].
///
/// The actual underlying trait is sealed and not exposed for usage.
/// No custom binders can be implemented. You can however customise
/// the individual steps as provided and used by `Binder`.
///
/// [`Socks5Acceptor`]: crate::server::Socks5Acceptor
/// [`Command::Bind`]: crate::proto::Command::Bind
pub trait Socks5Binder<S>: Socks5BinderSeal<S> {}

impl<S, C> Socks5Binder<S> for C where C: Socks5BinderSeal<S> {}

pub trait Socks5BinderSeal<S>: Send + Sync + 'static {
    fn accept_bind(
        &self,
        stream: S,
        destination: HostWithPort,
    ) -> impl Future<Output = Result<(), Error>> + Send + '_;
}

impl<S> Socks5BinderSeal<S> for ()
where
    S: Io + Unpin,
{
    async fn accept_bind(&self, mut stream: S, destination: HostWithPort) -> Result<(), Error> {
        tracing::debug!(
            server.address = %destination.host,
            server.port = %destination.port,
            "socks5 server: abort: command not supported: Bind",
        );

        Reply::error_reply(ReplyKind::CommandNotSupported)
            .write_to(&mut stream)
            .await
            .map_err(|err| {
                Error::io(err).with_context("write server reply: command not supported (bind)")
            })?;
        Err(Error::aborted("command not supported: Bind"))
    }
}

/// Default [`Binder`] type.
pub type DefaultBinder = Binder<DefaultTimeout<DefaultAcceptorFactory>, IoForwardService>;

/// Only "useful" public [`Socks5Binder`] implementation,
/// which actually is able to accept bind requests and process them.
///
/// The [`Default`] implementation opens a new socket for accepting 1
/// incoming connection. Once received it will pipe the original request (source)
/// stream together with the received inbound stream from the secondary callee.
///
/// You can customise the [`Binder`] fully by creating it using [`Binder::new`]
/// or overwrite any of the default components using either or both of [`Binder::with_acceptor`]
/// and [`Binder::with_service`].
#[derive(Debug, Clone)]
pub struct Binder<A, S> {
    acceptor: A,
    service: S,

    bind_address: Option<SocketAddress>,

    accept_timeout: Option<Duration>,
}

impl<A, S> Binder<A, S> {
    /// Create a new [`Binder`].
    ///
    /// In case you only wish to overwrite one of these components
    /// you can also use a [`Default`] [`Binder`] and overwrite the specific component
    /// using [`Binder::with_acceptor`] or [`Binder::with_service`].
    pub fn new(acceptor: A, service: S) -> Self {
        Self {
            acceptor,
            service,
            bind_address: None,
            accept_timeout: None,
        }
    }
}

impl<A, S> Binder<A, S> {
    /// Overwrite the [`Binder`]'s factory [`Service`],
    /// used to open a listener, return the address and
    /// wait for an incoming connection which it will return.
    pub fn with_acceptor<T>(self, acceptor: T) -> Binder<T, S> {
        Binder {
            acceptor,
            service: self.service,
            bind_address: self.bind_address,
            accept_timeout: self.accept_timeout,
        }
    }

    /// Overwrite the [`Binder`]'s [`Service`]
    /// used to actually do the proxy between the source and incoming bind [`Io`].
    ///
    /// Any [`Service`] can be used as long as it has the signature:
    ///
    /// ```plain
    /// (BridgeIo) -> ((), Into<BoxError>)
    /// ```
    pub fn with_service<T>(self, service: T) -> Binder<A, T> {
        Binder {
            acceptor: self.acceptor,
            service,
            bind_address: self.bind_address,
            accept_timeout: self.accept_timeout,
        }
    }

    generate_set_and_with! {
        /// Define the [`SocketAddress`] to bind to.
        ///
        /// By default it will use the client's requested bind address,
        /// which is in many cases not what you want.
        pub fn bind_address(mut self, addr: impl Into<SocketAddress>) -> Self {
            self.bind_address = Some(addr.into());
            self
        }
    }

    generate_set_and_with! {
        /// Define the default [`SocketAddress`] to bind to (`0.0.0.0:0`).
        ///
        /// By default it will use the client's requested bind address,
        /// which is in many cases not what you want.
        pub fn default_bind_address(mut self) -> Self {
            self.bind_address = Some(SocketAddress::default_ipv4(0));
            self
        }
    }

    generate_set_and_with! {
        /// Define the accept timeout for this socks5 bind server.
        pub fn accept_timeout(mut self, timeout: Option<Duration>) -> Self {
            self.accept_timeout = timeout;
            self
        }
    }
}

#[derive(Debug, Clone, Default)]
/// Default factory [`Service`] used by [`DefaultBinder`].
pub struct DefaultAcceptorFactory {
    exec: Executor,
}

impl Service<SocketAddress> for DefaultAcceptorFactory {
    type Output = TcpListener;
    type Error = BoxError;

    async fn serve(&self, addr: SocketAddress) -> Result<Self::Output, Self::Error> {
        let acceptor = TcpListener::bind_address(addr, self.exec.clone()).await?;
        Ok(acceptor)
    }
}

/// [`Acceptor`] created by an factory [`Service`] in function of a bind [`Service`].
pub trait Acceptor: Send + Sync + 'static {
    /// The [`Io`] returned by this [`Acceptor`].
    type Stream: Io;

    /// Returns the local address that this listener is bound to.
    fn local_addr(&self) -> io::Result<SocketAddress>;

    /// Returns the first succesfully accepted connection.
    fn accept(self) -> impl Future<Output = Result<(Self::Stream, SocketAddress), Error>> + Send;
}

impl Acceptor for TcpListener {
    type Stream = TcpStream;

    fn local_addr(&self) -> io::Result<SocketAddress> {
        Self::local_addr(self).map(Into::into)
    }

    #[inline]
    async fn accept(self) -> Result<(Self::Stream, SocketAddress), Error> {
        let (stream, addr) = Self::accept(&self).await.map_err(Error::io)?;
        tracing::trace!(
            network.peer.port = %addr.port,
            network.peer.address = %addr.ip_addr,
            "accepted incoming TCP connection"
        );
        Ok((stream, addr))
    }
}

impl DefaultBinder {
    /// Create a [`DefaultBinder`] whose forward bridge observes graceful
    /// shutdown via the given [`Executor`].
    #[must_use]
    pub fn default_with_exec(exec: Executor) -> Self {
        Self::new(
            DefaultTimeout::new(DefaultAcceptorFactory::default(), Duration::from_secs(30)),
            IoForwardService::new(exec),
        )
    }
}

impl Default for DefaultBinder {
    fn default() -> Self {
        Self::default_with_exec(Executor::default())
    }
}

impl<S, F, StreamService> Socks5BinderSeal<S> for Binder<F, StreamService>
where
    S: Io + Unpin,
    F: SocketService<Socket: Acceptor<Stream: Unpin>>,
    StreamService: Service<BridgeIo<S, <F::Socket as Acceptor>::Stream>, Error: Into<BoxError>>,
{
    async fn accept_bind(
        &self,
        mut ingress_stream: S,
        requested_bind_address: HostWithPort,
    ) -> Result<(), Error> {
        tracing::trace!("socks5 server: bind: try to create acceptor @ {requested_bind_address}");

        let HostWithPort {
            host: requested_host,
            port: requested_port,
        } = requested_bind_address;

        // Bind target MUST be an IP. `try_as_ip` bridges pct-encoded
        // IPv4 inside `Uninterpreted`; anything else is rejected.
        let Ok(requested_addr) = requested_host.try_as_ip() else {
            tracing::debug!(
                "bind command does not accept non-IP host {requested_host} as bind address"
            );
            let reply_kind = ReplyKind::AddressTypeNotSupported;
            Reply::error_reply(reply_kind)
                .write_to(&mut ingress_stream)
                .await
                .map_err(|err| Error::io(err).with_context("write server reply: bind failed"))?;
            return Err(Error::aborted("bind failed").with_context(reply_kind));
        };
        let requested_address = SocketAddress::new(requested_addr, requested_port);

        let bind_address = if let Some(bind_address) = self.bind_address {
            tracing::trace!(
                "socks5 server: bind: use server-defined bind interface: {bind_address}"
            );
            bind_address
        } else {
            tracing::debug!(
                "socks5 server: bind: no server-defined bind interface: use requested client interface @ {requested_address}"
            );
            requested_address
        };

        let acceptor = match self.acceptor.bind_socket_with_address(bind_address).await {
            Ok(twin) => twin,
            Err(err) => {
                let err = err.into();
                tracing::debug!("make bind listener failed: {err:?}");
                let reply_kind = ReplyKind::GeneralServerFailure;
                Reply::error_reply(reply_kind)
                    .write_to(&mut ingress_stream)
                    .await
                    .map_err(|err| {
                        Error::io(err).with_context("write server reply: make bind listener failed")
                    })?;
                return Err(Error::aborted("make bind listener failed")
                    .with_context(reply_kind)
                    .with_source(err));
            }
        };

        let bind_address = match acceptor.local_addr() {
            Ok(addr) => addr,
            Err(err) => {
                tracing::debug!(
                    "retrieve local addr of (tcp) acceptor failed @ {bind_address}: {err:?}",
                );
                let reply_kind = ReplyKind::GeneralServerFailure;
                Reply::error_reply(reply_kind)
                    .write_to(&mut ingress_stream)
                    .await
                    .map_err(|err| {
                        Error::io(err).with_context("write server reply: make bind listener failed")
                    })?;
                return Err(Error::aborted("make bind listener failed").with_context(reply_kind));
            }
        };

        Reply::new(bind_address)
            .write_to(&mut ingress_stream)
            .await
            .map_err(|err| {
                Error::io(err).with_context("write server reply: bind: acceptor listener ready")
            })?;

        let accept_future = acceptor.accept();

        let result = match self.accept_timeout {
            Some(duration) => match tokio::time::timeout(duration, accept_future).await {
                Ok(result) => result,
                Err(err) => {
                    tracing::debug!("accept future timed out @ {bind_address}: {err:?}",);
                    let reply_kind = ReplyKind::TtlExpired;
                    Reply::error_reply(reply_kind)
                        .write_to(&mut ingress_stream)
                        .await
                        .map_err(|err| {
                            Error::io(err).with_context("write server reply: bind failed")
                        })?;
                    return Err(Error::aborted("bind failed").with_context(reply_kind));
                }
            },
            None => accept_future.await,
        };

        let (incoming_stream, incoming_addr) = match result {
            Ok((stream, addr)) => (stream, addr),
            Err(err) => {
                let err: BoxError = err.into();
                tracing::debug!("socks5 server: abort: bind failed @ {bind_address}: {err:?}",);

                let reply_kind = (&err).into();
                Reply::error_reply(reply_kind)
                    .write_to(&mut ingress_stream)
                    .await
                    .map_err(|err| {
                        Error::io(err).with_context("write server reply: bind failed")
                    })?;
                return Err(Error::aborted("bind failed")
                    .with_context(reply_kind)
                    .with_source(err));
            }
        };

        tracing::trace!(
            "incoming connection {incoming_addr} received on bind interface {bind_address}",
        );

        Reply::new(incoming_addr)
            .write_to(&mut ingress_stream)
            .await
            .map_err(|err| {
                Error::io(err).with_context("write server reply: bind: connection received")
            })?;

        tracing::trace!(
            "socks5 server @ {bind_address}: bind: ready to serve from {incoming_addr}",
        );

        self.service
            .serve(BridgeIo(ingress_stream, incoming_stream))
            .instrument(tracing::trace_span!("socks5::bind::serve"))
            .await
            .map(drop)
            .map_err(|err| Error::service(err).with_context("serve bind pipe"))
    }
}

#[cfg(test)]
pub(crate) use test::MockBinder;

#[cfg(test)]
mod test {
    #![expect(
        clippy::unreachable,
        reason = "test fixtures: arms gated on the mock variants the test sets up"
    )]

    use super::*;
    use rama_net::address::HostWithPort;
    use std::{ops::DerefMut, sync::Arc};
    use tokio::sync::Mutex;

    #[derive(Debug)]
    pub(crate) struct MockBinder {
        reply: MockReply,
    }

    #[derive(Debug)]
    enum MockReply {
        Success {
            bind_addr: HostWithPort,
            second_reply: MockSecondReply,
        },
        Error(ReplyKind),
    }

    #[derive(Debug)]
    enum MockSecondReply {
        Success {
            recv_addr: HostWithPort,
            target: Option<Arc<Mutex<tokio_test::io::Mock>>>,
        },
        Error(ReplyKind),
    }

    impl MockBinder {
        pub(crate) fn new(bind_addr: HostWithPort, recv_addr: HostWithPort) -> Self {
            Self {
                reply: MockReply::Success {
                    bind_addr,
                    second_reply: MockSecondReply::Success {
                        recv_addr,
                        target: None,
                    },
                },
            }
        }
        pub(crate) fn new_err(reply: ReplyKind) -> Self {
            Self {
                reply: MockReply::Error(reply),
            }
        }
        pub(crate) fn new_bind_err(bind_addr: HostWithPort, reply: ReplyKind) -> Self {
            Self {
                reply: MockReply::Success {
                    bind_addr,
                    second_reply: MockSecondReply::Error(reply),
                },
            }
        }

        pub(crate) fn with_proxy_data(mut self, target: tokio_test::io::Mock) -> Self {
            self.reply = match self.reply {
                MockReply::Success {
                    bind_addr,
                    second_reply:
                        MockSecondReply::Success {
                            recv_addr,
                            target: None,
                        },
                } => MockReply::Success {
                    bind_addr,
                    second_reply: MockSecondReply::Success {
                        recv_addr,
                        target: Some(Arc::new(Mutex::new(target))),
                    },
                },
                MockReply::Error(_) | MockReply::Success { .. } => unreachable!(),
            };
            self
        }
    }

    impl<S> Socks5BinderSeal<S> for MockBinder
    where
        S: Io + Unpin,
    {
        async fn accept_bind(
            &self,
            mut stream: S,
            _requested_bind_address: HostWithPort,
        ) -> Result<(), Error> {
            match &self.reply {
                MockReply::Success {
                    bind_addr,
                    second_reply,
                } => {
                    Reply::new(bind_addr.clone())
                        .write_to(&mut stream)
                        .await
                        .map_err(Error::io)?;

                    match second_reply {
                        MockSecondReply::Success { recv_addr, target } => {
                            Reply::new(recv_addr.clone())
                                .write_to(&mut stream)
                                .await
                                .map_err(Error::io)?;

                            if let Some(target) = target.as_ref() {
                                let mut target = target.lock().await;
                                match tokio::io::copy_bidirectional(&mut stream, target.deref_mut())
                                    .await
                                {
                                    Ok((bytes_copied_north, bytes_copied_south)) => {
                                        tracing::trace!(
                                            %bytes_copied_north,
                                            %bytes_copied_south,
                                            "(proxy) I/O stream forwarder finished"
                                        );
                                        Ok(())
                                    }
                                    Err(err) => {
                                        if rama_net::conn::is_connection_error(&err) {
                                            Ok(())
                                        } else {
                                            Err(Error::io(err))
                                        }
                                    }
                                }
                            } else {
                                Ok(())
                            }
                        }
                        MockSecondReply::Error(reply_kind) => {
                            Reply::error_reply(*reply_kind)
                                .write_to(&mut stream)
                                .await
                                .map_err(Error::io)?;
                            Err(Error::aborted("mock abort 2nd reply").with_context(*reply_kind))
                        }
                    }
                }
                MockReply::Error(reply_kind) => {
                    Reply::error_reply(*reply_kind)
                        .write_to(&mut stream)
                        .await
                        .map_err(Error::io)?;
                    Err(Error::aborted("mock abort 1st reply").with_context(*reply_kind))
                }
            }
        }
    }
}