Skip to main content

rings_node/dns_relay/forward/
mod.rs

1//! The relay's forward: an accepted connection carried to the owner's node over the TCP relay.
2//!
3//! ```text
4//!   forward(s, o, p, h) = carry h·s over the TCP relay to o's relay_service(p)   o ≠ this node
5//!                       = splice h·s with this node's own target of p           o = this node
6//! ```
7//!
8//! The owner's node dials only the services it registered, and it registers only
9//! [`relay_service(p)`](super::relay_service) for each port `p` it serves, so a connection the
10//! ingress carries reaches exactly the local target the owner mapped to that port. A relay node
11//! that serves ports itself is its own owner: the overlay has no hop to itself, so its own
12//! connections go straight to its own targets. Either way the target reads the preamble `h` (a
13//! PROXY protocol header, or nothing) before the client's bytes.
14//!
15//! Either way the forward returns only when the connection is done, so the ingress holds the
16//! connection's admission slot for its whole life; a connection that carries nothing for
17//! [`RELAY_IDLE_TIMEOUT`] is done, as a TCP relay session is.
18
19use std::collections::BTreeMap;
20use std::net::SocketAddr;
21use std::num::NonZeroU16;
22use std::time::Duration;
23
24use async_trait::async_trait;
25use bytes::Bytes;
26use rings_dns_relay::Connection;
27use rings_dns_relay::Forward;
28use thiserror::Error;
29use tokio::io::AsyncReadExt;
30use tokio::io::AsyncWriteExt;
31use tokio::net::tcp::OwnedWriteHalf;
32use tokio::net::TcpStream;
33use tokio::time::timeout;
34use tokio::time::Instant;
35
36use super::relay_service;
37use super::DidOwner;
38use crate::extension::protocols::relay::RelayHandle;
39use crate::extension::transport::RELAY_IDLE_TIMEOUT;
40use crate::prelude::rings_core::dht::Did;
41
42/// Bytes one read of a spliced connection takes at most.
43const SPLICE_BUF: usize = 16 * 1024;
44
45/// Why a connection could not be carried, or ended abnormally.
46#[derive(Debug, Error)]
47pub enum ForwardError {
48    /// The connection is for this node, which serves no such port.
49    #[error("this node serves no port {0}")]
50    NotServed(NonZeroU16),
51    /// This node's own target cannot be reached.
52    #[error("cannot reach {target}: {source}")]
53    Connect {
54        /// The target.
55        target: SocketAddr,
56        /// Why.
57        source: std::io::Error,
58    },
59    /// A spliced connection failed.
60    #[error("spliced connection failed: {0}")]
61    Splice(#[source] std::io::Error),
62    /// A spliced connection carried nothing for this long, so it was closed.
63    #[error("spliced connection idle for {0:?}")]
64    Idle(Duration),
65    /// The TCP relay could not carry the connection.
66    #[error("TCP relay: {0}")]
67    Relay(#[source] crate::error::Error),
68}
69
70/// The forward over a node's TCP relay.
71pub struct RelayForward {
72    relay: RelayHandle,
73    own: Did,
74    own_targets: BTreeMap<u16, SocketAddr>,
75}
76
77impl RelayForward {
78    /// The forward over `relay`, run by the node `own`, which serves each of `own_targets`'
79    /// ports at its local address.
80    pub fn new(
81        relay: RelayHandle,
82        own: Did,
83        own_targets: impl IntoIterator<Item = (u16, SocketAddr)>,
84    ) -> Self {
85        Self {
86            relay,
87            own,
88            own_targets: own_targets.into_iter().collect(),
89        }
90    }
91
92    /// Splice `connection` with this node's own target of its port.
93    async fn splice_own(&self, connection: Connection<DidOwner>) -> Result<(), ForwardError> {
94        let Connection {
95            stream,
96            port,
97            preamble,
98            ..
99        } = connection;
100        let target = *self
101            .own_targets
102            .get(&port.get())
103            .ok_or(ForwardError::NotServed(port))?;
104        let mut upstream = TcpStream::connect(target)
105            .await
106            .map_err(|source| ForwardError::Connect { target, source })?;
107        within(RELAY_IDLE_TIMEOUT, upstream.write_all(&preamble)).await?;
108        splice(stream, upstream, RELAY_IDLE_TIMEOUT).await
109    }
110}
111
112#[async_trait]
113impl Forward for RelayForward {
114    type Error = ForwardError;
115    type Owner = DidOwner;
116
117    async fn forward(&self, connection: Connection<DidOwner>) -> Result<(), ForwardError> {
118        if connection.owner.0 == self.own {
119            return self.splice_own(connection).await;
120        }
121        let Connection {
122            stream,
123            owner,
124            port,
125            preamble,
126        } = connection;
127        self.relay
128            .carry_tcp_stream(
129                stream,
130                owner.0,
131                relay_service(port.get()),
132                Bytes::from(preamble),
133            )
134            .await
135            .map_err(ForwardError::Relay)
136    }
137}
138
139/// `io`, unless it takes longer than `idle`.
140async fn within<T>(
141    idle: Duration,
142    io: impl std::future::Future<Output = std::io::Result<T>>,
143) -> Result<T, ForwardError> {
144    timeout(idle, io)
145        .await
146        .map_err(|_elapsed| ForwardError::Idle(idle))?
147        .map_err(ForwardError::Splice)
148}
149
150/// Splice `client` with `upstream` until both directions have ended, each passing on the other's
151/// end of stream, or until no byte has moved for `idle`.
152///
153/// Only reads are raced: a read is cancel-safe, a write is not, so a write runs to its end (or
154/// to `idle`) before the next read.
155pub(crate) async fn splice(
156    client: TcpStream,
157    upstream: TcpStream,
158    idle: Duration,
159) -> Result<(), ForwardError> {
160    let (mut client_read, mut client_write) = client.into_split();
161    let (mut upstream_read, mut upstream_write) = upstream.into_split();
162    let mut up = vec![0u8; SPLICE_BUF];
163    let mut down = vec![0u8; SPLICE_BUF];
164    let (mut up_open, mut down_open) = (true, true);
165    let deadline = tokio::time::sleep(idle);
166    tokio::pin!(deadline);
167    while up_open || down_open {
168        tokio::select! {
169            read = client_read.read(&mut up), if up_open => {
170                up_open = pass_on(read, &up, &mut upstream_write, idle).await?;
171            }
172            read = upstream_read.read(&mut down), if down_open => {
173                down_open = pass_on(read, &down, &mut client_write, idle).await?;
174            }
175            () = &mut deadline => return Err(ForwardError::Idle(idle)),
176        }
177        deadline.as_mut().reset(Instant::now() + idle);
178    }
179    Ok(())
180}
181
182/// Pass on what one read into `buf` gave: write the bytes to `write`, or at the end of the
183/// stream shut `write` down. Return whether the direction is still open.
184async fn pass_on(
185    read: std::io::Result<usize>,
186    buf: &[u8],
187    write: &mut OwnedWriteHalf,
188    idle: Duration,
189) -> Result<bool, ForwardError> {
190    let len = read.map_err(ForwardError::Splice)?;
191    if len == 0 {
192        within(idle, write.shutdown()).await?;
193        return Ok(false);
194    }
195    let bytes = buf
196        .get(..len)
197        .ok_or_else(|| ForwardError::Splice(std::io::Error::other("read past its buffer")))?;
198    within(idle, write.write_all(bytes)).await?;
199    Ok(true)
200}
201
202#[cfg(test)]
203mod test_forward;