socks5_impl/protocol/
request.rs1#[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#[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 let command = Command::try_from(buf[0])?;
43 let address = Address::retrieve_from_stream(stream)?;
44
45 Ok(Self { command, address })
46 }
47
48 fn write_to_buf<B: bytes::BufMut>(&self, buf: &mut B) {
49 buf.put_u8(Version::V5.into());
50 buf.put_u8(u8::from(self.command));
51 buf.put_u8(0x00);
52 self.address.write_to_buf(buf);
53 }
54
55 fn len(&self) -> usize {
56 3 + self.address.len()
57 }
58}
59
60#[cfg(feature = "tokio")]
61#[async_trait::async_trait]
62impl AsyncStreamOperation for Request {
63 async fn retrieve_from_async_stream<R>(r: &mut R) -> std::io::Result<Self>
64 where
65 R: AsyncRead + Unpin + Send + ?Sized,
66 {
67 let ver = Version::try_from(r.read_u8().await?)?;
68
69 if ver != Version::V5 {
70 let err = format!("Unsupported SOCKS version {0:#x}", u8::from(ver));
71 return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err));
72 }
73
74 let mut buf = [0; 2];
75 r.read_exact(&mut buf).await?;
76
77 let command = Command::try_from(buf[0])?;
78 let address = Address::retrieve_from_async_stream(r).await?;
79
80 Ok(Self { command, address })
81 }
82}