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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
// Copyright 2026 Brainwires. MIT OR Apache-2.0.

//! A standalone `RTCIceTransport` (W3C webrtc-ice, "IceTransport Extensions
//! for WebRTC"): `new RTCIceTransport()`, then `gather()`, `start()`,
//! `addRemoteCandidate()` and `stop()`, without a peer connection.
//!
//! The engine's sans-I/O ICE agent (`rtci::ice::Agent`) does the checks,
//! nomination and role-conflict resolution (RFC 8445); this module owns the
//! I/O around it, as peer.rs does for a connection:
//!
//! - one UDP socket per host address, bound to that address (so the local
//!   address of every datagram is the candidate's, which the agent matches
//!   on), each one a host candidate. With `DENO_WEBRTC_LOOPBACK_ONLY=1`, or
//!   without interface enumeration, `127.0.0.1` alone;
//! - the same net permission gate as a connection: a datagram goes only to
//!   an address `--allow-net` allows (checked once per address);
//! - a driver task that moves datagrams between the sockets and the agent,
//!   fires its timers and queues its events for JavaScript.
//!
//! Gathering is host candidates only: server-reflexive and relay candidates
//! need the STUN / TURN clients peer.rs runs for a connection, which a
//! standalone transport doesn't have yet (`gather()` accepts and validates
//! `iceServers`, and with `gatherPolicy: "relay"` gathers nothing).
//!
//! Everything runs on the isolate's thread, like peer.rs: ops and the driver
//! share the [`IceCore`] through a `RefCell` and never hold it across an
//! `.await`.

use std::cell::Cell;
use std::cell::RefCell;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::net::SocketAddr;
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;

use crate::rt::Cancel;
use crate::rt::OrCancel;
use bytes::BytesMut;
use rtci::ice::Agent;
use rtci::ice::AgentConfig;
use rtci::ice::Event as AgentEvent;
use rtci::ice::mdns::MulticastDnsMode;
use rtci::peer_connection::transport::CandidateConfig;
use rtci::peer_connection::transport::CandidateHostConfig;
use rtci::peer_connection::transport::RTCIceCandidate;
use rtci::sansio::Protocol;
use rtci::shared::TaggedBytesMut;
use rtci::shared::TransportContext;
use rtci::shared::TransportProtocol;
use serde::Serialize;
use tokio::net::UdpSocket;
use tokio::sync::Notify;
use tokio::sync::mpsc;

use crate::error::Error;
use crate::error::ErrorKind;
use crate::gate::GateToken;
use crate::gate::NetGate;
use crate::gate::Proto;
use crate::gate::Reach;
use crate::gate::ReachKind;
use crate::gate_cache::GateCache;
use crate::gate_cache::Verdicts;
use crate::net_io::NetIo;
use crate::net_io::UdpOpts;
use crate::peer::PairCandidate;
use crate::peer::SelectedPair;
use crate::peer::rtc_err;

/// The largest UDP payload read from a socket (as peer.rs).
const RECV_BUFFER_SIZE: usize = 9216;
/// Datagrams queued between the socket readers and the driver.
const RECV_QUEUE: usize = 1024;
/// Most host candidates (sockets) one transport gathers.
const MAX_HOSTS: usize = 16;

/// An event for JavaScript, delivered in batches by
/// `op_webrtc_ice_next_events`.
#[derive(Serialize, Debug)]
#[serde(tag = "type")]
pub enum IceEvent {
  /// A gathered local candidate (its candidate-attribute value).
  #[serde(rename = "icecandidate")]
  Candidate { candidate: String },
  /// Gathering finished: the null candidate, then `complete`.
  #[serde(rename = "gatheringcomplete")]
  GatheringComplete,
  /// The agent's connection state, lower case (`checking`, `connected`,
  /// `completed`, `disconnected`, `failed`, `closed`).
  #[serde(rename = "statechange")]
  State { state: String },
  /// The agent selected a pair (`op_webrtc_ice_selected_pair` reads it).
  #[serde(rename = "selectedcandidatepairchange")]
  SelectedPair,
  /// A role conflict (RFC 8445 section 7.3.1.1) switched the role.
  #[serde(rename = "rolechange")]
  Role { controlling: bool },
}

