use std::io::{ErrorKind, Read, Write};
use std::net::{SocketAddr, TcpStream, UdpSocket};
use std::time::{Duration, Instant};
use crate::config::limits::CONNECT_PROBE_TIMEOUT;
use crate::fingerprint::Tunnel;
const LARGEST_DATAGRAM: u64 = 65_535;
pub(crate) struct Reply {
pub(crate) bytes: Vec<u8>,
pub(crate) complete: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ExchangeError {
TimedOut,
ConnectionRefused,
Reset,
}
impl ExchangeError {
fn of(error: &std::io::Error) -> Self {
match error.kind() {
ErrorKind::TimedOut | ErrorKind::WouldBlock => Self::TimedOut,
ErrorKind::ConnectionRefused => Self::ConnectionRefused,
_ => Self::Reset,
}
}
}
pub(crate) fn remaining(deadline: Instant) -> Option<Duration> {
deadline
.checked_duration_since(Instant::now())
.filter(|left| !left.is_zero())
}
pub(crate) fn tcp(
addr: SocketAddr,
tunnel: Option<Tunnel>,
bytes: &[u8],
deadline: Instant,
cap: u64,
) -> Result<Reply, ExchangeError> {
let timeout = remaining(deadline).ok_or(ExchangeError::TimedOut)?;
let tcp = TcpStream::connect_timeout(&addr, timeout.min(CONNECT_PROBE_TIMEOUT))
.map_err(|error| ExchangeError::of(&error))?;
tcp.set_read_timeout(Some(remaining(deadline).ok_or(ExchangeError::TimedOut)?))
.map_err(|error| ExchangeError::of(&error))?;
let mut stream = super::tls::wrap(tcp, addr.ip(), tunnel).ok_or(ExchangeError::Reset)?;
stream
.write_all(bytes)
.map_err(|error| ExchangeError::of(&error))?;
let mut reply = Vec::new();
let mut buffer = [0u8; 4096];
let mut closed = false;
while (reply.len() as u64) < cap {
let want = ((cap - reply.len() as u64) as usize).min(buffer.len());
match stream.read(&mut buffer[..want]) {
Ok(0) => {
closed = true;
break;
}
Ok(read) => reply.extend_from_slice(&buffer[..read]),
Err(_) => break,
}
}
Ok(Reply {
bytes: reply,
complete: closed,
})
}
pub(crate) fn udp(
addr: SocketAddr,
bytes: &[u8],
deadline: Instant,
cap: u64,
) -> Result<Reply, ExchangeError> {
let bind = if addr.is_ipv6() {
"[::]:0"
} else {
"0.0.0.0:0"
};
let socket = UdpSocket::bind(bind).map_err(|error| ExchangeError::of(&error))?;
socket
.connect(addr)
.map_err(|error| ExchangeError::of(&error))?;
socket
.set_read_timeout(Some(remaining(deadline).ok_or(ExchangeError::TimedOut)?))
.map_err(|error| ExchangeError::of(&error))?;
socket
.send(bytes)
.map_err(|error| ExchangeError::of(&error))?;
let mut buffer = vec![0u8; cap.min(LARGEST_DATAGRAM) as usize];
match socket.recv(&mut buffer) {
Ok(read) => {
buffer.truncate(read);
Ok(Reply {
bytes: buffer,
complete: true,
})
}
Err(error)
if error.kind() == ErrorKind::TimedOut || error.kind() == ErrorKind::WouldBlock =>
{
Ok(Reply {
bytes: Vec::new(),
complete: true,
})
}
Err(error) => Err(ExchangeError::of(&error)),
}
}