rtci-host 0.1.0

The host I/O around the sans-I/O rtci WebRTC engine: sockets, timers, STUN/TURN clients, ICE-TCP, mDNS and media, behind a permission gate and a socket factory
Documentation
// Copyright 2026 Brainwires. MIT OR Apache-2.0.

//! The socket factory ([`NetIo`]): the only place the engine creates
//! sockets and resolves names. [`PlainNetIo`] is the operating system's own
//! (socket2 and tokio); a front end may route them elsewhere (Deno's kernel
//! sandbox broker, for one).
//!
//! The engine asks its [`NetGate`](crate::NetGate) before it calls any of
//! these, and each call that creates a socket or resolves a name carries the
//! [`GateToken`] the allow minted (its [`GateToken::reach`] is the question
//! the gate allowed). [`NetIo::route_probe`] takes none: it sends nothing,
//! and the engine probes only addresses ICE or the gate vouched for.

use std::io;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
use std::net::SocketAddr;

use tokio::net::TcpListener;
use tokio::net::TcpStream;
use tokio::net::UdpSocket;

use crate::gate::GateToken;
use crate::gate::LocalBoxFuture;

/// How [`NetIo::bind_udp`] binds.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct UdpOpts {
  /// An IPv6 socket accepts IPv6 only (the engine keeps the two families
  /// on sockets of their own).
  pub ipv6_only: bool,
}

impl UdpOpts {
  /// The engine's options for a socket on `addr`: IPv6-only for an IPv6
  /// address.
  pub fn for_addr(addr: SocketAddr) -> Self {
    Self {
      ipv6_only: addr.is_ipv6(),
    }
  }
}

/// The socket factory.
pub trait NetIo {
  /// A non-blocking UDP socket bound on `addr` (port 0: any). `token`
  /// allowed a [`ReachKind::Bind`](crate::ReachKind::Bind) on `addr`'s IP.
  fn bind_udp(
    &self,
    token: &GateToken,
    addr: SocketAddr,
    opts: UdpOpts,
  ) -> io::Result<UdpSocket>;

  /// The mDNS socket: `0.0.0.0:5353` with address (and port) reuse, so it
  /// shares the port with the host's own responder, in the mDNS group on
  /// each IPv4 address of `hosts` (or the default interface). See
  /// [`mdns_socket`]. `token` allowed the
  /// [`ReachKind::Mdns`](crate::ReachKind::Mdns) bind on `0.0.0.0`.
  fn bind_mdns(
    &self,
    token: &GateToken,
    hosts: &[IpAddr],
  ) -> io::Result<UdpSocket>;

  /// A TCP listener on `addr` (an IPv6 one IPv6-only). `token` allowed a
  /// [`ReachKind::Bind`](crate::ReachKind::Bind) on `addr`'s IP.
  fn bind_tcp(
    &self,
    token: &GateToken,
    addr: SocketAddr,
  ) -> io::Result<TcpListener>;

  /// A TCP connection to `to`, from `bind` (port 0) when given (the engine
  /// passes only a `bind` of `to`'s family). `host` is the name `to` was
  /// resolved from, when there is one (a TURN server's). `token` allowed
  /// `to`: a [`ReachKind::TcpDial`](crate::ReachKind::TcpDial) (ICE-TCP) or
  /// a [`ReachKind::IceServerResolved`](crate::ReachKind::IceServerResolved)
  /// (a TURN server over TCP / TLS).
  fn connect_tcp<'a>(
    &'a self,
    token: &'a GateToken,
    bind: Option<IpAddr>,
    to: SocketAddr,
    host: Option<&'a str>,
  ) -> LocalBoxFuture<'a, io::Result<TcpStream>>;

  /// Resolves `host` (an ICE server URL's host: a name, an IP literal, or a
  /// bracketed IPv6 literal) and `port`. `token` allowed the
  /// [`ReachKind::IceServer`](crate::ReachKind::IceServer) question for
  /// `host` and `port`.
  fn resolve<'a>(
    &'a self,
    token: &'a GateToken,
    host: &'a str,
    port: u16,
  ) -> LocalBoxFuture<'a, io::Result<Vec<SocketAddr>>>;

  /// The local IP the OS sends to `peer` from: a connected UDP probe (no
  /// datagram leaves the machine), or `None`.
  fn route_probe(&self, peer: IpAddr) -> Option<IpAddr>;
}

/// The operating system's sockets and resolver, unrouted.
#[derive(Clone, Copy, Debug, Default)]
pub struct PlainNetIo;

impl NetIo for PlainNetIo {
  fn bind_udp(
    &self,
    _token: &GateToken,
    addr: SocketAddr,
    opts: UdpOpts,
  ) -> io::Result<UdpSocket> {
    let domain = if addr.is_ipv4() {
      socket2::Domain::IPV4
    } else {
      socket2::Domain::IPV6
    };
    let socket = socket2::Socket::new(
      domain,
      socket2::Type::DGRAM,
      Some(socket2::Protocol::UDP),
    )?;
    if addr.is_ipv6() && opts.ipv6_only {
      socket.set_only_v6(true)?;
    }
    socket.set_nonblocking(true)?;
    socket.bind(&addr.into())?;
    UdpSocket::from_std(socket.into())
  }