/// One received datagram, for the driver.
struct Datagram {
  local: SocketAddr,
  from: SocketAddr,
  data: BytesMut,
}

struct Endpoint {
  socket: Rc<UdpSocket>,
  local: SocketAddr,
}

/// The agent and the I/O state around it, shared by ops and the driver.
struct IceCore {
  agent: Agent,
  endpoints: Vec<Endpoint>,
  events: VecDeque<IceEvent>,
  allowed: HashSet<SocketAddr>,
  refused: HashSet<SocketAddr>,
  started: bool,
  recv_tx: mpsc::Sender<Datagram>,
  recv_rx: Option<mpsc::Receiver<Datagram>>,
}

pub struct IceTransport {
  core: RefCell<IceCore>,
  /// The permission gate, with the answers it gave this transport.
  gate: Rc<GateCache>,
  /// The socket factory (`gather()` binds through it).
  io: Rc<dyn NetIo>,
  /// Ops -> driver: there is something to flush.
  wake: Notify,
  /// Driver -> `next_events`: `core.events` is not empty.
  events_ready: Notify,
  cancel: Cancel,
  closed: Cell<bool>,
  driver_started: Cell<bool>,
}

impl IceTransport {
  /// A transport with fresh local ICE parameters (RFC 8445 section 5.3:
  /// at least 24 bits of ufrag and 128 of password, which the agent
  /// generates), gathering nothing until `gather()`.
  pub fn new(
    guard: Rc<dyn NetGate>,
    io: Rc<dyn NetIo>,
  ) -> Result<Rc<Self>, Error> {
    let provider = rtci::crypto::default_provider()
      .map_err(|e| Error::new(ErrorKind::Operation, e.to_string()))?;
    let config = AgentConfig {
      // `.local` names need the mDNS socket peer.rs opens for a connection;
      // a standalone transport takes literal addresses.
      multicast_dns_mode: MulticastDnsMode::Disabled,
      ..Default::default()
    };
    let agent = Agent::new(Instant::now(), Arc::new(config), provider)
      .map_err(rtc_err)?;
    let (recv_tx, recv_rx) = mpsc::channel(RECV_QUEUE);
    let gate = GateCache::new(guard);
    let transport = Rc::new(Self {
      core: RefCell::new(IceCore {
        agent,
        endpoints: Vec::new(),
        events: VecDeque::new(),
        allowed: HashSet::new(),
        refused: HashSet::new(),
        started: false,
        recv_tx,
        recv_rx: Some(recv_rx),
      }),
      gate,
      io,
      wake: Notify::new(),
      events_ready: Notify::new(),
      cancel: Cancel::new(),
      closed: Cell::new(false),
      driver_started: Cell::new(false),
    });
    // An answer lets held-back sends go: the driver tries them again.
    let weak = Rc::downgrade(&transport);
    transport.gate.set_on_answer(move || {
      if let Some(transport) = weak.upgrade() {
        transport.poke();
      }
    });
    Ok(transport)
  }

  /// `getLocalParameters()`: `(usernameFragment, password)`.
  pub fn local_parameters(&self) -> (String, String) {
    let core = self.core.borrow();
    let credentials = core.agent.get_local_credentials();
    (credentials.ufrag.clone(), credentials.pwd.clone())
  }

  /// `gather()`: binds a socket per host address and queues each host
  /// candidate, then the end of gathering. `relay_only` (`gatherPolicy:
  /// "relay"`) gathers no host candidate.
  pub fn gather(self: &Rc<Self>, relay_only: bool) -> Result<(), Error> {
    if self.closed.get() {
      return Err(Error::new(
        ErrorKind::InvalidState,
        "The RTCIceTransport is closed".to_string(),
      ));
    }
    // Two-phase: the binds wait for the gate (ready at once with a gate
    // that decides, which then gathers here, as before).
    let finish = Box::pin(Self::finish_gather(self.clone(), relay_only));
    if let Err(pending) = crate::rt::poll_now(finish) {
      crate::rt::spawn(pending.or_cancel(self.cancel.clone()));
    }
    Ok(())
  }

