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
use self::{associate::UdpAssociate, bind::Bind, connect::Connect};
use crate::{
    protocol::{Address, AuthMethod, Command, HandshakeRequest, HandshakeResponse, Reply, Request, Response},
    server::AuthExecutor,
};
use std::{net::SocketAddr, sync::Arc};
use tokio::{io::AsyncWriteExt, net::TcpStream};

pub mod associate;
pub mod bind;
pub mod connect;

/// An incoming connection. This may not be a valid socks5 connection. You need to call [`handshake()`](#method.handshake)
/// to perform the socks5 handshake. It will be converted to a proper socks5 connection after the handshake succeeds.
pub struct IncomingConnection {
    stream: TcpStream,
    auth: Arc<dyn AuthExecutor + Send + Sync>,
}

impl IncomingConnection {
    #[inline]
    pub(crate) fn new(stream: TcpStream, auth: Arc<dyn AuthExecutor + Send + Sync>) -> Self {
        IncomingConnection { stream, auth }
    }

    /// Perform the socks5 handshake on this connection.
    pub async fn handshake(mut self) -> std::io::Result<Connection> {
        if let Err(err) = self.auth().await {
            let _ = self.stream.shutdown().await;
            return Err(err);
        }

        let req = match Request::rebuild_from_stream(&mut self.stream).await {
            Ok(req) => req,
            Err(err) => {
                let resp = Response::new(Reply::GeneralFailure, Address::unspecified());
                resp.write_to(&mut self.stream).await?;
                let _ = self.stream.shutdown().await;
                return Err(err);
            }
        };

        match req.command {
            Command::UdpAssociate => Ok(Connection::UdpAssociate(
                UdpAssociate::<associate::NeedReply>::new(self.stream),
                req.address,
            )),
            Command::Bind => Ok(Connection::Bind(Bind::<bind::NeedFirstReply>::new(self.stream), req.address)),
            Command::Connect => Ok(Connection::Connect(Connect::<connect::NeedReply>::new(self.stream), req.address)),
        }
    }

    /// Returns the local address that this stream is bound to.
    #[inline]
    pub fn local_addr(&self) -> std::io::Result<SocketAddr> {
        self.stream.local_addr()
    }

    /// Returns the remote address that this stream is connected to.
    #[inline]
    pub fn peer_addr(&self) -> std::io::Result<SocketAddr> {
        self.stream.peer_addr()
    }

    /// Shutdown the TCP stream.
    #[inline]
    pub async fn shutdown(&mut self) -> std::io::Result<()> {
        self.stream.shutdown().await
    }

    #[inline]
    async fn auth(&mut self) -> std::io::Result<()> {
        let request = HandshakeRequest::rebuild_from_stream(&mut self.stream).await?;
        if let Some(method) = self.evaluate_request(&request) {
            let response = HandshakeResponse::new(method);
            response.write_to_stream(&mut self.stream).await?;
            self.auth.execute(&mut self.stream).await
        } else {
            let response = HandshakeResponse::new(AuthMethod::NoAcceptableMethods);
            response.write_to_stream(&mut self.stream).await?;
            let err = "No available handshake method provided by client";
            Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err))
        }
    }

    fn evaluate_request(&self, req: &HandshakeRequest) -> Option<AuthMethod> {
        let method = self.auth.auth_method();
        req.methods.iter().find(|&&m| m == method).copied()
    }
}

impl std::fmt::Debug for IncomingConnection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IncomingConnection").field("stream", &self.stream).finish()
    }
}

/// After the socks5 handshake succeeds, the connection may become:
///
/// - Associate
/// - Bind
/// - Connect
#[derive(Debug)]
pub enum Connection {
    UdpAssociate(UdpAssociate<associate::NeedReply>, Address),
    Bind(Bind<bind::NeedFirstReply>, Address),
    Connect(Connect<connect::NeedReply>, Address),
}