socks5_impl/protocol/
udp.rs1#[cfg(feature = "tokio")]
2use crate::protocol::AsyncStreamOperation;
3use crate::protocol::{Address, StreamOperation};
4#[cfg(feature = "tokio")]
5use tokio::io::{AsyncRead, AsyncReadExt};
6
7#[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 if buf[0] != 0x00 || buf[1] != 0x00 {
38 return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid UDP reserved bytes"));
39 }
40
41 let frag = buf[2];
42
43 let address = Address::retrieve_from_stream(stream)?;
44 Ok(Self { frag, address })
45 }
46
47 fn write_to_buf<B: bytes::BufMut>(&self, buf: &mut B) {
48 buf.put_bytes(0x00, 2);
49 buf.put_u8(self.frag);
50 self.address.write_to_buf(buf);
51 }
52
53 fn len(&self) -> usize {
54 3 + self.address.len()
55 }
56}
57
58#[cfg(feature = "tokio")]
59#[async_trait::async_trait]
60impl AsyncStreamOperation for UdpHeader {
61 async fn retrieve_from_async_stream<R>(r: &mut R) -> std::io::Result<Self>
62 where
63 R: AsyncRead + Unpin + Send + ?Sized,
64 {
65 let mut buf = [0; 3];
66 r.read_exact(&mut buf).await?;
67
68 if buf[0] != 0x00 || buf[1] != 0x00 {
69 return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid UDP reserved bytes"));
70 }
71
72 let frag = buf[2];
73
74 let address = Address::retrieve_from_async_stream(r).await?;
75 Ok(Self { frag, address })
76 }
77}