rings-node 1.0.0-pre.8

Rings is a browser-native, structured peer-to-peer network: browser tabs and native daemons find each other by DID and talk over WebRTC, routed by a Chord DHT.
Documentation
//! `tcp`: a byte stream over an onion session, native only (#834 D1′, D2′).
//!
//! The exit half is the socket world (`OnionTcpWorld`): a session's target is resolved once to
//! its public addresses and connected, and its two halves are the session's world. The client
//! half is [`NativeOnionOpenStream`]: a session opened over a route, relayed against a local
//! byte stream (a CONNECT tunnel or a captured gateway flow) by the shared duplex pump.
//!
//! ```text
//! local ─read─▶ pump ─data─▶ session ═loops═▶ h ─write─▶ target
//! local ◀write─ pump ◀data── session ◀replies═ h ◀read── target    (only while h holds credit)
//! ```
//!
//! Law (pause): `h` reads its socket only while the session holds reply blocks, so an
//! unreplenished session pauses the target instead of dropping its bytes, and resumes on credit.
//!
//! Law (fail closed): a session that ends by `abort`, a gap, or any failure resets the local
//! stream ([`OnionLocalStream::reset`], an RST for a socket); only a pump whose incoming bytes
//! ended with the session's `fin` closes it cleanly, so a truncated stream is never presented as
//! complete, and a complete one is never reset.

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;

/// Largest read of the local stream, split into frames by the session.
const TCP_BUF: usize = 30_000;

/// Longest wait for a target to connect.
const TCP_OPEN_TIMEOUT: Duration = Duration::from_secs(30);

/// The quantum a connect result is delayed to, so a client learns the resolver's and the
/// target's timing only to this resolution.
const TCP_OPEN_RESPONSE_QUANTUM_MS: u128 = 250;

/// The instant a connect result that took `now − opened_at` is released at: the next multiple
/// of the quantum after `opened_at`, at least one quantum.
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)
}

/// Connect the first public address of `target` that answers.
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()
    )))
}

/// The failure of the `tcp` world at its target, named as the onion `tcp` layer's.
fn tcp_target(reason: String) -> Error {
    Error::OnionRouteError(OnionRouteError::TcpTarget(reason))
}

/// The socket world of a `tcp` exit, whose reads are recorded against the exit's byte policy.
pub(crate) struct OnionTcpWorld {
    /// The policy whose byte budget the reads are recorded against.
    policy: OnionExitPolicy,
    /// The node-wide exit accounting.
    accounting: OnionExitAccounting,
}

impl OnionTcpWorld {
    /// The socket world recording its reads against `policy` in `accounting`.
    pub(crate) const fn new(policy: OnionExitPolicy, accounting: OnionExitAccounting) -> Self {
        Self { policy, accounting }
    }
}

/// The read half of a connected target, which records every byte it reads.
pub(crate) struct OnionTcpReader {
    /// The socket half.
    half: OwnedReadHalf,
    /// The policy whose byte budget the reads are recorded against.
    policy: OnionExitPolicy,
    /// The node-wide exit accounting.
    accounting: OnionExitAccounting,
    /// The read buffer, reused across reads: a read fills only what arrives, never zeroing.
    buffer: BytesMut,
}

/// The write half of a connected target.
pub(crate) struct OnionTcpWriter(OwnedWriteHalf);

#[cfg(all(test, rings_native))]
impl OnionTcpReader {
    /// Wrap an already-split read half for unit tests.
    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 {
    /// Wrap an already-split write half for unit tests.
    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;

    /// Resolve and connect `target`, releasing the result, success or failure, at the next open
    /// quantum.
    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 {
    /// Read up to `max` bytes and record them against the byte policy; a spent budget is a
    /// failure, which aborts the session.
    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}")))
    }
}

/// A client `tcp` session whose exit has connected its target.
pub struct NativeOnionOpenStream {
    /// The open session.
    stream: OnionClientStream,
}

impl NativeOnionOpenStream {
    /// Wrap an opened session.
    pub(crate) const fn new(stream: OnionClientStream) -> Self {
        Self { stream }
    }

    /// Relay the local byte stream `local` through the session, until both directions close or
    /// it idles for `RELAY_IDLE_TIMEOUT` (5 min); a pump whose incoming bytes did not end with
    /// the session's `fin` resets `local` (see the module's fail-closed law).
    pub fn relay<S>(self, local: S)
    where S: OnionLocalStream {
        let _ = self.relay_with(local, Some(RELAY_IDLE_TIMEOUT));
    }

    /// [`Self::relay`] for a boundary that owns the stream's idleness and cannot express a reset
    /// on `local` itself, such as a captured gateway flow (#950): no idle clock of the pump's
    /// own, and the session's witness returned, which reads `Failed` before a failed pump resets
    /// `local` (`session::witness`, Law Report before end), so the boundary never reads that
    /// reset as a clean end.
    pub(crate) fn relay_witnessed<S>(self, local: S) -> OnionSessionWitness
    where S: OnionLocalStream {
        self.relay_with(local, None)
    }

    /// Spawn the pump of `local` against the session, as a task of the session's node, with the
    /// idle timeout `idle_timeout`, or none; a failed pump records the failure in the session's
    /// witness, then resets `local`. The node's stop ends the pump as failed, since its bytes
    /// did not end with the session's `fin`; with no executor to pump on, the session fails at
    /// once.
    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
    }
}

/// A local byte stream a client `tcp` session is relayed against, with the effect that ends it
/// as failed.
///
/// Law: `reset` is observably distinct from a clean close to the stream's peer wherever the
/// stream's transport can express it, so a failed session is never read as a complete one.
pub trait OnionLocalStream:
    tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static
{
    /// End the stream as failed: never a clean shutdown.
    fn reset(self);
}

impl OnionLocalStream for TcpStream {
    /// An RST: `SO_LINGER = 0` makes the close abortive, discarding unsent bytes.
    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;