Skip to main content

rings_node/onion/tcp/
mod.rs

1//! `tcp`: a byte stream over an onion session, native only (#834 D1′, D2′).
2//!
3//! The exit half is the socket world (`OnionTcpWorld`): a session's target is resolved once to
4//! its public addresses and connected, and its two halves are the session's world. The client
5//! half is [`NativeOnionOpenStream`]: a session opened over a route, relayed against a local
6//! byte stream (a CONNECT tunnel or a captured gateway flow) by the shared duplex pump.
7//!
8//! ```text
9//! local ─read─▶ pump ─data─▶ session ═loops═▶ h ─write─▶ target
10//! local ◀write─ pump ◀data── session ◀replies═ h ◀read── target    (only while h holds credit)
11//! ```
12//!
13//! Law (pause): `h` reads its socket only while the session holds reply blocks, so an
14//! unreplenished session pauses the target instead of dropping its bytes, and resumes on credit.
15//!
16//! Law (fail closed): a session that ends by `abort`, a gap, or any failure resets the local
17//! stream ([`OnionLocalStream::reset`], an RST for a socket); only a pump whose incoming bytes
18//! ended with the session's `fin` closes it cleanly, so a truncated stream is never presented as
19//! complete, and a complete one is never reset.
20
21use std::time::Duration;
22
23use bytes::Bytes;
24use bytes::BytesMut;
25use futures::future::select;
26use futures::future::Either;
27use futures::pin_mut;
28use tokio::io::AsyncReadExt;
29use tokio::io::AsyncWriteExt;
30use tokio::net::tcp::OwnedReadHalf;
31use tokio::net::tcp::OwnedWriteHalf;
32use tokio::net::TcpStream;
33use tokio::time::timeout;
34use tokio::time::Instant;
35
36use crate::error::Error;
37use crate::error::Result;
38use crate::extension::transport::RELAY_IDLE_TIMEOUT;
39use crate::onion::exit_accounting::OnionExitAccounting;
40use crate::onion::session::dial::OnionClientStream;
41use crate::onion::session::serve::OnionWorld;
42use crate::onion::session::serve::OnionWorldReader;
43use crate::onion::session::serve::OnionWorldWriter;
44use crate::onion::session::witness::OnionSessionWitness;
45use crate::onion::target::resolve_public_target;
46use crate::onion::OnionExitPolicy;
47use crate::onion::OnionProxyTarget;
48use crate::onion::OnionRouteError;
49
50mod duplex;
51mod pump;
52
53use pump::pump_tcp_duplex;
54use pump::OnionPumpEnd;
55
56/// Largest read of the local stream, split into frames by the session.
57const TCP_BUF: usize = 30_000;
58
59/// Longest wait for a target to connect.
60const TCP_OPEN_TIMEOUT: Duration = Duration::from_secs(30);
61
62/// The quantum a connect result is delayed to, so a client learns the resolver's and the
63/// target's timing only to this resolution.
64const TCP_OPEN_RESPONSE_QUANTUM_MS: u128 = 250;
65
66/// The instant a connect result that took `now − opened_at` is released at: the next multiple
67/// of the quantum after `opened_at`, at least one quantum.
68fn open_response_deadline(opened_at: Instant, now: Instant) -> Instant {
69    let elapsed_ms = now.saturating_duration_since(opened_at).as_millis();
70    let quanta = elapsed_ms.div_ceil(TCP_OPEN_RESPONSE_QUANTUM_MS).max(1);
71    let deadline_ms =
72        u64::try_from(quanta.saturating_mul(TCP_OPEN_RESPONSE_QUANTUM_MS)).unwrap_or(u64::MAX);
73    opened_at
74        .checked_add(Duration::from_millis(deadline_ms))
75        .unwrap_or(now)
76}
77
78/// Connect the first public address of `target` that answers.
79async fn connect(target: &OnionProxyTarget) -> Result<TcpStream> {
80    let addresses = resolve_public_target(target).await?;
81    let mut last = None;
82    for address in addresses {
83        match TcpStream::connect(address).await {
84            Ok(stream) => return Ok(stream),
85            Err(error) => last = Some(error),
86        }
87    }
88    Err(tcp_target(format!(
89        "{} did not connect: {last:?}",
90        target.authority()
91    )))
92}
93
94/// The failure of the `tcp` world at its target, named as the onion `tcp` layer's.
95fn tcp_target(reason: String) -> Error {
96    Error::OnionRouteError(OnionRouteError::TcpTarget(reason))
97}
98
99/// The socket world of a `tcp` exit, whose reads are recorded against the exit's byte policy.
100pub(crate) struct OnionTcpWorld {
101    /// The policy whose byte budget the reads are recorded against.
102    policy: OnionExitPolicy,
103    /// The node-wide exit accounting.
104    accounting: OnionExitAccounting,
105}
106
107impl OnionTcpWorld {
108    /// The socket world recording its reads against `policy` in `accounting`.
109    pub(crate) const fn new(policy: OnionExitPolicy, accounting: OnionExitAccounting) -> Self {
110        Self { policy, accounting }
111    }
112}
113
114/// The read half of a connected target, which records every byte it reads.
115pub(crate) struct OnionTcpReader {
116    /// The socket half.
117    half: OwnedReadHalf,
118    /// The policy whose byte budget the reads are recorded against.
119    policy: OnionExitPolicy,
120    /// The node-wide exit accounting.
121    accounting: OnionExitAccounting,
122    /// The read buffer, reused across reads: a read fills only what arrives, never zeroing.
123    buffer: BytesMut,
124}
125
126/// The write half of a connected target.
127pub(crate) struct OnionTcpWriter(OwnedWriteHalf);
128
129#[cfg(all(test, rings_native))]
130impl OnionTcpReader {
131    /// Wrap an already-split read half for unit tests.
132    pub(crate) fn from_split(
133        half: OwnedReadHalf,
134        policy: OnionExitPolicy,
135        accounting: OnionExitAccounting,
136    ) -> Self {
137        Self {
138            half,
139            policy,
140            accounting,
141            buffer: BytesMut::new(),
142        }
143    }
144}
145
146#[cfg(all(test, rings_native))]
147impl OnionTcpWriter {
148    /// Wrap an already-split write half for unit tests.
149    pub(crate) const fn from_split(half: OwnedWriteHalf) -> Self {
150        Self(half)
151    }
152}
153
154#[async_trait::async_trait]
155impl OnionWorld for OnionTcpWorld {
156    type Reader = OnionTcpReader;
157    type Writer = OnionTcpWriter;
158
159    /// Resolve and connect `target`, releasing the result, success or failure, at the next open
160    /// quantum.
161    async fn open(&self, target: &OnionProxyTarget) -> Result<(Self::Reader, Self::Writer)> {
162        let opened_at = Instant::now();
163        let connected = match timeout(TCP_OPEN_TIMEOUT, connect(target)).await {
164            Ok(connected) => connected,
165            Err(_) => Err(Error::OnionRouteError(OnionRouteError::TcpOpenTimedOut)),
166        };
167        tokio::time::sleep_until(open_response_deadline(opened_at, Instant::now())).await;
168        let (read, write) = connected?.into_split();
169        Ok((
170            OnionTcpReader {
171                half: read,
172                policy: self.policy.clone(),
173                accounting: self.accounting.clone(),
174                buffer: BytesMut::new(),
175            },
176            OnionTcpWriter(write),
177        ))
178    }
179}
180
181#[async_trait::async_trait]
182impl OnionWorldReader for OnionTcpReader {
183    /// Read up to `max` bytes and record them against the byte policy; a spent budget is a
184    /// failure, which aborts the session.
185    async fn read(&mut self, max: usize) -> Result<Option<Bytes>> {
186        let max = max.max(1);
187        self.buffer.reserve(max);
188        let limit = u64::try_from(max).unwrap_or(u64::MAX);
189        let read = (&mut self.half)
190            .take(limit)
191            .read_buf(&mut self.buffer)
192            .await
193            .map_err(|error| tcp_target(format!("read: {error}")))?;
194        if read == 0 {
195            return Ok(None);
196        }
197        let buffer = self.buffer.split();
198        let bytes = u64::try_from(read).map_err(|_| Error::InvalidData)?;
199        self.accounting
200            .record_bytes(&self.policy, bytes, self.accounting.now_ms())?;
201        Ok(Some(buffer.freeze()))
202    }
203}
204
205#[async_trait::async_trait]
206impl OnionWorldWriter for OnionTcpWriter {
207    async fn write(&mut self, bytes: Bytes) -> Result<()> {
208        self.0
209            .write_all(&bytes)
210            .await
211            .map_err(|error| tcp_target(format!("write: {error}")))
212    }
213
214    async fn shutdown(&mut self) -> Result<()> {
215        self.0
216            .shutdown()
217            .await
218            .map_err(|error| tcp_target(format!("shutdown: {error}")))
219    }
220}
221
222/// A client `tcp` session whose exit has connected its target.
223pub struct NativeOnionOpenStream {
224    /// The open session.
225    stream: OnionClientStream,
226}
227
228impl NativeOnionOpenStream {
229    /// Wrap an opened session.
230    pub(crate) const fn new(stream: OnionClientStream) -> Self {
231        Self { stream }
232    }
233
234    /// Relay the local byte stream `local` through the session, until both directions close or
235    /// it idles for `RELAY_IDLE_TIMEOUT` (5 min); a pump whose incoming bytes did not end with
236    /// the session's `fin` resets `local` (see the module's fail-closed law).
237    pub fn relay<S>(self, local: S)
238    where S: OnionLocalStream {
239        let _ = self.relay_with(local, Some(RELAY_IDLE_TIMEOUT));
240    }
241
242    /// [`Self::relay`] for a boundary that owns the stream's idleness and cannot express a reset
243    /// on `local` itself, such as a captured gateway flow (#950): no idle clock of the pump's
244    /// own, and the session's witness returned, which reads `Failed` before a failed pump resets
245    /// `local` (`session::witness`, Law Report before end), so the boundary never reads that
246    /// reset as a clean end.
247    pub(crate) fn relay_witnessed<S>(self, local: S) -> OnionSessionWitness
248    where S: OnionLocalStream {
249        self.relay_with(local, None)
250    }
251
252    /// Spawn the pump of `local` against the session, as a task of the session's node, with the
253    /// idle timeout `idle_timeout`, or none; a failed pump records the failure in the session's
254    /// witness, then resets `local`. The node's stop ends the pump as failed, since its bytes
255    /// did not end with the session's `fin`; with no executor to pump on, the session fails at
256    /// once.
257    fn relay_with<S>(self, local: S, idle_timeout: Option<Duration>) -> OnionSessionWitness
258    where S: OnionLocalStream {
259        let witness = self.stream.witness();
260        let Ok(spawner) = self.stream.tasks().spawner() else {
261            witness.record_failed();
262            local.reset();
263            return witness;
264        };
265        let recorded = witness.clone();
266        let (sender, receiver) = self.stream.split();
267        spawner.spawn_winding_down(move |stop| async move {
268            let mut local = local;
269            let end = {
270                let pump = pump_tcp_duplex(&mut local, sender, receiver, idle_timeout);
271                let stopped = stop.stopped();
272                pin_mut!(pump, stopped);
273                match select(pump, stopped).await {
274                    Either::Left(((_, end), _)) => end,
275                    Either::Right(((), _)) => OnionPumpEnd::Failed,
276                }
277            };
278            if end == OnionPumpEnd::Failed {
279                recorded.record_failed();
280                local.reset();
281            }
282        });
283        witness
284    }
285}
286
287/// A local byte stream a client `tcp` session is relayed against, with the effect that ends it
288/// as failed.
289///
290/// Law: `reset` is observably distinct from a clean close to the stream's peer wherever the
291/// stream's transport can express it, so a failed session is never read as a complete one.
292pub trait OnionLocalStream:
293    tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static
294{
295    /// End the stream as failed: never a clean shutdown.
296    fn reset(self);
297}
298
299impl OnionLocalStream for TcpStream {
300    /// An RST: `SO_LINGER = 0` makes the close abortive, discarding unsent bytes.
301    fn reset(self) {
302        if let Err(error) = self.set_zero_linger() {
303            tracing::debug!(%error, "onion TCP local reset fell back to a close");
304        }
305    }
306}
307
308#[cfg(test)]
309mod tests;