socks5_impl/protocol/
udp.rs

1#[cfg(feature = "tokio")]
2use crate::protocol::AsyncStreamOperation;
3use crate::protocol::{Address, StreamOperation};
4#[cfg(feature = "tokio")]
5use tokio::io::{AsyncRead, AsyncReadExt};
6
7/// SOCKS5 UDP packet header
8///
9/// ```plain
10/// +-----+------+------+----------+----------+----------+
11/// | RSV | FRAG | ATYP | DST.ADDR | DST.PORT |   DATA   |
12/// +-----+------+------+----------+----------+----------+
13/// |  2  |  1   |  1   | Variable |    2     | Variable |
14/// +-----+------+------+----------+----------+----------+
15/// ```
16#[derive(Clone, Debug)]
17pub struct UdpHeader {
18    pub frag: u8,
19    pub address: Address,
20}
21
22impl UdpHeader {
23    pub fn new(frag: u8, address: Address) -> Self {
24        Self { frag, address }
25    }
26
27    pub const fn max_serialized_len() -> usize {
28        3 + Address::max_serialized_len()
29    }
30}
31
32impl StreamOperation for UdpHeader {
33    fn retrieve_from_stream<R: std::io::Read>(stream: &mut R) -> std::io::Result<Self> {
34        let mut buf = [0; 3];
35        stream.read_exact(&mut buf)?;
36
37        let frag = buf[2];
38
39        let address = Address::retrieve_from_stream(stream)?;
40        Ok(Self { frag, address })
41    }
42
43    fn write_to_buf<B: bytes::BufMut>(&self, buf: &mut B) {
44        buf.put_bytes(0x00, 2);
45        buf.put_u8(self.frag);
46        self.address.write_to_buf(buf);
47    }
48
49    fn len(&self) -> usize {
50        3 + self.address.len()
51    }
52}
53
54#[cfg(feature = "tokio")]
55#[async_trait::async_trait]
56impl AsyncStreamOperation for UdpHeader {
57    async fn retrieve_from_async_stream<R>(r: &mut R) -> std::io::Result<Self>
58    where
59        R: AsyncRead + Unpin + Send + ?Sized,
60    {
61        let mut buf = [0; 3];
62        r.read_exact(&mut buf).await?;
63
64        let frag = buf[2];
65
66        let address = Address::retrieve_from_async_stream(r).await?;
67        Ok(Self { frag, address })
68    }
69}