socksx/common/
addresses.rs

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
use std::convert::{TryFrom, TryInto};
use std::net::{IpAddr, SocketAddr};

use anyhow::Result;
use tokio::io::{AsyncRead, AsyncReadExt};
use url::Url;

use crate::{constants::*, Credentials};

/// Represents a SOCKS proxy address.
#[derive(Clone, Debug, PartialEq)]
pub struct ProxyAddress {
    /// The version of the SOCKS protocol.
    pub socks_version: u8,
    /// The hostname or IP address of the proxy.
    pub host: String,
    /// The port number of the proxy.
    pub port: u16,
    /// Optional credentials for authentication.
    pub credentials: Option<Credentials>,
}


impl ProxyAddress {
    /// Creates a new `ProxyAddress` instance.
    pub fn new(
        socks_version: u8,
        host: String,
        port: u16,
        credentials: Option<Credentials>,
    ) -> Self {
        Self {
            socks_version,
            host,
            port,
            credentials,
        }
    }

    /// Creates a root `ProxyAddress` with predefined settings.
    pub fn root() -> Self {
        ProxyAddress::new(6, String::from("root"), 1080, None)
    }
}


impl ToString for ProxyAddress {
    // Converts the `ProxyAddress` to a string representation.
    fn to_string(&self) -> String {
        format!("socks{}://{}:{}", self.socks_version, self.host, self.port)
    }
}

impl TryFrom<String> for ProxyAddress {
    type Error = anyhow::Error;

    // Converts a string to a `ProxyAddress`.
    fn try_from(proxy_addr: String) -> Result<Self> {
        let proxy_addr = Url::parse(&proxy_addr)?;

        ensure!(
            proxy_addr.host().is_some(),
            "Missing explicit IP/host in proxy address."
        );
        ensure!(proxy_addr.port().is_some(), "Missing explicit port in proxy address.");

        let socks_version = match proxy_addr.scheme() {
            "socks5" => SOCKS_VER_5,
            "socks6" => SOCKS_VER_6,
            scheme => bail!("Unrecognized SOCKS scheme: {}", scheme),
        };

        let username = proxy_addr.username();
        let credentials = if username.is_empty() {
            None
        } else {
            let password = proxy_addr.password().unwrap_or_default();
            Some(Credentials::new(username, password))
        };

        Ok(Self::new(
            socks_version,
            proxy_addr.host().map(|h| h.to_string()).unwrap(),
            proxy_addr.port().unwrap(),
            credentials,
        ))
    }
}

/// Represents a network address, which could be either a domain name or an IP address.
#[derive(Clone, Debug, PartialEq)]
pub enum Address {
    /// An address represented by a domain name.
    Domainname { host: String, port: u16 },
    /// An address represented by an IP address.
    Ip(SocketAddr),
}


impl Address {
    /// Creates a new `Address` instance.
    pub fn new<S: Into<String>>(
        host: S,
        port: u16,
    ) -> Self {
        let host = host.into();

        if let Ok(host) = host.parse::<IpAddr>() {
            Address::Ip(SocketAddr::new(host, port))
        } else {
            Address::Domainname { host, port }
        }
    }

    /// Converts the `Address` into a byte sequence compatible with the SOCKS protocol.
    pub fn as_socks_bytes(&self) -> Vec<u8> {
        let mut bytes = vec![];

        match self {
            Address::Ip(dst_addr) => {
                match dst_addr.ip() {
                    IpAddr::V4(host) => {
                        bytes.push(SOCKS_ATYP_IPV4);
                        bytes.extend(host.octets().iter());
                    }
                    IpAddr::V6(host) => {
                        bytes.push(SOCKS_ATYP_IPV6);
                        bytes.extend(host.octets().iter());
                    }
                }

                bytes.extend(dst_addr.port().to_be_bytes().iter())
            }
            Address::Domainname { host, port } => {
                bytes.push(SOCKS_ATYP_DOMAINNAME);

                let host = host.as_bytes();
                bytes.push(host.len() as u8);
                bytes.extend(host);

                bytes.extend(port.to_be_bytes().iter());
            }
        }

        bytes
    }
}

impl ToString for Address {
    // Converts the `Address` to a string representation.
    fn to_string(&self) -> String {
        match self {
            Address::Domainname { host, port } => format!("{}:{}", host, port),
            Address::Ip(socket_addr) => socket_addr.to_string(),
        }
    }
}

/// Tries to convert a `SocketAddr` into an `Address`.
impl TryFrom<SocketAddr> for Address {
    type Error = anyhow::Error;

    fn try_from(addr: SocketAddr) -> Result<Self, Self::Error> {
        addr.to_string().try_into()
    }
}

/// Tries to convert a `String` into an `Address`.
impl TryFrom<String> for Address {
    type Error = anyhow::Error;

    fn try_from(addr: String) -> Result<Self> {
        if let Some((host, port)) = addr.split_once(':') {
            Ok(Address::new(host, port.parse()?))
        } else {
            bail!("Address doesn't seperate host and port by ':'.")
        }
    }
}

/// Tries to convert a `ProxyAddress` into an `Address`.
impl TryFrom<&ProxyAddress> for Address {
    type Error = anyhow::Error;

