use crate::general::ConnectionTimeouts;
use crate::proxy::ProxyStream;
use tokio::net::TcpStream;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::time::timeout;
use std::pin::Pin;
use core::task::{Poll, Context};
use std::net::SocketAddrV4;
use std::borrow::Cow;
use std::fmt;
use std::io;
pub struct Socks4General {
wrapped_stream: TcpStream
}
pub enum ErrorKind {
ConnectionFailed,
IOError(std::io::Error),
BadBuffer,
RequestDenied,
IdentIsUnavailable,
BadIdent,
OperationTimeoutReached
}
#[repr(u8)]
pub enum Command {
TcpConnectionEstablishment = 1,
TcpPortBinding
}
pub struct ConnParams {
dest_addr: SocketAddrV4,
ident: Cow<'static, str>,
timeouts: ConnectionTimeouts
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self {
ErrorKind::ConnectionFailed => f.write_str("connection failed"),
ErrorKind::IOError(e)
=> f.write_str(&format!("I/O error: {}", e)),
ErrorKind::BadBuffer => f.write_str("bad buffer has been received"),
ErrorKind::RequestDenied => f.write_str("request denied"),
ErrorKind::IdentIsUnavailable => f.write_str("ident is unavailable"),
ErrorKind::BadIdent => f.write_str("bad ident"),
ErrorKind::OperationTimeoutReached => f.write_str("operation timeout reached")
}
}
}
impl ConnParams {
pub fn new(dest_addr: SocketAddrV4, ident: Cow<'static, str>,
timeouts: ConnectionTimeouts)
-> ConnParams
{
ConnParams { dest_addr, ident, timeouts }
}
}
#[async_trait::async_trait]
impl ProxyStream for Socks4General {
type Stream = TcpStream;
type ErrorKind = ErrorKind;
type ConnParams = ConnParams;
async fn connect(mut stream: Self::Stream, params: Self::ConnParams)
-> Result<Self, Self::ErrorKind>
{
let buf_len = 1 + 1 + 2 + 4 + params.ident.len() + 1;
let mut buf = Vec::with_capacity(buf_len);
buf.push(4);
buf.push(Command::TcpConnectionEstablishment as u8);
let port_in_bytes = params.dest_addr.port().to_be_bytes();
buf.extend_from_slice(&port_in_bytes[..]);
let ipaddr_in_bytes = params.dest_addr.ip().octets();
buf.extend_from_slice(&ipaddr_in_bytes[..]);
buf.extend_from_slice(¶ms.ident.as_bytes());
buf.push(0);
let future = stream.write_all(&buf);
let future = timeout(params.timeouts.write_timeout, future);
let _ = future.await.map_err(|_| ErrorKind::OperationTimeoutReached)?
.map_err(|e| ErrorKind::IOError(e))?;
let future = stream.read(&mut buf);
let future = timeout(params.timeouts.read_timeout, future);
let read_bytes = future.await.map_err(|_| ErrorKind::OperationTimeoutReached)?
.map_err(|e| ErrorKind::IOError(e))?;
if read_bytes != 8 {
return Err(ErrorKind::BadBuffer)
}
match buf[1] {
0x5a => Ok(Socks4General { wrapped_stream: stream }),
0x5b => Err(ErrorKind::RequestDenied),
0x5c => Err(ErrorKind::IdentIsUnavailable),
0x5d => Err(ErrorKind::BadIdent),
_ => Err(ErrorKind::BadBuffer)
}
}
}
impl AsyncRead for Socks4General {
fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8])
-> Poll<io::Result<usize>>
{
let pinned = &mut Pin::into_inner(self).wrapped_stream;
Pin::new(pinned).poll_read(cx, buf)
}
}
impl AsyncWrite for Socks4General {
fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8])
-> Poll<Result<usize, io::Error>>
{
let stream = &mut Pin::into_inner(self).wrapped_stream;
Pin::new(stream).poll_write(cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>)
-> Poll<Result<(), io::Error>>
{
let stream = &mut Pin::into_inner(self).wrapped_stream;
Pin::new(stream).poll_flush(cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>)
-> Poll<Result<(), io::Error>>
{
let stream = &mut Pin::into_inner(self).wrapped_stream;
Pin::new(stream).poll_shutdown(cx)
}
}