Skip to main content

pb_mapper_server/direct/
mod.rs

1//! Setup coordination is serialized by the existing routing manager. Established
2//! direct sessions are observations only and never acquire an authorization lease.
3use super::ImutableKey;
4use pb_mapper_auth::AuthContext;
5use pb_mapper_core::conn_id::RemoteConnId;
6use pb_mapper_protocol::direct::*;
7use std::net::{IpAddr, Ipv4Addr, SocketAddr};
8use tokio::sync::{mpsc, oneshot};
9
10#[cfg(feature = "p2p")]
11mod stun;
12
13mod control;
14mod state;
15
16pub(crate) use control::handle_control;
17pub(crate) use state::DirectState;
18
19#[derive(Clone, Debug)]
20pub struct DirectServerConfig {
21    /// UDP address the STUN service binds.
22    pub listen: SocketAddr,
23    /// Public address announced to clients. Port 0 takes the bound port. An
24    /// unspecified IP announces only the port: each client then uses the relay
25    /// IP it dialed, which is right whenever the UDP port is forwarded like the
26    /// TCP one, including behind cloud 1:1 NAT where the host never sees its
27    /// public IP.
28    pub advertise: SocketAddr,
29}
30
31impl DirectServerConfig {
32    /// Direct coordination on the relay's own port number over UDP, announcing
33    /// only that port: each client pairs it with the relay address it dialed.
34    pub fn on_relay_port(ip: IpAddr, port: u16) -> Self {
35        Self {
36            listen: SocketAddr::new(ip, port),
37            advertise: SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0),
38        }
39    }
40
41    /// [`Self::on_relay_port`] if that UDP port can be bound now, so that a
42    /// relay asked for no direct service in particular can still start,
43    /// relay-only, when the port is taken. The probe socket is closed again
44    /// before this returns.
45    pub fn probe_relay_port(ip: IpAddr, port: u16) -> std::io::Result<Self> {
46        let config = Self::on_relay_port(ip, port);
47        drop(std::net::UdpSocket::bind(config.listen)?);
48        Ok(config)
49    }
50}
51
52/// The STUN service direct coordination runs: what it announces to clients,
53/// and the task serving it.
54pub(crate) struct StunService {
55    pub(crate) capability: DirectCapability,
56    pub(crate) task: tokio_util::task::AbortOnDropHandle<()>,
57}
58
59/// Start the STUN service `config` asks for, if any.
60pub(crate) async fn bind(
61    config: Option<DirectServerConfig>,
62) -> std::io::Result<Option<StunService>> {
63    let Some(config) = config else {
64        return Ok(None);
65    };
66    #[cfg(not(feature = "p2p"))]
67    {
68        let _ = config;
69        Err(std::io::Error::new(
70            std::io::ErrorKind::Unsupported,
71            "binary built without p2p",
72        ))
73    }
74    #[cfg(feature = "p2p")]
75    {
76        let socket = tokio::net::UdpSocket::bind(config.listen).await?;
77        let mut advertise = config.advertise;
78        if advertise.port() == 0 {
79            advertise.set_port(socket.local_addr()?.port());
80        }
81        if !advertise.ip().is_unspecified() && !valid_candidate(&advertise) {
82            return Err(std::io::Error::other(
83                "direct advertise address must be reachable unicast IP:port",
84            ));
85        }
86        let capability = DirectCapability {
87            version: DIRECT_VERSION,
88            stun_addr: advertise,
89        };
90        if advertise.ip().is_unspecified() {
91            tracing::info!(
92                event = "direct_service_listening",
93                listen = %socket.local_addr()?,
94                advertise_port = advertise.port(),
95                "direct coordination announces its port; clients pair it with the relay address they dialed"
96            );
97        } else {
98            tracing::info!(event = "direct_service_listening", listen = %socket.local_addr()?, %advertise);
99        }
100        let task = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
101            if let Err(error) = stun::serve(socket).await {
102                tracing::error!(%error, "STUN service stopped");
103            }
104        }));
105        Ok(Some(StunService { capability, task }))
106    }
107}
108
109pub type RelaySelection = (ImutableKey, RemoteConnId, u64);
110
111pub enum DirectTask {
112    Connect {
113        connection: RemoteConnId,
114        namespace: u64,
115        auth: AuthContext,
116        sender: mpsc::Sender<DirectEvent>,
117    },
118    Client {
119        connection: RemoteConnId,
120        message: DirectClientMessage,
121    },
122    Provider {
123        connection: RemoteConnId,
124        key: ImutableKey,
125        message: DirectProviderMessage,
126    },
127    Disconnect {
128        connection: RemoteConnId,
129    },
130    Relay {
131        auth: AuthContext,
132        namespace: u64,
133        id: SessionId,
134        secret: SessionSecret,
135        response: oneshot::Sender<Option<RelaySelection>>,
136    },
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    /// The default a relay offers: the relay's port, announced without an IP,
144    /// and nothing at all where that UDP port is already taken.
145    #[test]
146    fn the_relay_port_default_yields_to_a_taken_port() {
147        let ip = IpAddr::V4(Ipv4Addr::LOCALHOST);
148        let held = std::net::UdpSocket::bind((ip, 0)).unwrap();
149        let port = held.local_addr().unwrap().port();
150        let config = DirectServerConfig::on_relay_port(ip, port);
151        assert_eq!(config.listen, SocketAddr::new(ip, port));
152        assert_eq!(
153            config.advertise,
154            SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0)
155        );
156        assert!(DirectServerConfig::probe_relay_port(ip, port).is_err());
157        let free = DirectServerConfig::probe_relay_port(ip, 0).unwrap();
158        assert_eq!(free.listen, SocketAddr::new(ip, 0));
159    }
160}