socks5_impl/protocol/handshake/
request.rs

1#[cfg(feature = "tokio")]
2use crate::protocol::AsyncStreamOperation;
3use crate::protocol::{AuthMethod, StreamOperation, Version};
4#[cfg(feature = "tokio")]
5use tokio::io::{AsyncRead, AsyncReadExt};
6
7/// SOCKS5 handshake request
8///
9/// ```plain
10/// +-----+----------+----------+
11/// | VER | NMETHODS | METHODS  |
12/// +-----+----------+----------+
13/// |  1  |    1     | 1 to 255 |
14/// +-----+----------+----------|
15/// ```
16#[derive(Clone, Debug)]
17pub struct Request {
18    methods: Vec<AuthMethod>,
19}
20
21impl Request {
22    pub fn new(methods: Vec<AuthMethod>) -> Self {
23        Self { methods }
24    }
25
26    pub fn evaluate_method(&self, server_method: AuthMethod) -> bool {
27        self.methods.contains(&server_method)
28    }
29}
30
31impl StreamOperation for Request {
32    fn retrieve_from_stream<R: std::io::Read>(r: &mut R) -> std::io::Result<Self> {
33        let mut ver = [0; 1];
34        r.read_exact(&mut ver)?;
35        let ver = Version::try_from(ver[0])?;
36
37        if ver != Version::V5 {
38            let err = format!("Unsupported SOCKS version {0:#x}", u8::from(ver));
39            return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err));
40        }
41
42        let mut mlen = [0; 1];
43        r.read_exact(&mut mlen)?;
44        let mlen = mlen[0];
45
46        let mut methods = vec![0; mlen as usize];
47        r.read_exact(&mut methods)?;
48
49        let methods = methods.into_iter().map(AuthMethod::from).collect();
50
51        Ok(Self { methods })
52    }
53
54    fn write_to_buf<B: bytes::BufMut>(&self, buf: &mut B) {
55        buf.put_u8(Version::V5.into());
56        buf.put_u8(self.methods.len() as u8);
57
58        let methods = self.methods.iter().map(u8::from).collect::<Vec<u8>>();
59        buf.put_slice(&methods);
60    }
61
62    fn len(&self) -> usize {
63        2 + self.methods.len()
64    }
65}
66
67#[cfg(feature = "tokio")]
68#[async_trait::async_trait]
69impl AsyncStreamOperation for Request {
70    async fn retrieve_from_async_stream<R>(r: &mut R) -> std::io::Result<Self>
71    where
72        R: AsyncRead + Unpin + Send + ?Sized,
73    {
74        let ver = Version::try_from(r.read_u8().await?)?;
75
76        if ver != Version::V5 {
77            let err = format!("Unsupported SOCKS version {0:#x}", u8::from(ver));
78            return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err));
79        }
80
81        let mlen = r.read_u8().await?;
82        let mut methods = vec![0; mlen as usize];
83        r.read_exact(&mut methods).await?;
84
85        let methods = methods.into_iter().map(AuthMethod::from).collect();
86
87        Ok(Self { methods })
88    }
89}