  /// `gather()` once the gate answered for the host addresses.
  async fn finish_gather(self: Rc<Self>, relay_only: bool) {
    let hosts = if relay_only {
      Vec::new()
    } else {
      host_addresses(&Verdicts::Cache(self.gate.clone())).await
    };
    if self.closed.get() {
      return;
    }
    for (ip, token) in hosts {
      let addr = SocketAddr::new(ip, 0);
      let socket = match self.io.bind_udp(&token, addr, UdpOpts::for_addr(addr))
      {
        Ok(s) => Rc::new(s),
        Err(e) => {
          log::debug!("webrtc: RTCIceTransport bind on {ip}: {e}");
          continue;
        }
      };
      let Ok(local) = socket.local_addr() else {
        continue;
      };
      let candidate = CandidateHostConfig {
        base_config: CandidateConfig {
          network: "udp".to_owned(),
          address: local.ip().to_string(),
          port: local.port(),
          component: 1,
          ..Default::default()
        },
        ..Default::default()
      }
      .new_candidate_host();
      let mut core = self.core.borrow_mut();
      let candidate = match candidate {
        Ok(c) => c,
        Err(e) => {
          log::debug!("webrtc: RTCIceTransport candidate on {local}: {e}");
          continue;
        }
      };
      let line = RTCIceCandidate::from(&candidate)
        .to_json()
        .map(|init| init.candidate);
      if core.agent.add_local_candidate(candidate).is_err() {
        continue;
      }
      if let Ok(line) = line {
        core
          .events
          .push_back(IceEvent::Candidate { candidate: line });
      }
      spawn_reader(
        socket.clone(),
        local,
        core.recv_tx.clone(),
        self.cancel.clone(),
      );
      core.endpoints.push(Endpoint { socket, local });
    }
    self
      .core
      .borrow_mut()
      .events
      .push_back(IceEvent::GatheringComplete);
    self.ensure_driver();
    self.poke();
    self.events_ready.notify_one();
  }

  /// `start()`: the remote ICE parameters and the role. A later call with
  /// other parameters is an ICE restart of the remote side: the remote
  /// candidates are flushed (W3C webrtc-ice `start()` step "flush").
  pub fn start(
    self: &Rc<Self>,
    ufrag: String,
    pwd: String,
    controlling: bool,
  ) -> Result<(), Error> {
    if self.closed.get() {
      return Err(Error::new(
        ErrorKind::InvalidState,
        "The RTCIceTransport is closed".to_string(),
      ));
    }
    {
      let mut core = self.core.borrow_mut();
      let now = Instant::now();
      if core.started {
        let same = core
          .agent
          .get_remote_credentials()
          .is_some_and(|c| c.ufrag == ufrag && c.pwd == pwd);
        if same {
          return Ok(());
        }
        // Keeps the local candidates and credentials; drops the remote
        // credentials, candidates and pairs.
        core.agent.apply_restart(now, true).map_err(rtc_err)?;
      }
      core
        .agent
        .start_connectivity_checks(now, controlling, ufrag, pwd)
        .map_err(rtc_err)?;
      core.started = true;
    }
    self.ensure_driver();
    self.poke();
    Ok(())
  }

  /// `addRemoteCandidate()`: a candidate-attribute value (`candidate:...`).
  pub fn add_remote_candidate(
    self: &Rc<Self>,
    candidate: &str,
  ) -> Result<(), Error> {
    if self.closed.get() {
      return Err(Error::new(
        ErrorKind::InvalidState,
        "The RTCIceTransport is closed".to_string(),
      ));
    }
    let value = candidate.trim();
    let value = value.strip_prefix("a=").unwrap_or(value);
    let value = value.strip_prefix("candidate:").unwrap_or(value);
    let parsed =
      rtci::ice::candidate::unmarshal_candidate(value).map_err(|e| {
        Error::new(ErrorKind::Operation, format!("Invalid candidate: {e}"))
      })?;
    self
      .core
      .borrow_mut()
      .agent
      .add_remote_candidate(parsed)
      .map_err(rtc_err)?;
    self.ensure_driver();
    self.poke();
    Ok(())
  }

