use std::io;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::task::{Context, Poll};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use crate::packet::{status, Header, PacketType, HEADER_LEN};
#[derive(Debug, Clone, Default)]
pub struct TunnelMode(Arc<AtomicBool>);
impl TunnelMode {
pub fn new_handshake() -> Self {
Self(Arc::new(AtomicBool::new(true)))
}
pub fn set_passthrough(&self) {
self.0.store(false, Ordering::SeqCst);
}
#[inline]
fn is_handshake(&self) -> bool {
self.0.load(Ordering::SeqCst)
}
}
#[derive(Debug)]
enum ReadPhase {
Idle,
Header { hdr_fill: usize },
Body { body_fill: usize, body_len: usize },
Deliver { body_pos: usize, body_len: usize },
Raw { peeked: Option<u8> },
}
pub struct TlsTunnel<S> {
inner: S,
mode: TunnelMode,
r_hdr: [u8; HEADER_LEN],
r_body: Vec<u8>,
r_phase: ReadPhase,
w_buf: Vec<u8>,
w_pos: usize,
packet_id: u8,
}
impl<S> TlsTunnel<S> {
pub fn new(inner: S, mode: TunnelMode) -> Self {
Self {
inner,
mode,
r_hdr: [0u8; HEADER_LEN],
r_body: Vec::new(),
r_phase: ReadPhase::Idle,
w_buf: Vec::new(),
w_pos: 0,
packet_id: 1,
}
}
pub fn get_ref(&self) -> &S {
&self.inner
}
pub fn into_inner(self) -> S {
self.inner
}
}
impl<S: AsyncRead + AsyncWrite + Unpin> AsyncRead for TlsTunnel<S> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let this = self.get_mut();
loop {
match this.r_phase {
ReadPhase::Idle => {
let mut one = [0u8; 1];
let mut peek = ReadBuf::new(&mut one);
match Pin::new(&mut this.inner).poll_read(cx, &mut peek) {
Poll::Ready(Ok(())) => {
let n = peek.filled().len();
if n == 0 {
return Poll::Ready(Ok(()));
}
if one[0] == PacketType::PreLogin as u8 {
this.r_hdr[0] = one[0];
this.r_phase = ReadPhase::Header { hdr_fill: 1 };
} else {
this.r_phase = ReadPhase::Raw {
peeked: Some(one[0]),
};
}
}
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Pending => return Poll::Pending,
}
}
ReadPhase::Header { hdr_fill } => {
if hdr_fill < HEADER_LEN {
let mut hbuf = ReadBuf::new(&mut this.r_hdr[hdr_fill..HEADER_LEN]);
match Pin::new(&mut this.inner).poll_read(cx, &mut hbuf) {
Poll::Ready(Ok(())) => {
let n = hbuf.filled().len();
if n == 0 {
return Poll::Ready(Err(io::Error::from(
io::ErrorKind::UnexpectedEof,
)));
}
this.r_phase = ReadPhase::Header {
hdr_fill: hdr_fill + n,
};
}
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Pending => return Poll::Pending,
}
} else {
let hdr = Header::decode(&this.r_hdr).map_err(io::Error::other)?;
if hdr.ptype != PacketType::PreLogin {
return Poll::Ready(Err(io::Error::other(
"tls-tunnel: framed header had non-PRELOGIN packet type",
)));
}
let body_len = (hdr.length as usize).saturating_sub(HEADER_LEN);
if body_len == 0 {
this.r_phase = ReadPhase::Idle;
} else {
if this.r_body.len() < body_len {
this.r_body.resize(body_len, 0);
}
this.r_phase = ReadPhase::Body {
body_fill: 0,
body_len,
};
}
}
}
ReadPhase::Body {
body_fill,
body_len,
} => {
if body_fill < body_len {
let mut bbuf = ReadBuf::new(&mut this.r_body[body_fill..body_len]);
match Pin::new(&mut this.inner).poll_read(cx, &mut bbuf) {
Poll::Ready(Ok(())) => {
let n = bbuf.filled().len();
if n == 0 {
return Poll::Ready(Err(io::Error::from(
io::ErrorKind::UnexpectedEof,
)));
}
this.r_phase = ReadPhase::Body {
body_fill: body_fill + n,
body_len,
};
}
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Pending => return Poll::Pending,
}
} else {
this.r_phase = ReadPhase::Deliver {
body_pos: 0,
body_len,
};
}
}
ReadPhase::Deliver { body_pos, body_len } => {
let n = (body_len - body_pos).min(buf.remaining());
if n == 0 {
return Poll::Ready(Ok(()));
}
buf.put_slice(&this.r_body[body_pos..body_pos + n]);
let new_pos = body_pos + n;
if new_pos == body_len {
this.r_phase = ReadPhase::Idle;
} else {
this.r_phase = ReadPhase::Deliver {
body_pos: new_pos,
body_len,
};
}
return Poll::Ready(Ok(()));
}
ReadPhase::Raw { peeked } => {
if let Some(b) = peeked {
if buf.remaining() == 0 {
return Poll::Ready(Ok(()));
}
buf.put_slice(&[b]);
this.r_phase = ReadPhase::Raw { peeked: None };
}
match Pin::new(&mut this.inner).poll_read(cx, buf) {
Poll::Ready(Ok(())) => {
this.r_phase = ReadPhase::Idle;
return Poll::Ready(Ok(()));
}
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Pending => {
if !buf.filled().is_empty() {
return Poll::Ready(Ok(()));
}
return Poll::Pending;
}
}
}
}
}
}
}
impl<S: AsyncRead + AsyncWrite + Unpin> AsyncWrite for TlsTunnel<S> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
data: &[u8],
) -> Poll<io::Result<usize>> {
let this = self.get_mut();
if !this.mode.is_handshake() {
return Pin::new(&mut this.inner).poll_write(cx, data);
}
while this.w_pos < this.w_buf.len() {
match Pin::new(&mut this.inner).poll_write(cx, &this.w_buf[this.w_pos..]) {
Poll::Ready(Ok(0)) => {
return Poll::Ready(Err(io::Error::from(io::ErrorKind::WriteZero)));
}
Poll::Ready(Ok(n)) => this.w_pos += n,
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Pending => return Poll::Pending,
}
}
if data.is_empty() {
return Poll::Ready(Ok(0));
}
const MAX_BODY: usize = u16::MAX as usize - HEADER_LEN;
let chunk_len = data.len().min(MAX_BODY);
let mut hbuf = [0u8; HEADER_LEN];
let hdr = Header::new(
PacketType::PreLogin,
status::END_OF_MESSAGE,
(HEADER_LEN + chunk_len) as u16,
this.packet_id,
);
hdr.encode(&mut hbuf);
this.packet_id = this.packet_id.wrapping_add(1);
this.w_buf.clear();
this.w_buf.reserve(HEADER_LEN + chunk_len);
this.w_buf.extend_from_slice(&hbuf);
this.w_buf.extend_from_slice(&data[..chunk_len]);
this.w_pos = 0;
while this.w_pos < this.w_buf.len() {
match Pin::new(&mut this.inner).poll_write(cx, &this.w_buf[this.w_pos..]) {
Poll::Ready(Ok(0)) => {
return Poll::Ready(Err(io::Error::from(io::ErrorKind::WriteZero)));
}
Poll::Ready(Ok(n)) => this.w_pos += n,
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Pending => {
return Poll::Ready(Ok(chunk_len));
}
}
}
Poll::Ready(Ok(chunk_len))
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let this = self.get_mut();
while this.w_pos < this.w_buf.len() {
match Pin::new(&mut this.inner).poll_write(cx, &this.w_buf[this.w_pos..]) {
Poll::Ready(Ok(0)) => {
return Poll::Ready(Err(io::Error::from(io::ErrorKind::WriteZero)));
}
Poll::Ready(Ok(n)) => this.w_pos += n,
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Pending => return Poll::Pending,
}
}
Pin::new(&mut this.inner).poll_flush(cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let this = self.get_mut();
while this.w_pos < this.w_buf.len() {
match Pin::new(&mut this.inner).poll_write(cx, &this.w_buf[this.w_pos..]) {
Poll::Ready(Ok(0)) => {
return Poll::Ready(Err(io::Error::from(io::ErrorKind::WriteZero)));
}
Poll::Ready(Ok(n)) => this.w_pos += n,
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Pending => return Poll::Pending,
}
}
Pin::new(&mut this.inner).poll_shutdown(cx)
}
}