    fn try_from(addr: &ProxyAddress) -> Result<Self> {
        format!("{}:{}", addr.host, addr.port).try_into()
    }
}

/// Reads the destination address from a stream and returns it as an `Address`.
pub async fn read_address<S>(stream: &mut S) -> Result<Address>
where
    S: AsyncRead + Unpin,
{
    // Read address type.
    let mut address_type = [0; 1];
    stream.read_exact(&mut address_type).await?;

    let dst_addr = match address_type[0] {
        SOCKS_ATYP_IPV4 => {
            let mut dst_addr = [0; 4];
            stream.read_exact(&mut dst_addr).await?;

            IpAddr::from(dst_addr).to_string()
        }
        SOCKS_ATYP_IPV6 => {
            let mut dst_addr = [0; 16];
            stream.read_exact(&mut dst_addr).await?;

            IpAddr::from(dst_addr).to_string()
        }
        SOCKS_ATYP_DOMAINNAME => {
            let mut length = [0; 1];
            stream.read_exact(&mut length).await?;

            let mut dst_addr = vec![0; length[0] as usize];
            stream.read_exact(&mut dst_addr).await?;

            String::from_utf8_lossy(&dst_addr[..]).to_string()
        }
        _ => unreachable!(),
    };

    // Read destination port.
    let mut dst_port = [0; 2];
    stream.read_exact(&mut dst_port).await?;

    let dst_port = ((dst_port[0] as u16) << 8) | dst_port[1] as u16;

    Ok(Address::new(dst_addr, dst_port))
}

#[cfg(test)]
mod tests {
    use std::net::SocketAddr;

    use anyhow::Result;

    use super::*;

    #[test]
    fn test_proxy_address_new() {
        let proxy_address = ProxyAddress::new(5, "localhost".to_string(), 1080, None);
        assert_eq!(proxy_address.socks_version, 5);
        assert_eq!(proxy_address.host, "localhost");
        assert_eq!(proxy_address.port, 1080);
        assert!(proxy_address.credentials.is_none());
    }

    #[test]
    fn test_proxy_address_root() {
        let root_address = ProxyAddress::root();
        assert_eq!(root_address.socks_version, 6);
        assert_eq!(root_address.host, "root");
        assert_eq!(root_address.port, 1080);
        assert!(root_address.credentials.is_none());
    }

    #[test]
    fn test_address_new_domain() {
        let address = Address::new("example.com", 80);
        match address {
            Address::Domainname { host, port } => {
                assert_eq!(host, "example.com");
                assert_eq!(port, 80);
            },
            _ => panic!("Expected a domain name address"),
        }
    }

    #[test]
    fn test_address_new_ip() {
        let address = Address::new("192.168.1.1", 22);
        match address {
            Address::Ip(socket_addr) => {
                assert_eq!(socket_addr.ip().to_string(), "192.168.1.1");
                assert_eq!(socket_addr.port(), 22);
            },
            _ => panic!("Expected an IP address"),
        }
    }

    #[test]
    fn test_proxy_address_try_from_valid_string() -> Result<()> {
        let proxy_str = "socks5://localhost:1080".to_string();
        let proxy_address: ProxyAddress = proxy_str.try_into()?;
        assert_eq!(proxy_address.socks_version, SOCKS_VER_5);
        assert_eq!(proxy_address.host, "localhost");
        assert_eq!(proxy_address.port, 1080);
        Ok(())
    }

    #[test]
    fn test_proxy_address_try_from_invalid_string() {
        let proxy_str = "invalid://localhost:1080".to_string();
        let result: Result<ProxyAddress> = proxy_str.try_into();
        assert!(result.is_err());
    }

    #[test]
    fn test_address_try_from_valid_string() -> Result<()> {
        let addr_str = "localhost:8000".to_string();
        let address: Address = addr_str.try_into()?;
        match address {
            Address::Domainname { host, port } => {
                assert_eq!(host, "localhost");
                assert_eq!(port, 8000);
            },
            _ => panic!("Expected a domain name address"),
        }
        Ok(())
    }

    #[test]
    fn test_address_try_from_invalid_string() {
        let addr_str = "localhost&8000".to_string();
        let result: Result<Address> = addr_str.try_into();
        assert!(result.is_err());
    }

    #[test]
    fn test_address_try_from_socket_addr() -> Result<()> {
        let socket_addr: SocketAddr = "192.168.1.1:22".parse()?;
        let address: Address = socket_addr.try_into()?;
        match address {
            Address::Ip(addr) => {
                assert_eq!(addr.ip().to_string(), "192.168.1.1");
                assert_eq!(addr.port(), 22);
            },
            _ => panic!("Expected an IP address"),
        }
        Ok(())
    }

    #[test]
    fn test_address_try_from_proxy_address() -> Result<()> {
        let proxy_address = ProxyAddress::new(5, "localhost".to_string(), 1080, None);
        let address: Address = (&proxy_address).try_into()?;
        match address {
            Address::Domainname { host, port } => {
                assert_eq!(host, "localhost");
                assert_eq!(port, 1080);
            },
            _ => panic!("Expected a domain name address"),
        }
        Ok(())
    }

    // TODO: Add tests for `read_address` function once we have a way to mock the `AsyncRead`.
}