use std::time::Duration;
use bytes::Bytes;
use bytes::BytesMut;
use futures::future::select;
use futures::future::Either;
use futures::pin_mut;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::net::tcp::OwnedReadHalf;
use tokio::net::tcp::OwnedWriteHalf;
use tokio::net::TcpStream;
use tokio::time::timeout;
use tokio::time::Instant;
use crate::error::Error;
use crate::error::Result;
use crate::extension::transport::RELAY_IDLE_TIMEOUT;
use crate::onion::exit_accounting::OnionExitAccounting;
use crate::onion::session::dial::OnionClientStream;
use crate::onion::session::serve::OnionWorld;
use crate::onion::session::serve::OnionWorldReader;
use crate::onion::session::serve::OnionWorldWriter;
use crate::onion::session::witness::OnionSessionWitness;
use crate::onion::target::resolve_public_target;
use crate::onion::OnionExitPolicy;
use crate::onion::OnionProxyTarget;
use crate::onion::OnionRouteError;
mod duplex;
mod pump;
use pump::pump_tcp_duplex;
use pump::OnionPumpEnd;
const TCP_BUF: usize = 30_000;
const TCP_OPEN_TIMEOUT: Duration = Duration::from_secs(30);
const TCP_OPEN_RESPONSE_QUANTUM_MS: u128 = 250;
fn open_response_deadline(opened_at: Instant, now: Instant) -> Instant {
let elapsed_ms = now.saturating_duration_since(opened_at).as_millis();
let quanta = elapsed_ms.div_ceil(TCP_OPEN_RESPONSE_QUANTUM_MS).max(1);
let deadline_ms =
u64::try_from(quanta.saturating_mul(TCP_OPEN_RESPONSE_QUANTUM_MS)).unwrap_or(u64::MAX);
opened_at
.checked_add(Duration::from_millis(deadline_ms))
.unwrap_or(now)
}
async fn connect(target: &OnionProxyTarget) -> Result<TcpStream> {
let addresses = resolve_public_target(target).await?;
let mut last = None;
for address in addresses {
match TcpStream::connect(address).await {
Ok(stream) => return Ok(stream),
Err(error) => last = Some(error),
}
}
Err(tcp_target(format!(
"{} did not connect: {last:?}",
target.authority()
)))
}
fn tcp_target(reason: String) -> Error {
Error::OnionRouteError(OnionRouteError::TcpTarget(reason))
}
pub(crate) struct OnionTcpWorld {
policy: OnionExitPolicy,
accounting: OnionExitAccounting,
}
impl OnionTcpWorld {
pub(crate) const fn new(policy: OnionExitPolicy, accounting: OnionExitAccounting) -> Self {
Self { policy, accounting }
}
}
pub(crate) struct OnionTcpReader {
half: OwnedReadHalf,
policy: OnionExitPolicy,
accounting: OnionExitAccounting,
buffer: BytesMut,
}
pub(crate) struct OnionTcpWriter(OwnedWriteHalf);
#[cfg(all(test, rings_native))]
impl OnionTcpReader {
pub(crate) fn from_split(
half: OwnedReadHalf,
policy: OnionExitPolicy,
accounting: OnionExitAccounting,
) -> Self {
Self {
half,
policy,
accounting,
buffer: BytesMut::new(),
}
}
}
#[cfg(all(test, rings_native))]
impl OnionTcpWriter {
pub(crate) const fn from_split(half: OwnedWriteHalf) -> Self {
Self(half)
}
}
#[async_trait::async_trait]
impl OnionWorld for OnionTcpWorld {
type Reader = OnionTcpReader;
type Writer = OnionTcpWriter;
async fn open(&self, target: &OnionProxyTarget) -> Result<(Self::Reader, Self::Writer)> {
let opened_at = Instant::now();
let connected = match timeout(TCP_OPEN_TIMEOUT, connect(target)).await {
Ok(connected) => connected,
Err(_) => Err(Error::OnionRouteError(OnionRouteError::TcpOpenTimedOut)),
};
tokio::time::sleep_until(open_response_deadline(opened_at, Instant::now())).await;
let (read, write) = connected?.into_split();
Ok((
OnionTcpReader {
half: read,
policy: self.policy.clone(),
accounting: self.accounting.clone(),
buffer: BytesMut::new(),
},
OnionTcpWriter(write),
))
}
}
#[async_trait::async_trait]
impl OnionWorldReader for OnionTcpReader {
async fn read(&mut self, max: usize) -> Result<Option<Bytes>> {
let max = max.max(1);
self.buffer.reserve(max);
let limit = u64::try_from(max).unwrap_or(u64::MAX);
let read = (&mut self.half)
.take(limit)
.read_buf(&mut self.buffer)
.await
.map_err(|error| tcp_target(format!("read: {error}")))?;
if read == 0 {
return Ok(None);
}
let buffer = self.buffer.split();
let bytes = u64::try_from(read).map_err(|_| Error::InvalidData)?;
self.accounting
.record_bytes(&self.policy, bytes, self.accounting.now_ms())?;
Ok(Some(buffer.freeze()))
}
}
#[async_trait::async_trait]
impl OnionWorldWriter for OnionTcpWriter {
async fn write(&mut self, bytes: Bytes) -> Result<()> {
self.0
.write_all(&bytes)
.await
.map_err(|error| tcp_target(format!("write: {error}")))
}
async fn shutdown(&mut self) -> Result<()> {
self.0
.shutdown()
.await
.map_err(|error| tcp_target(format!("shutdown: {error}")))
}
}
pub struct NativeOnionOpenStream {
stream: OnionClientStream,
}
impl NativeOnionOpenStream {
pub(crate) const fn new(stream: OnionClientStream) -> Self {
Self { stream }
}
pub fn relay<S>(self, local: S)
where S: OnionLocalStream {
let _ = self.relay_with(local, Some(RELAY_IDLE_TIMEOUT));
}
pub(crate) fn relay_witnessed<S>(self, local: S) -> OnionSessionWitness
where S: OnionLocalStream {
self.relay_with(local, None)
}
fn relay_with<S>(self, local: S, idle_timeout: Option<Duration>) -> OnionSessionWitness
where S: OnionLocalStream {
let witness = self.stream.witness();
let Ok(spawner) = self.stream.tasks().spawner() else {
witness.record_failed();
local.reset();
return witness;
};
let recorded = witness.clone();
let (sender, receiver) = self.stream.split();
spawner.spawn_winding_down(move |stop| async move {
let mut local = local;
let end = {
let pump = pump_tcp_duplex(&mut local, sender, receiver, idle_timeout);
let stopped = stop.stopped();
pin_mut!(pump, stopped);
match select(pump, stopped).await {
Either::Left(((_, end), _)) => end,
Either::Right(((), _)) => OnionPumpEnd::Failed,
}
};
if end == OnionPumpEnd::Failed {
recorded.record_failed();
local.reset();
}
});
witness
}
}
pub trait OnionLocalStream:
tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static
{
fn reset(self);
}
impl OnionLocalStream for TcpStream {
fn reset(self) {
if let Err(error) = self.set_zero_linger() {
tracing::debug!(%error, "onion TCP local reset fell back to a close");
}
}
}
#[cfg(test)]
mod tests;