socks5_impl/protocol/handshake/
request.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
#[cfg(feature = "tokio")]
use crate::protocol::AsyncStreamOperation;
use crate::protocol::{AuthMethod, StreamOperation, Version};
#[cfg(feature = "tokio")]
use async_trait::async_trait;
#[cfg(feature = "tokio")]
use tokio::io::{AsyncRead, AsyncReadExt};

/// SOCKS5 handshake request
///
/// ```plain
/// +-----+----------+----------+
/// | VER | NMETHODS | METHODS  |
/// +-----+----------+----------+
/// |  1  |    1     | 1 to 255 |
/// +-----+----------+----------|
/// ```
#[derive(Clone, Debug)]
pub struct Request {
    methods: Vec<AuthMethod>,
}

impl Request {
    pub fn new(methods: Vec<AuthMethod>) -> Self {
        Self { methods }
    }

    pub fn evaluate_method(&self, server_method: AuthMethod) -> bool {
        self.methods.iter().any(|&m| m == server_method)
    }
}

impl StreamOperation for Request {
    fn retrieve_from_stream<R: std::io::Read>(r: &mut R) -> std::io::Result<Self> {
        let mut ver = [0; 1];
        r.read_exact(&mut ver)?;
        let ver = Version::try_from(ver[0])?;

        if ver != Version::V5 {
            let err = format!("Unsupported SOCKS version {0:#x}", u8::from(ver));
            return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err));
        }

        let mut mlen = [0; 1];
        r.read_exact(&mut mlen)?;
        let mlen = mlen[0];

        let mut methods = vec![0; mlen as usize];
        r.read_exact(&mut methods)?;

        let methods = methods.into_iter().map(AuthMethod::from).collect();

        Ok(Self { methods })
    }

    fn write_to_buf<B: bytes::BufMut>(&self, buf: &mut B) {
        buf.put_u8(Version::V5.into());
        buf.put_u8(self.methods.len() as u8);

        let methods = self.methods.iter().map(u8::from).collect::<Vec<u8>>();
        buf.put_slice(&methods);
    }

    fn len(&self) -> usize {
        2 + self.methods.len()
    }
}

#[cfg(feature = "tokio")]
#[async_trait]
impl AsyncStreamOperation for Request {
    async fn retrieve_from_async_stream<R>(r: &mut R) -> std::io::Result<Self>
    where
        R: AsyncRead + Unpin + Send + ?Sized,
    {
        let ver = Version::try_from(r.read_u8().await?)?;

        if ver != Version::V5 {
            let err = format!("Unsupported SOCKS version {0:#x}", u8::from(ver));
            return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err));
        }

        let mlen = r.read_u8().await?;
        let mut methods = vec![0; mlen as usize];
        r.read_exact(&mut methods).await?;

        let methods = methods.into_iter().map(AuthMethod::from).collect();

        Ok(Self { methods })
    }
}