Skip to main content

socks5_impl/protocol/
request.rs

1#[cfg(feature = "tokio")]
2use crate::AsyncStreamOperation;
3use crate::{
4    Address, StreamOperation,
5    protocol::{Command, Version},
6};
7#[cfg(feature = "tokio")]
8use tokio::io::{AsyncRead, AsyncReadExt};
9
10/// SOCKS5 request
11///
12/// ```plain
13/// +-----+-----+-------+------+----------+----------+
14/// | VER | CMD |  RSV  | ATYP | DST.ADDR | DST.PORT |
15/// +-----+-----+-------+------+----------+----------+
16/// |  1  |  1  | X'00' |  1   | Variable |    2     |
17/// +-----+-----+-------+------+----------+----------+
18/// ```
19#[derive(Clone, Debug)]
20pub struct Request {
21    pub command: Command,
22    pub address: Address,
23}
24
25impl Request {
26    pub fn new(command: Command, address: Address) -> Self {
27        Self { command, address }
28    }
29}
30
31impl StreamOperation for Request {
32    fn retrieve_from_stream<R: std::io::Read>(stream: &mut R) -> std::io::Result<Self> {
33        let mut ver = [0u8; 1];
34        stream.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 buf = [0; 2];
43        stream.read_exact(&mut buf)?;
44
45        if buf[1] != 0x00 {
46            return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid reserved byte"));
47        }
48
49        let command = Command::try_from(buf[0])?;
50        let address = Address::retrieve_from_stream(stream)?;
51
52        Ok(Self { command, address })
53    }
54
55    fn write_to_buf<B: bytes::BufMut>(&self, buf: &mut B) {
56        buf.put_u8(Version::V5.into());
57        buf.put_u8(u8::from(self.command));
58        buf.put_u8(0x00);
59        self.address.write_to_buf(buf);
60    }
61
62    fn len(&self) -> usize {
63        3 + self.address.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 mut buf = [0; 2];
82        r.read_exact(&mut buf).await?;
83
84        if buf[1] != 0x00 {
85            return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid reserved byte"));
86        }
87
88        let command = Command::try_from(buf[0])?;
89        let address = Address::retrieve_from_async_stream(r).await?;
90
91        Ok(Self { command, address })
92    }
93}