rtci-host 0.3.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 net permission gate ([`NetGate`]): every address the engine reaches,
//! every socket it binds and the machine's interface list go through it
//! first.
//!
//! The engine first calls [`NetGate::decide`] (or [`NetGate::interfaces`]).
//! A gate that answers there (a runtime's permission set) is synchronous,
//! and the engine behaves as if nothing were asynchronous. When `decide`
//! returns `None`, the engine calls [`NetGate::ask`] once for that question
//! and waits for the answer, holding back whatever needed it: no socket is
//! bound, no name resolved and no datagram sent until the answer is
//! [`Verdict::Allow`]. An answer that doesn't come within
//! [`NetGate::ask_timeout`], a gate that panics, and a dropped request are
//! refusals (deny by default). [`AskGate`](crate::AskGate) is a ready-made
//! asynchronous gate whose questions a front end answers by ticket.
//!
//! Every [`NetIo`](crate::NetIo) call that creates a socket or resolves a
//! name takes a [`GateToken`], which only the engine mints, from an allow
//! for the matching [`Reach`].

use std::fmt;
use std::future::Future;
use std::net::IpAddr;
use std::net::SocketAddr;
use std::pin::Pin;
use std::time::Duration;

/// A boxed, `!Send` future (the engine is single-threaded).
pub type LocalBoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;

/// The transport of a [`Reach`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Proto {
  Udp,
  Tcp,
  Tls,
}

impl Proto {
  /// `"udp"`, `"tcp"` or `"tls"` (the `proto` of a `gaterequest`).
  pub fn as_str(self) -> &'static str {
    match self {
      Proto::Udp => "udp",
      Proto::Tcp => "tcp",
      Proto::Tls => "tls",
    }
  }
}

/// Whether a [`Reach`] sends to an address or binds one.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Direction {
  Connect,
  Listen,
}

impl Direction {
  /// `"connect"` or `"listen"` (the `dir` of a `gaterequest`).
  pub fn as_str(self) -> &'static str {
    match self {
      Direction::Connect => "connect",
      Direction::Listen => "listen",
    }
  }
}

/// Why the engine asks (for logs and prompts; a gate may also decide on
/// it). The engine's cache of asked answers ignores the kind: an answer for
/// one kind is reused for another with the same direction, transport, host,
/// port and `resolved_from`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ReachKind {
  /// An ICE server URL's host, before DNS.
  IceServer,
  /// The address an ICE server's host resolved to.
  IceServerResolved,
  /// A remote candidate's address (`setRemoteDescription`,
  /// `addIceCandidate`).
  RemoteCandidate,
  /// The first datagram to a new address (a peer-reflexive or
  /// mDNS-resolved candidate, a relayed peer, ...).
  SendTo,
  /// An ICE-TCP active dial.
  TcpDial,
  /// A UDP or TCP bind on an IP.
  Bind,
  /// The mDNS socket: binding `0.0.0.0:5353` and sending to
  /// `224.0.0.251:5353`.
  Mdns,
}

impl ReachKind {
  /// The kind's name in a `gaterequest` (`"iceServer"`,
  /// `"iceServerResolved"`, `"remoteCandidate"`, `"sendTo"`, `"tcpDial"`,
  /// `"bind"`, `"mdns"`).
  pub fn as_str(self) -> &'static str {
    match self {
      ReachKind::IceServer => "iceServer",
      ReachKind::IceServerResolved => "iceServerResolved",
      ReachKind::RemoteCandidate => "remoteCandidate",
      ReachKind::SendTo => "sendTo",
      ReachKind::TcpDial => "tcpDial",
      ReachKind::Bind => "bind",
      ReachKind::Mdns => "mdns",
    }
  }
}

/// A host a [`Reach`] names: a name (an ICE server URL's host, before DNS)
/// or an IP address.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Host {
  Name(String),
  Ip(IpAddr),
}

impl fmt::Display for Host {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Host::Name(name) => f.write_str(name),
      Host::Ip(ip) => ip.fmt(f),
    }
  }
}

