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