  fn bind_mdns(
    &self,
    _token: &GateToken,
    hosts: &[IpAddr],
  ) -> io::Result<UdpSocket> {
    let socket = socket2::Socket::new(
      socket2::Domain::IPV4,
      socket2::Type::DGRAM,
      Some(socket2::Protocol::UDP),
    )?;
    mdns_socket(socket, false, hosts)
  }

  fn bind_tcp(
    &self,
    _token: &GateToken,
    addr: SocketAddr,
  ) -> io::Result<TcpListener> {
    let domain = if addr.is_ipv4() {
      socket2::Domain::IPV4
    } else {
      socket2::Domain::IPV6
    };
    let socket = socket2::Socket::new(
      domain,
      socket2::Type::STREAM,
      Some(socket2::Protocol::TCP),
    )?;
    if addr.is_ipv6() {
      socket.set_only_v6(true)?;
    }
    #[cfg(not(windows))]
    socket.set_reuse_address(true)?;
    socket.set_nonblocking(true)?;
    socket.bind(&addr.into())?;
    socket.listen(128)?;
    TcpListener::from_std(socket.into())
  }

  fn connect_tcp<'a>(
    &'a self,
    _token: &'a GateToken,
    bind: Option<IpAddr>,
    to: SocketAddr,
    _host: Option<&'a str>,
  ) -> LocalBoxFuture<'a, io::Result<TcpStream>> {
    Box::pin(async move {
      let Some(ip) = bind else {
        return TcpStream::connect(to).await;
      };
      let socket = if to.is_ipv4() {
        tokio::net::TcpSocket::new_v4()?
      } else {
        tokio::net::TcpSocket::new_v6()?
      };
      if ip.is_ipv4() == to.is_ipv4() {
        socket.bind(SocketAddr::new(ip, 0))?;
      }
      socket.connect(to).await
    })
  }

  fn resolve<'a>(
    &'a self,
    _token: &'a GateToken,
    host: &'a str,
    port: u16,
  ) -> LocalBoxFuture<'a, io::Result<Vec<SocketAddr>>> {
    Box::pin(async move {
      let host = lookup_name(host);
      Ok(tokio::net::lookup_host((host, port)).await?.collect())
    })
  }

  fn route_probe(&self, peer: IpAddr) -> Option<IpAddr> {
    let unspecified: IpAddr = if peer.is_ipv4() {
      Ipv4Addr::UNSPECIFIED.into()
    } else {
      Ipv6Addr::UNSPECIFIED.into()
    };
    let probe = std::net::UdpSocket::bind((unspecified, 0)).ok()?;
    probe.connect((peer, 9)).ok()?;
    Some(probe.local_addr().ok()?.ip())
  }
}

/// The name [`PlainNetIo::resolve`] looks up for `host`, as Deno's
/// `resolve_addr` does: an empty host is `0.0.0.0`, IPv6 brackets go, and a
/// subdomain of `localhost` (RFC 6761 section 6.3) is `localhost`.
fn lookup_name(host: &str) -> &str {
  if host.is_empty() {
    return "0.0.0.0";
  }
  let addr = host.trim_start_matches('[').trim_end_matches(']');
  let name = addr.strip_suffix('.').unwrap_or(addr).to_ascii_lowercase();
  if name.len() > ".localhost".len() && name.ends_with(".localhost") {
    return "localhost";
  }
  addr
}

/// Finishes an mDNS socket (IPv4, UDP): reuse options and the bind on
/// `0.0.0.0:5353` unless `bound` (a socket handed out bound already, as a
/// sandbox broker does), non-blocking, multicast TTL 255 with loopback, and
/// the mDNS group joined on each non-loopback IPv4 address of `hosts` (on
/// the default interface when none joins). For [`NetIo::bind_mdns`]
/// implementations.
pub fn mdns_socket(
  socket: socket2::Socket,
  bound: bool,
  hosts: &[IpAddr],
) -> io::Result<UdpSocket> {
  let mdns_addr =
    SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), rtci::mdns::MDNS_PORT);
  if !bound {
    socket.set_reuse_address(true)?;
    #[cfg(all(unix, not(target_os = "solaris"), not(target_os = "illumos")))]
    socket.set_reuse_port(true)?;
  }
  socket.set_nonblocking(true)?;
  socket.set_multicast_ttl_v4(255)?;
  socket.set_multicast_loop_v4(true)?;
  if !bound {
    socket.bind(&mdns_addr.into())?;
  }
  let group = rtci::mdns::MDNS_MULTICAST_IPV4;
  let mut joined = false;
  for ip in hosts {
    if let IpAddr::V4(iface) = ip
      && !iface.is_loopback()
      && socket.join_multicast_v4(&group, iface).is_ok()
    {
      joined = true;
    }
  }
  if !joined {
    socket.join_multicast_v4(&group, &Ipv4Addr::UNSPECIFIED)?;
  }
  UdpSocket::from_std(socket.into())
}

#[cfg(test)]
mod tests {
  use super::lookup_name;

  #[test]
  fn lookup_name_matches_deno_resolve_addr() {
    assert_eq!(lookup_name(""), "0.0.0.0");
    assert_eq!(lookup_name("[::1]"), "::1");
    assert_eq!(lookup_name("stun.example"), "stun.example");
    assert_eq!(lookup_name("app.localhost"), "localhost");
    assert_eq!(lookup_name("App.Localhost."), "localhost");
    assert_eq!(lookup_name("localhost"), "localhost");
  }
}