/// One thing the engine wants to reach.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Reach {
  pub kind: ReachKind,
  pub dir: Direction,
  pub proto: Proto,
  pub host: Host,
  /// The port, where the engine knows it. A [`ReachKind::Bind`] carries
  /// none: the permission is for the IP, whatever port the OS picks.
  pub port: Option<u16>,
  /// For [`ReachKind::IceServerResolved`]: the host name it was resolved
  /// from.
  pub resolved_from: Option<String>,
}

impl Reach {
  /// Sending to `addr`.
  pub fn connect(kind: ReachKind, proto: Proto, addr: SocketAddr) -> Self {
    Self {
      kind,
      dir: Direction::Connect,
      proto,
      host: Host::Ip(addr.ip()),
      port: Some(addr.port()),
      resolved_from: None,
    }
  }

  /// Binding a socket on `ip` (any port).
  pub fn bind(kind: ReachKind, proto: Proto, ip: IpAddr) -> Self {
    Self {
      kind,
      dir: Direction::Listen,
      proto,
      host: Host::Ip(ip),
      port: None,
      resolved_from: None,
    }
  }

  /// An ICE server URL's host and port, before DNS.
  pub fn ice_server(proto: Proto, host: &str, port: u16) -> Self {
    Self {
      kind: ReachKind::IceServer,
      dir: Direction::Connect,
      proto,
      host: Host::Name(host.to_string()),
      port: Some(port),
      resolved_from: None,
    }
  }

  /// The socket address, for an IP host with a port.
  pub fn socket_addr(&self) -> Option<SocketAddr> {
    match (&self.host, self.port) {
      (Host::Ip(ip), Some(port)) => Some(SocketAddr::new(*ip, port)),
      _ => None,
    }
  }
}

/// A gate's answer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Verdict {
  Allow,
  /// Refused, with the message the engine reports (an
  /// `icecandidateerror`'s text, or a [`NotCapable`] error's message).
  ///
  /// [`NotCapable`]: crate::ErrorKind::NotCapable
  Deny(String),
}

impl Verdict {
  pub fn is_allow(&self) -> bool {
    matches!(self, Verdict::Allow)
  }

  /// `Ok(())` for [`Verdict::Allow`], else the refusal's message.
  pub fn into_result(self) -> Result<(), String> {
    match self {
      Verdict::Allow => Ok(()),
      Verdict::Deny(message) => Err(message),
    }
  }
}

/// How long the engine waits for an asked answer by default
/// ([`NetGate::ask_timeout`]).
pub const DEFAULT_ASK_TIMEOUT: Duration = Duration::from_secs(10);

/// The net permission gate. There is no allowing default: every
/// [`Peer`](crate::Peer), [`Network`](crate::Network) and
/// [`IceTransport`](crate::IceTransport) is given one, and [`DenyAllGate`]
/// refuses everything.
pub trait NetGate {
  /// Answers now if it can. A gate that answers synchronously (a runtime's
  /// permission set) always returns `Some`; `None` makes the engine
  /// [`ask`](NetGate::ask). Called again each time the engine needs the
  /// question answered, so it may answer from a cache of its own.
  fn decide(&self, reach: &Reach) -> Option<Verdict>;

