vproxy 2.5.5

A high-performance HTTP/HTTPS/SOCKS5 proxy server
use smallvec::SmallVec;
use tokio::io::{AsyncRead, AsyncReadExt};

use crate::server::socks::proto::{AsyncStreamOperation, Method, StreamOperation, Version};

/// SOCKS5 handshake request
///
/// ```plain
/// +-----+----------+----------+
/// | VER | NMETHODS | METHODS  |
/// +-----+----------+----------+
/// |  1  |    1     | 1 to 255 |
/// +-----+----------+----------|
/// ```
#[derive(Clone, Debug)]
pub struct Request {
    methods: SmallVec<[Method; 8]>,
}

impl Request {
    pub fn evaluate_method(&self, server_method: Method) -> bool {
        self.methods.contains(&server_method)
    }
}

impl StreamOperation for Request {
    fn retrieve_from_stream<R: std::io::Read>(r: &mut R) -> std::io::Result<Self> {
        let mut ver = [0; 1];
        r.read_exact(&mut ver)?;
        let ver = Version::try_from(ver[0])?;

        if ver != Version::V5 {
            let err = format!("Unsupported SOCKS version {0:#x}", u8::from(ver));
            return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err));
        }

        let mut mlen = [0; 1];
        r.read_exact(&mut mlen)?;
        let mlen = mlen[0];

        let mut methods: SmallVec<[u8; 8]> = SmallVec::with_capacity(mlen as usize);
        r.read_exact(&mut methods)?;

        Ok(Self {
            methods: methods.into_iter().map(Method::from).collect(),
        })
    }

    fn write_to_buf<B: bytes::BufMut>(&self, buf: &mut B) {
        buf.put_u8(Version::V5.into());
        buf.put_u8(self.methods.len() as u8);
        for &method in &self.methods {
            buf.put_u8(u8::from(method));
        }
    }

    #[inline]
    fn len(&self) -> usize {
        2 + self.methods.len()
    }
}

impl AsyncStreamOperation for Request {
    async fn retrieve_from_async_stream<R>(r: &mut R) -> std::io::Result<Self>
    where
        R: AsyncRead + Unpin + Send,
    {
        let ver = Version::try_from(r.read_u8().await?)?;

        if ver != Version::V5 {
            let err = format!("Unsupported SOCKS version {0:#x}", u8::from(ver));
            return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err));
        }

        let mlen = r.read_u8().await?;
        let mut methods = vec![0; mlen as usize];
        r.read_exact(&mut methods).await?;

        let methods = methods.into_iter().map(Method::from).collect();

        Ok(Self { methods })
    }
}