Skip to main content

rtci_host/
net_io.rs

1// Copyright 2026 Brainwires. MIT OR Apache-2.0.
2
3//! The socket factory ([`NetIo`]): the only place the engine creates
4//! sockets and resolves names. [`PlainNetIo`] is the operating system's own
5//! (socket2 and tokio); a front end may route them elsewhere (Deno's kernel
6//! sandbox broker, for one).
7//!
8//! The engine asks its [`NetGate`](crate::NetGate) before it calls any of
9//! these, and each call that creates a socket or resolves a name carries the
10//! [`GateToken`] the allow minted (its [`GateToken::reach`] is the question
11//! the gate allowed). [`NetIo::route_probe`] takes none: it sends nothing,
12//! and the engine probes only addresses ICE or the gate vouched for.
13
14use std::io;
15use std::net::IpAddr;
16use std::net::Ipv4Addr;
17use std::net::Ipv6Addr;
18use std::net::SocketAddr;
19
20use tokio::net::TcpListener;
21use tokio::net::TcpStream;
22use tokio::net::UdpSocket;
23
24use crate::gate::GateToken;
25use crate::gate::LocalBoxFuture;
26
27/// How [`NetIo::bind_udp`] binds.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29#[non_exhaustive]
30pub struct UdpOpts {
31  /// An IPv6 socket accepts IPv6 only (the engine keeps the two families
32  /// on sockets of their own).
33  pub ipv6_only: bool,
34}
35
36impl UdpOpts {
37  /// The engine's options for a socket on `addr`: IPv6-only for an IPv6
38  /// address.
39  pub fn for_addr(addr: SocketAddr) -> Self {
40    Self {
41      ipv6_only: addr.is_ipv6(),
42    }
43  }
44}
45
46/// The socket factory.
47pub trait NetIo {
48  /// A non-blocking UDP socket bound on `addr` (port 0: any). `token`
49  /// allowed a [`ReachKind::Bind`](crate::ReachKind::Bind) on `addr`'s IP.
50  fn bind_udp(
51    &self,
52    token: &GateToken,
53    addr: SocketAddr,
54    opts: UdpOpts,
55  ) -> io::Result<UdpSocket>;
56
57  /// The mDNS socket: `0.0.0.0:5353` with address (and port) reuse, so it
58  /// shares the port with the host's own responder, in the mDNS group on
59  /// each IPv4 address of `hosts` (or the default interface). See
60  /// [`mdns_socket`]. `token` allowed the
61  /// [`ReachKind::Mdns`](crate::ReachKind::Mdns) bind on `0.0.0.0`.
62  fn bind_mdns(
63    &self,
64    token: &GateToken,
65    hosts: &[IpAddr],
66  ) -> io::Result<UdpSocket>;
67
68  /// A TCP listener on `addr` (an IPv6 one IPv6-only). `token` allowed a
69  /// [`ReachKind::Bind`](crate::ReachKind::Bind) on `addr`'s IP.
70  fn bind_tcp(
71    &self,
72    token: &GateToken,
73    addr: SocketAddr,
74  ) -> io::Result<TcpListener>;
75
76  /// A TCP connection to `to`, from `bind` (port 0) when given (the engine
77  /// passes only a `bind` of `to`'s family). `host` is the name `to` was
78  /// resolved from, when there is one (a TURN server's). `token` allowed
79  /// `to`: a [`ReachKind::TcpDial`](crate::ReachKind::TcpDial) (ICE-TCP) or
80  /// a [`ReachKind::IceServerResolved`](crate::ReachKind::IceServerResolved)
81  /// (a TURN server over TCP / TLS).
82  fn connect_tcp<'a>(
83    &'a self,
84    token: &'a GateToken,
85    bind: Option<IpAddr>,
86    to: SocketAddr,
87    host: Option<&'a str>,
88  ) -> LocalBoxFuture<'a, io::Result<TcpStream>>;
89
90  /// Resolves `host` (an ICE server URL's host: a name, an IP literal, or a
91  /// bracketed IPv6 literal) and `port`. `token` allowed the
92  /// [`ReachKind::IceServer`](crate::ReachKind::IceServer) question for
93  /// `host` and `port`.
94  fn resolve<'a>(
95    &'a self,
96    token: &'a GateToken,
97    host: &'a str,
98    port: u16,
99  ) -> LocalBoxFuture<'a, io::Result<Vec<SocketAddr>>>;
100
101  /// The local IP the OS sends to `peer` from: a connected UDP probe (no
102  /// datagram leaves the machine), or `None`.
103  fn route_probe(&self, peer: IpAddr) -> Option<IpAddr>;
104}
105
106/// The operating system's sockets and resolver, unrouted.
107#[derive(Clone, Copy, Debug, Default)]
108pub struct PlainNetIo;
109
110impl NetIo for PlainNetIo {
111  fn bind_udp(
112    &self,
113    _token: &GateToken,
114    addr: SocketAddr,
115    opts: UdpOpts,
116  ) -> io::Result<UdpSocket> {
117    let domain = if addr.is_ipv4() {
118      socket2::Domain::IPV4
119    } else {
120      socket2::Domain::IPV6
121    };
122    let socket = socket2::Socket::new(
123      domain,
124      socket2::Type::DGRAM,
125      Some(socket2::Protocol::UDP),
126    )?;
127    if addr.is_ipv6() && opts.ipv6_only {
128      socket.set_only_v6(true)?;
129    }
130    socket.set_nonblocking(true)?;
131    socket.bind(&addr.into())?;
132    UdpSocket::from_std(socket.into())
133  }
134
135  fn bind_mdns(
136    &self,
137    _token: &GateToken,
138    hosts: &[IpAddr],
139  ) -> io::Result<UdpSocket> {
140    let socket = socket2::Socket::new(
141      socket2::Domain::IPV4,
142      socket2::Type::DGRAM,
143      Some(socket2::Protocol::UDP),
144    )?;
145    mdns_socket(socket, false, hosts)
146  }
147
148  fn bind_tcp(
149    &self,
150    _token: &GateToken,
151    addr: SocketAddr,
152  ) -> io::Result<TcpListener> {
153    let domain = if addr.is_ipv4() {
154      socket2::Domain::IPV4
155    } else {
156      socket2::Domain::IPV6
157    };
158    let socket = socket2::Socket::new(
159      domain,
160      socket2::Type::STREAM,
161      Some(socket2::Protocol::TCP),
162    )?;
163    if addr.is_ipv6() {
164      socket.set_only_v6(true)?;
165    }
166    #[cfg(not(windows))]
167    socket.set_reuse_address(true)?;
168    socket.set_nonblocking(true)?;
169    socket.bind(&addr.into())?;
170    socket.listen(128)?;
171    TcpListener::from_std(socket.into())
172  }
173
174  fn connect_tcp<'a>(
175    &'a self,
176    _token: &'a GateToken,
177    bind: Option<IpAddr>,
178    to: SocketAddr,
179    _host: Option<&'a str>,
180  ) -> LocalBoxFuture<'a, io::Result<TcpStream>> {
181    Box::pin(async move {
182      let Some(ip) = bind else {
183        return TcpStream::connect(to).await;
184      };
185      let socket = if to.is_ipv4() {
186        tokio::net::TcpSocket::new_v4()?
187      } else {
188        tokio::net::TcpSocket::new_v6()?
189      };
190      if ip.is_ipv4() == to.is_ipv4() {
191        socket.bind(SocketAddr::new(ip, 0))?;
192      }
193      socket.connect(to).await
194    })
195  }
196
197  fn resolve<'a>(
198    &'a self,
199    _token: &'a GateToken,
200    host: &'a str,
201    port: u16,
202  ) -> LocalBoxFuture<'a, io::Result<Vec<SocketAddr>>> {
203    Box::pin(async move {
204      let host = lookup_name(host);
205      Ok(tokio::net::lookup_host((host, port)).await?.collect())
206    })
207  }
208
209  fn route_probe(&self, peer: IpAddr) -> Option<IpAddr> {
210    let unspecified: IpAddr = if peer.is_ipv4() {
211      Ipv4Addr::UNSPECIFIED.into()
212    } else {
213      Ipv6Addr::UNSPECIFIED.into()
214    };
215    let probe = std::net::UdpSocket::bind((unspecified, 0)).ok()?;
216    probe.connect((peer, 9)).ok()?;
217    Some(probe.local_addr().ok()?.ip())
218  }
219}
220
221/// The name [`PlainNetIo::resolve`] looks up for `host`, as Deno's
222/// `resolve_addr` does: an empty host is `0.0.0.0`, IPv6 brackets go, and a
223/// subdomain of `localhost` (RFC 6761 section 6.3) is `localhost`.
224fn lookup_name(host: &str) -> &str {
225  if host.is_empty() {
226    return "0.0.0.0";
227  }
228  let addr = host.trim_start_matches('[').trim_end_matches(']');
229  let name = addr.strip_suffix('.').unwrap_or(addr).to_ascii_lowercase();
230  if name.len() > ".localhost".len() && name.ends_with(".localhost") {
231    return "localhost";
232  }
233  addr
234}
235
236/// Finishes an mDNS socket (IPv4, UDP): reuse options and the bind on
237/// `0.0.0.0:5353` unless `bound` (a socket handed out bound already, as a
238/// sandbox broker does), non-blocking, multicast TTL 255 with loopback, and
239/// the mDNS group joined on each non-loopback IPv4 address of `hosts` (on
240/// the default interface when none joins). For [`NetIo::bind_mdns`]
241/// implementations.
242pub fn mdns_socket(
243  socket: socket2::Socket,
244  bound: bool,
245  hosts: &[IpAddr],
246) -> io::Result<UdpSocket> {
247  let mdns_addr =
248    SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), rtci::mdns::MDNS_PORT);
249  if !bound {
250    socket.set_reuse_address(true)?;
251    #[cfg(all(unix, not(target_os = "solaris"), not(target_os = "illumos")))]
252    socket.set_reuse_port(true)?;
253  }
254  socket.set_nonblocking(true)?;
255  socket.set_multicast_ttl_v4(255)?;
256  socket.set_multicast_loop_v4(true)?;
257  if !bound {
258    socket.bind(&mdns_addr.into())?;
259  }
260  let group = rtci::mdns::MDNS_MULTICAST_IPV4;
261  let mut joined = false;
262  for ip in hosts {
263    if let IpAddr::V4(iface) = ip
264      && !iface.is_loopback()
265      && socket.join_multicast_v4(&group, iface).is_ok()
266    {
267      joined = true;
268    }
269  }
270  if !joined {
271    socket.join_multicast_v4(&group, &Ipv4Addr::UNSPECIFIED)?;
272  }
273  UdpSocket::from_std(socket.into())
274}
275
276#[cfg(test)]
277mod tests {
278  use super::lookup_name;
279
280  #[test]
281  fn lookup_name_matches_deno_resolve_addr() {
282    assert_eq!(lookup_name(""), "0.0.0.0");
283    assert_eq!(lookup_name("[::1]"), "::1");
284    assert_eq!(lookup_name("stun.example"), "stun.example");
285    assert_eq!(lookup_name("app.localhost"), "localhost");
286    assert_eq!(lookup_name("App.Localhost."), "localhost");
287    assert_eq!(lookup_name("localhost"), "localhost");
288  }
289}