  /// Asks, the answer arriving through the returned future. Called only
  /// after `decide` returned `None`, at most once per question at a time
  /// per connection (the engine dedupes and remembers the answer). The
  /// future is dropped when the connection closes or
  /// [`NetGate::ask_timeout`] passes (a refusal). The default answers from
  /// [`NetGate::decide`] (`None` is a refusal).
  fn ask(&self, reach: Reach) -> LocalBoxFuture<'static, Verdict> {
    let verdict = self.decide(&reach).unwrap_or_else(|| pending(&reach));
    Box::pin(std::future::ready(verdict))
  }

  /// May the engine list the machine's interface addresses (its host
  /// candidates beyond loopback)? (Deno's `--allow-sys=networkInterfaces`.)
  fn interfaces(&self) -> Option<Verdict>;

  /// [`NetGate::interfaces`], asked. The default answers from
  /// `interfaces()` (`None` is a refusal).
  fn ask_interfaces(&self) -> LocalBoxFuture<'static, Verdict> {
    let verdict = self.interfaces().unwrap_or_else(|| {
      Verdict::Deny("The network interfaces were not allowed".to_string())
    });
    Box::pin(std::future::ready(verdict))
  }

  /// How long the engine waits for an [`ask`](NetGate::ask) /
  /// [`ask_interfaces`](NetGate::ask_interfaces) answer before it takes
  /// the question as refused.
  fn ask_timeout(&self) -> Duration {
    DEFAULT_ASK_TIMEOUT
  }
}

/// Proof that the gate allowed a [`Reach`]: every [`NetIo`](crate::NetIo)
/// call that creates a socket or resolves a name takes one. Only the engine
/// mints them (there is no public constructor), from an allow for the
/// `Reach` the call is for, so a `NetIo` implementation may check
/// [`GateToken::reach`] against its arguments.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GateToken {
  reach: Reach,
}

impl GateToken {
  /// Only after an allow for `reach`.
  pub(crate) fn new(reach: Reach) -> Self {
    Self { reach }
  }

  /// The question the gate allowed.
  pub fn reach(&self) -> &Reach {
    &self.reach
  }
}

/// What an answer is remembered by: a [`Reach`] without its kind.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct ReachKey {
  dir: Direction,
  proto: Proto,
  host: Host,
  port: Option<u16>,
  resolved_from: Option<String>,
}

impl From<&Reach> for ReachKey {
  fn from(r: &Reach) -> Self {
    Self {
      dir: r.dir,
      proto: r.proto,
      host: r.host.clone(),
      port: r.port,
      resolved_from: r.resolved_from.clone(),
    }
  }
}

/// Refuses everything.
#[derive(Clone, Copy, Debug, Default)]
pub struct DenyAllGate;

impl NetGate for DenyAllGate {
  fn decide(&self, reach: &Reach) -> Option<Verdict> {
    Some(Verdict::Deny(format!(
      "Requires net access to \"{}\"",
      describe(reach)
    )))
  }

  fn interfaces(&self) -> Option<Verdict> {
    Some(Verdict::Deny(
      "Requires sys access to \"networkInterfaces\"".to_string(),
    ))
  }
}

/// The refusal for a `decide` that had no answer.
pub(crate) fn pending(reach: &Reach) -> Verdict {
  Verdict::Deny(format!(
    "Net access to \"{}\" was not decided",
    describe(reach)
  ))
}

pub(crate) fn describe(reach: &Reach) -> String {
  match (&reach.host, reach.port) {
    (Host::Ip(IpAddr::V6(ip)), Some(port)) => format!("[{ip}]:{port}"),
    (host, Some(port)) => format!("{host}:{port}"),
    (host, None) => host.to_string(),
  }
}

/// The refusal for an `interfaces()` that had no answer.
pub(crate) fn interfaces_pending() -> Verdict {
  Verdict::Deny("The network interfaces were not allowed".to_string())
}

/// The synchronous questions (`None` answers refused): the callers that
/// can't wait ([`crate::check_ice_servers`], [`crate::Network::new`]).
pub(crate) trait GateExt {
  fn check(&self, reach: &Reach) -> Result<(), String>;
  fn check_interfaces(&self) -> Result<(), String>;
}

impl<G: NetGate + ?Sized> GateExt for G {
  fn check(&self, reach: &Reach) -> Result<(), String> {
    self
      .decide(reach)
      .unwrap_or_else(|| pending(reach))
      .into_result()
  }

  fn check_interfaces(&self) -> Result<(), String> {
    self
      .interfaces()
      .unwrap_or_else(|| {
        Verdict::Deny("The network interfaces were not allowed".to_string())
      })
      .into_result()
  }
}