  /// `getSelectedCandidatePair()`.
  pub fn selected_pair(&self) -> Option<SelectedPair> {
    if self.closed.get() {
      return None;
    }
    let core = self.core.borrow();
    let (local, remote) = core.agent.get_selected_candidate_pair()?;
    Some(SelectedPair {
      local: PairCandidate::of(&RTCIceCandidate::from(local)),
      remote: PairCandidate::of(&RTCIceCandidate::from(remote)),
    })
  }

  /// `stop()`: closes the agent and the sockets, for good.
  pub fn stop(&self) {
    if self.closed.replace(true) {
      return;
    }
    if let Ok(mut core) = self.core.try_borrow_mut() {
      let _ = core.agent.close();
      core.endpoints.clear();
      core.events.clear();
    }
    self.gate.close();
    self.cancel.cancel();
    self.events_ready.notify_one();
  }

  pub async fn next_events(&self) -> Option<Vec<IceEvent>> {
    loop {
      {
        let mut core = self.core.borrow_mut();
        if self.closed.get() {
          return None;
        }
        if !core.events.is_empty() {
          return Some(core.events.drain(..).collect());
        }
      }
      self.events_ready.notified().await;
    }
  }

  fn poke(&self) {
    self.wake.notify_one();
  }

  fn ensure_driver(self: &Rc<Self>) {
    if self.driver_started.replace(true) || self.closed.get() {
      return;
    }
    let Some(rx) = self.core.borrow_mut().recv_rx.take() else {
      return;
    };
    let transport = self.clone();
    let cancel = self.cancel.clone();
    crate::rt::spawn(async move {
      let _ = run_driver(transport, rx).or_cancel(cancel).await;
    });
  }
}

impl IceCore {
  /// The send-side permission gate: once per destination address. A
  /// question still being asked drops the datagram (ICE retransmits; the
  /// answer pokes the driver).
  fn permit(&mut self, gate: &Rc<GateCache>, addr: SocketAddr) -> bool {
    if self.allowed.contains(&addr) {
      return true;
    }
    if self.refused.contains(&addr) {
      return false;
    }
    match gate.lookup(&Reach::connect(ReachKind::SendTo, Proto::Udp, addr)) {
      Some(Ok(_)) => {
        self.allowed.insert(addr);
        true
      }
      Some(Err(e)) => {
        log::debug!("webrtc: RTCIceTransport may not send to {addr}: {e}");
        self.refused.insert(addr);
        false
      }
      None => false,
    }
  }

  /// Sends what the agent wants sent, and queues its events. A selected
  /// pair is reported before the `connected` it comes with (the agent
  /// queues them the other way round), so `getSelectedCandidatePair()`
  /// already answers when the state changes.
  fn pump(&mut self, gate: &Rc<GateCache>) {
    while let Some(msg) = self.agent.poll_write() {
      let to = msg.transport.peer_addr;
      let local = msg.transport.local_addr;
      if !self.permit(gate, to) {
        continue;
      }
      let Some(endpoint) = self.endpoints.iter().find(|e| e.local == local)
      else {
        continue;
      };
      if let Err(e) = endpoint.socket.try_send_to(&msg.message, to) {
        log::debug!("webrtc: RTCIceTransport send to {to}: {e}");
      }
    }
    let mut states = Vec::new();
    while let Some(tagged) = self.agent.poll_event() {
      match tagged.event {
        AgentEvent::ConnectionStateChange(state) => {
          let state = state.to_string().to_ascii_lowercase();
          if state != "unspecified" && state != "new" {
            states.push(IceEvent::State { state });
          }
        }
        AgentEvent::SelectedCandidatePairChange(_, _) => {
          self.events.push_back(IceEvent::SelectedPair);
        }
        AgentEvent::RoleChange(controlling) => {
          self.events.push_back(IceEvent::Role { controlling });
        }
        _ => {}
      }
    }
    self.events.extend(states);
  }

