Skip to main content

socks5_impl/protocol/
request.rs

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