Skip to main content

rtci_host/
ice_transport.rs

1// Copyright 2026 Brainwires. MIT OR Apache-2.0.
2
3//! A standalone `RTCIceTransport` (W3C webrtc-ice, "IceTransport Extensions
4//! for WebRTC"): `new RTCIceTransport()`, then `gather()`, `start()`,
5//! `addRemoteCandidate()` and `stop()`, without a peer connection.
6//!
7//! The engine's sans-I/O ICE agent (`rtci::ice::Agent`) does the checks,
8//! nomination and role-conflict resolution (RFC 8445); this module owns the
9//! I/O around it, as peer.rs does for a connection:
10//!
11//! - one UDP socket per host address, bound to that address (so the local
12//!   address of every datagram is the candidate's, which the agent matches
13//!   on), each one a host candidate. With `DENO_WEBRTC_LOOPBACK_ONLY=1`, or
14//!   without interface enumeration, `127.0.0.1` alone;
15//! - the same net permission gate as a connection: a datagram goes only to
16//!   an address `--allow-net` allows (checked once per address);
17//! - a driver task that moves datagrams between the sockets and the agent,
18//!   fires its timers and queues its events for JavaScript.
19//!
20//! Gathering is host candidates only: server-reflexive and relay candidates
21//! need the STUN / TURN clients peer.rs runs for a connection, which a
22//! standalone transport doesn't have yet (`gather()` accepts and validates
23//! `iceServers`, and with `gatherPolicy: "relay"` gathers nothing).
24//!
25//! Everything runs on the isolate's thread, like peer.rs: ops and the driver
26//! share the [`IceCore`] through a `RefCell` and never hold it across an
27//! `.await`.
28
29use std::cell::Cell;
30use std::cell::RefCell;
31use std::collections::HashSet;
32use std::collections::VecDeque;
33use std::net::IpAddr;
34use std::net::Ipv4Addr;
35use std::net::SocketAddr;
36use std::rc::Rc;
37use std::sync::Arc;
38use std::time::Duration;
39use std::time::Instant;
40
41use crate::rt::Cancel;
42use crate::rt::OrCancel;
43use bytes::BytesMut;
44use rtci::ice::Agent;
45use rtci::ice::AgentConfig;
46use rtci::ice::Event as AgentEvent;
47use rtci::ice::mdns::MulticastDnsMode;
48use rtci::peer_connection::transport::CandidateConfig;
49use rtci::peer_connection::transport::CandidateHostConfig;
50use rtci::peer_connection::transport::RTCIceCandidate;
51use rtci::sansio::Protocol;
52use rtci::shared::TaggedBytesMut;
53use rtci::shared::TransportContext;
54use rtci::shared::TransportProtocol;
55use serde::Serialize;
56use tokio::net::UdpSocket;
57use tokio::sync::Notify;
58use tokio::sync::mpsc;
59
60use crate::error::Error;
61use crate::error::ErrorKind;
62use crate::gate::GateToken;
63use crate::gate::NetGate;
64use crate::gate::Proto;
65use crate::gate::Reach;
66use crate::gate::ReachKind;
67use crate::gate_cache::GateCache;
68use crate::gate_cache::Verdicts;
69use crate::net_io::NetIo;
70use crate::net_io::UdpOpts;
71use crate::peer::PairCandidate;
72use crate::peer::SelectedPair;
73use crate::peer::rtc_err;
74
75/// The largest UDP payload read from a socket (as peer.rs).
76const RECV_BUFFER_SIZE: usize = 9216;
77/// Datagrams queued between the socket readers and the driver.
78const RECV_QUEUE: usize = 1024;
79/// Most host candidates (sockets) one transport gathers.
80const MAX_HOSTS: usize = 16;
81
82/// An event for JavaScript, delivered in batches by
83/// `op_webrtc_ice_next_events`.
84#[derive(Serialize, Debug)]
85#[serde(tag = "type")]
86pub enum IceEvent {
87  /// A gathered local candidate (its candidate-attribute value).
88  #[serde(rename = "icecandidate")]
89  Candidate { candidate: String },
90  /// Gathering finished: the null candidate, then `complete`.
91  #[serde(rename = "gatheringcomplete")]
92  GatheringComplete,
93  /// The agent's connection state, lower case (`checking`, `connected`,
94  /// `completed`, `disconnected`, `failed`, `closed`).
95  #[serde(rename = "statechange")]
96  State { state: String },
97  /// The agent selected a pair (`op_webrtc_ice_selected_pair` reads it).
98  #[serde(rename = "selectedcandidatepairchange")]
99  SelectedPair,
100  /// A role conflict (RFC 8445 section 7.3.1.1) switched the role.
101  #[serde(rename = "rolechange")]
102  Role { controlling: bool },
103}
104
105/// One received datagram, for the driver.
106struct Datagram {
107  local: SocketAddr,
108  from: SocketAddr,
109  data: BytesMut,
110}
111
112struct Endpoint {
113  socket: Rc<UdpSocket>,
114  local: SocketAddr,
115}
116
117/// The agent and the I/O state around it, shared by ops and the driver.
118struct IceCore {
119  agent: Agent,
120  endpoints: Vec<Endpoint>,
121  events: VecDeque<IceEvent>,
122  allowed: HashSet<SocketAddr>,
123  refused: HashSet<SocketAddr>,
124  started: bool,
125  recv_tx: mpsc::Sender<Datagram>,
126  recv_rx: Option<mpsc::Receiver<Datagram>>,
127}
128
129pub struct IceTransport {
130  core: RefCell<IceCore>,
131  /// The permission gate, with the answers it gave this transport.
132  gate: Rc<GateCache>,
133  /// The socket factory (`gather()` binds through it).
134  io: Rc<dyn NetIo>,
135  /// Ops -> driver: there is something to flush.
136  wake: Notify,
137  /// Driver -> `next_events`: `core.events` is not empty.
138  events_ready: Notify,
139  cancel: Cancel,
140  closed: Cell<bool>,
141  driver_started: Cell<bool>,
142}
143
144impl IceTransport {
145  /// A transport with fresh local ICE parameters (RFC 8445 section 5.3:
146  /// at least 24 bits of ufrag and 128 of password, which the agent
147  /// generates), gathering nothing until `gather()`.
148  pub fn new(
149    guard: Rc<dyn NetGate>,
150    io: Rc<dyn NetIo>,
151  ) -> Result<Rc<Self>, Error> {
152    let provider = rtci::crypto::default_provider()
153      .map_err(|e| Error::new(ErrorKind::Operation, e.to_string()))?;
154    let config = AgentConfig {
155      // `.local` names need the mDNS socket peer.rs opens for a connection;
156      // a standalone transport takes literal addresses.
157      multicast_dns_mode: MulticastDnsMode::Disabled,
158      ..Default::default()
159    };
160    let agent = Agent::new(Instant::now(), Arc::new(config), provider)
161      .map_err(rtc_err)?;
162    let (recv_tx, recv_rx) = mpsc::channel(RECV_QUEUE);
163    let gate = GateCache::new(guard);
164    let transport = Rc::new(Self {
165      core: RefCell::new(IceCore {
166        agent,
167        endpoints: Vec::new(),
168        events: VecDeque::new(),
169        allowed: HashSet::new(),
170        refused: HashSet::new(),
171        started: false,
172        recv_tx,
173        recv_rx: Some(recv_rx),
174      }),
175      gate,
176      io,
177      wake: Notify::new(),
178      events_ready: Notify::new(),
179      cancel: Cancel::new(),
180      closed: Cell::new(false),
181      driver_started: Cell::new(false),
182    });
183    // An answer lets held-back sends go: the driver tries them again.
184    let weak = Rc::downgrade(&transport);
185    transport.gate.set_on_answer(move || {
186      if let Some(transport) = weak.upgrade() {
187        transport.poke();
188      }
189    });
190    Ok(transport)
191  }
192
193  /// `getLocalParameters()`: `(usernameFragment, password)`.
194  pub fn local_parameters(&self) -> (String, String) {
195    let core = self.core.borrow();
196    let credentials = core.agent.get_local_credentials();
197    (credentials.ufrag.clone(), credentials.pwd.clone())
198  }
199
200  /// `gather()`: binds a socket per host address and queues each host
201  /// candidate, then the end of gathering. `relay_only` (`gatherPolicy:
202  /// "relay"`) gathers no host candidate.
203  pub fn gather(self: &Rc<Self>, relay_only: bool) -> Result<(), Error> {
204    if self.closed.get() {
205      return Err(Error::new(
206        ErrorKind::InvalidState,
207        "The RTCIceTransport is closed".to_string(),
208      ));
209    }
210    // Two-phase: the binds wait for the gate (ready at once with a gate
211    // that decides, which then gathers here, as before).
212    let finish = Box::pin(Self::finish_gather(self.clone(), relay_only));
213    if let Err(pending) = crate::rt::poll_now(finish) {
214      crate::rt::spawn(pending.or_cancel(self.cancel.clone()));
215    }
216    Ok(())
217  }
218
219  /// `gather()` once the gate answered for the host addresses.
220  async fn finish_gather(self: Rc<Self>, relay_only: bool) {
221    let hosts = if relay_only {
222      Vec::new()
223    } else {
224      host_addresses(&Verdicts::Cache(self.gate.clone())).await
225    };
226    if self.closed.get() {
227      return;
228    }
229    for (ip, token) in hosts {
230      let addr = SocketAddr::new(ip, 0);
231      let socket = match self.io.bind_udp(&token, addr, UdpOpts::for_addr(addr))
232      {
233        Ok(s) => Rc::new(s),
234        Err(e) => {
235          log::debug!("webrtc: RTCIceTransport bind on {ip}: {e}");
236          continue;
237        }
238      };
239      let Ok(local) = socket.local_addr() else {
240        continue;
241      };
242      let candidate = CandidateHostConfig {
243        base_config: CandidateConfig {
244          network: "udp".to_owned(),
245          address: local.ip().to_string(),
246          port: local.port(),
247          component: 1,
248          ..Default::default()
249        },
250        ..Default::default()
251      }
252      .new_candidate_host();
253      let mut core = self.core.borrow_mut();
254      let candidate = match candidate {
255        Ok(c) => c,
256        Err(e) => {
257          log::debug!("webrtc: RTCIceTransport candidate on {local}: {e}");
258          continue;
259        }
260      };
261      let line = RTCIceCandidate::from(&candidate)
262        .to_json()
263        .map(|init| init.candidate);
264      if core.agent.add_local_candidate(candidate).is_err() {
265        continue;
266      }
267      if let Ok(line) = line {
268        core
269          .events
270          .push_back(IceEvent::Candidate { candidate: line });
271      }
272      spawn_reader(
273        socket.clone(),
274        local,
275        core.recv_tx.clone(),
276        self.cancel.clone(),
277      );
278      core.endpoints.push(Endpoint { socket, local });
279    }
280    self
281      .core
282      .borrow_mut()
283      .events
284      .push_back(IceEvent::GatheringComplete);
285    self.ensure_driver();
286    self.poke();
287    self.events_ready.notify_one();
288  }
289
290  /// `start()`: the remote ICE parameters and the role. A later call with
291  /// other parameters is an ICE restart of the remote side: the remote
292  /// candidates are flushed (W3C webrtc-ice `start()` step "flush").
293  pub fn start(
294    self: &Rc<Self>,
295    ufrag: String,
296    pwd: String,
297    controlling: bool,
298  ) -> Result<(), Error> {
299    if self.closed.get() {
300      return Err(Error::new(
301        ErrorKind::InvalidState,
302        "The RTCIceTransport is closed".to_string(),
303      ));
304    }
305    {
306      let mut core = self.core.borrow_mut();
307      let now = Instant::now();
308      if core.started {
309        let same = core
310          .agent
311          .get_remote_credentials()
312          .is_some_and(|c| c.ufrag == ufrag && c.pwd == pwd);
313        if same {
314          return Ok(());
315        }
316        // Keeps the local candidates and credentials; drops the remote
317        // credentials, candidates and pairs.
318        core.agent.apply_restart(now, true).map_err(rtc_err)?;
319      }
320      core
321        .agent
322        .start_connectivity_checks(now, controlling, ufrag, pwd)
323        .map_err(rtc_err)?;
324      core.started = true;
325    }
326    self.ensure_driver();
327    self.poke();
328    Ok(())
329  }
330
331  /// `addRemoteCandidate()`: a candidate-attribute value (`candidate:...`).
332  pub fn add_remote_candidate(
333    self: &Rc<Self>,
334    candidate: &str,
335  ) -> Result<(), Error> {
336    if self.closed.get() {
337      return Err(Error::new(
338        ErrorKind::InvalidState,
339        "The RTCIceTransport is closed".to_string(),
340      ));
341    }
342    let value = candidate.trim();
343    let value = value.strip_prefix("a=").unwrap_or(value);
344    let value = value.strip_prefix("candidate:").unwrap_or(value);
345    let parsed =
346      rtci::ice::candidate::unmarshal_candidate(value).map_err(|e| {
347        Error::new(ErrorKind::Operation, format!("Invalid candidate: {e}"))
348      })?;
349    self
350      .core
351      .borrow_mut()
352      .agent
353      .add_remote_candidate(parsed)
354      .map_err(rtc_err)?;
355    self.ensure_driver();
356    self.poke();
357    Ok(())
358  }
359
360  /// `getSelectedCandidatePair()`.
361  pub fn selected_pair(&self) -> Option<SelectedPair> {
362    if self.closed.get() {
363      return None;
364    }
365    let core = self.core.borrow();
366    let (local, remote) = core.agent.get_selected_candidate_pair()?;
367    Some(SelectedPair {
368      local: PairCandidate::of(&RTCIceCandidate::from(local)),
369      remote: PairCandidate::of(&RTCIceCandidate::from(remote)),
370    })
371  }
372
373  /// `stop()`: closes the agent and the sockets, for good.
374  pub fn stop(&self) {
375    if self.closed.replace(true) {
376      return;
377    }
378    if let Ok(mut core) = self.core.try_borrow_mut() {
379      let _ = core.agent.close();
380      core.endpoints.clear();
381      core.events.clear();
382    }
383    self.gate.close();
384    self.cancel.cancel();
385    self.events_ready.notify_one();
386  }
387
388  pub async fn next_events(&self) -> Option<Vec<IceEvent>> {
389    loop {
390      {
391        let mut core = self.core.borrow_mut();
392        if self.closed.get() {
393          return None;
394        }
395        if !core.events.is_empty() {
396          return Some(core.events.drain(..).collect());
397        }
398      }
399      self.events_ready.notified().await;
400    }
401  }
402
403  fn poke(&self) {
404    self.wake.notify_one();
405  }
406
407  fn ensure_driver(self: &Rc<Self>) {
408    if self.driver_started.replace(true) || self.closed.get() {
409      return;
410    }
411    let Some(rx) = self.core.borrow_mut().recv_rx.take() else {
412      return;
413    };
414    let transport = self.clone();
415    let cancel = self.cancel.clone();
416    crate::rt::spawn(async move {
417      let _ = run_driver(transport, rx).or_cancel(cancel).await;
418    });
419  }
420}
421
422impl IceCore {
423  /// The send-side permission gate: once per destination address. A
424  /// question still being asked drops the datagram (ICE retransmits; the
425  /// answer pokes the driver).
426  fn permit(&mut self, gate: &Rc<GateCache>, addr: SocketAddr) -> bool {
427    if self.allowed.contains(&addr) {
428      return true;
429    }
430    if self.refused.contains(&addr) {
431      return false;
432    }
433    match gate.lookup(&Reach::connect(ReachKind::SendTo, Proto::Udp, addr)) {
434      Some(Ok(_)) => {
435        self.allowed.insert(addr);
436        true
437      }
438      Some(Err(e)) => {
439        log::debug!("webrtc: RTCIceTransport may not send to {addr}: {e}");
440        self.refused.insert(addr);
441        false
442      }
443      None => false,
444    }
445  }
446
447  /// Sends what the agent wants sent, and queues its events. A selected
448  /// pair is reported before the `connected` it comes with (the agent
449  /// queues them the other way round), so `getSelectedCandidatePair()`
450  /// already answers when the state changes.
451  fn pump(&mut self, gate: &Rc<GateCache>) {
452    while let Some(msg) = self.agent.poll_write() {
453      let to = msg.transport.peer_addr;
454      let local = msg.transport.local_addr;
455      if !self.permit(gate, to) {
456        continue;
457      }
458      let Some(endpoint) = self.endpoints.iter().find(|e| e.local == local)
459      else {
460        continue;
461      };
462      if let Err(e) = endpoint.socket.try_send_to(&msg.message, to) {
463        log::debug!("webrtc: RTCIceTransport send to {to}: {e}");
464      }
465    }
466    let mut states = Vec::new();
467    while let Some(tagged) = self.agent.poll_event() {
468      match tagged.event {
469        AgentEvent::ConnectionStateChange(state) => {
470          let state = state.to_string().to_ascii_lowercase();
471          if state != "unspecified" && state != "new" {
472            states.push(IceEvent::State { state });
473          }
474        }
475        AgentEvent::SelectedCandidatePairChange(_, _) => {
476          self.events.push_back(IceEvent::SelectedPair);
477        }
478        AgentEvent::RoleChange(controlling) => {
479          self.events.push_back(IceEvent::Role { controlling });
480        }
481        _ => {}
482      }
483    }
484    self.events.extend(states);
485  }
486
487  fn handle_datagram(&mut self, dg: Datagram) {
488    if self.refused.contains(&dg.from) {
489      return;
490    }
491    let _ = self.agent.handle_read(TaggedBytesMut {
492      now: Instant::now(),
493      transport: TransportContext {
494        local_addr: dg.local,
495        peer_addr: dg.from,
496        ecn: None,
497        transport_protocol: TransportProtocol::UDP,
498      },
499      message: dg.data,
500    });
501  }
502}
503
504/// The host addresses to gather on: `127.0.0.1` alone under
505/// `DENO_WEBRTC_LOOPBACK_ONLY=1` or without interface enumeration
506/// (`--allow-sys=networkInterfaces`), else the interface addresses the
507/// listen permission allows (`127.0.0.1` when there is none), each with
508/// the gate's token for its bind.
509async fn host_addresses(guard: &Verdicts<'_>) -> Vec<(IpAddr, GateToken)> {
510  let loopback = IpAddr::V4(Ipv4Addr::LOCALHOST);
511  let mut out = Vec::new();
512  let listen = async |ip: IpAddr| {
513    guard
514      .reach(Reach::bind(ReachKind::Bind, Proto::Udp, ip))
515      .await
516      .ok()
517  };
518  if !crate::peer::loopback_only() && guard.interfaces().await.is_ok() {
519    for ip in crate::peer::interface_addresses(None) {
520      if out.len() < MAX_HOSTS
521        && let Some(token) = listen(ip).await
522      {
523        out.push((ip, token));
524      }
525    }
526  }
527  if out.is_empty()
528    && let Some(token) = listen(loopback).await
529  {
530    out.push((loopback, token));
531  }
532  out
533}
534
535fn spawn_reader(
536  socket: Rc<UdpSocket>,
537  local: SocketAddr,
538  tx: mpsc::Sender<Datagram>,
539  cancel: Cancel,
540) {
541  crate::rt::spawn(
542    async move {
543      let mut buf = vec![0u8; RECV_BUFFER_SIZE];
544      loop {
545        match socket.recv_from(&mut buf).await {
546          Ok((n, from)) => {
547            let dg = Datagram {
548              local,
549              from,
550              data: BytesMut::from(&buf[..n]),
551            };
552            if let Err(mpsc::error::TrySendError::Closed(_)) = tx.try_send(dg) {
553              break;
554            }
555          }
556          Err(e) => {
557            // ICMP port unreachable surfaces as a read error on some
558            // platforms; keep reading.
559            log::debug!("webrtc: RTCIceTransport recv on {local}: {e}");
560            tokio::time::sleep(Duration::from_millis(1)).await;
561          }
562        }
563      }
564    }
565    .or_cancel(cancel),
566  );
567}
568
569async fn run_driver(
570  transport: Rc<IceTransport>,
571  mut rx: mpsc::Receiver<Datagram>,
572) {
573  loop {
574    if transport.closed.get() {
575      break;
576    }
577    let (has_events, deadline) = {
578      let mut core = transport.core.borrow_mut();
579      core.pump(&transport.gate);
580      (!core.events.is_empty(), core.agent.poll_timeout())
581    };
582    if has_events {
583      transport.events_ready.notify_one();
584    }
585    let sleep = async {
586      match deadline {
587        Some(d) => {
588          tokio::time::sleep_until(tokio::time::Instant::from_std(d)).await
589        }
590        None => std::future::pending::<()>().await,
591      }
592    };
593    tokio::select! {
594      _ = transport.wake.notified() => {}
595      dg = rx.recv() => match dg {
596        Some(dg) => {
597          let mut core = transport.core.borrow_mut();
598          core.handle_datagram(dg);
599          while let Ok(dg) = rx.try_recv() {
600            core.handle_datagram(dg);
601          }
602        }
603        None => break,
604      },
605      _ = sleep => {
606        let _ = transport.core.borrow_mut().agent.handle_timeout(Instant::now());
607      }
608    }
609  }
610}