  fn handle_datagram(&mut self, dg: Datagram) {
    if self.refused.contains(&dg.from) {
      return;
    }
    let _ = self.agent.handle_read(TaggedBytesMut {
      now: Instant::now(),
      transport: TransportContext {
        local_addr: dg.local,
        peer_addr: dg.from,
        ecn: None,
        transport_protocol: TransportProtocol::UDP,
      },
      message: dg.data,
    });
  }
}

/// The host addresses to gather on: `127.0.0.1` alone under
/// `DENO_WEBRTC_LOOPBACK_ONLY=1` or without interface enumeration
/// (`--allow-sys=networkInterfaces`), else the interface addresses the
/// listen permission allows (`127.0.0.1` when there is none), each with
/// the gate's token for its bind.
async fn host_addresses(guard: &Verdicts<'_>) -> Vec<(IpAddr, GateToken)> {
  let loopback = IpAddr::V4(Ipv4Addr::LOCALHOST);
  let mut out = Vec::new();
  let listen = async |ip: IpAddr| {
    guard
      .reach(Reach::bind(ReachKind::Bind, Proto::Udp, ip))
      .await
      .ok()
  };
  if !crate::peer::loopback_only() && guard.interfaces().await.is_ok() {
    for ip in crate::peer::interface_addresses(None) {
      if out.len() < MAX_HOSTS
        && let Some(token) = listen(ip).await
      {
        out.push((ip, token));
      }
    }
  }
  if out.is_empty()
    && let Some(token) = listen(loopback).await
  {
    out.push((loopback, token));
  }
  out
}

fn spawn_reader(
  socket: Rc<UdpSocket>,
  local: SocketAddr,
  tx: mpsc::Sender<Datagram>,
  cancel: Cancel,
) {
  crate::rt::spawn(
    async move {
      let mut buf = vec![0u8; RECV_BUFFER_SIZE];
      loop {
        match socket.recv_from(&mut buf).await {
          Ok((n, from)) => {
            let dg = Datagram {
              local,
              from,
              data: BytesMut::from(&buf[..n]),
            };
            if let Err(mpsc::error::TrySendError::Closed(_)) = tx.try_send(dg) {
              break;
            }
          }
          Err(e) => {
            // ICMP port unreachable surfaces as a read error on some
            // platforms; keep reading.
            log::debug!("webrtc: RTCIceTransport recv on {local}: {e}");
            tokio::time::sleep(Duration::from_millis(1)).await;
          }
        }
      }
    }
    .or_cancel(cancel),
  );
}

async fn run_driver(
  transport: Rc<IceTransport>,
  mut rx: mpsc::Receiver<Datagram>,
) {
  loop {
    if transport.closed.get() {
      break;
    }
    let (has_events, deadline) = {
      let mut core = transport.core.borrow_mut();
      core.pump(&transport.gate);
      (!core.events.is_empty(), core.agent.poll_timeout())
    };
    if has_events {
      transport.events_ready.notify_one();
    }
    let sleep = async {
      match deadline {
        Some(d) => {
          tokio::time::sleep_until(tokio::time::Instant::from_std(d)).await
        }
        None => std::future::pending::<()>().await,
      }
    };
    tokio::select! {
      _ = transport.wake.notified() => {}
      dg = rx.recv() => match dg {
        Some(dg) => {
          let mut core = transport.core.borrow_mut();
          core.handle_datagram(dg);
          while let Ok(dg) = rx.try_recv() {
            core.handle_datagram(dg);
          }
        }
        None => break,
      },
      _ = sleep => {
        let _ = transport.core.borrow_mut().agent.handle_timeout(Instant::now());
      }
    }
  }
}