pb_mapper_server/direct/
mod.rs1use 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 pub listen: SocketAddr,
23 pub advertise: SocketAddr,
29}
30
31impl DirectServerConfig {
32 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 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
52pub(crate) struct StunService {
55 pub(crate) capability: DirectCapability,
56 pub(crate) task: tokio_util::task::AbortOnDropHandle<()>,
57}
58
59pub(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 #[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}