rings_node/onion/tcp/
mod.rs1use 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
56const TCP_BUF: usize = 30_000;
58
59const TCP_OPEN_TIMEOUT: Duration = Duration::from_secs(30);
61
62const TCP_OPEN_RESPONSE_QUANTUM_MS: u128 = 250;
65
66fn 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
78async 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
94fn tcp_target(reason: String) -> Error {
96 Error::OnionRouteError(OnionRouteError::TcpTarget(reason))
97}
98
99pub(crate) struct OnionTcpWorld {
101 policy: OnionExitPolicy,
103 accounting: OnionExitAccounting,
105}
106
107impl OnionTcpWorld {
108 pub(crate) const fn new(policy: OnionExitPolicy, accounting: OnionExitAccounting) -> Self {
110 Self { policy, accounting }
111 }
112}
113
114pub(crate) struct OnionTcpReader {
116 half: OwnedReadHalf,
118 policy: OnionExitPolicy,
120 accounting: OnionExitAccounting,
122 buffer: BytesMut,
124}
125
126pub(crate) struct OnionTcpWriter(OwnedWriteHalf);
128
129#[cfg(all(test, rings_native))]
130impl OnionTcpReader {
131 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 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 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 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
222pub struct NativeOnionOpenStream {
224 stream: OnionClientStream,
226}
227
228impl NativeOnionOpenStream {
229 pub(crate) const fn new(stream: OnionClientStream) -> Self {
231 Self { stream }
232 }
233
234 pub fn relay<S>(self, local: S)
238 where S: OnionLocalStream {
239 let _ = self.relay_with(local, Some(RELAY_IDLE_TIMEOUT));
240 }
241
242 pub(crate) fn relay_witnessed<S>(self, local: S) -> OnionSessionWitness
248 where S: OnionLocalStream {
249 self.relay_with(local, None)
250 }
251
252 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
287pub trait OnionLocalStream:
293 tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static
294{
295 fn reset(self);
297}
298
299impl OnionLocalStream for TcpStream {
300 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;