Skip to main content

rtci_host/
peer.rs

1// Copyright 2026 Brainwires. MIT OR Apache-2.0.
2
3//! One `RTCPeerConnection`: webrtc-rs's sans-I/O `rtci` engine plus the I/O
4//! that engine leaves to its host, owned here.
5//!
6//! `rtci` runs ICE, DTLS, SCTP and the data channels as state machines: it
7//! never opens a socket, arms a timer or reads the clock. This module gives
8//! each peer connection
9//!
10//! - one UDP socket per address family. With interface enumeration and a
11//!   listen grant for the wildcard address it is bound to `0.0.0.0` (and
12//!   `[::]` when the machine has a usable IPv6 address), and every interface
13//!   address becomes a host candidate on that port; otherwise it is bound to
14//!   `127.0.0.1` alone. The engine matches a datagram to a local candidate by
15//!   its exact local address, which a wildcard socket doesn't report, so the
16//!   local address of a datagram from a peer is the address the OS routes to
17//!   that peer from (a connected probe socket, cached per peer: bounded, and
18//!   only for a peer ICE or the permission gate vouched for);
19//! - one sans-I/O STUN/TURN client per ICE server URL: over the UDP socket,
20//!   or over its own TCP or TLS connection for `?transport=tcp` and `turns:`
21//!   (RFC 6544 framing: STUN messages and padded ChannelData on the stream);
22//! - on a `tcpPort` network (net.rs), ICE over TCP (RFC 6544): passive host
23//!   candidates on the network's listeners and an active one (port 9) per
24//!   host address; a check to a remote passive candidate dials it, and each
25//!   connection, accepted or dialled, carries RFC 4571 frames;
26//! - mDNS (`.local` host candidates): one multicast socket on port 5353,
27//!   opened when a remote `.local` candidate needs resolving or, on an
28//!   `mdns: true` network, when the connection publishes its own;
29//! - a driver task that moves datagrams between the sockets, those clients
30//!   and the engine, fires the timers and queues the engine's events for
31//!   JavaScript.
32//!
33//! Guards the engine doesn't provide:
34//!
35//! - **Net permission gate** ([`NetGate`]): every datagram is sent only to
36//!   an allowed address (checked once per address); a refused one is never
37//!   sent to and is reported as an `icecandidateerror`.
38//! - **Selected-pair filter**: the engine doesn't check where a non-STUN
39//!   packet (DTLS, SCTP inside it, RTP) comes from, so only those from the
40//!   selected candidate pair reach it (see [`Core::is_from_selected_pair`]); STUN is
41//!   authenticated by ICE itself.
42//! - **DTLS watchdog**: the engine logs and drops handshake errors, so a
43//!   connection whose ICE is up but whose DTLS hasn't connected within
44//!   [`DTLS_TIMEOUT`] is reported as `failed`.
45//! - **Panic boundary**: a panic in the engine poisons the connection (it
46//!   reports `failed` and closes) instead of unwinding into the runtime. In a
47//!   `panic = "abort"` build (Deno's release profile) a panic still aborts.
48//!
49//! Everything runs on the isolate's thread: ops and the driver share the
50//! [`Core`] through a `RefCell` and never hold it across an `.await`.
51
52use std::cell::Cell;
53use std::cell::RefCell;
54use std::collections::HashMap;
55use std::collections::HashSet;
56use std::collections::VecDeque;
57use std::net::IpAddr;
58use std::net::Ipv4Addr;
59use std::net::SocketAddr;
60use std::panic::AssertUnwindSafe;
61use std::rc::Rc;
62use std::rc::Weak;
63use std::sync::Arc;
64use std::time::Duration;
65use std::time::Instant;
66use std::time::SystemTime;
67use std::time::UNIX_EPOCH;
68
69use crate::rt::Cancel;
70use crate::rt::OrCancel;
71use bytes::BytesMut;
72use rtci::data_channel::RTCDataChannelId;
73use rtci::data_channel::RTCDataChannelInit;
74use rtci::data_channel::RTCDataChannelState;
75use rtci::ice::mdns::MulticastDnsMode;
76use rtci::ice::tcp_type::TcpType;
77use rtci::ice::url::ProtoType;
78use rtci::ice::url::SchemeType;
79use rtci::ice::url::Url as IceUrl;
80use rtci::mdns::MDNS_DEST_ADDR;
81use rtci::mdns::MDNS_PORT;
82use rtci::peer_connection::RTCPeerConnection;
83use rtci::peer_connection::RTCPeerConnectionBuilder;
84use rtci::peer_connection::certificate::RTCCertificate;
85use rtci::peer_connection::configuration::RTCBundlePolicy;
86use rtci::peer_connection::configuration::RTCConfigurationBuilder;
87use rtci::peer_connection::configuration::setting_engine::SctpMaxMessageSize;
88use rtci::peer_connection::configuration::setting_engine::SettingEngineBuilder;
89use rtci::peer_connection::event::RTCDataChannelEvent;
90use rtci::peer_connection::event::RTCPeerConnectionEvent;
91use rtci::peer_connection::event::RTCTrackEvent;
92use rtci::peer_connection::message::RTCMessage;
93use rtci::peer_connection::sdp::RTCSessionDescription;
94use rtci::peer_connection::transport::CandidateConfig;
95use rtci::peer_connection::transport::CandidateHostConfig;
96use rtci::peer_connection::transport::CandidateRelayConfig;
97use rtci::peer_connection::transport::CandidateServerReflexiveConfig;
98use rtci::peer_connection::transport::RTCIceCandidate;
99use rtci::peer_connection::transport::RTCIceCandidateInit;
100use rtci::peer_connection::transport::RTCIceCandidateType;
101use rtci::peer_connection::transport::RTCSctpTransportState;
102use rtci::sansio::Protocol;
103use rtci::shared::EcnCodepoint;
104use rtci::shared::TaggedBytesMut;
105use rtci::shared::TransportContext;
106use rtci::shared::TransportProtocol;
107use rtci::shared::error::Error as RtcError;
108use rtci::shared::marshal::Marshal;
109use rtci::shared::tcp_framing::TcpFrameDecoder;
110use rtci::shared::tcp_framing::try_frame_packet;
111use rtci::statistics::StatsSelector;
112use rtci::statistics::report::RTCStatsReportEntry;
113use rtci::stun::message::TransactionId;
114use rtci::turn::client::Client as TurnClient;
115use rtci::turn::client::ClientConfig as TurnClientConfig;
116use rtci::turn::client::Event as TurnEvent;
117use serde::Serialize;
118use tokio::io::AsyncReadExt;
119use tokio::io::AsyncWriteExt;
120use tokio::sync::Notify;
121use tokio::sync::mpsc;
122
123use crate::ecn::EcnUdpSocket;
124use crate::error::Error;
125use crate::error::ErrorKind;
126use crate::gate::GateToken;
127use crate::gate::LocalBoxFuture;
128use crate::gate::NetGate;
129use crate::gate::Proto;
130use crate::gate::Reach;
131use crate::gate::ReachKind;
132use crate::gate_cache::GateCache;
133use crate::media::MediaState;
134use crate::net::MdnsMode;
135use crate::net::Network;
136use crate::net::NetworkOptions;
137use crate::net_io::NetIo;
138use crate::net_io::UdpOpts;
139
140/// The largest UDP payload read from a socket. ICE, DTLS and SCTP packets
141/// stay under the path MTU; this leaves room for jumbo frames.
142const RECV_BUFFER_SIZE: usize = 9216;
143/// Datagrams queued between the socket readers and the driver. A full queue
144/// drops new datagrams, as a full socket buffer would.
145const RECV_QUEUE: usize = 4096;
146/// How many times one driver pass loops over writes, server clients and
147/// events before it waits again (each loop can produce more work, e.g. a
148/// relayed datagram the engine answers).
149const MAX_PUMP_ROUNDS: usize = 32;
150/// `icecandidateerror` code for "no server response / not reachable", the
151/// code browsers use for gathering failures without a STUN error code.
152const ERROR_CODE_UNREACHABLE: u16 = 701;
153/// How long DTLS may take once ICE is connected before the connection is
154/// reported as failed (the handshake retransmits for up to ~60 s in the
155/// engine, but a peer that connects ICE and never finishes DTLS is broken:
156/// a wrong fingerprint, a certificate the engine refused).
157pub const DTLS_TIMEOUT: Duration = Duration::from_secs(15);
158/// How long ICE may stay `checking` without a connection while the remote
159/// side hasn't signalled end-of-candidates before it is reported
160/// `disconnected` (W3C webrtc-pc 4.3.3: checked the pairs it has and found no
161/// connection, still waiting for remote candidates). The engine's own
162/// disconnected timeout.
163const CHECKING_STALL: Duration = Duration::from_secs(5);
164/// Remote addresses remembered as having sent STUN.
165const MAX_STUN_PEERS: usize = 256;
166/// Peer IPs whose local route is cached (wildcard sockets).
167pub(crate) const MAX_ROUTES: usize = 1024;
168/// The largest frame read from a TCP/TLS TURN connection (a STUN message or
169/// a ChannelData frame: 4 + 65535 bytes, padded).
170const MAX_STREAM_FRAME: usize = 4 + 65536;
171/// The port an active ICE-TCP candidate is signalled with (RFC 6544 ยง4.5):
172/// it connects out and never listens.
173const ACTIVE_TCP_PORT: u16 = 9;
174/// ICE-TCP connections (accepted and dialled) one peer connection keeps.
175const MAX_TCP_LINKS: usize = 32;
176/// Frames queued for one ICE-TCP connection's writer; a full queue drops
177/// new ones, as a full UDP socket buffer would (ICE and DTLS retransmit).
178const TCP_WRITE_QUEUE: usize = 256;
179/// Frames held for a remote passive candidate while it is being dialled.
180const MAX_DIAL_QUEUE: usize = 8;
181/// How long dialling a remote passive candidate may take.
182const TCP_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
183/// How long an mDNS query for a remote `.local` candidate is retried.
184const MDNS_QUERY_TIMEOUT: Duration = Duration::from_secs(10);
185/// The longest TURN username STUN carries (RFC 8489 section 14.3).
186const MAX_TURN_USERNAME_BYTES: usize = 509;
187
188/// How a STUN/TURN client reaches its server.
189#[derive(Clone, Copy, Debug, PartialEq, Eq)]
190pub enum ServerTransport {
191  Udp,
192  Tcp,
193  Tls,
194}
195
196/// A STUN or TURN server URL from `RTCConfiguration.iceServers`, parsed and
197/// permission-checked by the constructor.
198#[derive(Clone, Debug)]
199pub struct IceServerSpec {
200  pub url: String,
201  pub turn: bool,
202  pub host: String,
203  pub port: u16,
204  pub username: String,
205  pub credential: String,
206  pub transport: ServerTransport,
207}
208
209impl IceServerSpec {
210  /// Parses one URL of an `RTCIceServer`. `Err` is the W3C `SyntaxError`
211  /// (bad URL) or `InvalidAccessError` (TURN without usable credentials)
212  /// message.
213  pub fn parse(
214    url: &str,
215    username: Option<&str>,
216    credential: Option<&str>,
217  ) -> Result<Self, Error> {
218    let parsed = IceUrl::parse_url(url).map_err(|e| {
219      Error::new(
220        ErrorKind::Syntax,
221        format!("Invalid ICE server URL '{url}': {e}"),
222      )
223    })?;
224    // RFC 7064 / 7065: `scheme ":" host [":" port]` and, for TURN, a
225    // `?transport=` query; no userinfo, authority or path.
226    let address = url
227      .split_once(':')
228      .map_or("", |(_, rest)| rest.split('?').next().unwrap_or_default());
229    if address.contains(['@', '/', '\\']) {
230      return Err(Error::new(
231        ErrorKind::Syntax,
232        format!(
233          "Invalid ICE server URL '{url}': only a host and a port may follow the scheme"
234        ),
235      ));
236    }
237    let turn = matches!(parsed.scheme, SchemeType::Turn | SchemeType::Turns);
238    if turn {
239      match (username, credential) {
240        (Some(username), Some(credential))
241          if !credential.is_empty()
242            && username.len() <= MAX_TURN_USERNAME_BYTES => {}
243        (Some(username), Some(_))
244          if username.len() > MAX_TURN_USERNAME_BYTES =>
245        {
246          return Err(Error::new(
247            ErrorKind::InvalidAccess,
248            format!(
249              "TURN server '{url}': the username is longer than {MAX_TURN_USERNAME_BYTES} bytes"
250            ),
251          ));
252        }
253        _ => {
254          return Err(Error::new(
255            ErrorKind::InvalidAccess,
256            format!(
257              "TURN server '{url}' needs a username and a non-empty credential"
258            ),
259          ));
260        }
261      }
262      // W3C webrtc-pc 4.4.1.5: a username or credential that fails RFC 8489
263      // section 14.3 / RFC 8265 section 4.1 (the OpaqueString profile: no
264      // control, default-ignorable or unassigned code point) is an
265      // InvalidAccessError now, not a TURN key that can't be derived later.
266      // rtci 0.3 checks its own configuration so; this host gathers from
267      // the servers itself, so it checks them here. An empty username stays
268      // as it was taken.
269      let opaque = |value: &str| {
270        value.is_empty() || rtci::stun::opaque::opaque_string(value).is_ok()
271      };
272      if !opaque(username.unwrap_or_default())
273        || !opaque(credential.unwrap_or_default())
274      {
275        return Err(Error::new(
276          ErrorKind::InvalidAccess,
277          format!(
278            "TURN server '{url}': the username or credential is not an RFC 8265 OpaqueString"
279          ),
280        ));
281      }
282    }
283    let transport = match (parsed.scheme, parsed.proto) {
284      (SchemeType::Turns | SchemeType::Stuns, _) => ServerTransport::Tls,
285      (_, ProtoType::Tcp) => ServerTransport::Tcp,
286      _ => ServerTransport::Udp,
287    };
288    Ok(Self {
289      url: url.to_string(),
290      turn,
291      host: parsed.host.trim_matches(['[', ']']).to_string(),
292      port: parsed.port,
293      username: username.unwrap_or_default().to_string(),
294      credential: credential.unwrap_or_default().to_string(),
295      transport,
296    })
297  }
298}
299
300/// The stats fields the engine writes from a `SystemInstant`, as
301/// milliseconds since the epoch (`rtci_shared::serde::instant_to_epoch`).
302const STATS_EPOCH_FIELDS: [&str; 5] = [
303  "timestamp",
304  "lastPacketSentTimestamp",
305  "lastPacketReceivedTimestamp",
306  "remoteTimestamp",
307  "estimatedPlayoutTimestamp",
308];
309
310/// Adds the packets the pacer's full queue refused
311/// ([`crate::media::FactorPacer`]) to the selected candidate pair's
312/// `packetsDiscardedOnSend` / `bytesDiscardedOnSend`, beside the
313/// `availableOutgoingBitrate` that pacer follows: like a packet the socket
314/// refused, it never left. The count is the connection's (one pacer).
315pub(crate) fn add_pacer_refusals(
316  stats: &mut [serde_json::Value],
317  (packets, bytes): (u64, u64),
318) {
319  let selected = stats
320    .iter()
321    .find(|s| s["type"] == "transport")
322    .and_then(|s| s["selectedCandidatePairId"].as_str())
323    .map(str::to_owned);
324  for s in stats.iter_mut() {
325    if s["type"] != "candidate-pair" {
326      continue;
327    }
328    // The sockets are the driver's, so every pair has the members (rtci 0.2
329    // leaves them out until the application reports a discard): 0 until
330    // something is discarded.
331    let refused = selected.as_deref() == s["id"].as_str();
332    for (key, n) in [
333      ("packetsDiscardedOnSend", packets),
334      ("bytesDiscardedOnSend", bytes),
335    ] {
336      let before = s[key].as_u64().unwrap_or(0);
337      s[key] = (before + if refused { n } else { 0 }).into();
338    }
339  }
340}
341
342/// One stats dictionary with its epoch fields made relative to `wall_ms`, the
343/// wall clock (milliseconds since the epoch) when the report was asked for:
344/// JavaScript adds the Performance time of that moment, so the timestamps are
345/// `DOMHighResTimeStamp`s on `performance.timeOrigin`'s timeline (W3C
346/// webrtc-stats, hr-time) whatever the wall clock does.
347pub fn epoch_fields_relative(
348  mut stats: serde_json::Value,
349  wall_ms: f64,
350) -> serde_json::Value {
351  if let Some(map) = stats.as_object_mut() {
352    for key in STATS_EPOCH_FIELDS {
353      if let Some(ms) = map.get(key).and_then(serde_json::Value::as_f64) {
354        map.insert(key.to_string(), serde_json::json!(ms - wall_ms));
355      }
356    }
357  }
358  stats
359}
360
361/// Options for [`Peer::new`], from `RTCConfiguration`.
362#[derive(Default)]
363pub struct PeerOptions {
364  pub ice_servers: Vec<IceServerSpec>,
365  /// `iceTransportPolicy: "relay"`: only relay candidates are signalled.
366  pub relay_only: bool,
367  /// For `turns:` servers: the runtime's TLS client configuration (its root
368  /// store, `--unsafely-ignore-certificate-errors`).
369  pub tls: Option<Arc<rustls::ClientConfig>>,
370  /// `RTCConfiguration.certificates` (one is generated when empty).
371  pub certificates: Vec<RTCCertificate>,
372  /// `RTCConfiguration.bundlePolicy`.
373  pub bundle_policy: RTCBundlePolicy,
374  /// `RTCConfiguration.denoNetwork` (net.rs).
375  pub network: Option<Rc<Network>>,
376}
377
378/// An event for JavaScript, delivered in batches by [`Peer::next_events`].
379/// Data channels are named by their engine handle (`channel`), which
380/// exists before the SCTP stream id does.
381///
382/// `P` is how a received payload is held: [`Payload`] from the engine; a
383/// front end that hands buffers to its JavaScript without a copy swaps it
384/// for its own buffer type with [`JsEvent::map_payload`].
385#[derive(Serialize, Debug)]
386#[serde(tag = "type")]
387pub enum JsEvent<P = Payload> {
388  #[serde(rename = "icecandidate", rename_all = "camelCase")]
389  IceCandidate {
390    candidate: String,
391    sdp_mid: Option<String>,
392    #[serde(rename = "sdpMLineIndex")]
393    sdp_m_line_index: Option<u16>,
394    username_fragment: Option<String>,
395    url: Option<String>,
396  },
397  #[serde(rename = "icecandidateerror", rename_all = "camelCase")]
398  IceCandidateError {
399    address: Option<String>,
400    port: Option<u16>,
401    url: String,
402    error_code: u16,
403    error_text: String,
404  },
405  #[serde(rename = "signalingstatechange")]
406  SignalingState { state: String },
407  #[serde(rename = "icegatheringstatechange")]
408  IceGatheringState { state: String },
409  #[serde(rename = "iceconnectionstatechange")]
410  IceConnectionState { state: String },
411  #[serde(rename = "connectionstatechange")]
412  ConnectionState { state: String },
413  #[serde(rename = "negotiationneeded")]
414  NegotiationNeeded,
415  /// `RTCSctpTransport.state`, from the SCTP association.
416  #[serde(rename = "sctpstatechange")]
417  SctpState { state: &'static str },
418  /// The DTLS transport's own state, as the engine has it (the peer's
419  /// close_notify closes it while the connection stays `connected`).
420  #[serde(rename = "dtlsstatechange")]
421  DtlsState { state: String },
422  #[serde(rename = "dcopen", rename_all = "camelCase")]
423  DataChannelOpen {
424    channel: u32,
425    id: Option<u16>,
426    label: String,
427    protocol: String,
428    ordered: bool,
429    max_packet_life_time: Option<u16>,
430    max_retransmits: Option<u16>,
431    negotiated: bool,
432    /// The DCEP priority (RFC 8832 5.1): the peer's, for a channel it opened.
433    priority: u16,
434  },
435  #[serde(rename = "dcclosing")]
436  DataChannelClosing { channel: u32 },
437  #[serde(rename = "dcclose")]
438  DataChannelClose { channel: u32 },
439  /// A data channel failed (W3C: an `error` event with an `RTCError`, then
440  /// the channel closes): the engine's `RTCError` for it
441  /// (`RTCPeerConnection::data_channel_error`), and what names the channel.
442  #[serde(rename = "dcerror", rename_all = "camelCase")]
443  DataChannelError {
444    channel: u32,
445    error_detail: String,
446    message: String,
447    sctp_cause_code: Option<u16>,
448    label: Option<String>,
449    id: Option<u16>,
450  },
451  /// SCTP took `bytes` more of the channel's application data from its send
452  /// queue (W3C: "when the underlying data transport sends data from its
453  /// queue ... reduce [[BufferedAmount]]").
454  #[serde(rename = "dcsent")]
455  DataChannelSent { channel: u32, bytes: f64 },
456  #[serde(rename = "dcmessage")]
457  DataChannelMessage { channel: u32, text: bool, data: P },
458  /// A receiver's first RTP packet since JavaScript last muted its track:
459  /// the track unmutes, unless JavaScript muted it again (or started
460  /// receiving again) since, which `generation` tells.
461  #[serde(rename = "trackunmute")]
462  TrackUnmute { transceiver: u32, generation: u32 },
463  /// An RTP packet for a `Deno.webrtc.readRtp()` reader (header included).
464  #[serde(rename = "rtp")]
465  Rtp { transceiver: u32, data: P },
466  /// The remote receiver asked a sender for a key frame (PLI / FIR).
467  #[serde(rename = "keyframerequest")]
468  KeyFrameRequest { transceiver: u32 },
469  /// A received frame, for the receiver's encoded transform.
470  #[serde(rename = "encodedframe")]
471  EncodedFrame {
472    transceiver: u32,
473    data: P,
474    #[serde(rename = "keyFrame")]
475    key_frame: bool,
476    width: Option<u16>,
477    height: Option<u16>,
478    info: crate::encoded_frames::ReceivedFrameInfo,
479  },
480  // wpt100:mediasink
481  /// A receiver's RTP stopped for `media_sink::SILENCE`: its track mutes.
482  #[serde(rename = "trackmute")]
483  TrackMute { transceiver: u32 },
484  /// A receiver's video names a new coded size (`getSettings()`).
485  #[serde(rename = "trackresize")]
486  TrackResize {
487    transceiver: u32,
488    width: u32,
489    height: u32,
490  },
491  /// A received frame, for `Deno.webrtc.readFrames()` readers.
492  #[serde(rename = "mediaframe")]
493  MediaFrame {
494    transceiver: u32,
495    data: P,
496    #[serde(rename = "keyFrame")]
497    key_frame: bool,
498    #[serde(rename = "mimeType")]
499    mime_type: String,
500    #[serde(rename = "rtpTimestamp")]
501    rtp_timestamp: u32,
502    width: Option<u32>,
503    height: Option<u32>,
504  },
505  /// A two-phase operation finished ([`Peer::set_remote_description`],
506  /// [`Peer::add_ice_candidate`]): `op` is the id the call returned, and
507  /// `error` (left out on success) its failure as
508  /// `{"kind": "NotCapable", "message": "..."}`, `kind` being an
509  /// [`ErrorKind::name`].
510  #[serde(rename = "opdone")]
511  OpDone {
512    op: u32,
513    #[serde(skip_serializing_if = "Option::is_none")]
514    error: Option<Error>,
515  },
516}
517
518/// A received payload's bytes (a data channel message, an RTP packet, a
519/// frame). Serializes as bytes.
520#[derive(Debug, Clone, PartialEq, Eq)]
521pub struct Payload(bytes::Bytes);
522
523impl Payload {
524  pub(crate) fn new(bytes: impl Into<bytes::Bytes>) -> Self {
525    Self(bytes.into())
526  }
527
528  pub fn as_bytes(&self) -> &[u8] {
529    &self.0
530  }
531
532  /// The bytes (`Vec::from` of them takes the buffer without a copy when
533  /// nothing else holds it).
534  pub fn into_bytes(self) -> bytes::Bytes {
535    self.0
536  }
537
538  #[cfg(test)]
539  pub fn bytes(&self) -> Vec<u8> {
540    self.0.to_vec()
541  }
542}
543
544impl Serialize for Payload {
545  fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
546    s.serialize_bytes(&self.0)
547  }
548}
549
550impl<P> JsEvent<P> {
551  /// The same event with its payload (if any) converted by `f`.
552  pub fn map_payload<Q>(self, f: impl FnOnce(P) -> Q) -> JsEvent<Q> {
553    use JsEvent as E;
554    match self {
555      E::IceCandidate {
556        candidate,
557        sdp_mid,
558        sdp_m_line_index,
559        username_fragment,
560        url,
561      } => E::IceCandidate {
562        candidate,
563        sdp_mid,
564        sdp_m_line_index,
565        username_fragment,
566        url,
567      },
568      E::IceCandidateError {
569        address,
570        port,
571        url,
572        error_code,
573        error_text,
574      } => E::IceCandidateError {
575        address,
576        port,
577        url,
578        error_code,
579        error_text,
580      },
581      E::SignalingState { state } => E::SignalingState { state },
582      E::IceGatheringState { state } => E::IceGatheringState { state },
583      E::IceConnectionState { state } => E::IceConnectionState { state },
584      E::ConnectionState { state } => E::ConnectionState { state },
585      E::NegotiationNeeded => E::NegotiationNeeded,
586      E::OpDone { op, error } => E::OpDone { op, error },
587      E::SctpState { state } => E::SctpState { state },
588      E::DtlsState { state } => E::DtlsState { state },
589      E::DataChannelOpen {
590        channel,
591        id,
592        label,
593        protocol,
594        ordered,
595        max_packet_life_time,
596        max_retransmits,
597        negotiated,
598        priority,
599      } => E::DataChannelOpen {
600        channel,
601        id,
602        label,
603        protocol,
604        ordered,
605        max_packet_life_time,
606        max_retransmits,
607        negotiated,
608        priority,
609      },
610      E::DataChannelClosing { channel } => E::DataChannelClosing { channel },
611      E::DataChannelClose { channel } => E::DataChannelClose { channel },
612      E::DataChannelError {
613        channel,
614        error_detail,
615        message,
616        sctp_cause_code,
617        label,
618        id,
619      } => E::DataChannelError {
620        channel,
621        error_detail,
622        message,
623        sctp_cause_code,
624        label,
625        id,
626      },
627      E::DataChannelSent { channel, bytes } => {
628        E::DataChannelSent { channel, bytes }
629      }
630      E::DataChannelMessage {
631        channel,
632        text,
633        data,
634      } => E::DataChannelMessage {
635        channel,
636        text,
637        data: f(data),
638      },
639      E::TrackUnmute {
640        transceiver,
641        generation,
642      } => E::TrackUnmute {
643        transceiver,
644        generation,
645      },
646      E::Rtp { transceiver, data } => E::Rtp {
647        transceiver,
648        data: f(data),
649      },
650      E::KeyFrameRequest { transceiver } => E::KeyFrameRequest { transceiver },
651      E::EncodedFrame {
652        transceiver,
653        data,
654        key_frame,
655        width,
656        height,
657        info,
658      } => E::EncodedFrame {
659        transceiver,
660        data: f(data),
661        key_frame,
662        width,
663        height,
664        info,
665      },
666      E::TrackMute { transceiver } => E::TrackMute { transceiver },
667      E::TrackResize {
668        transceiver,
669        width,
670        height,
671      } => E::TrackResize {
672        transceiver,
673        width,
674        height,
675      },
676      E::MediaFrame {
677        transceiver,
678        data,
679        key_frame,
680        mime_type,
681        rtp_timestamp,
682        width,
683        height,
684      } => E::MediaFrame {
685        transceiver,
686        data: f(data),
687        key_frame,
688        mime_type,
689        rtp_timestamp,
690        width,
691        height,
692      },
693    }
694  }
695}
696
697/// A datagram one of the readers received. `stream` is the index of the
698/// server client whose TCP/TLS connection carried it.
699pub(crate) struct Datagram {
700  pub(crate) local: SocketAddr,
701  pub(crate) from: SocketAddr,
702  pub(crate) stream: Option<usize>,
703  /// Which kind of socket it came from.
704  pub(crate) via: Via,
705  pub(crate) data: BytesMut,
706  /// A TCP/TLS link to a TURN server ended (`stream` names it): why.
707  pub(crate) closed: Option<String>,
708  /// The ECN codepoint a UDP datagram arrived with (`None`: Not-ECT, or a
709  /// socket without ECN; always `None` over TCP and TURN).
710  pub(crate) ecn: Option<EcnCodepoint>,
711}
712
713/// Where a [`Datagram`] came from.
714#[derive(Clone, Copy, Debug, PartialEq, Eq)]
715pub(crate) enum Via {
716  /// A UDP socket, or a TURN server's stream (`Datagram::stream`).
717  Socket,
718  /// The ICE-TCP connection with this id.
719  IceTcp(u64),
720  /// The mDNS socket.
721  Mdns,
722}
723
724/// One ICE-TCP connection, accepted on a passive candidate or dialled from
725/// an active one.
726struct TcpLink {
727  id: u64,
728  writer: mpsc::Sender<Vec<u8>>,
729}
730
731/// The connection's UDP socket for one address family.
732struct UdpEndpoint {
733  socket: Rc<EcnUdpSocket>,
734  /// What the socket is bound to; a wildcard address for a wildcard bind.
735  bound: SocketAddr,
736  /// The host candidate addresses on this socket's port.
737  hosts: Vec<IpAddr>,
738}
739
740enum ServerLink {
741  Udp,
742  /// A TCP or TLS connection: frames for the writer task.
743  Stream(mpsc::UnboundedSender<Vec<u8>>),
744}
745
746/// One STUN/TURN client, for one ICE server URL.
747struct ServerClient {
748  url: String,
749  client: TurnClient,
750  /// The client's local address: a host candidate address on the UDP
751  /// socket, or the stream's local address.
752  base: SocketAddr,
753  server: SocketAddr,
754  link: ServerLink,
755  binding: Option<TransactionId>,
756  allocate: Option<TransactionId>,
757  relay: Option<SocketAddr>,
758}
759
760impl ServerClient {
761  fn pending(&self) -> bool {
762    self.binding.is_some() || self.allocate.is_some()
763  }
764
765  fn protocol(&self) -> TransportProtocol {
766    match self.link {
767      ServerLink::Udp => TransportProtocol::UDP,
768      ServerLink::Stream(_) => TransportProtocol::TCP,
769    }
770  }
771}
772
773#[derive(Clone, Copy, PartialEq, Eq, Debug)]
774enum GatherPhase {
775  NotStarted,
776  Running,
777  Complete,
778}
779
780/// The engine and the I/O state around it, shared by ops and the driver.
781pub struct Core {
782  pub pc: RTCPeerConnection,
783  options: PeerOptions,
784  endpoints: Vec<UdpEndpoint>,
785  servers: Vec<ServerClient>,
786  gathering: GatherPhase,
787  /// ICE server URLs still being resolved / connected before their client
788  /// exists.
789  resolving: usize,
790  /// The first gathering waits for the gate's answers for its binds.
791  binds_pending: bool,
792  srflx_seen: HashSet<SocketAddr>,
793  pub(crate) events: VecDeque<JsEvent>,
794  allowed: HashSet<SocketAddr>,
795  refused: HashSet<SocketAddr>,
796  /// Peer IP -> the local IP the OS routes to it from (wildcard sockets).
797  /// Only for addresses ICE or the permission gate vouched for (see
798  /// [`Core::local_for`]), and at most [`MAX_ROUTES`].
799  routes: HashMap<IpAddr, IpAddr>,
800  /// The selected candidate pair as (local, remote): where the engine's
801  /// last non-STUN datagram went.
802  selected: Option<(SocketAddr, SocketAddr)>,
803  /// Remote addresses that sent STUN (see [`Core::is_from_selected_pair`]).
804  stun_peers: HashSet<SocketAddr>,
805  /// ICE is connected or completed.
806  ice_up: bool,
807  /// When ICE last reached connected/completed while DTLS hadn't.
808  ice_up_at: Option<Instant>,
809  dtls_connected: bool,
810  /// A synthetic `failed` was reported (watchdog or panic): later engine
811  /// connection states other than `closed` are not reported.
812  failed: bool,
813  recv_tx: mpsc::Sender<Datagram>,
814  recv_rx: Option<mpsc::Receiver<Datagram>>,
815  /// Transceivers, senders and receivers (media.rs).
816  pub(crate) media: MediaState,
817  /// Receivers whose frames go to an encoded transform (encoded_frames.rs).
818  pub(crate) transforms: crate::encoded_frames::ReceiverTransforms,
819  /// Received frames, sizes and silence per receiver (media_sink.rs).
820  pub(crate) sinks: crate::media_sink::MediaSinks,
821  /// A remote candidate is known (signalled, or a check arrived): until
822  /// then ICE stays `new`, as the spec's `checking` needs one.
823  remote_known: bool,
824  /// `collect_events` wrote RTCP (a key-frame request after a loss): the
825  /// pump goes round again so that it leaves now, not with the next
826  /// datagram or timer.
827  pub(crate) wrote_rtcp: bool,
828  /// The engine went `checking` before that: reported once one is.
829  checking_held: bool,
830  /// An ICE restart's `checking` on a connected transport was not reported
831  /// (see `collect_events`); cleared by the next other ICE state.
832  restart_masked: bool,
833  /// When `checking` was last reported (see [`CHECKING_STALL`]).
834  checking_since: Option<Instant>,
835  /// Per data channel handle, the application bytes SCTP had taken from the
836  /// send queue when last reported (`track_sent`).
837  sent: HashMap<u32, u64>,
838  /// The `RTCSctpTransport` state last reported ("" before any).
839  sctp_state: &'static str,
840  /// The DTLS transport state last reported ("" before any).
841  dtls_state: String,
842  /// Local candidates signalled in this gathering phase (an ICE restart
843  /// starts a new one).
844  local_gathered: usize,
845  /// The remote side signalled end-of-candidates for its current ICE
846  /// generation (`addIceCandidate` with an empty candidate, or
847  /// `a=end-of-candidates`).
848  remote_gathered: bool,
849  /// The current gathering phase runs under the relay-only ICE transport
850  /// policy (`relay_only` when it started: the first gathering, or the ICE
851  /// restart that applied a `setConfiguration`). Its traffic to and from the
852  /// peer goes through TURN relays only (see [`Core::relay_path`]).
853  relay_generation: bool,
854  /// The connection itself, for a shared-port network's routes.
855  this: Weak<Peer>,
856  /// The socket factory (every socket the connection opens).
857  pub(crate) io: Rc<dyn NetIo>,
858  /// The permission gate, with the answers it gave this connection.
859  gate: Rc<GateCache>,
860  /// ICE-TCP connections by remote address.
861  tcp_links: HashMap<SocketAddr, TcpLink>,
862  /// Remote passive candidates being dialled, with the frames waiting for
863  /// the connection.
864  tcp_dialing: HashMap<SocketAddr, Vec<Vec<u8>>>,
865  next_tcp_link: u64,
866  /// The selected pair is an ICE-TCP one.
867  selected_tcp: bool,
868  /// What this connection does with `.local` candidates (`Off` when mDNS
869  /// can't be used here: loopback only, or a permission refused).
870  mdns_mode: MdnsMode,
871  /// The mDNS socket, once opened.
872  mdns_socket: Option<Rc<EcnUdpSocket>>,
873  /// Opening the mDNS socket failed (reported once), or the gate refused
874  /// it.
875  mdns_failed: bool,
876  /// The gate's allow for the mDNS socket, once it gave one.
877  mdns_token: Option<GateToken>,
878  /// 1:1 NAT in host mode is the engine's (`with_nat_1to1_ips`): a host
879  /// candidate is added on its private address and announced on the public
880  /// one, its base staying the private socket, so the addresses the engine
881  /// reads and writes on are the sockets' own. Off with mDNS names (the
882  /// engine can't map a name), where the public address is signalled here.
883  engine_nat: bool,
884  /// The remote description's `a=simulcast` lines the engine was given
885  /// without a repeated rid-id, each with the line as signalled
886  /// ([`simulcast_without_repeated_rids`]): `remoteDescription` shows the
887  /// signalled one.
888  remote_simulcast_lines: Vec<(String, String)>,
889  /// The beginnings of the last datagrams sent through a TURN relay, so a
890  /// TURN message the socket refused for its size can be traced to the
891  /// path the engine sent on ([`Core::relayed_too_big`]).
892  relayed_recent: VecDeque<RelayedWrite>,
893}
894
895/// How many relayed datagrams [`Core::relayed_recent`] remembers.
896const RELAYED_RECENT: usize = 16;
897
898/// How many octets of a relayed datagram [`RelayedWrite`] keeps: more than
899/// the 13 the engine needs to match a quote against a DTLS datagram it sent
900/// (RFC 8899 section 4.6.1), and enough to tell datagrams apart.
901const RELAYED_HEAD: usize = 32;
902
903/// A datagram the engine sent through a TURN relay: the relayed address it
904/// went from, the peer, and its first octets.
905struct RelayedWrite {
906  relay: SocketAddr,
907  peer: SocketAddr,
908  head: [u8; RELAYED_HEAD],
909  len: usize,
910}
911
912impl RelayedWrite {
913  fn head(&self) -> &[u8] {
914    &self.head[..self.len]
915  }
916}
917
918/// The newest of `recent` sent from `relay` whose first octets (13 at
919/// least, so a short match means nothing) the TURN message `message` holds.
920fn find_relayed<'a>(
921  recent: &'a VecDeque<RelayedWrite>,
922  relay: SocketAddr,
923  message: &[u8],
924) -> Option<&'a RelayedWrite> {
925  recent.iter().rev().find(|w| {
926    w.relay == relay
927      && w.len >= 13
928      && message.windows(w.len).any(|window| window == w.head())
929  })
930}
931
932/// RFC 7983 section 7: a first octet of 20 to 63 is DTLS.
933fn is_dtls(data: &[u8]) -> bool {
934  data.first().is_some_and(|b| (20..=63).contains(b))
935}
936
937/// One candidate of [`SelectedPair`], with the fields JavaScript needs to
938/// build the `RTCIceCandidate` (a peer-reflexive remote candidate is exposed
939/// without its address, so it can't be found among the signalled ones).
940#[derive(serde::Serialize, Debug)]
941#[serde(rename_all = "camelCase")]
942pub struct PairCandidate {
943  /// `ip:port` (`[ip]:port` for IPv6), as the signalled candidates are matched.
944  pub addr: String,
945  pub address: String,
946  pub port: u16,
947  pub protocol: String,
948  #[serde(rename = "type")]
949  pub typ: String,
950  pub foundation: String,
951  pub priority: u32,
952  pub related_address: String,
953  pub related_port: u16,
954}
955
956impl PairCandidate {
957  pub(crate) fn of(
958    c: &rtci::peer_connection::transport::RTCIceCandidate,
959  ) -> Self {
960    let addr = match c.address.parse::<IpAddr>() {
961      Ok(IpAddr::V6(ip)) => format!("[{ip}]:{}", c.port),
962      Ok(IpAddr::V4(ip)) => format!("{ip}:{}", c.port),
963      Err(_) => format!("{}:{}", c.address, c.port),
964    };
965    Self {
966      addr,
967      address: c.address.clone(),
968      port: c.port,
969      protocol: c.protocol.to_string(),
970      typ: c.typ.to_string(),
971      foundation: c.foundation.clone(),
972      priority: c.priority,
973      related_address: c.related_address.clone(),
974      related_port: c.related_port,
975    }
976  }
977}
978
979/// The ICE agent's selected candidate pair.
980#[derive(serde::Serialize, Debug)]
981pub struct SelectedPair {
982  pub local: PairCandidate,
983  pub remote: PairCandidate,
984}
985
986/// The four description slots of a connection, each `(type, sdp)`.
987#[derive(serde::Serialize)]
988#[serde(rename_all = "camelCase")]
989pub struct PeerDescriptions {
990  pub current_local: Option<(String, String)>,
991  pub pending_local: Option<(String, String)>,
992  pub current_remote: Option<(String, String)>,
993  pub pending_remote: Option<(String, String)>,
994}
995
996pub struct Peer {
997  pub(crate) core: RefCell<Core>,
998  /// The permission gate, with the answers it gave this connection.
999  gate: Rc<GateCache>,
1000  /// `setRemoteDescription` / `addIceCandidate` operations waiting, in
1001  /// order, for the gate (or for the one before them).
1002  ops: RefCell<VecDeque<(u32, PendingOp)>>,
1003  /// The operation the ops task is running, if any.
1004  current_op: Cell<Option<u32>>,
1005  /// The ops task is running.
1006  ops_running: Cell<bool>,
1007  last_op: Cell<u32>,
1008  /// Ops -> driver: there is something to flush.
1009  wake: Notify,
1010  /// Driver -> `op_webrtc_pc_next_events`: `core.events` is not empty.
1011  events_ready: Notify,
1012  cancel: Cancel,
1013  closed: Cell<bool>,
1014  driver_started: Cell<bool>,
1015}
1016
1017/// A queued two-phase operation (its outcome is the `opdone` event).
1018type PendingOp = LocalBoxFuture<'static, Result<(), Error>>;
1019
1020/// When a remote description's line is given to the engine.
1021enum Keep {
1022  Always,
1023  /// A candidate whose address the gate must allow (else the call fails).
1024  Allowed(Reach),
1025  /// A `.local` candidate: when the connection can resolve it.
1026  Mdns,
1027}
1028
1029pub(crate) fn rtc_err(e: impl std::fmt::Display) -> Error {
1030  Error::new(ErrorKind::Operation, e.to_string())
1031}
1032
1033/// The largest session description handed to the engine, in bytes (the
1034/// engine's own `MAX_SDP_SIZE`, 1 MiB).
1035pub(crate) const MAX_SDP_BYTES: usize = 1 << 20;
1036
1037/// Refuses an offer, answer or pranswer longer than [`MAX_SDP_BYTES`] before
1038/// anything reads it, with the OperationError a description the engine can't
1039/// parse gets. A rollback's text is ignored, and an unknown type stays the
1040/// TypeError `description` reports.
1041pub(crate) fn check_sdp_size(kind: &str, sdp: &str) -> Result<(), Error> {
1042  if matches!(kind, "offer" | "answer" | "pranswer")
1043    && sdp.len() > MAX_SDP_BYTES
1044  {
1045    return Err(Error::new(
1046      ErrorKind::Operation,
1047      format!(
1048        "session description of {} bytes exceeds {MAX_SDP_BYTES}",
1049        sdp.len()
1050      ),
1051    ));
1052  }
1053  Ok(())
1054}
1055
1056/// Whether an SDP has an m-section that isn't rejected: port zero without
1057/// `a=bundle-only` is a rejected one (RFC 8843 ยง6).
1058pub(crate) fn has_live_media_section(sdp: &str) -> bool {
1059  sdp.split("\nm=").skip(1).any(|section| {
1060    let port = section.split_ascii_whitespace().nth(1);
1061    port != Some("0") || section.contains("a=bundle-only")
1062  })
1063}
1064
1065/// An engine error applying a description: a type the signaling state
1066/// doesn't take (RFC 9429 ยง5.5 / ยง5.6) is an InvalidStateError (W3C "set the
1067/// RTCSessionDescription", step 4); anything else an OperationError.
1068fn description_err(e: RtcError) -> Error {
1069  match e {
1070    RtcError::ErrSignalingStateCannotRollback
1071    | RtcError::ErrSignalingStateProposedTransitionInvalid(_) => {
1072      Error::new(ErrorKind::InvalidState, e.to_string())
1073    }
1074    // A description the engine can't apply as written (the legacy
1075    // InvalidAccessError browsers and the WPT keep).
1076    RtcError::ErrSessionDescriptionInvalidIceCredentials => {
1077      Error::new(ErrorKind::InvalidAccess, e.to_string())
1078    }
1079    e => rtc_err(e),
1080  }
1081}
1082
1083/// The candidate's transport, address and port, from a candidate attribute
1084/// value (`candidate:<foundation> <component> <transport> <priority>
1085/// <address> <port> typ ...`).
1086pub fn candidate_address(candidate: &str) -> Option<(String, String, u16)> {
1087  let value = candidate
1088    .trim()
1089    .strip_prefix("a=")
1090    .unwrap_or(candidate.trim());
1091  let value = value.strip_prefix("candidate:").unwrap_or(value);
1092  let mut fields = value.split_ascii_whitespace();
1093  let _foundation = fields.next()?;
1094  let _component = fields.next()?;
1095  let transport = fields.next()?.to_ascii_lowercase();
1096  let _priority = fields.next()?;
1097  let address = fields.next()?.to_string();
1098  let port = fields.next()?.parse().ok()?;
1099  Some((transport, address, port))
1100}
1101
1102/// What to do with a remote candidate before the engine sees it.
1103#[derive(Debug, PartialEq, Eq)]
1104pub enum RemoteCandidate {
1105  /// A UDP candidate with a literal address: check it, then add it.
1106  Udp(SocketAddr),
1107  /// A passive (or simultaneous-open) TCP candidate with a literal address,
1108  /// on a connection doing ICE over TCP: check it, then add it.
1109  Tcp(SocketAddr),
1110  /// An mDNS `.local` host candidate, on a connection that resolves them:
1111  /// the engine resolves it, and the address it resolves to is checked
1112  /// against the net permission before anything is sent there.
1113  Mdns,
1114  /// An active TCP candidate, on a connection doing ICE over TCP: handed
1115  /// to the engine unchecked, since nothing is sent to it (its port is RFC
1116  /// 6544's placeholder 9; the peer dials our passive candidate). The
1117  /// engine's check list then waits at end-of-candidates for that dial
1118  /// rather than failing with no pair (RFC 8838 section 8), until its
1119  /// checking timeout.
1120  Active,
1121  /// Skipped and reported as accepted, as a browser does with a candidate it
1122  /// cannot use: TCP candidates without ICE over TCP (a `tcpPort` network),
1123  /// untyped TCP candidates, and `.local` names when mDNS is off (such a
1124  /// peer is still reached as a peer-reflexive candidate once its checks
1125  /// arrive).
1126  Ignore,
1127}
1128
1129/// The `tcptype` of a candidate attribute value, if it has one.
1130fn candidate_tcp_type(candidate: &str) -> Option<TcpType> {
1131  let mut fields = candidate.split_ascii_whitespace();
1132  while let Some(field) = fields.next() {
1133    if field.eq_ignore_ascii_case("tcptype") {
1134      return fields
1135        .next()
1136        .map(|t| TcpType::from(t.to_ascii_lowercase().as_str()));
1137    }
1138  }
1139  None
1140}
1141
1142/// Classifies a remote candidate for a connection that does (`tcp`) or
1143/// doesn't do ICE over TCP, and does (`mdns`) or doesn't resolve `.local`
1144/// names.
1145pub fn classify_remote_candidate(
1146  candidate: &str,
1147  tcp: bool,
1148  mdns: bool,
1149) -> Result<RemoteCandidate, Error> {
1150  let Some((transport, address, port)) = candidate_address(candidate) else {
1151    return Err(Error::new(
1152      ErrorKind::Operation,
1153      format!("Invalid ICE candidate '{candidate}'"),
1154    ));
1155  };
1156  let is_tcp = match transport.as_str() {
1157    "udp" => false,
1158    "tcp" if tcp => true,
1159    _ => return Ok(RemoteCandidate::Ignore),
1160  };
1161  if is_tcp {
1162    match candidate_tcp_type(candidate) {
1163      Some(TcpType::Passive | TcpType::SimultaneousOpen) => {}
1164      Some(TcpType::Active) => return Ok(RemoteCandidate::Active),
1165      _ => return Ok(RemoteCandidate::Ignore),
1166    }
1167  }
1168  match address.trim_matches(['[', ']']).parse::<IpAddr>() {
1169    Ok(ip) if is_tcp => Ok(RemoteCandidate::Tcp(SocketAddr::new(ip, port))),
1170    Ok(ip) => Ok(RemoteCandidate::Udp(SocketAddr::new(ip, port))),
1171    Err(_) if mdns && is_mdns_name(&address) => Ok(RemoteCandidate::Mdns),
1172    Err(_) => Ok(RemoteCandidate::Ignore),
1173  }
1174}
1175
1176/// A host candidate's `<name>.local` address (RFC 6762 names; WebRTC's are
1177/// `<uuid>.local`).
1178fn is_mdns_name(address: &str) -> bool {
1179  let lower = address.to_ascii_lowercase();
1180  let Some(label) = lower.strip_suffix(".local") else {
1181    return false;
1182  };
1183  !label.is_empty()
1184    && label.len() <= 63
1185    && label
1186      .bytes()
1187      .all(|b| b.is_ascii_alphanumeric() || b == b'-')
1188}
1189
1190/// Whether this connection can use mDNS at all: never with
1191/// `DENO_WEBRTC_LOOPBACK_ONLY=1`, and only with the permissions the socket
1192/// needs (listening on the wildcard address, sending to the mDNS group) and
1193/// interface enumeration, without which the connection is on loopback and
1194/// can't reach a LAN address anyway.
1195///
1196/// Asks in that order, each question once the one before is allowed; the
1197/// token is the bind's.
1198async fn mdns_permitted(gate: Rc<GateCache>) -> Result<GateToken, String> {
1199  if loopback_only() {
1200    return Err("DENO_WEBRTC_LOOPBACK_ONLY=1".to_string());
1201  }
1202  gate.interfaces().await?;
1203  let token = gate
1204    .verdict(Reach::bind(
1205      ReachKind::Mdns,
1206      Proto::Udp,
1207      IpAddr::V4(Ipv4Addr::UNSPECIFIED),
1208    ))
1209    .await?;
1210  gate
1211    .verdict(Reach::connect(ReachKind::Mdns, Proto::Udp, MDNS_DEST_ADDR))
1212    .await?;
1213  Ok(token)
1214}
1215
1216/// An `a=simulcast` value (RFC 8853 section 5.1: `<direction> <alt-list>
1217/// [<direction> <alt-list>]`) without the rid-ids it repeats, or `None` when
1218/// it repeats none. webrtc-pc ignores a repeated rid in a remote offer
1219/// (w3c/webrtc-pc#2780, WPT `simulcast/negotiation-encodings`
1220/// "Duplicate rids in sRD(offer) are ignored"); rtci 0.2 refuses the
1221/// description for it (RFC 8853 section 5.8).
1222pub(crate) fn simulcast_without_repeated_rids(value: &str) -> Option<String> {
1223  let mut seen: Vec<&str> = Vec::new();
1224  let mut repeated = false;
1225  let mut fields: Vec<String> = Vec::new();
1226  for (i, field) in value.split(' ').enumerate() {
1227    // Odd fields are the rid lists; the others the directions.
1228    if i % 2 == 0 {
1229      fields.push(field.to_string());
1230      continue;
1231    }
1232    let mut alternatives: Vec<String> = Vec::new();
1233    for alternative in field.split(';') {
1234      let mut rids: Vec<&str> = Vec::new();
1235      for rid in alternative.split(',') {
1236        let id = rid.strip_prefix('~').unwrap_or(rid);
1237        if seen.contains(&id) {
1238          repeated = true;
1239        } else {
1240          seen.push(id);
1241          rids.push(rid);
1242        }
1243      }
1244      if !rids.is_empty() {
1245        alternatives.push(rids.join(","));
1246      }
1247    }
1248    fields.push(alternatives.join(";"));
1249  }
1250  repeated.then(|| fields.join(" "))
1251}
1252
1253/// Whether an `a=extmap` value (`<id>[/<direction>] <uri> [attributes]`)
1254/// names its extension by an absolute URI, and for RFC 6904's encrypted form
1255/// (`urn:ietf:params:rtp-hdrext:encrypt <uri>`) the one it encrypts too.
1256pub(crate) fn extmap_names_absolute_uris(value: &str) -> bool {
1257  fn absolute(uri: &str) -> bool {
1258    let Some((scheme, rest)) = uri.split_once(':') else {
1259      return false;
1260    };
1261    !rest.is_empty()
1262      && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
1263      && scheme
1264        .chars()
1265        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
1266  }
1267  let mut tokens = value.split_ascii_whitespace().skip(1);
1268  match tokens.next() {
1269    Some("urn:ietf:params:rtp-hdrext:encrypt") => {
1270      tokens.next().is_none_or(absolute)
1271    }
1272    Some(uri) => absolute(uri),
1273    // A line without a URI is malformed, which the engine judges.
1274    None => true,
1275  }
1276}
1277
1278/// Whether `name` is an SDP `attribute-name`, a token (RFC 8866 section 9:
1279/// `token-char = %x21 / %x23-27 / %x2A-2B / %x2D-2E / %x30-39 / %x41-5A /
1280/// %x5E-7E`).
1281pub(crate) fn is_attribute_name(name: &str) -> bool {
1282  !name.is_empty()
1283    && name.bytes().all(|b| {
1284      matches!(b,
1285        0x21 | 0x23..=0x27 | 0x2a..=0x2b | 0x2d..=0x2e | 0x30..=0x39
1286          | 0x41..=0x5a | 0x5e..=0x7e)
1287    })
1288}
1289
1290/// Whether an `a=identity` value has RFC 8827 section 5's form, which the
1291/// engine's SDP parser requires: a base64 assertion, then single-space
1292/// separated extensions.
1293fn is_identity_value(value: &str) -> bool {
1294  let mut fields = value.split(' ');
1295  let assertion = fields.next().unwrap_or_default();
1296  let bytes = assertion.as_bytes();
1297  let pad = bytes.iter().rev().take_while(|b| **b == b'=').count();
1298  !bytes.is_empty()
1299    && bytes.len().is_multiple_of(4)
1300    && pad <= 2
1301    && bytes[..bytes.len() - pad]
1302      .iter()
1303      .all(|b| b.is_ascii_alphanumeric() || *b == b'+' || *b == b'/')
1304    && fields.all(|f| !f.is_empty())
1305}
1306
1307/// Sends one mDNS message to the IPv4 group from `from`, the address the
1308/// engine says it leaves from: an answer leaves from the address its record
1309/// names (rtci-mdns aggregates records per address), on that address's
1310/// interface (RFC 6762 section 14), so that its IP source is that address. A
1311/// resolver takes an A record only from the address it names, and only from
1312/// an on-link source (RFC 6762 section 11, the engine's hardening): sent from
1313/// the wildcard socket's default multicast interface instead, every answer
1314/// left from one address (a cloud host's public one, refused as off-link),
1315/// and no `.local` name resolved. A message from the unspecified address (a
1316/// query) or an IPv6 one (this socket is IPv4) takes the default interface.
1317fn send_mdns(socket: &EcnUdpSocket, message: &[u8], from: IpAddr) {
1318  let interface = match from {
1319    IpAddr::V4(v4) if !v4.is_unspecified() && !v4.is_loopback() => v4,
1320    _ => Ipv4Addr::UNSPECIFIED,
1321  };
1322  if let Err(e) =
1323    socket2::SockRef::from(&**socket).set_multicast_if_v4(&interface)
1324  {
1325    log::debug!("webrtc: mDNS interface {interface}: {e}");
1326    return;
1327  }
1328  if let Err(e) = socket.try_send_to(message, MDNS_DEST_ADDR) {
1329    log::debug!("webrtc: mDNS send from {interface}: {e}");
1330  }
1331}
1332
1333/// Hides the base address a server-reflexive or relay candidate names
1334/// (`raddr` / `rport`) when the host candidates are published under mDNS
1335/// names, as browsers do: it is the host address the name stands for.
1336pub(crate) fn redact_related_address(candidate: &str) -> String {
1337  let mut out = Vec::new();
1338  let mut fields = candidate.split(' ');
1339  while let Some(field) = fields.next() {
1340    out.push(field.to_string());
1341    let hidden = match field {
1342      "raddr" => fields
1343        .next()
1344        .map(|addr| if addr.contains(':') { "::" } else { "0.0.0.0" }),
1345      "rport" => fields.next().map(|_| "0"),
1346      _ => None,
1347    };
1348    if let Some(value) = hidden {
1349      out.push(value.to_string());
1350    }
1351  }
1352  out.join(" ")
1353}
1354
1355/// `DENO_WEBRTC_LOOPBACK_ONLY=1`: gather on `127.0.0.1` alone, never binding
1356/// the wildcard address (test machines whose firewall asks about every
1357/// non-loopback listener; two peers on one machine still connect). Read by
1358/// the runtime like its other `DENO_*` switches, without `--allow-env`.
1359pub(crate) fn loopback_only() -> bool {
1360  std::env::var_os("DENO_WEBRTC_LOOPBACK_ONLY").is_some_and(|v| v == "1")
1361}
1362
1363/// The machine's usable interface addresses (no loopback, no link-local),
1364/// of the named interfaces only when `names` is given.
1365pub(crate) fn interface_addresses(names: Option<&[String]>) -> Vec<IpAddr> {
1366  let Ok(ifaces) = netif::up() else {
1367    return Vec::new();
1368  };
1369  let mut out = Vec::new();
1370  for iface in ifaces {
1371    if names.is_some_and(|names| !names.iter().any(|n| n == iface.name())) {
1372      continue;
1373    }
1374    let ip = *iface.address();
1375    let usable = match ip {
1376      IpAddr::V4(v4) => {
1377        !v4.is_loopback() && !v4.is_link_local() && !v4.is_unspecified()
1378      }
1379      IpAddr::V6(v6) => {
1380        // Link-local addresses need a scope id the candidate grammar can't
1381        // carry; IPv4-mapped ones duplicate the IPv4 candidate.
1382        !v6.is_loopback()
1383          && !v6.is_unspecified()
1384          && (v6.segments()[0] & 0xffc0) != 0xfe80
1385          && v6.to_ipv4_mapped().is_none()
1386      }
1387    };
1388    if usable && !out.contains(&ip) {
1389      out.push(ip);
1390    }
1391  }
1392  out
1393}
1394
1395/// RFC 7983 demultiplexing: a STUN message starts with 0-3.
1396fn is_stun(data: &[u8]) -> bool {
1397  data.first().is_some_and(|b| *b < 4)
1398}
1399
1400fn candidate_line(
1401  candidate: rtci::shared::error::Result<rtci::ice::candidate::Candidate>,
1402) -> Result<String, Error> {
1403  let candidate = candidate.map_err(rtc_err)?;
1404  Ok(
1405    RTCIceCandidate::from(&candidate)
1406      .to_json()
1407      .map_err(rtc_err)?
1408      .candidate,
1409  )
1410}
1411
1412fn base_config(addr: SocketAddr) -> CandidateConfig {
1413  CandidateConfig {
1414    network: "udp".to_owned(),
1415    address: addr.ip().to_string(),
1416    port: addr.port(),
1417    component: 1,
1418    ..Default::default()
1419  }
1420}
1421
1422/// An ICE-TCP host candidate's line.
1423fn tcp_host_line(addr: SocketAddr, tcp_type: TcpType) -> Result<String, Error> {
1424  candidate_line(
1425    CandidateHostConfig {
1426      base_config: CandidateConfig {
1427        network: "tcp".to_owned(),
1428        ..base_config(addr)
1429      },
1430      tcp_type,
1431    }
1432    .new_candidate_host(),
1433  )
1434}
1435
1436/// The length of the first complete RFC 6544 frame in `buf` (a STUN message
1437/// or a padded ChannelData message), `Some(0)` for an incomplete one, `None`
1438/// for garbage.
1439fn stream_frame_len(buf: &[u8]) -> Option<usize> {
1440  if buf.len() < 4 {
1441    return Some(0);
1442  }
1443  let len = u16::from_be_bytes([buf[2], buf[3]]) as usize;
1444  let total = match buf[0] >> 6 {
1445    0 => 20 + len,
1446    1 => 4 + len.div_ceil(4) * 4,
1447    _ => return None,
1448  };
1449  if total > MAX_STREAM_FRAME {
1450    return None;
1451  }
1452  Some(if buf.len() >= total { total } else { 0 })
1453}
1454
1455impl Core {
1456  /// The local description's first media section id, for candidates the
1457  /// engine reports without one (W3C: `sdpMid` of the bundled section).
1458  fn first_mid(&self) -> Option<String> {
1459    let desc = self.pc.local_description()?;
1460    desc.sdp.lines().find_map(|l| {
1461      l.trim_end()
1462        .strip_prefix("a=mid:")
1463        .map(|mid| mid.trim().to_string())
1464    })
1465  }
1466
1467  fn local_ufrag(&self) -> Option<String> {
1468    let desc = self.pc.local_description()?;
1469    desc.sdp.lines().find_map(|l| {
1470      l.trim_end()
1471        .strip_prefix("a=ice-ufrag:")
1472        .map(|u| u.trim().to_string())
1473    })
1474  }
1475
1476  fn add_local(
1477    &mut self,
1478    candidate: String,
1479    url: Option<String>,
1480  ) -> Result<(), Error> {
1481    self
1482      .pc
1483      .add_local_candidate(RTCIceCandidateInit {
1484        candidate,
1485        url,
1486        ..Default::default()
1487      })
1488      .map_err(rtc_err)?;
1489    self.local_gathered += 1;
1490    Ok(())
1491  }
1492
1493  fn remote_ufrag(&self) -> Option<String> {
1494    let desc = self.pc.remote_description()?;
1495    desc.sdp.lines().find_map(|l| {
1496      l.trim_end()
1497        .strip_prefix("a=ice-ufrag:")
1498        .map(|u| u.trim().to_string())
1499    })
1500  }
1501
1502  /// W3C `RTCSctpTransport.state`: `connecting` until the association is
1503  /// up, `connected`, then `closed` for good once it ends (the engine forgets
1504  /// a closed association, so anything after `connected` is `closed`).
1505  fn track_sctp_state(&mut self) {
1506    let Some(engine) = self.pc.sctp().map(|s| s.state()) else {
1507      return;
1508    };
1509    let next = match (self.sctp_state, engine) {
1510      ("closed", _) => "closed",
1511      (_, RTCSctpTransportState::Connected) => "connected",
1512      ("connected", _) | (_, RTCSctpTransportState::Closed) => "closed",
1513      _ => "connecting",
1514    };
1515    if next != self.sctp_state {
1516      self.sctp_state = next;
1517      self.events.push_back(JsEvent::SctpState { state: next });
1518    }
1519  }
1520
1521  /// Reports what each channel's SCTP stream has sent since the last pass.
1522  fn track_sent(&mut self) {
1523    let handles: Vec<u32> = self.sent.keys().copied().collect();
1524    for handle in handles {
1525      let Some(now) = self
1526        .pc
1527        .data_channel(handle as RTCDataChannelId)
1528        .map(|c| c.bytes_dequeued())
1529      else {
1530        self.sent.remove(&handle);
1531        continue;
1532      };
1533      let last = self.sent.insert(handle, now).unwrap_or(0);
1534      if now > last {
1535        self.events.push_back(JsEvent::DataChannelSent {
1536          channel: handle,
1537          bytes: (now - last) as f64,
1538        });
1539      }
1540    }
1541  }
1542
1543  /// The DTLS transport's state: reached through the SCTP transport, else
1544  /// through a receiver (all of them share the one bundled transport).
1545  fn track_dtls_state(&mut self) {
1546    let state = match self.pc.sctp() {
1547      Some(sctp) => Some(sctp.transport().state()),
1548      None => {
1549        let receivers: Vec<_> = self.pc.get_receivers().collect();
1550        receivers.into_iter().find_map(|id| {
1551          self
1552            .pc
1553            .rtp_receiver(id)
1554            .and_then(|r| r.transport().map(|t| t.state()))
1555        })
1556      }
1557    };
1558    let Some(state) = state.map(|s| s.to_string()) else {
1559      return;
1560    };
1561    if state != self.dtls_state {
1562      self.dtls_state.clone_from(&state);
1563      self.events.push_back(JsEvent::DtlsState { state });
1564    }
1565  }
1566
1567  /// The engine's ICE transport's selected pair, reached through the SCTP
1568  /// transport, else through a receiver or a sender (all of them share the one
1569  /// bundled transport; a receiver or sender has one once it has a mid).
1570  fn ice_selected_pair(&mut self) -> Option<SelectedPair> {
1571    let to_pair =
1572      |p: rtci::peer_connection::transport::RTCIceCandidatePair| SelectedPair {
1573        local: PairCandidate::of(p.local()),
1574        remote: PairCandidate::of(p.remote()),
1575      };
1576    if let Some(sctp) = self.pc.sctp() {
1577      return sctp
1578        .transport()
1579        .ice_transport()
1580        .get_selected_candidate_pair()
1581        .map(to_pair);
1582    }
1583    let receivers: Vec<_> = self.pc.get_receivers().collect();
1584    for id in receivers {
1585      let pair = self.pc.rtp_receiver(id).and_then(|r| {
1586        r.transport()
1587          .map(|t| t.ice_transport().get_selected_candidate_pair())
1588      });
1589      match pair {
1590        Some(pair) => return pair.map(to_pair),
1591        None => continue,
1592      }
1593    }
1594    let senders: Vec<_> = self.pc.get_senders().collect();
1595    for id in senders {
1596      let pair = self.pc.rtp_sender(id).and_then(|s| {
1597        s.transport()
1598          .map(|t| t.ice_transport().get_selected_candidate_pair())
1599      });
1600      match pair {
1601        Some(pair) => return pair.map(to_pair),
1602        None => continue,
1603      }
1604    }
1605    None
1606  }
1607
1608  /// W3C webrtc-pc 5.6.4 "failed" ("either zero local candidates were
1609  /// gathered or the PAC timer has expired"): with gathering complete on
1610  /// both sides and no local candidate at all (a relay-only policy without
1611  /// a TURN server), nothing can ever connect, so ICE is `failed` rather
1612  /// than left `checking` until the timeout.
1613  ///
1614  /// A connection with local candidates and none from the remote side is
1615  /// left to the engine: the peer, which has ours, can still check us and
1616  /// form a peer-reflexive pair, and rtci 0.3's RFC 8863 PAC timer holds the
1617  /// check list (39.5 s with the defaults) for that check before failing it.
1618  fn fail_without_pairs(&mut self) {
1619    if self.failed
1620      || self.gathering != GatherPhase::Complete
1621      || !self.remote_gathered
1622      || self.pc.remote_description().is_none()
1623    {
1624      return;
1625    }
1626    if self.local_gathered == 0 {
1627      self.fail("no local candidates, and gathering is complete");
1628    }
1629  }
1630
1631  fn report_error(
1632    &mut self,
1633    url: &str,
1634    base: Option<SocketAddr>,
1635    error_code: u16,
1636    error_text: String,
1637  ) {
1638    self.events.push_back(JsEvent::IceCandidateError {
1639      address: base.map(|b| b.ip().to_string()),
1640      port: base.map(|b| b.port()),
1641      url: url.to_string(),
1642      error_code,
1643      error_text,
1644    });
1645  }
1646
1647  /// Reports `failed` on the engine's behalf (watchdog, panic).
1648  fn fail(&mut self, why: &str) {
1649    if self.failed {
1650      return;
1651    }
1652    log::debug!("webrtc: connection failed: {why}");
1653    self.failed = true;
1654    self.events.push_back(JsEvent::IceConnectionState {
1655      state: "failed".to_string(),
1656    });
1657    self.events.push_back(JsEvent::ConnectionState {
1658      state: "failed".to_string(),
1659    });
1660  }
1661
1662  /// The send-side permission gate: once per destination address. A
1663  /// question still being asked drops the datagram (counted as discarded
1664  /// on send; ICE and DTLS retransmit, and the answer pokes the driver).
1665  fn permit(
1666    &mut self,
1667    addr: SocketAddr,
1668    kind: ReachKind,
1669    proto: Proto,
1670    len: usize,
1671  ) -> bool {
1672    if self.allowed.contains(&addr) {
1673      return true;
1674    }
1675    if self.refused.contains(&addr) {
1676      return false;
1677    }
1678    match self.gate.lookup(&Reach::connect(kind, proto, addr)) {
1679      None => {
1680        self.media.pacer_refusals.add(len);
1681        false
1682      }
1683      Some(Ok(_)) => {
1684        self.allowed.insert(addr);
1685        true
1686      }
1687      Some(Err(message)) => {
1688        self.refused.insert(addr);
1689        self.events.push_back(JsEvent::IceCandidateError {
1690          address: Some(addr.ip().to_string()),
1691          port: Some(addr.port()),
1692          url: String::new(),
1693          error_code: ERROR_CODE_UNREACHABLE,
1694          error_text: message,
1695        });
1696        false
1697      }
1698    }
1699  }
1700
1701  /// Marks a remote address as already checked (by `addIceCandidate` /
1702  /// `setRemoteDescription`, which reject when it is refused).
1703  pub(crate) fn mark_allowed(&mut self, addr: SocketAddr) {
1704    self.allowed.insert(addr);
1705    self.remote_known = true;
1706  }
1707
1708  /// The UDP socket a datagram from `local` (a host candidate address or a
1709  /// base) goes out on.
1710  fn endpoint_for(&self, local: SocketAddr) -> Option<Rc<EcnUdpSocket>> {
1711    self
1712      .endpoints
1713      .iter()
1714      .find(|e| {
1715        e.bound.port() == local.port() && e.bound.is_ipv4() == local.is_ipv4()
1716      })
1717      .map(|e| e.socket.clone())
1718  }
1719
1720  /// The local address a datagram on `endpoint` from `from` arrived on.
1721  /// The OS route is probed and cached only for an address ICE or the
1722  /// permission gate vouched for ([`Core::is_known_remote`]).
1723  fn local_for(&mut self, endpoint: usize, from: SocketAddr) -> SocketAddr {
1724    let known = self.is_known_remote(from.ip());
1725    self.local_address(endpoint, from, known)
1726  }
1727
1728  /// Whether `ip` is a remote address ICE or the permission gate vouched for:
1729  /// a signalled remote candidate, a STUN/TURN server, a destination the
1730  /// engine sent to (which it does only for a signalled candidate or after
1731  /// authenticating a check), or the selected pair's.
1732  fn is_known_remote(&self, ip: IpAddr) -> bool {
1733    self.selected.is_some_and(|(_, r)| r.ip() == ip)
1734      || self.allowed.iter().any(|a| a.ip() == ip)
1735  }
1736
1737  /// [`Core::local_for`] with the trust decided by the caller. With `probe`,
1738  /// the OS route to `from` (a connected probe socket) is resolved and
1739  /// cached. Without it the first host address stands in and nothing is
1740  /// opened or kept, so a datagram from an address nobody vouched for costs
1741  /// neither a socket nor memory.
1742  fn local_address(
1743    &mut self,
1744    endpoint: usize,
1745    from: SocketAddr,
1746    probe: bool,
1747  ) -> SocketAddr {
1748    let e = &self.endpoints[endpoint];
1749    let port = e.bound.port();
1750    let ip = if !e.bound.ip().is_unspecified() {
1751      e.bound.ip()
1752    } else if let Some(ip) = self.routes.get(&from.ip()) {
1753      *ip
1754    } else if !probe || e.hosts.len() <= 1 {
1755      // With one host address (or none) a probe could give no other answer.
1756      e.hosts.first().copied().unwrap_or(from.ip())
1757    } else {
1758      let ip = self
1759        .io
1760        .route_probe(from.ip())
1761        .filter(|ip| e.hosts.contains(ip))
1762        .or_else(|| e.hosts.first().copied())
1763        .unwrap_or(from.ip());
1764      // A cache: once full it starts over rather than grow.
1765      if self.routes.len() >= MAX_ROUTES {
1766        self.routes.clear();
1767      }
1768      self.routes.insert(from.ip(), ip);
1769      ip
1770    };
1771    // 1:1 NAT in host mode: the host candidate is the public address (unless
1772    // the engine maps it, keeping the private socket as the base).
1773    let ip = match self.options.network.as_ref().map(|n| &n.options) {
1774      Some(net) if !net.public_srflx && !self.engine_nat => {
1775        net.public_for(ip).unwrap_or(ip)
1776      }
1777      _ => ip,
1778    };
1779    SocketAddr::new(ip, port)
1780  }
1781
1782  /// Whether a non-STUN packet on (`local`, `from`) belongs to the selected
1783  /// pair. The engine sends DTLS (and everything inside it) only on the
1784  /// selected pair, so the pair is the one its last non-STUN datagram went
1785  /// out on. Until it has sent one (the DTLS server waiting for the client's
1786  /// first flight), a packet is accepted only while ICE is connected and only
1787  /// from an address ICE has exchanged STUN with. The local side is compared
1788  /// by family and port (exactly for a relay): a wildcard socket's local
1789  /// address is the routed one.
1790  fn is_from_selected_pair(
1791    &self,
1792    local: SocketAddr,
1793    from: SocketAddr,
1794    relayed: bool,
1795  ) -> bool {
1796    match self.selected {
1797      Some(_) if self.selected_tcp => false,
1798      Some((l, r)) => {
1799        r == from
1800          && if relayed {
1801            l == local
1802          } else {
1803            l.port() == local.port() && l.is_ipv4() == local.is_ipv4()
1804          }
1805      }
1806      None => self.ice_up && self.stun_peers.contains(&from),
1807    }
1808  }
1809
1810  /// Remembers a remote address that sent STUN (bounded: a flood of
1811  /// spoofed sources can't grow it without limit).
1812  fn saw_stun(&mut self, from: SocketAddr) {
1813    self.remote_known = true;
1814    if self.stun_peers.len() < MAX_STUN_PEERS {
1815      self.stun_peers.insert(from);
1816    }
1817  }
1818
1819  /// ICE over TCP (a `tcpPort` network): a passive candidate on each of the
1820  /// network's listeners per host address, and an active one (port 9) per
1821  /// host address, which dials the peer's passive candidates.
1822  /// Signals the host (and 1:1 NAT server-reflexive) candidates of one UDP
1823  /// endpoint, unless the policy is relay-only; `advertised` keeps an address
1824  /// shared by two endpoints from being signalled twice.
1825  fn announce_udp_hosts(
1826    &mut self,
1827    opts: &NetworkOptions,
1828    bound: SocketAddr,
1829    hosts: &[IpAddr],
1830    gather_names: bool,
1831    advertised: &mut HashSet<SocketAddr>,
1832  ) {
1833    if !self.options.relay_only {
1834      for ip in &published_hosts(hosts, gather_names) {
1835        let private = SocketAddr::new(*ip, bound.port());
1836        let public = opts
1837          .public_for(*ip)
1838          .map(|p| SocketAddr::new(p, bound.port()));
1839        let (host, srflx) = match public {
1840          Some(p) if opts.public_srflx => (private, Some(p)),
1841          // The engine announces it on the public address.
1842          Some(_) if self.engine_nat => (private, None),
1843          Some(p) => (p, None),
1844          None => (private, None),
1845        };
1846        if advertised.insert(host) {
1847          let line = candidate_line(
1848            CandidateHostConfig {
1849              base_config: base_config(host),
1850              ..Default::default()
1851            }
1852            .new_candidate_host(),
1853          );
1854          if let Err(e) = line.and_then(|line| self.add_local(line, None)) {
1855            self.report_error(
1856              "",
1857              Some(host),
1858              ERROR_CODE_UNREACHABLE,
1859              e.to_string(),
1860            );
1861          }
1862        }
1863        if let Some(srflx) = srflx
1864          && advertised.insert(srflx)
1865        {
1866          let line = candidate_line(
1867            CandidateServerReflexiveConfig {
1868              base_config: base_config(srflx),
1869              rel_addr: private.ip().to_string(),
1870              rel_port: private.port(),
1871              url: None,
1872            }
1873            .new_candidate_server_reflexive(),
1874          );
1875          if let Err(e) = line.and_then(|line| self.add_local(line, None)) {
1876            self.report_error(
1877              "",
1878              Some(srflx),
1879              ERROR_CODE_UNREACHABLE,
1880              e.to_string(),
1881            );
1882          }
1883        }
1884      }
1885    }
1886  }
1887
1888  /// What candidates are gathered on: the network's options, or loopback
1889  /// included by default.
1890  fn gather_options(&self) -> NetworkOptions {
1891    match self.options.network.as_ref() {
1892      Some(n) => n.options.clone(),
1893      None => NetworkOptions {
1894        include_loopback: true,
1895        ..Default::default()
1896      },
1897    }
1898  }
1899
1900  fn gather_tcp(&mut self, opts: &NetworkOptions, gather_names: bool) {
1901    let Some(net) = self.options.network.clone().filter(|n| n.has_tcp()) else {
1902      return;
1903    };
1904    let mut lines: Vec<(SocketAddr, TcpType)> = Vec::new();
1905    let mut active: Vec<IpAddr> = Vec::new();
1906    for endpoint in &net.tcp {
1907      for ip in published_hosts(&endpoint.hosts, gather_names) {
1908        // 1:1 NAT: the public address in place of the private one (host
1909        // mode), as for UDP; in srflx mode, or when the engine maps it, the
1910        // host address itself.
1911        let advertised = match opts.public_for(ip) {
1912          Some(public) if !opts.public_srflx && !self.engine_nat => public,
1913          _ => ip,
1914        };
1915        let passive = SocketAddr::new(advertised, endpoint.bound.port());
1916        if !lines.contains(&(passive, TcpType::Passive)) {
1917          lines.push((passive, TcpType::Passive));
1918        }
1919        if !active.contains(&advertised) {
1920          active.push(advertised);
1921        }
1922      }
1923    }
1924    for ip in active {
1925      lines.push((SocketAddr::new(ip, ACTIVE_TCP_PORT), TcpType::Active));
1926    }
1927    for (addr, tcp_type) in lines {
1928      if let Err(e) = tcp_host_line(addr, tcp_type)
1929        .and_then(|line| self.add_local(line, None))
1930      {
1931        self.report_error(
1932          "",
1933          Some(addr),
1934          ERROR_CODE_UNREACHABLE,
1935          e.to_string(),
1936        );
1937      }
1938    }
1939  }
1940
1941  /// Sends an ICE-TCP frame: on the connection to `to`, or, from an active
1942  /// candidate, by dialling `to` (a remote passive candidate) first. A
1943  /// passive candidate only answers on connections it accepted.
1944  fn send_tcp(&mut self, local: SocketAddr, to: SocketAddr, data: &[u8]) {
1945    let Some(frame) = try_frame_packet(data) else {
1946      return;
1947    };
1948    if let Some(link) = self.tcp_links.get(&to) {
1949      if link.writer.try_send(frame).is_err() {
1950        log::debug!("webrtc: ICE-TCP queue to {to} is full");
1951      }
1952      return;
1953    }
1954    if local.port() != ACTIVE_TCP_PORT {
1955      return;
1956    }
1957    if let Some(queue) = self.tcp_dialing.get_mut(&to) {
1958      if queue.len() < MAX_DIAL_QUEUE {
1959        queue.push(frame);
1960      }
1961      return;
1962    }
1963    if self.tcp_links.len() + self.tcp_dialing.len() >= MAX_TCP_LINKS {
1964      return;
1965    }
1966    // `permit` asked this dial's question (as a `TcpDial`): this is a cache
1967    // hit, or the synchronous gate asked again.
1968    let Some(Ok(token)) =
1969      self
1970        .gate
1971        .lookup(&Reach::connect(ReachKind::TcpDial, Proto::Tcp, to))
1972    else {
1973      return;
1974    };
1975    self.tcp_dialing.insert(to, vec![frame]);
1976    let bind = self.tcp_bind_ip(local.ip());
1977    if let Some(peer) = self.this.upgrade() {
1978      let cancel = peer.cancel.clone();
1979      let weak = self.this.clone();
1980      let io = self.io.clone();
1981      crate::rt::spawn(
1982        async move {
1983          let stream = tokio::time::timeout(
1984            TCP_CONNECT_TIMEOUT,
1985            connect_tcp(&*io, &token, bind, to),
1986          )
1987          .await;
1988          let Some(peer) = weak.upgrade() else {
1989            return;
1990          };
1991          match stream {
1992            Ok(Ok(stream)) => {
1993              peer.attach_tcp(stream, to, TcpFrameDecoder::new(), None)
1994            }
1995            Ok(Err(e)) => {
1996              log::debug!("webrtc: ICE-TCP connect to {to}: {e}");
1997              peer.core.borrow_mut().tcp_dialing.remove(&to);
1998            }
1999            Err(_) => {
2000              log::debug!("webrtc: ICE-TCP connect to {to} timed out");
2001              peer.core.borrow_mut().tcp_dialing.remove(&to);
2002            }
2003          }
2004        }
2005        .or_cancel(cancel),
2006      );
2007    }
2008  }
2009
2010  /// The local address an outbound ICE-TCP connection binds for an active
2011  /// candidate on `ip`: that host address itself (a public one in 1:1 NAT
2012  /// host mode stands for its private address), or none (the OS picks).
2013  fn tcp_bind_ip(&self, ip: IpAddr) -> Option<IpAddr> {
2014    let net = self.options.network.as_ref()?;
2015    let hosts: Vec<IpAddr> = net
2016      .tcp
2017      .iter()
2018      .flat_map(|e| e.hosts.iter().copied())
2019      .collect();
2020    if hosts.contains(&ip) {
2021      return Some(ip);
2022    }
2023    net
2024      .options
2025      .private_for(ip, &hosts)
2026      .filter(|private| hosts.contains(private))
2027  }
2028
2029  /// The local address the engine knows an ICE-TCP connection's local
2030  /// address by: in 1:1 NAT host mode the public address stands for the
2031  /// private one, as for UDP.
2032  fn tcp_local(&self, local: SocketAddr) -> SocketAddr {
2033    match self.options.network.as_ref().map(|n| &n.options) {
2034      Some(net) if !net.public_srflx && !self.engine_nat => SocketAddr::new(
2035        net.public_for(local.ip()).unwrap_or(local.ip()),
2036        local.port(),
2037      ),
2038      _ => local,
2039    }
2040  }
2041
2042  /// Opens the mDNS socket once (on first need): `false` when it can't be.
2043  fn open_mdns(&mut self) -> bool {
2044    if self.mdns_socket.is_some() {
2045      return true;
2046    }
2047    if self.mdns_failed || self.mdns_mode == MdnsMode::Off {
2048      return false;
2049    }
2050    let hosts = if self.endpoints.is_empty() {
2051      interface_addresses(
2052        self
2053          .options
2054          .network
2055          .as_ref()
2056          .and_then(|n| n.options.interfaces.as_deref()),
2057      )
2058    } else {
2059      self
2060        .endpoints
2061        .iter()
2062        .flat_map(|e| e.hosts.clone())
2063        .collect()
2064    };
2065    let Some(token) = self.mdns_token.clone() else {
2066      return false;
2067    };
2068    let socket = match self.io.bind_mdns(&token, &hosts) {
2069      Ok(socket) => Rc::new(EcnUdpSocket::plain(socket)),
2070      Err(e) => {
2071        self.mdns_failed = true;
2072        self.report_error(
2073          "",
2074          None,
2075          ERROR_CODE_UNREACHABLE,
2076          format!("mDNS is unavailable: {e}"),
2077        );
2078        return false;
2079      }
2080    };
2081    if let Some(peer) = self.this.upgrade() {
2082      spawn_udp_reader_via(
2083        socket.clone(),
2084        SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), MDNS_PORT),
2085        self.recv_tx.clone(),
2086        peer.cancel.clone(),
2087        Via::Mdns,
2088      );
2089    }
2090    self.mdns_socket = Some(socket);
2091    true
2092  }
2093
2094  /// Whether a remote `.local` candidate can be resolved here (opening the
2095  /// mDNS socket if it isn't yet).
2096  fn resolves_mdns(&mut self) -> bool {
2097    self.mdns_mode != MdnsMode::Off && self.open_mdns()
2098  }
2099
2100  /// Whether this connection does ICE over TCP (a `tcpPort` network).
2101  fn ice_tcp(&self) -> bool {
2102    self.options.network.as_ref().is_some_and(|n| n.has_tcp())
2103  }
2104
2105  /// A candidate line as JavaScript sees it: with the host candidates
2106  /// published under mDNS names, the base address a server-reflexive or
2107  /// relay candidate names is hidden too.
2108  fn public_candidate(&self, line: String) -> String {
2109    if self.mdns_mode == MdnsMode::Gather && line.contains(" raddr ") {
2110      redact_related_address(&line)
2111    } else {
2112      line
2113    }
2114  }
2115
2116  /// Whether the engine's path from local address `local` may carry
2117  /// traffic to and from the peer: any path, or under a relay-only
2118  /// gathering phase (W3C webrtc-pc 4.2.2 `relay`: "The ICE Agent uses only
2119  /// media relay candidates such as candidates passing through a TURN
2120  /// server") only one from a TURN relay's address.
2121  ///
2122  /// The engine is not told the policy (this driver gathers for it), and an
2123  /// ICE restart keeps the previous generation's selected pair in use until
2124  /// the new generation selects one (RFC 8445 section 9, rtci's
2125  /// `previous_media_path`), consent included. After `setConfiguration({
2126  /// iceTransportPolicy: "relay" })` and the restart it causes, that pair is
2127  /// a host or server-reflexive one, which the new policy rules out: without
2128  /// this the connection went on over it, both sides answering its consent
2129  /// checks, and never failed (WPT RTCConfiguration-iceTransportPolicy
2130  /// "Changing iceTransportPolicy from \"all\" to \"relay\" causes an ICE
2131  /// restart which should fail" timed out waiting for the answerer's
2132  /// `failed`). Refused here, the pair loses consent on both sides, and the
2133  /// peer fails as its PAC timer runs out.
2134  fn relay_path(&self, local: SocketAddr) -> bool {
2135    !self.relay_generation
2136      || self.servers.iter().any(|s| s.relay == Some(local))
2137  }
2138
2139  /// Sends what the engine wants sent, through the socket or a TURN relay.
2140  fn flush_engine_writes(&mut self) -> bool {
2141    let mut progressed = false;
2142    while let Some(msg) = self.pc.poll_write() {
2143      progressed = true;
2144      let local = msg.transport.local_addr;
2145      let to = msg.transport.peer_addr;
2146      // mDNS queries and answers (permitted when the socket was opened).
2147      if to == MDNS_DEST_ADDR {
2148        if let Some(socket) = &self.mdns_socket {
2149          send_mdns(socket, &msg.message, local.ip());
2150        }
2151        continue;
2152      }
2153      if !self.relay_path(local) {
2154        continue;
2155      }
2156      let tcp = msg.transport.transport_protocol == TransportProtocol::TCP;
2157      // The first frame to a remote passive candidate from an active one
2158      // dials it: an ICE-TCP dial.
2159      let (kind, proto) = if !tcp {
2160        (ReachKind::SendTo, Proto::Udp)
2161      } else if local.port() == ACTIVE_TCP_PORT
2162        && !self.tcp_links.contains_key(&to)
2163      {
2164        (ReachKind::TcpDial, Proto::Tcp)
2165      } else {
2166        (ReachKind::SendTo, Proto::Tcp)
2167      };
2168      if !self.permit(to, kind, proto, msg.message.len()) {
2169        continue;
2170      }
2171      if !is_stun(&msg.message) {
2172        self.selected = Some((local, to));
2173        self.selected_tcp = tcp;
2174      }
2175      if tcp {
2176        self.send_tcp(local, to, &msg.message);
2177        continue;
2178      }
2179      if let Some(server) =
2180        self.servers.iter_mut().find(|s| s.relay == Some(local))
2181      {
2182        let now = Instant::now();
2183        let sent = server
2184          .client
2185          .relay(local)
2186          .and_then(|mut relay| relay.send_to(now, &msg.message, to));
2187        if sent.is_err() {
2188          // No permission for this peer on the relay yet: ask for it and
2189          // drop the datagram (ICE retransmits its checks).
2190          if let Ok(mut relay) = server.client.relay(local) {
2191            let _ = relay.create_permission(now, to);
2192          }
2193        } else if !is_stun(&msg.message) {
2194          self.remember_relayed(local, to, &msg.message);
2195        }
2196        continue;
2197      }
2198      // The codepoint the engine chose (ECT(1) on the RTP of a stream
2199      // that negotiated `ack ccfb`, with ECN on), per datagram.
2200      let Some(socket) = self.endpoint_for(local) else {
2201        continue;
2202      };
2203      if let Err(e) =
2204        socket.try_send_to_ecn(&msg.message, to, msg.transport.ecn)
2205      {
2206        log::debug!("webrtc: send {local} -> {to}: {e}");
2207        if crate::ecn::refused_for_size(&e) {
2208          self.datagram_too_big(msg.transport, &msg.message);
2209        }
2210      }
2211    }
2212    progressed
2213  }
2214
2215  /// Tells the engine that a datagram it sent on `transport` was refused
2216  /// for its size (RFC 6347 4.1.1.1, RFC 9147 section 4.4: the DTLS record
2217  /// layer "MUST inform the upper layer protocol of the error"). The engine
2218  /// takes it only for the path a transport sends DTLS on, cuts its DTLS
2219  /// handshake records for it and reports `OnPathMtuExceeded`
2220  /// (`collect_events`). A refused send names no MTU, so the engine assumes
2221  /// the family's minimum (576 / 1280). Only a DTLS datagram is quoted: the
2222  /// engine checks a quote against the DTLS datagrams it sent (RFC 8899
2223  /// section 4.6.1), and with a checked quote SCTP lowers its packet size
2224  /// too. An SRTP or STUN datagram goes unquoted (it would not match and the
2225  /// report would be ignored), which still reaches the DTLS handshake and
2226  /// the event, not SCTP.
2227  fn datagram_too_big(&mut self, transport: TransportContext, datagram: &[u8]) {
2228    let quoted = is_dtls(datagram).then_some(datagram);
2229    let taken =
2230      self
2231        .pc
2232        .handle_datagram_too_big(Instant::now(), transport, None, quoted);
2233    log::debug!(
2234      "webrtc: {} -> {}: a datagram was too big for the path{}",
2235      transport.local_addr,
2236      transport.peer_addr,
2237      if taken {
2238        ""
2239      } else {
2240        " (ignored by the engine)"
2241      }
2242    );
2243  }
2244
2245  /// Remembers the first octets of a datagram the engine sent from a TURN
2246  /// relay's address `relay` to `peer` (see [`Core::relayed_too_big`]).
2247  fn remember_relayed(
2248    &mut self,
2249    relay: SocketAddr,
2250    peer: SocketAddr,
2251    datagram: &[u8],
2252  ) {
2253    let len = datagram.len().min(RELAYED_HEAD);
2254    let mut head = [0; RELAYED_HEAD];
2255    head[..len].copy_from_slice(&datagram[..len]);
2256    if self.relayed_recent.len() == RELAYED_RECENT {
2257      self.relayed_recent.pop_front();
2258    }
2259    self.relayed_recent.push_back(RelayedWrite {
2260      relay,
2261      peer,
2262      head,
2263      len,
2264    });
2265  }
2266
2267  /// The path and the beginning of the engine's datagram that a TURN
2268  /// message `message` the socket refused for its size carried: the newest
2269  /// datagram sent from `relay` whose first octets the message holds (in its
2270  /// ChannelData or its Send indication's DATA attribute). `None` when the
2271  /// message carried none of them (a refresh, a permission request).
2272  fn relayed_too_big(
2273    &self,
2274    relay: SocketAddr,
2275    message: &[u8],
2276  ) -> Option<(TransportContext, Vec<u8>)> {
2277    let sent = find_relayed(&self.relayed_recent, relay, message)?;
2278    let transport = TransportContext {
2279      local_addr: sent.relay,
2280      peer_addr: sent.peer,
2281      ecn: None,
2282      transport_protocol: TransportProtocol::UDP,
2283    };
2284    Some((transport, sent.head().to_vec()))
2285  }
2286
2287  /// Runs the STUN/TURN clients: their datagrams out, their results in.
2288  fn service_servers(&mut self, now: Instant) -> bool {
2289    let mut progressed = false;
2290    let mut found: Vec<(String, SocketAddr, SocketAddr)> = Vec::new();
2291    let mut relays: Vec<(String, SocketAddr, SocketAddr)> = Vec::new();
2292    let mut errors: Vec<(String, SocketAddr, String)> = Vec::new();
2293    let mut relayed_in: Vec<(SocketAddr, SocketAddr, BytesMut)> = Vec::new();
2294    // TURN messages the socket refused for their size, by relayed address.
2295    let mut too_big: Vec<(SocketAddr, Vec<u8>)> = Vec::new();
2296    for server in &mut self.servers {
2297      while let Some(tx) = server.client.poll_write() {
2298        progressed = true;
2299        match &server.link {
2300          ServerLink::Stream(writer) => {
2301            let _ = writer.send(tx.message.to_vec());
2302          }
2303          ServerLink::Udp => {
2304            if let Some(net) =
2305              self.options.network.as_ref().filter(|n| n.is_shared())
2306            {
2307              net.register_transaction(&tx.message, &self.this);
2308            }
2309            if let Some(e) = self.endpoints.iter().find(|e| {
2310              e.bound.port() == tx.transport.local_addr.port()
2311                && e.bound.is_ipv4() == tx.transport.local_addr.is_ipv4()
2312            }) && let Err(err) =
2313              e.socket.try_send_to(&tx.message, tx.transport.peer_addr)
2314            {
2315              log::debug!("webrtc: STUN/TURN send: {err}");
2316              if crate::ecn::refused_for_size(&err)
2317                && let Some(relay) = server.relay
2318              {
2319                too_big.push((relay, tx.message.to_vec()));
2320              }
2321            }
2322          }
2323        }
2324      }
2325      while let Some(event) = server.client.poll_event() {
2326        progressed = true;
2327        let url = server.url.clone();
2328        match event {
2329          TurnEvent::BindingResponse(tid, addr) => {
2330            if server.binding == Some(tid) {
2331              server.binding = None;
2332              if matches!(server.link, ServerLink::Udp) {
2333                found.push((url, server.base, addr));
2334              }
2335            }
2336          }
2337          TurnEvent::BindingError(tid, e) => {
2338            if server.binding == Some(tid) {
2339              server.binding = None;
2340              errors.push((url, server.base, e.to_string()));
2341            }
2342          }
2343          TurnEvent::AllocateResponse(tid, relay) => {
2344            if server.allocate == Some(tid) {
2345              server.allocate = None;
2346              server.relay = Some(relay);
2347              relays.push((url, server.base, relay));
2348            }
2349          }
2350          TurnEvent::AllocateError(tid, e) => {
2351            if server.allocate == Some(tid) {
2352              server.allocate = None;
2353              errors.push((url, server.base, e.to_string()));
2354            }
2355          }
2356          TurnEvent::TransactionTimeout(tid) => {
2357            if server.binding == Some(tid) {
2358              server.binding = None;
2359              errors.push((
2360                url,
2361                server.base,
2362                "STUN binding request timed out".to_string(),
2363              ));
2364            } else if server.allocate == Some(tid) {
2365              server.allocate = None;
2366              errors.push((
2367                url,
2368                server.base,
2369                "TURN allocate request timed out".to_string(),
2370              ));
2371            }
2372          }
2373          TurnEvent::DataIndicationOrChannelData(_, from, data) => {
2374            if let Some(relay) = server.relay {
2375              relayed_in.push((relay, from, data));
2376            }
2377          }
2378          _ => {}
2379        }
2380      }
2381    }
2382    for (url, base, addr) in found {
2383      let host = self
2384        .endpoints
2385        .iter()
2386        .any(|e| e.bound.port() == addr.port() && e.hosts.contains(&addr.ip()));
2387      if host || self.options.relay_only || !self.srflx_seen.insert(addr) {
2388        continue;
2389      }
2390      let line = candidate_line(
2391        CandidateServerReflexiveConfig {
2392          base_config: base_config(addr),
2393          rel_addr: base.ip().to_string(),
2394          rel_port: base.port(),
2395          url: Some(url.clone()),
2396        }
2397        .new_candidate_server_reflexive(),
2398      );
2399      if let Err(e) =
2400        line.and_then(|line| self.add_local(line, Some(url.clone())))
2401      {
2402        self.report_error(
2403          &url,
2404          Some(base),
2405          ERROR_CODE_UNREACHABLE,
2406          e.to_string(),
2407        );
2408      }
2409    }
2410    for (url, base, relay) in relays {
2411      let line = candidate_line(
2412        CandidateRelayConfig {
2413          base_config: base_config(relay),
2414          rel_addr: base.ip().to_string(),
2415          rel_port: base.port(),
2416          url: Some(url.clone()),
2417        }
2418        .new_candidate_relay(),
2419      );
2420      if let Err(e) =
2421        line.and_then(|line| self.add_local(line, Some(url.clone())))
2422      {
2423        self.report_error(
2424          &url,
2425          Some(base),
2426          ERROR_CODE_UNREACHABLE,
2427          e.to_string(),
2428        );
2429      }
2430    }
2431    // A relayed datagram's TURN message too big for the path to the server
2432    // is the relayed path's report: the engine matches it on the relayed
2433    // address and the peer, and takes the TURN header off the MTU itself.
2434    for (relay, message) in too_big {
2435      if let Some((transport, head)) = self.relayed_too_big(relay, &message) {
2436        self.datagram_too_big(transport, &head);
2437      }
2438    }
2439    for (url, base, text) in errors {
2440      self.report_error(&url, Some(base), ERROR_CODE_UNREACHABLE, text);
2441    }
2442    for (relay, from, data) in relayed_in {
2443      if self.refused.contains(&from) {
2444        continue;
2445      }
2446      if is_stun(&data) {
2447        self.saw_stun(from);
2448      } else if !self.is_from_selected_pair(relay, from, true) {
2449        continue;
2450      }
2451      let _ = self.pc.handle_read(TaggedBytesMut {
2452        now,
2453        transport: TransportContext {
2454          local_addr: relay,
2455          peer_addr: from,
2456          ecn: None,
2457          transport_protocol: TransportProtocol::UDP,
2458        },
2459        message: data,
2460      });
2461    }
2462    progressed
2463  }
2464
2465  /// Moves the engine's events and received messages to the JS queue.
2466  pub(crate) fn collect_events(&mut self, now: Instant) {
2467    if self.checking_held && self.remote_known {
2468      self.checking_held = false;
2469      if !self.failed {
2470        self.checking_since = Some(now);
2471        self.events.push_back(JsEvent::IceConnectionState {
2472          state: "checking".to_string(),
2473        });
2474      }
2475    }
2476    let mut mid = None::<String>;
2477    // A channel's closing, error and close come after the messages the engine
2478    // delivered with them: the engine queues messages apart from events, and
2479    // a close the peer started follows its data on the wire (RFC 8831
2480    // section 6.7), so none of it may be dropped as arriving "after" close.
2481    let mut closes = Vec::new();
2482    while let Some(event) = self.pc.poll_event() {
2483      match event {
2484        RTCPeerConnectionEvent::OnNegotiationNeededEvent => {
2485          self.events.push_back(JsEvent::NegotiationNeeded)
2486        }
2487        RTCPeerConnectionEvent::OnIceCandidateEvent(e) => {
2488          // The engine's end-of-candidates (a "" candidate) and its null
2489          // candidate: the JS side fires both itself, from the gathering
2490          // state this driver ends (`maybe_complete_gathering`).
2491          let Some(candidate) = e.candidate.filter(|c| !c.end_of_candidates)
2492          else {
2493            continue;
2494          };
2495          if self.options.relay_only
2496            && candidate.typ != RTCIceCandidateType::Relay
2497          {
2498            continue;
2499          }
2500          let Ok(init) = candidate.to_json() else {
2501            continue;
2502          };
2503          if mid.is_none() {
2504            mid = Some(self.first_mid().unwrap_or_else(|| "0".to_string()));
2505          }
2506          let ufrag = self.local_ufrag();
2507          let candidate = self.public_candidate(init.candidate);
2508          self.events.push_back(JsEvent::IceCandidate {
2509            candidate,
2510            sdp_mid: mid.clone(),
2511            sdp_m_line_index: Some(0),
2512            username_fragment: ufrag,
2513            url: e.url.filter(|u| !u.is_empty()),
2514          });
2515        }
2516        RTCPeerConnectionEvent::OnIceCandidateErrorEvent(e) => {
2517          self.events.push_back(JsEvent::IceCandidateError {
2518            address: Some(e.address.clone()).filter(|a| !a.is_empty()),
2519            port: Some(e.port).filter(|p| *p != 0),
2520            url: e.url.clone(),
2521            error_code: e.error_code,
2522            error_text: e.error_text.clone(),
2523          })
2524        }
2525        RTCPeerConnectionEvent::OnSignalingStateChangeEvent(s) => {
2526          self.events.push_back(JsEvent::SignalingState {
2527            state: s.to_string(),
2528          })
2529        }
2530        RTCPeerConnectionEvent::OnIceConnectionStateChangeEvent(s) => {
2531          // rtci 0.2's agent goes `completed` once both sides have ended
2532          // their candidates (`Agent::healthy_state`); the 0.22 engine
2533          // stayed `connected`, as Chromium and WebKit do for these
2534          // connections. It is reported as `connected`: WPT
2535          // RTCRtpTransceiver.https.html's `iceConnected(pc)` resolves only
2536          // on `connected`, so the side it waits for second, already
2537          // `completed`, never resolved and the file timed out
2538          // (`checkSendrecvWithNoSendTrack`, `checkStopAfterCreateAnswer`).
2539          let mut state = s.to_string();
2540          if state == "completed" {
2541            state = "connected".to_string();
2542          }
2543          // An ICE restart on a connected transport keeps its selected pair
2544          // (the engine's previous media path) until the new generation
2545          // selects one, so the transport stays connected: W3C webrtc-pc
2546          // 4.3.3 has `checking` only for a transport with no working pair.
2547          // Its `checking` (and the connection's `connecting`) is not
2548          // reported; a restart from `disconnected` or `failed` is.
2549          if state == "checking" && self.ice_up {
2550            self.restart_masked = true;
2551            continue;
2552          }
2553          if state != "checking" {
2554            self.restart_masked = false;
2555          }
2556          if state == "checking" && !self.remote_known {
2557            self.checking_held = true;
2558            continue;
2559          }
2560          self.checking_held = false;
2561          if state == "connected" || state == "completed" {
2562            self.ice_up = true;
2563            if !self.dtls_connected && self.ice_up_at.is_none() {
2564              self.ice_up_at = Some(now);
2565            }
2566          } else {
2567            self.ice_up = false;
2568            self.ice_up_at = None;
2569          }
2570          self.checking_since =
2571            (state == "checking" && !self.failed).then_some(now);
2572          if !self.failed || state == "closed" {
2573            self.events.push_back(JsEvent::IceConnectionState { state });
2574          }
2575        }
2576        RTCPeerConnectionEvent::OnIceGatheringStateChangeEvent(s) => {
2577          let state = s.to_string();
2578          // W3C webrtc-pc 4.4.4 "update the ICE gathering state": with no
2579          // transport to gather for (a local description without a live
2580          // media section) the state stays where it is; rtci 0.2 still
2581          // reports gathering for one (WPT
2582          // RTCPeerConnection-iceGatheringState "setLocalDescription() with
2583          // no transports should not cause iceGatheringState to change").
2584          // Its `new` (transports closed) is passed on.
2585          if state != "new"
2586            && !self
2587              .pc
2588              .local_description()
2589              .is_some_and(|d| has_live_media_section(&d.sdp))
2590          {
2591            continue;
2592          }
2593          self.events.push_back(JsEvent::IceGatheringState { state })
2594        }
2595        RTCPeerConnectionEvent::OnConnectionStateChangeEvent(s) => {
2596          let state = s.to_string();
2597          if state == "connecting" && self.restart_masked {
2598            continue;
2599          }
2600          if state == "connected" {
2601            self.dtls_connected = true;
2602            self.ice_up_at = None;
2603          }
2604          if !self.failed || state == "closed" {
2605            self.events.push_back(JsEvent::ConnectionState { state });
2606          }
2607        }
2608        RTCPeerConnectionEvent::OnDataChannel(dc) => {
2609          let event = match dc {
2610            RTCDataChannelEvent::OnOpen(handle) => {
2611              self.sent.entry(handle as u32).or_insert(0);
2612              let Some(channel) = self.pc.data_channel(handle) else {
2613                continue;
2614              };
2615              JsEvent::DataChannelOpen {
2616                channel: handle as u32,
2617                id: channel.stream_id(),
2618                label: channel.label().to_string(),
2619                protocol: channel.protocol().to_string(),
2620                ordered: channel.ordered(),
2621                max_packet_life_time: channel.max_packet_life_time(),
2622                max_retransmits: channel.max_retransmits(),
2623                negotiated: channel.negotiated(),
2624                priority: channel.priority(),
2625              }
2626            }
2627            RTCDataChannelEvent::OnClosing(handle) => {
2628              JsEvent::DataChannelClosing {
2629                channel: handle as u32,
2630              }
2631            }
2632            RTCDataChannelEvent::OnClose(handle) => JsEvent::DataChannelClose {
2633              channel: handle as u32,
2634            },
2635            RTCDataChannelEvent::OnError(handle) => {
2636              let error = self.pc.data_channel_error(handle).cloned();
2637              let channel = self.pc.data_channel(handle);
2638              JsEvent::DataChannelError {
2639                channel: handle as u32,
2640                error_detail: error.as_ref().map_or_else(
2641                  || "data-channel-failure".to_string(),
2642                  |e| e.error_detail.to_string(),
2643                ),
2644                message: error
2645                  .as_ref()
2646                  .map(|e| e.message.clone())
2647                  .filter(|m| !m.is_empty())
2648                  .unwrap_or_default(),
2649                sctp_cause_code: error.as_ref().and_then(|e| e.sctp_cause_code),
2650                label: channel.as_ref().map(|c| c.label().to_string()),
2651                id: channel.as_ref().and_then(|c| c.stream_id()),
2652              }
2653            }
2654            // `bufferedamountlow` follows what is sent, not what is
2655            // acknowledged (`track_sent`).
2656            _ => continue,
2657          };
2658          if matches!(event, JsEvent::DataChannelOpen { .. }) {
2659            self.events.push_back(event);
2660          } else {
2661            closes.push(event);
2662          }
2663        }
2664        RTCPeerConnectionEvent::OnTrack(RTCTrackEvent::OnOpen(init)) => {
2665          let index: usize = init.receiver_id.into();
2666          if let Some(key) = self.key_for_receiver_index(index) {
2667            self.media.track_keys.insert(init.track_id.clone(), key);
2668          }
2669        }
2670        // The engine took a datagram-too-big report (`datagram_too_big`):
2671        // its DTLS handshake and SCTP already keep to the new size; the
2672        // RTP this crate packetizes keeps to it from the next frame
2673        // (`MediaState::path_datagram_limit`). Not a W3C event, so nothing
2674        // goes to JavaScript.
2675        RTCPeerConnectionEvent::OnPathMtuExceeded {
2676          path_mtu,
2677          max_datagram,
2678          validated,
2679          ..
2680        } => {
2681          log::debug!(
2682            "webrtc: path MTU {path_mtu} (datagrams of {max_datagram} bytes{})",
2683            if validated { "" } else { ", unvalidated" }
2684          );
2685          self.media.limit_datagrams(max_datagram);
2686        }
2687        _ => {}
2688      }
2689    }
2690    while let Some(message) = self.pc.poll_read() {
2691      match message.message {
2692        RTCMessage::DataChannelMessage(handle, message) => {
2693          self.events.push_back(JsEvent::DataChannelMessage {
2694            channel: handle as u32,
2695            text: message.is_string,
2696            data: Payload::new(message.data.to_vec()),
2697          });
2698        }
2699        RTCMessage::RtpPacket(track_id, packet) => {
2700          let Some(key) = self.key_for_track(&track_id) else {
2701            continue;
2702          };
2703          // A packet unmutes only once this side's negotiation receives on
2704          // the section (`currentDirection`): one the remote sent before it
2705          // stopped (a pacer's queue, a datagram read late) and that is read
2706          // while a renegotiation is still under way is no media of the new
2707          // state.
2708          if !self.media.flowing.contains(&key) && self.receives_now(key) {
2709            self.media.flowing.insert(key);
2710            let generation =
2711              self.media.unmute_generation.get(&key).copied().unwrap_or(0);
2712            self.events.push_back(JsEvent::TrackUnmute {
2713              transceiver: key,
2714              generation,
2715            });
2716          }
2717          self.media.saw_rtp(key, &packet.header);
2718          self.count_received_frame(key, &packet);
2719          // wpt100:mediasink
2720          let sink = self.sink_packet(key, &packet, now);
2721          if let Some((width, height)) = sink.resize {
2722            self.events.push_back(JsEvent::TrackResize {
2723              transceiver: key,
2724              width,
2725              height,
2726            });
2727          }
2728          if let Some(frame) = sink.frame {
2729            self.events.push_back(JsEvent::MediaFrame {
2730              transceiver: key,
2731              key_frame: frame.key_frame,
2732              mime_type: frame.mime_type,
2733              rtp_timestamp: frame.rtp_timestamp,
2734              width: frame.width_height.map(|(w, _)| w),
2735              height: frame.width_height.map(|(_, h)| h),
2736              data: Payload::new(frame.data),
2737            });
2738          }
2739          if let Some(frame) = self.receive_for_transform(key, &packet) {
2740            self.events.push_back(JsEvent::EncodedFrame {
2741              transceiver: key,
2742              data: Payload::new(frame.data),
2743              key_frame: frame.key_frame,
2744              width: frame.width_height.map(|(w, _)| w),
2745              height: frame.width_height.map(|(_, h)| h),
2746              info: frame.info,
2747            });
2748          }
2749          // A frame assembler that lost a frame stays broken until a key
2750          // frame: ask the sender for one (rate-limited per stream).
2751          if self.sink_needs_key_frame(key)
2752            || self.transform_needs_key_frame(key)
2753          {
2754            self.request_key_frame_after_loss(key, packet.header.ssrc, now);
2755          }
2756          if self.media.reading.contains(&key)
2757            && let Ok(bytes) = packet.marshal()
2758          {
2759            self.events.push_back(JsEvent::Rtp {
2760              transceiver: key,
2761              data: Payload::new(bytes.to_vec()),
2762            });
2763          }
2764        }
2765        RTCMessage::RtcpPacket(track_id, packets) => {
2766          if crate::media::wants_key_frame(&packets)
2767            && let Some(key) = self.key_for_track(&track_id)
2768          {
2769            // A fake device's video starts over on its key frame.
2770            if let Some(cursor) = self.media.fake.get_mut(&key) {
2771              cursor.next = 0;
2772            }
2773            self
2774              .events
2775              .push_back(JsEvent::KeyFrameRequest { transceiver: key });
2776          }
2777        }
2778        _ => {}
2779      }
2780    }
2781    self.events.extend(closes);
2782  }
2783
2784  /// Ends gathering once every server answered or gave up.
2785  fn maybe_complete_gathering(&mut self) {
2786    if self.gathering != GatherPhase::Running
2787      || self.binds_pending
2788      || self.resolving > 0
2789      || self.servers.iter().any(ServerClient::pending)
2790    {
2791      return;
2792    }
2793    self.gathering = GatherPhase::Complete;
2794    // An empty candidate is the engine's end-of-candidates: it sets the
2795    // gathering state to "complete" and emits the state change.
2796    let _ = self.pc.add_local_candidate(RTCIceCandidateInit::default());
2797  }
2798
2799  /// One driver pass: loop until the engine and the clients are idle.
2800  fn pump(&mut self) {
2801    let now = Instant::now();
2802    if self
2803      .ice_up_at
2804      .is_some_and(|t| now.duration_since(t) >= DTLS_TIMEOUT)
2805    {
2806      self.ice_up_at = None;
2807      self.fail("DTLS did not connect after ICE did");
2808    }
2809    if let Some(since) = self.checking_since
2810      && now.duration_since(since) >= CHECKING_STALL
2811    {
2812      self.checking_since = None;
2813      if !self.failed && !self.remote_gathered {
2814        self.events.push_back(JsEvent::IceConnectionState {
2815          state: "disconnected".to_string(),
2816        });
2817        self.events.push_back(JsEvent::ConnectionState {
2818          state: "disconnected".to_string(),
2819        });
2820      }
2821    }
2822    for _ in 0..MAX_PUMP_ROUNDS {
2823      let a = self.flush_engine_writes();
2824      let b = self.service_servers(now);
2825      self.maybe_complete_gathering();
2826      self.fail_without_pairs();
2827      // The transports' states before the events they come with (a channel's
2828      // open after its SCTP transport is connected).
2829      self.track_sctp_state();
2830      self.track_dtls_state();
2831      self.collect_events(now);
2832      self.track_sent();
2833      // wpt100:mediasink
2834      self.check_silence(now);
2835      let c = std::mem::take(&mut self.wrote_rtcp);
2836      if !a && !b && !c {
2837        break;
2838      }
2839    }
2840  }
2841
2842  fn next_deadline(&mut self) -> Option<Instant> {
2843    let mut deadline = self.pc.poll_timeout();
2844    for server in &mut self.servers {
2845      if let Some(t) = server.client.poll_timeout() {
2846        deadline = Some(deadline.map_or(t, |d| d.min(t)));
2847      }
2848    }
2849    if let Some(up) = self.ice_up_at {
2850      let t = up + DTLS_TIMEOUT;
2851      deadline = Some(deadline.map_or(t, |d| d.min(t)));
2852    }
2853    if let Some(since) = self.checking_since {
2854      let t = since + CHECKING_STALL;
2855      deadline = Some(deadline.map_or(t, |d| d.min(t)));
2856    }
2857    // wpt100:mediasink
2858    if let Some(t) = self.sinks.silence_deadline() {
2859      deadline = Some(deadline.map_or(t, |d| d.min(t)));
2860    }
2861    deadline
2862  }
2863
2864  fn handle_timeout(&mut self, now: Instant) {
2865    let _ = self.pc.handle_timeout(now);
2866    for server in &mut self.servers {
2867      let _ = server.client.handle_timeout(now);
2868    }
2869  }
2870
2871  fn handle_datagram(&mut self, dg: Datagram) {
2872    if self.refused.contains(&dg.from) {
2873      return;
2874    }
2875    let now = Instant::now();
2876    match dg.via {
2877      Via::Socket => {}
2878      Via::Mdns => {
2879        // Only what a responder sends from its mDNS port; the engine takes
2880        // answers only from the mDNS socket (local port 5353).
2881        if dg.from.port() == MDNS_PORT {
2882          let _ = self.pc.handle_read(TaggedBytesMut {
2883            now,
2884            transport: TransportContext {
2885              local_addr: dg.local,
2886              peer_addr: dg.from,
2887              ecn: None,
2888              transport_protocol: TransportProtocol::UDP,
2889            },
2890            message: dg.data,
2891          });
2892        }
2893        return;
2894      }
2895      Via::IceTcp(id) => {
2896        if dg.closed.is_some() {
2897          if self.tcp_links.get(&dg.from).is_some_and(|l| l.id == id) {
2898            self.tcp_links.remove(&dg.from);
2899          }
2900          return;
2901        }
2902        if !self.tcp_links.get(&dg.from).is_some_and(|l| l.id == id)
2903          || self.relay_generation
2904        {
2905          return;
2906        }
2907        if is_stun(&dg.data) {
2908          self.saw_stun(dg.from);
2909        } else {
2910          let from_selected = match self.selected {
2911            Some((_, r)) => self.selected_tcp && r == dg.from,
2912            None => self.ice_up && self.stun_peers.contains(&dg.from),
2913          };
2914          if !from_selected {
2915            return;
2916          }
2917        }
2918        let local = self.tcp_local(dg.local);
2919        let _ = self.pc.handle_read(TaggedBytesMut {
2920          now,
2921          transport: TransportContext {
2922            local_addr: local,
2923            peer_addr: dg.from,
2924            ecn: None,
2925            transport_protocol: TransportProtocol::TCP,
2926          },
2927          message: dg.data,
2928        });
2929        return;
2930      }
2931    }
2932    if let (Some(index), Some(reason)) = (dg.stream, dg.closed.as_ref()) {
2933      if let Some(server) = self.servers.get_mut(index) {
2934        let (url, base) = (server.url.clone(), server.base);
2935        server.binding = None;
2936        server.allocate = None;
2937        server.relay = None;
2938        self.report_error(
2939          &url,
2940          Some(base),
2941          ERROR_CODE_UNREACHABLE,
2942          format!("The TURN connection ended: {reason}"),
2943        );
2944      }
2945      return;
2946    }
2947    if let Some(index) = dg.stream {
2948      if let Some(server) = self.servers.get_mut(index) {
2949        let protocol = server.protocol();
2950        let _ = server.client.handle_read(TaggedBytesMut {
2951          now,
2952          transport: TransportContext {
2953            local_addr: server.base,
2954            peer_addr: dg.from,
2955            ecn: None,
2956            transport_protocol: protocol,
2957          },
2958          message: dg.data,
2959        });
2960      }
2961      return;
2962    }
2963    // A reply from a STUN/TURN server on the UDP socket.
2964    if let Some(server) = self.servers.iter_mut().find(|s| {
2965      matches!(s.link, ServerLink::Udp)
2966        && s.server == dg.from
2967        && s.base.port() == dg.local.port()
2968    }) {
2969      let base = server.base;
2970      let _ = server.client.handle_read(TaggedBytesMut {
2971        now,
2972        transport: TransportContext {
2973          local_addr: base,
2974          peer_addr: dg.from,
2975          ecn: None,
2976          transport_protocol: TransportProtocol::UDP,
2977        },
2978        message: dg.data,
2979      });
2980      return;
2981    }
2982    // The peer straight on a socket: not a relayed path (`relay_path`).
2983    if self.relay_generation {
2984      return;
2985    }
2986    let Some(endpoint) = self
2987      .endpoints
2988      .iter()
2989      .position(|e| e.bound.port() == dg.local.port())
2990    else {
2991      return;
2992    };
2993    let local = self.local_for(endpoint, dg.from);
2994    if is_stun(&dg.data) {
2995      self.saw_stun(dg.from);
2996    } else if !self.is_from_selected_pair(local, dg.from, false) {
2997      return;
2998    }
2999    let _ = self.pc.handle_read(TaggedBytesMut {
3000      now,
3001      transport: TransportContext {
3002        local_addr: local,
3003        peer_addr: dg.from,
3004        ecn: dg.ecn,
3005        transport_protocol: TransportProtocol::UDP,
3006      },
3007      message: dg.data,
3008    });
3009  }
3010}
3011
3012impl Peer {
3013  pub fn new(
3014    options: PeerOptions,
3015    guard: Rc<dyn NetGate>,
3016    io: Rc<dyn NetIo>,
3017  ) -> Result<Rc<Self>, Error> {
3018    let config = RTCConfigurationBuilder::new()
3019      .with_certificates(options.certificates.clone())
3020      .with_bundle_policy(options.bundle_policy)
3021      .build();
3022    let pacer_refusals = Arc::<crate::media::PacerRefusals>::default();
3023    let (media_engine, registry) =
3024      crate::media::media_stack_counting(pacer_refusals.clone())?;
3025    // Messages up to 256 KiB, as browsers take (the engine's own default is
3026    // RFC 8841's 64 KiB); the connection's maxMessageSize is the smaller of
3027    // this and the peer's.
3028    let net = options.network.as_ref().map(|n| &n.options);
3029    // An ICE restart starts a new gathering phase (`regather`), so the
3030    // previous generation's local candidates go with the old credentials.
3031    let mut settings = SettingEngineBuilder::new()
3032      .with_discard_local_candidates_during_ice_restart(true)
3033      // A new DTLS association (a peer's new `a=tls-id`, the engine's SRTP
3034      // re-keying) keeps the sockets this driver has: one per family, or a
3035      // network's shared port, which can't move to new ports (RFC 8842
3036      // section 5.1's new 3-tuple is left to the peer). The engine's default
3037      // would refuse their addresses and wait for candidates on new ports.
3038      .with_dtls_new_association_on_previous_addresses(true)
3039      .with_sctp_max_message_size(SctpMaxMessageSize::Bounded(
3040        net
3041          .and_then(|n| n.max_message_size)
3042          .unwrap_or(SctpMaxMessageSize::MAX_MESSAGE_SIZE),
3043      ))
3044      // ECN (L4S): the engine marks the RTP of a stream that negotiated
3045      // `ack ccfb` ECT(1) and counts the codepoints datagrams arrive with,
3046      // which the UDP sockets carry both ways where the platform lets them
3047      // (`crate::ecn`). Over ICE-TCP and TURN relays nothing is marked on
3048      // the wire, which the remote's feedback reports as bleached.
3049      .with_ecn(crate::ecn::supported())
3050      // A bundle-only section of an initial offer (every section but the
3051      // first under `max-bundle`, a second section of one media type under
3052      // `balanced`) in the form browsers take: `a=rtcp-mux` and the group's
3053      // ICE credentials in it (rtci's `Chrome` profile value). Chromium,
3054      // WebKit and Firefox refuse the RFC 9143 / RFC 9429 section 5.2.1 form
3055      // ("rtcp-mux must be enabled when BUNDLE is enabled."), and this side
3056      // offers to browsers.
3057      .with_bundle_only_sections_in_browser_form(true)
3058      // An app that never relays the peer's end-of-candidates (the common
3059      // `if (e.candidate) pc.addIceCandidate(e.candidate)`) still reaches
3060      // `failed` once the RFC 8863 PAC timer runs out, as Chrome, Safari and
3061      // Firefox do, instead of staying `disconnected` for ever.
3062      .with_ice_failed_without_end_of_candidates(true);
3063    if let Some(net) = net {
3064      settings = settings.with_lite(net.ice_lite);
3065      if let Some((disconnected, failed, keep_alive)) = net.ice_timeouts {
3066        settings = settings.with_ice_timeouts(disconnected, failed, keep_alive);
3067      }
3068    }
3069    // mDNS: what the network asks for (resolving the peer's `.local`
3070    // candidates by default, as browsers do), when it can be used here.
3071    // A gate that hasn't answered yet leaves the connection resolving names
3072    // only, once it allows (publishing them needs the socket now).
3073    let gate = GateCache::new(guard);
3074    let mut mdns_note = None;
3075    let mut mdns_token = None;
3076    let mdns_mode = match net.map(|n| n.mdns).unwrap_or_default() {
3077      MdnsMode::Off => MdnsMode::Off,
3078      wanted => {
3079        match crate::rt::poll_now(Box::pin(mdns_permitted(gate.clone()))) {
3080          Ok(Ok(token)) => {
3081            mdns_token = Some(token);
3082            wanted
3083          }
3084          Ok(Err(why)) => {
3085            if wanted == MdnsMode::Gather {
3086              mdns_note = Some(format!(
3087                "Host candidates are not published under mDNS names: {why}"
3088              ));
3089            }
3090            MdnsMode::Off
3091          }
3092          Err(_asked) => {
3093            if wanted == MdnsMode::Gather {
3094              mdns_note = Some(
3095                "Host candidates are not published under mDNS names: the \
3096                 permission gate has not answered yet"
3097                  .to_string(),
3098              );
3099            }
3100            MdnsMode::Resolve
3101          }
3102        }
3103      }
3104    };
3105    // Publishing names nobody could resolve would hide the host candidates
3106    // for nothing: the socket is opened first, and a failure keeps them
3107    // literal.
3108    let mut mdns_socket = None;
3109    let mdns_mode = if mdns_mode == MdnsMode::Gather
3110      && let Some(token) = &mdns_token
3111    {
3112      match io.bind_mdns(
3113        token,
3114        &interface_addresses(net.and_then(|n| n.interfaces.as_deref())),
3115      ) {
3116        Ok(socket) => {
3117          mdns_socket = Some(Rc::new(EcnUdpSocket::plain(socket)));
3118          MdnsMode::Gather
3119        }
3120        Err(e) => {
3121          mdns_note = Some(format!(
3122            "Host candidates are not published under mDNS names: {e}"
3123          ));
3124          MdnsMode::Resolve
3125        }
3126      }
3127    } else {
3128      mdns_mode
3129    };
3130    // 1:1 NAT in host mode: the engine announces a mapped host candidate on
3131    // the public address and keeps its private socket as the base, which is
3132    // what its remote-address policy pairs (a loopback remote only from a
3133    // loopback base). It can't map an mDNS name.
3134    let engine_nat = mdns_mode != MdnsMode::Gather
3135      && net.is_some_and(|n| !n.public_srflx && !n.public_addresses.is_empty());
3136    if engine_nat && let Some(net) = net {
3137      settings = settings.with_nat_1to1_ips(
3138        net
3139          .public_addresses
3140          .iter()
3141          .map(|p| match p.private {
3142            Some(private) => format!("{}/{private}", p.public),
3143            None => p.public.to_string(),
3144          })
3145          .collect(),
3146        RTCIceCandidateType::Host,
3147      );
3148    }
3149    settings = settings
3150      .with_multicast_dns_mode(match mdns_mode {
3151        MdnsMode::Off => MulticastDnsMode::Disabled,
3152        MdnsMode::Resolve => MulticastDnsMode::QueryOnly,
3153        MdnsMode::Gather => MulticastDnsMode::QueryAndGather,
3154      })
3155      .with_multicast_dns_timeout(Some(MDNS_QUERY_TIMEOUT));
3156    let settings = settings.build();
3157    let pc = RTCPeerConnectionBuilder::new()
3158      .with_configuration(config)
3159      .with_setting_engine(settings)
3160      .with_media_engine(media_engine)
3161      .with_interceptor_registry(registry)
3162      .build(Instant::now())
3163      .map_err(rtc_err)?;
3164    let (recv_tx, recv_rx) = mpsc::channel(RECV_QUEUE);
3165    let mut events = VecDeque::new();
3166    if let Some(note) = mdns_note {
3167      events.push_back(JsEvent::IceCandidateError {
3168        address: None,
3169        port: None,
3170        url: String::new(),
3171        error_code: ERROR_CODE_UNREACHABLE,
3172        error_text: note,
3173      });
3174    }
3175    let peer = Rc::new_cyclic(|this| Self {
3176      core: RefCell::new(Core {
3177        pc,
3178        options,
3179        endpoints: Vec::new(),
3180        servers: Vec::new(),
3181        gathering: GatherPhase::NotStarted,
3182        resolving: 0,
3183        binds_pending: false,
3184        srflx_seen: HashSet::new(),
3185        events,
3186        allowed: HashSet::new(),
3187        refused: HashSet::new(),
3188        routes: HashMap::new(),
3189        selected: None,
3190        stun_peers: HashSet::new(),
3191        ice_up: false,
3192        ice_up_at: None,
3193        dtls_connected: false,
3194        failed: false,
3195        recv_tx,
3196        recv_rx: Some(recv_rx),
3197        media: MediaState {
3198          pacer_refusals,
3199          ..Default::default()
3200        },
3201        transforms: Default::default(),
3202        sinks: Default::default(),
3203        remote_known: false,
3204        wrote_rtcp: false,
3205        sent: HashMap::new(),
3206        sctp_state: "",
3207        dtls_state: String::new(),
3208        local_gathered: 0,
3209        remote_gathered: false,
3210        relay_generation: false,
3211        checking_held: false,
3212        restart_masked: false,
3213        checking_since: None,
3214        this: this.clone(),
3215        io: io.clone(),
3216        gate: gate.clone(),
3217        tcp_links: HashMap::new(),
3218        tcp_dialing: HashMap::new(),
3219        next_tcp_link: 0,
3220        selected_tcp: false,
3221        mdns_mode,
3222        mdns_socket: mdns_socket.clone(),
3223        mdns_failed: false,
3224        mdns_token,
3225        engine_nat,
3226        remote_simulcast_lines: Vec::new(),
3227        relayed_recent: VecDeque::new(),
3228      }),
3229      gate,
3230      ops: RefCell::new(VecDeque::new()),
3231      current_op: Cell::new(None),
3232      ops_running: Cell::new(false),
3233      last_op: Cell::new(0),
3234      wake: Notify::new(),
3235      events_ready: Notify::new(),
3236      cancel: Cancel::new(),
3237      closed: Cell::new(false),
3238      driver_started: Cell::new(false),
3239    });
3240    // An answer lets held-back sends go (the driver tries them again).
3241    // Operations waiting on it hold their own futures.
3242    let weak = Rc::downgrade(&peer);
3243    peer.gate.set_on_answer(move || {
3244      if let Some(peer) = weak.upgrade() {
3245        peer.poke();
3246      }
3247    });
3248    if let Some(socket) = mdns_socket {
3249      spawn_udp_reader_via(
3250        socket,
3251        SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), MDNS_PORT),
3252        peer.core.borrow().recv_tx.clone(),
3253        peer.cancel.clone(),
3254        Via::Mdns,
3255      );
3256    }
3257    Ok(peer)
3258  }
3259
3260  pub fn is_closed(&self) -> bool {
3261    self.closed.get()
3262  }
3263
3264  /// The panic boundary: runs `f` on the engine; a panic poisons the
3265  /// connection (`failed`, then closed) and becomes an `OperationError`.
3266  fn guarded<T>(
3267    &self,
3268    f: impl FnOnce(&mut Core) -> Result<T, Error>,
3269  ) -> Result<T, Error> {
3270    if self.closed.get() {
3271      return Err(Error::new(
3272        ErrorKind::InvalidState,
3273        "RTCPeerConnection is closed".to_string(),
3274      ));
3275    }
3276    let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
3277      f(&mut self.core.borrow_mut())
3278    }));
3279    match result {
3280      Ok(r) => r,
3281      Err(_) => {
3282        self.poison();
3283        Err(Error::new(
3284          ErrorKind::Operation,
3285          "the WebRTC engine failed; the connection is closed".to_string(),
3286        ))
3287      }
3288    }
3289  }
3290
3291  fn poison(&self) {
3292    if let Ok(mut core) = self.core.try_borrow_mut() {
3293      core.fail("engine panic");
3294    }
3295    self.shutdown(false);
3296  }
3297
3298  /// Ops call this after changing the engine: the driver flushes what the
3299  /// change produced and JavaScript gets the resulting events.
3300  pub fn poke(&self) {
3301    self.wake.notify_one();
3302  }
3303
3304  /// The next batch of events, or `None` once the connection is closed and
3305  /// the queue is drained.
3306  pub async fn next_events(&self) -> Option<Vec<JsEvent>> {
3307    loop {
3308      {
3309        let mut core = self.core.borrow_mut();
3310        if !core.events.is_empty() {
3311          return Some(core.events.drain(..).collect());
3312        }
3313        if self.closed.get() {
3314          return None;
3315        }
3316      }
3317      self.events_ready.notified().await;
3318    }
3319  }
3320
3321  pub fn create_offer(
3322    self: &Rc<Self>,
3323    ice_restart: bool,
3324  ) -> Result<String, Error> {
3325    let sdp = self.guarded(|core| {
3326      if ice_restart {
3327        core.pc.restart_ice();
3328      }
3329      Ok(core.pc.create_offer(None).map_err(rtc_err)?.sdp)
3330    })?;
3331    Ok(sdp)
3332  }
3333
3334  /// `setConfiguration`: the ICE servers and policy the next gathering
3335  /// (an ICE restart) uses.
3336  pub fn set_ice_servers(
3337    &self,
3338    specs: Vec<IceServerSpec>,
3339    relay_only: bool,
3340    tls: Option<Arc<rustls::ClientConfig>>,
3341  ) {
3342    let mut core = self.core.borrow_mut();
3343    core.options.ice_servers = specs;
3344    core.options.relay_only = relay_only;
3345    if tls.is_some() {
3346      core.options.tls = tls;
3347    }
3348  }
3349
3350  pub fn selected_pair(&self) -> Option<(SocketAddr, SocketAddr)> {
3351    self.core.borrow().selected
3352  }
3353
3354  /// The ICE agent's selected candidate pair (W3C webrtc-pc 5.6
3355  /// `getSelectedCandidatePair()`): the nominated pair as soon as ICE has
3356  /// one, on the controlled side too, before either side sent anything on it.
3357  /// `None` before that, or when the connection is closed.
3358  pub fn ice_selected_pair(&self) -> Option<SelectedPair> {
3359    if self.closed.get() {
3360      return None;
3361    }
3362    self
3363      .guarded(|core| Ok(core.ice_selected_pair()))
3364      .ok()
3365      .flatten()
3366  }
3367
3368  /// Whether the selected pair is an ICE-TCP one.
3369  pub fn selected_is_tcp(&self) -> bool {
3370    self.core.borrow().selected_tcp
3371  }
3372
3373  /// The engine's answer. It lists only the formats the remote offer has
3374  /// (rtci 0.3's default, `with_answer_offered_formats_only`), so a peer
3375  /// can't switch to a format its offer lacked (DENEXT.md item 565).
3376  pub fn create_answer(&self) -> Result<String, Error> {
3377    self.guarded(|core| Ok(core.pc.create_answer(None).map_err(rtc_err)?.sdp))
3378  }
3379
3380  fn description(
3381    kind: &str,
3382    sdp: String,
3383  ) -> Result<RTCSessionDescription, Error> {
3384    match kind {
3385      "offer" => RTCSessionDescription::offer(sdp),
3386      "answer" => RTCSessionDescription::answer(sdp),
3387      "pranswer" => RTCSessionDescription::pranswer(sdp),
3388      "rollback" => RTCSessionDescription::rollback(None),
3389      other => {
3390        return Err(Error::new(
3391          ErrorKind::Type,
3392          format!("'{other}' is not a valid RTCSdpType"),
3393        ));
3394      }
3395    }
3396    .map_err(rtc_err)
3397  }
3398
3399  pub fn set_local_description(
3400    self: &Rc<Self>,
3401    kind: &str,
3402    sdp: String,
3403  ) -> Result<(), Error> {
3404    check_sdp_size(kind, &sdp)?;
3405    // Gathering starts with the first description that has a transport to
3406    // gather for (W3C: an m-section that isn't rejected).
3407    let has_transport = has_live_media_section(&sdp);
3408    let desc = Self::description(kind, sdp)?;
3409    let restarted = self.guarded(|core| {
3410      let ufrag_before = core.local_ufrag();
3411      let applied = core.pc.set_local_description(Instant::now(), desc);
3412      // The engine may have removed transceivers (a rollback, an answer
3413      // rejecting a stopped one's section), even on the way to an error.
3414      core.sync_removed_transceivers();
3415      applied.map_err(|e| match e {
3416        // JSEP: an offer or answer other than the last one created.
3417        RtcError::ErrSDPDoesNotMatchOffer
3418        | RtcError::ErrSDPDoesNotMatchAnswer => {
3419          Error::new(ErrorKind::InvalidModification, e.to_string())
3420        }
3421        e => description_err(e),
3422      })?;
3423      Ok(
3424        kind != "rollback"
3425          && ufrag_before.is_some()
3426          && core.local_ufrag() != ufrag_before,
3427      )
3428    })?;
3429    if kind != "rollback" && has_transport {
3430      if restarted {
3431        self.regather();
3432      } else {
3433        self.start_gathering();
3434      }
3435      self.register_on_shared_port();
3436    }
3437    self.ensure_driver();
3438    self.poke();
3439    Ok(())
3440  }
3441
3442  /// On a shared-port network, the local ufrag routes the remote peer's
3443  /// checks to this connection (registered again after an ICE restart).
3444  fn register_on_shared_port(&self) {
3445    let core = self.core.borrow();
3446    if let Some(net) = core
3447      .options
3448      .network
3449      .as_ref()
3450      .filter(|n| n.routes_by_ufrag())
3451      && let Some(ufrag) = core.local_ufrag()
3452    {
3453      net.register_ufrag(ufrag, &core.this);
3454    }
3455  }
3456
3457  /// A datagram a shared-port network routed to this connection.
3458  pub(crate) fn deliver(&self, dg: Datagram) {
3459    if self.closed.get() {
3460      return;
3461    }
3462    if let Ok(core) = self.core.try_borrow() {
3463      let _ = core.recv_tx.try_send(dg);
3464    }
3465  }
3466
3467  /// Runs `op` here when no operation is waiting and the gate answers at
3468  /// once (its `opdone` is queued before this returns), else queues it
3469  /// behind the others; returns its id.
3470  fn submit_op(self: &Rc<Self>, op: PendingOp) -> u32 {
3471    let id = self.last_op.get().wrapping_add(1);
3472    self.last_op.set(id);
3473    if self.ops_running.get() || !self.ops.borrow().is_empty() {
3474      self.ops.borrow_mut().push_back((id, op));
3475      return id;
3476    }
3477    match crate::rt::poll_now(op) {
3478      Ok(result) => self.op_done(id, result),
3479      Err(op) => {
3480        self.ops.borrow_mut().push_back((id, op));
3481        self.ops_running.set(true);
3482        let peer = self.clone();
3483        let cancel = self.cancel.clone();
3484        crate::rt::spawn(async move {
3485          let _ = Self::run_ops(peer).or_cancel(cancel).await;
3486        });
3487      }
3488    }
3489    id
3490  }
3491
3492  /// Runs the queued operations in order (closing the connection cancels
3493  /// this; `shutdown` reports the ones left).
3494  async fn run_ops(peer: Rc<Self>) {
3495    loop {
3496      let next = peer.ops.borrow_mut().pop_front();
3497      let Some((id, op)) = next else {
3498        break;
3499      };
3500      peer.current_op.set(Some(id));
3501      let result = op.await;
3502      if peer.current_op.take() == Some(id) {
3503        peer.op_done(id, result);
3504      }
3505    }
3506    peer.ops_running.set(false);
3507  }
3508
3509  /// Queues the `opdone` event for operation `op`.
3510  fn op_done(&self, op: u32, result: Result<(), Error>) {
3511    self.core.borrow_mut().events.push_back(JsEvent::OpDone {
3512      op,
3513      error: result.err(),
3514    });
3515    self.events_ready.notify_one();
3516  }
3517
3518  fn check_open(&self) -> Result<(), Error> {
3519    if self.closed.get() {
3520      return Err(Error::new(
3521        ErrorKind::InvalidState,
3522        "RTCPeerConnection is closed".to_string(),
3523      ));
3524    }
3525    Ok(())
3526  }
3527
3528  /// Whether the connection can resolve `.local` candidates now, waiting
3529  /// for the gate's answer for the mDNS socket if it was asked (and
3530  /// opening the socket on the first allow).
3531  async fn mdns_ready(self: &Rc<Self>) -> bool {
3532    {
3533      let core = self.core.borrow();
3534      if core.mdns_socket.is_some() {
3535        return true;
3536      }
3537      if core.mdns_mode == MdnsMode::Off || core.mdns_failed {
3538        return false;
3539      }
3540    }
3541    if self.core.borrow().mdns_token.is_none() {
3542      match mdns_permitted(self.gate.clone()).await {
3543        Ok(token) => self.core.borrow_mut().mdns_token = Some(token),
3544        Err(why) => {
3545          log::debug!("webrtc: mDNS is not used: {why}");
3546          self.core.borrow_mut().mdns_failed = true;
3547          return false;
3548        }
3549      }
3550    }
3551    if self.closed.get() {
3552      return false;
3553    }
3554    self.core.borrow_mut().resolves_mdns()
3555  }
3556
3557  /// Checks every candidate the remote description carries and hands the
3558  /// engine a copy without the ones it can't use (see
3559  /// [`RemoteCandidate::Ignore`]). A refused address fails the whole call.
3560  ///
3561  /// Two-phase: an `Err` here is an argument error (a closed connection, an
3562  /// oversized description, an invalid type, a malformed candidate). The
3563  /// rest happens once the gate answered for every candidate (at once with
3564  /// a gate that decides, before this returns), and its outcome is the
3565  /// `opdone` event whose `op` is the id returned: no `error` when the
3566  /// description was applied, else a [`ErrorKind::NotCapable`] refusal or
3567  /// the engine's error. Operations complete in the order they were made.
3568  pub fn set_remote_description(
3569    self: &Rc<Self>,
3570    kind: &str,
3571    sdp: String,
3572  ) -> Result<u32, Error> {
3573    self.check_open()?;
3574    check_sdp_size(kind, &sdp)?;
3575    if !matches!(kind, "offer" | "answer" | "pranswer" | "rollback") {
3576      return Err(Error::new(
3577        ErrorKind::Type,
3578        format!("'{kind}' is not a valid RTCSdpType"),
3579      ));
3580    }
3581    // The lines the engine is given, each with the condition it is kept on.
3582    let mut lines: Vec<(String, Keep)> = Vec::new();
3583    let mut simulcast_lines = Vec::new();
3584    let mut section_rids: Vec<String> = Vec::new();
3585    // A candidate kept without an address to check: an active TCP one.
3586    let mut unchecked = false;
3587    let (tcp, mdns) = {
3588      let core = self.core.borrow();
3589      (core.ice_tcp(), core.mdns_mode != MdnsMode::Off)
3590    };
3591    for line in sdp.split_inclusive('\n') {
3592      // webrtc-identity: JavaScript validates the a=identity assertion
3593      // (06_identity.js), and a malformed one rejects `peerIdentity`, not the
3594      // description; the engine's RFC 8827 grammar would refuse the whole
3595      // description, so it isn't given one it can't parse.
3596      if let Some(value) = line.trim_end().strip_prefix("a=identity:")
3597        && !is_identity_value(value)
3598      {
3599        continue;
3600      }
3601      // RFC 8866 section 9's `attribute-name` is a token: a line such as
3602      // `a=notssrc1 cname:x` (WPT RTCPeerConnection-connectionState munges
3603      // `a=ssrc:` so, to hide the SSRCs) names no attribute anyone knows,
3604      // which browsers ignore as an attribute they don't understand (RFC
3605      // 9429 section 5.8); rtci 0.2's parser refuses the description for it.
3606      if let Some(attribute) = line.trim_end().strip_prefix("a=")
3607        && !is_attribute_name(
3608          attribute
3609            .split_once(':')
3610            .map_or(attribute, |(name, _)| name),
3611        )
3612      {
3613        continue;
3614      }
3615      // An `a=extmap` line whose extension is not named by an absolute URI
3616      // (RFC 8285 section 5: "The URI ... MUST be absolute") is one no
3617      // endpoint understands, which an answerer leaves out (section 7, WPT
3618      // `protocol/rtp-headerextensions` "Negotiates the subset of supported
3619      // extensions offered" offers `bogus`). rtci 0.2 takes it into its
3620      // negotiated extensions and then fails to write the answer ("url
3621      // parse: relative URL without a base"), so it isn't given the line.
3622      if let Some(value) = line.trim_end().strip_prefix("a=extmap:")
3623        && !extmap_names_absolute_uris(value)
3624      {
3625        continue;
3626      }
3627      // A media section's rids are its own (RFC 8851 section 4).
3628      if line.starts_with("m=") {
3629        section_rids.clear();
3630      }
3631      // A second `a=rid` line for a rid-id the section declared already
3632      // (WPT `simulcast/negotiation-encodings` writes one per entry of
3633      // `a=simulcast:recv foo;bar;foo`): the engine is given the first one
3634      // only, as the repeated rid in `a=simulcast` is dropped below; with
3635      // both it negotiated no simulcast in its answer.
3636      if let Some(value) = line.trim_end().strip_prefix("a=rid:") {
3637        let id = value.split(' ').next().unwrap_or_default().to_string();
3638        if section_rids.contains(&id) {
3639          continue;
3640        }
3641        section_rids.push(id);
3642      }
3643      if let Some(value) = line.trim_end().strip_prefix("a=simulcast:")
3644        && let Some(deduped) = simulcast_without_repeated_rids(value)
3645      {
3646        let end = &line[line.trim_end().len()..];
3647        let engine_line = format!("a=simulcast:{deduped}");
3648        lines.push((format!("{engine_line}{end}"), Keep::Always));
3649        simulcast_lines.push((engine_line, line.trim_end().to_string()));
3650        continue;
3651      }
3652      if let Some(value) = line.trim_end().strip_prefix("a=candidate:") {
3653        let keep = match classify_remote_candidate(value, tcp, mdns)? {
3654          RemoteCandidate::Ignore => continue,
3655          RemoteCandidate::Active => {
3656            unchecked = true;
3657            Keep::Always
3658          }
3659          RemoteCandidate::Udp(addr) => Keep::Allowed(Reach::connect(
3660            ReachKind::RemoteCandidate,
3661            Proto::Udp,
3662            addr,
3663          )),
3664          RemoteCandidate::Tcp(addr) => Keep::Allowed(Reach::connect(
3665            ReachKind::RemoteCandidate,
3666            Proto::Tcp,
3667            addr,
3668          )),
3669          RemoteCandidate::Mdns => Keep::Mdns,
3670        };
3671        lines.push((line.to_string(), keep));
3672        continue;
3673      }
3674      lines.push((line.to_string(), Keep::Always));
3675    }
3676    let kind = kind.to_string();
3677    let peer = self.clone();
3678    Ok(self.submit_op(Box::pin(async move {
3679      // Each candidate's address in order; the first refusal fails the call.
3680      let mut checked = Vec::new();
3681      for (_, keep) in &lines {
3682        if let Keep::Allowed(reach) = keep {
3683          peer
3684            .gate
3685            .verdict(reach.clone())
3686            .await
3687            .map_err(Error::not_capable)?;
3688          checked.extend(reach.socket_addr());
3689        }
3690      }
3691      // `.local` candidates, all kept or all skipped.
3692      let mdns = if lines.iter().any(|(_, k)| matches!(k, Keep::Mdns)) {
3693        let ready = peer.mdns_ready().await;
3694        unchecked |= ready;
3695        ready
3696      } else {
3697        false
3698      };
3699      let kept: String = lines
3700        .iter()
3701        .filter(|(_, k)| mdns || !matches!(k, Keep::Mdns))
3702        .map(|(l, _)| l.as_str())
3703        .collect();
3704      let end_of_candidates =
3705        kept.lines().any(|l| l.trim_end() == "a=end-of-candidates");
3706      let desc = Self::description(&kind, kept)?;
3707      peer.guarded(|core| {
3708        let ufrag_before = core.remote_ufrag();
3709        let applied = core.pc.set_remote_description(Instant::now(), desc);
3710        core.sync_removed_transceivers();
3711        applied.map_err(description_err)?;
3712        core.remote_simulcast_lines = simulcast_lines;
3713        // An ICE restart by the remote side: its candidates, and its
3714        // end-of-candidates, start over.
3715        if ufrag_before.is_some() && core.remote_ufrag() != ufrag_before {
3716          core.remote_known = false;
3717          core.remote_gathered = false;
3718        }
3719        if end_of_candidates {
3720          core.remote_gathered = true;
3721        }
3722        for addr in checked {
3723          core.mark_allowed(addr);
3724        }
3725        if unchecked {
3726          core.remote_known = true;
3727        }
3728        Ok(())
3729      })?;
3730      peer.ensure_driver();
3731      peer.poke();
3732      Ok(())
3733    })))
3734  }
3735
3736  /// Two-phase, as [`Peer::set_remote_description`]: an `Err` is an
3737  /// argument error (a closed connection, a malformed candidate); the
3738  /// outcome (a refused address, the engine's error, or none) is the
3739  /// `opdone` event for the id returned.
3740  pub fn add_ice_candidate(
3741    &self,
3742    candidate: String,
3743    sdp_mid: Option<String>,
3744    sdp_m_line_index: Option<u16>,
3745    username_fragment: Option<String>,
3746  ) -> Result<u32, Error> {
3747    self.check_open()?;
3748    let Some(peer) = self.core.borrow().this.upgrade() else {
3749      return Err(Error::new(
3750        ErrorKind::InvalidState,
3751        "RTCPeerConnection is closed".to_string(),
3752      ));
3753    };
3754    let init = |candidate: String| RTCIceCandidateInit {
3755      candidate,
3756      sdp_mid: sdp_mid.clone(),
3757      sdp_mline_index: sdp_m_line_index,
3758      username_fragment: username_fragment.clone(),
3759      url: None,
3760      relay_protocol: None,
3761    };
3762    if candidate.trim().is_empty() {
3763      // End-of-candidates: the engine checks the media section and the
3764      // usernameFragment and marks the remote description; then the
3765      // remote's current generation is complete.
3766      let init = init(String::new());
3767      let this = peer.clone();
3768      return Ok(peer.submit_op(Box::pin(async move {
3769        this.guarded(|core| {
3770          core.pc.add_remote_candidate(init).map_err(rtc_err)?;
3771          core.remote_gathered = true;
3772          Ok(())
3773        })?;
3774        this.poke();
3775        Ok(())
3776      })));
3777    }
3778    let (tcp, mdns) = {
3779      let core = self.core.borrow();
3780      (core.ice_tcp(), core.mdns_mode != MdnsMode::Off)
3781    };
3782    let class = classify_remote_candidate(&candidate, tcp, mdns)?;
3783    let init = init(candidate);
3784    let this = peer.clone();
3785    Ok(peer.submit_op(Box::pin(async move {
3786      let addr = match class {
3787        RemoteCandidate::Ignore => return Ok(()),
3788        RemoteCandidate::Active => None,
3789        RemoteCandidate::Mdns => {
3790          if !this.mdns_ready().await {
3791            return Ok(());
3792          }
3793          None
3794        }
3795        RemoteCandidate::Udp(addr) => Some((addr, Proto::Udp)),
3796        RemoteCandidate::Tcp(addr) => Some((addr, Proto::Tcp)),
3797      };
3798      if let Some((addr, proto)) = addr {
3799        this
3800          .gate
3801          .verdict(Reach::connect(ReachKind::RemoteCandidate, proto, addr))
3802          .await
3803          .map_err(Error::not_capable)?;
3804      }
3805      this.guarded(|core| {
3806        core.pc.add_remote_candidate(init).map_err(rtc_err)?;
3807        match addr {
3808          Some((addr, _)) => core.mark_allowed(addr),
3809          None => core.remote_known = true,
3810        }
3811        Ok(())
3812      })?;
3813      this.poke();
3814      Ok(())
3815    })))
3816  }
3817
3818  /// Returns the channel's engine handle and its SCTP stream id when it
3819  /// already has one (a negotiated channel).
3820  pub fn create_data_channel(
3821    self: &Rc<Self>,
3822    label: &str,
3823    init: RTCDataChannelInit,
3824  ) -> Result<(u32, Option<u16>), Error> {
3825    let created = self.guarded(|core| {
3826      let channel = core
3827        .pc
3828        .create_data_channel(label, Some(init))
3829        .map_err(rtc_err)?;
3830      let handle = channel.id() as u32;
3831      let id = channel.stream_id();
3832      core.sent.insert(handle, 0);
3833      // A negotiated channel created on a live association is open at once
3834      // and the engine reports no open for it; JavaScript still gets its
3835      // `open` event (asynchronously, as the spec has it).
3836      if channel.ready_state() == RTCDataChannelState::Open {
3837        let open = JsEvent::DataChannelOpen {
3838          channel: handle,
3839          id,
3840          label: channel.label().to_string(),
3841          protocol: channel.protocol().to_string(),
3842          ordered: channel.ordered(),
3843          max_packet_life_time: channel.max_packet_life_time(),
3844          max_retransmits: channel.max_retransmits(),
3845          negotiated: channel.negotiated(),
3846          priority: channel.priority(),
3847        };
3848        core.events.push_back(open);
3849      }
3850      Ok((handle, id))
3851    })?;
3852    self.events_ready.notify_one();
3853    self.poke();
3854    Ok(created)
3855  }
3856
3857  /// Sends one message and returns the channel's buffered amount after it.
3858  pub fn send(
3859    &self,
3860    handle: u32,
3861    text: bool,
3862    data: &[u8],
3863  ) -> Result<u32, Error> {
3864    let buffered = self.guarded(|core| {
3865      let Some(mut channel) = core.pc.data_channel(handle as RTCDataChannelId)
3866      else {
3867        return Err(Error::new(ErrorKind::InvalidState,
3868          "RTCDataChannel is closed".to_string(),
3869        ));
3870      };
3871      let now = Instant::now();
3872      let sent = if text {
3873        let s = std::str::from_utf8(data)
3874          .map_err(|e| Error::new(ErrorKind::Type, e.to_string()))?;
3875        channel.send_text(now, s)
3876      } else {
3877        channel.send(now, BytesMut::from(data))
3878      };
3879      match sent {
3880        Ok(()) => {}
3881        // W3C: a message over the SCTP transport's maxMessageSize is a
3882        // TypeError; a channel that isn't open an InvalidStateError.
3883        Err(RtcError::ErrOutboundPacketTooLarge) => {
3884          return Err(Error::new(ErrorKind::Type, format!(
3885            "The message ({} bytes) is larger than the connection's maxMessageSize",
3886            data.len()
3887          )));
3888        }
3889        Err(
3890          e @ (RtcError::ErrDataChannelNotOpen | RtcError::ErrDataChannelClosed),
3891        ) => {
3892          return Err(Error::new(ErrorKind::InvalidState, e.to_string()));
3893        }
3894        Err(e) => return Err(rtc_err(e)),
3895      }
3896      Ok(u32::try_from(channel.outstanding_bytes()).unwrap_or(u32::MAX))
3897    })?;
3898    self.poke();
3899    Ok(buffered)
3900  }
3901
3902  /// Bytes sent that SCTP hasn't released (acknowledged or abandoned): the
3903  /// engine's send back-pressure, which the tests watch drain.
3904  #[cfg(test)]
3905  pub fn buffered_amount(&self, handle: u32) -> u32 {
3906    let mut core = self.core.borrow_mut();
3907    core
3908      .pc
3909      .data_channel(handle as RTCDataChannelId)
3910      .map(|c| u32::try_from(c.outstanding_bytes()).unwrap_or(u32::MAX))
3911      .unwrap_or(0)
3912  }
3913
3914  /// `RTCDataChannel.id`: the SCTP stream id, once the engine has assigned
3915  /// one (when the DTLS role is negotiated, RFC 8832 section 6).
3916  pub fn data_channel_id(&self, handle: u32) -> Option<u16> {
3917    let mut core = self.core.borrow_mut();
3918    core
3919      .pc
3920      .data_channel(handle as RTCDataChannelId)
3921      .and_then(|c| c.stream_id())
3922  }
3923
3924  pub fn set_buffered_amount_low_threshold(&self, handle: u32, threshold: u32) {
3925    let _ = self.guarded(|core| {
3926      if let Some(mut channel) =
3927        core.pc.data_channel(handle as RTCDataChannelId)
3928      {
3929        channel.set_buffered_amount_low_threshold(threshold);
3930      }
3931      Ok(())
3932    });
3933  }
3934
3935  pub fn close_data_channel(&self, handle: u32) {
3936    let _ = self.guarded(|core| {
3937      if let Some(mut channel) =
3938        core.pc.data_channel(handle as RTCDataChannelId)
3939      {
3940        let _ = channel.close();
3941      }
3942      Ok(())
3943    });
3944    self.poke();
3945  }
3946
3947  /// `RTCSctpTransport.maxMessageSize`, once SCTP is up.
3948  pub fn max_message_size(&self) -> Option<u32> {
3949    self
3950      .core
3951      .borrow()
3952      .pc
3953      .sctp()
3954      .and_then(|s| s.max_message_size())
3955  }
3956
3957  /// `localDescription`: the pending local description, else the current
3958  /// one.
3959  pub fn local_description(&self) -> Option<(String, String)> {
3960    let d = self.descriptions();
3961    d.pending_local.or(d.current_local)
3962  }
3963
3964  /// `remoteDescription`: the pending remote description, else the current
3965  /// one.
3966  pub fn remote_description(&self) -> Option<(String, String)> {
3967    let d = self.descriptions();
3968    d.pending_remote.or(d.current_remote)
3969  }
3970
3971  /// The four description slots of the W3C API, each as `(type, sdp)`: a
3972  /// current description stays in place while a new offer is pending, as
3973  /// `currentLocalDescription` / `pendingLocalDescription` (and the remote
3974  /// pair) have it.
3975  pub fn descriptions(&self) -> PeerDescriptions {
3976    let core = self.core.borrow();
3977    let redact = core.mdns_mode == MdnsMode::Gather;
3978    let local = |d: RTCSessionDescription| {
3979      let sdp = if redact {
3980        d.sdp
3981          .split_inclusive('\n')
3982          .map(|line| match line.strip_prefix("a=candidate:") {
3983            Some(_) if line.contains(" raddr ") => {
3984              let end = line.len() - line.trim_end().len();
3985              let (body, tail) = line.split_at(line.len() - end);
3986              redact_related_address(body) + tail
3987            }
3988            _ => line.to_string(),
3989          })
3990          .collect()
3991      } else {
3992        d.sdp
3993      };
3994      (d.sdp_type.to_string(), sdp)
3995    };
3996    let remote = |d: &RTCSessionDescription| {
3997      let sdp = if core.remote_simulcast_lines.is_empty() {
3998        d.sdp.clone()
3999      } else {
4000        d.sdp
4001          .split_inclusive('\n')
4002          .map(|line| {
4003            let body = line.trim_end();
4004            match core.remote_simulcast_lines.iter().find(|(e, _)| e == body) {
4005              Some((_, signalled)) => {
4006                format!("{signalled}{}", &line[body.len()..])
4007              }
4008              None => line.to_string(),
4009            }
4010          })
4011          .collect()
4012      };
4013      (d.sdp_type.to_string(), sdp)
4014    };
4015    PeerDescriptions {
4016      current_local: core.pc.current_local_description().map(local),
4017      pending_local: core.pc.pending_local_description().map(local),
4018      current_remote: core.pc.current_remote_description().map(remote),
4019      pending_remote: core.pc.pending_remote_description().map(remote),
4020    }
4021  }
4022
4023  /// `getStats()`; `selector` is a transceiver key and whether its sender
4024  /// (else its receiver) is the selector.
4025  pub fn stats(
4026    &self,
4027    selector: Option<(u32, bool)>,
4028  ) -> Result<Vec<serde_json::Value>, Error> {
4029    self.guarded(|core| {
4030      let selector = match selector {
4031        None => StatsSelector::None,
4032        Some((key, sender)) => {
4033          let Some(index) = core.media.keys.iter().position(|k| *k == key)
4034          else {
4035            return Ok(Vec::new());
4036          };
4037          if sender {
4038            StatsSelector::Sender(index.into())
4039          } else {
4040            StatsSelector::Receiver(index.into())
4041          }
4042        }
4043      };
4044      let wall_ms = SystemTime::now()
4045        .duration_since(UNIX_EPOCH)
4046        .unwrap_or_default()
4047        .as_secs_f64()
4048        * 1000.0;
4049      let now = Instant::now();
4050      core.refresh_media_stats(now);
4051      let report = core.pc.get_stats(now, selector);
4052      use RTCStatsReportEntry as E;
4053      let mut stats: Vec<serde_json::Value> = report
4054        .iter()
4055        .filter_map(|entry| {
4056          match entry {
4057            E::PeerConnection(s) => serde_json::to_value(s),
4058            E::Transport(s) => serde_json::to_value(s),
4059            E::IceCandidatePair(s) => serde_json::to_value(s),
4060            E::LocalCandidate(s) => serde_json::to_value(s),
4061            E::RemoteCandidate(s) => serde_json::to_value(s),
4062            E::Certificate(s) => serde_json::to_value(s),
4063            E::Codec(s) => serde_json::to_value(s),
4064            E::DataChannel(s) => serde_json::to_value(s),
4065            E::InboundRtp(s) => serde_json::to_value(s),
4066            E::OutboundRtp(s) => serde_json::to_value(s),
4067            E::RemoteInboundRtp(s) => serde_json::to_value(s),
4068            E::RemoteOutboundRtp(s) => serde_json::to_value(s),
4069            E::AudioSource(s) => serde_json::to_value(s),
4070            E::VideoSource(s) => serde_json::to_value(s),
4071            E::AudioPlayout(s) => serde_json::to_value(s),
4072            _ => return None,
4073          }
4074          .ok()
4075          .map(|stats| epoch_fields_relative(stats, wall_ms))
4076        })
4077        .collect();
4078      add_pacer_refusals(&mut stats, core.media.pacer_refusals.get());
4079      Ok(stats)
4080    })
4081  }
4082
4083  /// Runs a media operation on the engine (media.rs), then lets the driver
4084  /// flush what it produced.
4085  pub(crate) fn media<T>(
4086    &self,
4087    f: impl FnOnce(&mut Core) -> Result<T, Error>,
4088  ) -> Result<T, Error> {
4089    let out = self.guarded(f)?;
4090    self.events_ready.notify_one();
4091    self.poke();
4092    Ok(out)
4093  }
4094
4095  /// `close()`: stops the engine, the sockets and the driver. Idempotent.
4096  pub fn close(&self) {
4097    self.shutdown(true);
4098  }
4099
4100  fn shutdown(&self, graceful: bool) {
4101    if self.closed.replace(true) {
4102      return;
4103    }
4104    // Operations still waiting (for the gate, or for the one before them)
4105    // fail as the closed connection's.
4106    let mut unfinished: Vec<u32> = self.current_op.take().into_iter().collect();
4107    let dropped: Vec<_> = self.ops.borrow_mut().drain(..).collect();
4108    unfinished.extend(dropped.iter().map(|(id, _)| *id));
4109    drop(dropped);
4110    self.gate.close();
4111    if graceful && let Ok(mut core) = self.core.try_borrow_mut() {
4112      let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
4113        let now = Instant::now();
4114        let _ = core.pc.close();
4115        core.collect_events(now);
4116        for server in &mut core.servers {
4117          if let Some(relay) = server.relay
4118            && let Ok(mut relay) = server.client.relay(relay)
4119          {
4120            let _ = relay.close(now);
4121          }
4122        }
4123        // A last flush so the peer hears the SCTP abort / DTLS close and a
4124        // TURN allocation is released, then the sockets go.
4125        let writes: Vec<_> =
4126          std::iter::from_fn(|| core.pc.poll_write()).collect();
4127        for msg in writes {
4128          if core.allowed.contains(&msg.transport.peer_addr)
4129            && core
4130              .servers
4131              .iter()
4132              .all(|s| s.relay != Some(msg.transport.local_addr))
4133            && let Some(socket) = core.endpoint_for(msg.transport.local_addr)
4134          {
4135            let _ = socket.try_send_to_ecn(
4136              &msg.message,
4137              msg.transport.peer_addr,
4138              msg.transport.ecn,
4139            );
4140          }
4141        }
4142        let mut udp_writes = Vec::new();
4143        for server in &mut core.servers {
4144          while let Some(tx) = server.client.poll_write() {
4145            match &server.link {
4146              ServerLink::Stream(writer) => {
4147                let _ = writer.send(tx.message.to_vec());
4148              }
4149              ServerLink::Udp => udp_writes.push(tx),
4150            }
4151          }
4152        }
4153        for tx in udp_writes {
4154          if let Some(socket) = core.endpoint_for(tx.transport.local_addr) {
4155            let _ = socket.try_send_to(&tx.message, tx.transport.peer_addr);
4156          }
4157        }
4158      }));
4159    }
4160    if let Ok(mut core) = self.core.try_borrow_mut() {
4161      for op in unfinished {
4162        core.events.push_back(JsEvent::OpDone {
4163          op,
4164          error: Some(Error::new(
4165            ErrorKind::InvalidState,
4166            "RTCPeerConnection is closed".to_string(),
4167          )),
4168        });
4169      }
4170      core.servers.clear();
4171      core.endpoints.clear();
4172      core.tcp_links.clear();
4173      core.tcp_dialing.clear();
4174      core.mdns_socket = None;
4175      if let Some(net) = core.options.network.take() {
4176        net.forget(self);
4177      }
4178    }
4179    self.cancel.cancel();
4180    self.wake.notify_one();
4181    self.events_ready.notify_one();
4182  }
4183
4184  /// An ICE-TCP stream the network accepted for this connection (its first
4185  /// frame, a binding request, named our ufrag).
4186  pub(crate) fn adopt_tcp(
4187    self: &Rc<Self>,
4188    stream: tokio::net::TcpStream,
4189    remote: SocketAddr,
4190    decoder: TcpFrameDecoder,
4191    first: Vec<u8>,
4192  ) {
4193    self.attach_tcp(stream, remote, decoder, Some(first));
4194  }
4195
4196  /// Starts an ICE-TCP connection's reader and writer and makes it the one
4197  /// frames to `remote` go out on (with what waited while it was dialled).
4198  fn attach_tcp(
4199    self: &Rc<Self>,
4200    stream: tokio::net::TcpStream,
4201    remote: SocketAddr,
4202    decoder: TcpFrameDecoder,
4203    first: Option<Vec<u8>>,
4204  ) {
4205    if self.closed.get() {
4206      return;
4207    }
4208    let Ok(local) = stream.local_addr() else {
4209      return;
4210    };
4211    let mut core = self.core.borrow_mut();
4212    let queued = core.tcp_dialing.remove(&remote).unwrap_or_default();
4213    if core.tcp_links.len() >= MAX_TCP_LINKS
4214      && !core.tcp_links.contains_key(&remote)
4215    {
4216      return;
4217    }
4218    core.next_tcp_link += 1;
4219    let id = core.next_tcp_link;
4220    let (writer, rx) = mpsc::channel(TCP_WRITE_QUEUE);
4221    for frame in queued {
4222      let _ = writer.try_send(frame);
4223    }
4224    core.tcp_links.insert(remote, TcpLink { id, writer });
4225    let recv_tx = core.recv_tx.clone();
4226    drop(core);
4227    let (r, w) = stream.into_split();
4228    crate::rt::spawn(
4229      read_ice_tcp(r, local, remote, id, decoder, first, recv_tx)
4230        .or_cancel(self.cancel.clone()),
4231    );
4232    crate::rt::spawn(write_ice_tcp(w, rx).or_cancel(self.cancel.clone()));
4233    self.ensure_driver();
4234    self.poke();
4235  }
4236
4237  fn ensure_driver(self: &Rc<Self>) {
4238    if self.driver_started.replace(true) || self.closed.get() {
4239      return;
4240    }
4241    let Some(rx) = self.core.borrow_mut().recv_rx.take() else {
4242      return;
4243    };
4244    let peer = self.clone();
4245    let cancel = self.cancel.clone();
4246    crate::rt::spawn(async move {
4247      let _ = run_driver(peer, rx).or_cancel(cancel).await;
4248    });
4249  }
4250
4251  /// Binds one UDP socket per family and adds the host candidates, then
4252  /// starts one client per ICE server, once (the first
4253  /// `setLocalDescription`).
4254  /// An ICE restart applied by setLocalDescription: a new gathering phase
4255  /// (RFC 8445 section 9, JSEP section 3.5.1) on the sockets already bound,
4256  /// under the current ICE candidate policy and servers. The engine dropped
4257  /// the previous generation's local candidates when it applied the restart.
4258  fn regather(self: &Rc<Self>) {
4259    let specs = {
4260      let mut core = self.core.borrow_mut();
4261      if core.gathering == GatherPhase::NotStarted {
4262        drop(core);
4263        self.start_gathering();
4264        return;
4265      }
4266      // The new generation's policy, for its paths as for its candidates.
4267      core.relay_generation = core.options.relay_only;
4268      // The first gathering hasn't bound yet: it gathers under the current
4269      // policy and servers when it does.
4270      if core.binds_pending {
4271        return;
4272      }
4273      core.gathering = GatherPhase::Running;
4274      core.failed = false;
4275      core.local_gathered = 0;
4276      core.events.push_back(JsEvent::IceGatheringState {
4277        state: "gathering".to_string(),
4278      });
4279      let opts = core.gather_options();
4280      let gather_names = core.mdns_mode == MdnsMode::Gather;
4281      let endpoints: Vec<(SocketAddr, Vec<IpAddr>)> = core
4282        .endpoints
4283        .iter()
4284        .map(|e| (e.bound, e.hosts.clone()))
4285        .collect();
4286      let mut advertised: HashSet<SocketAddr> = HashSet::new();
4287      for (bound, hosts) in endpoints {
4288        core.announce_udp_hosts(
4289          &opts,
4290          bound,
4291          &hosts,
4292          gather_names,
4293          &mut advertised,
4294        );
4295      }
4296      if !core.options.relay_only {
4297        core.gather_tcp(&opts, gather_names);
4298      }
4299      core.servers.clear();
4300      core.resolving = core.options.ice_servers.len();
4301      core.options.ice_servers.clone()
4302    };
4303    for spec in specs {
4304      let peer = self.clone();
4305      let cancel = self.cancel.clone();
4306      crate::rt::spawn(async move {
4307        let _ = add_server(peer, spec).or_cancel(cancel).await;
4308      });
4309    }
4310    self.poke();
4311  }
4312
4313  fn start_gathering(self: &Rc<Self>) {
4314    let (net, opts) = {
4315      let mut core = self.core.borrow_mut();
4316      if core.gathering != GatherPhase::NotStarted {
4317        return;
4318      }
4319      core.gathering = GatherPhase::Running;
4320      core.relay_generation = core.options.relay_only;
4321      core.binds_pending = true;
4322      core.events.push_back(JsEvent::IceGatheringState {
4323        state: "gathering".to_string(),
4324      });
4325      (core.options.network.clone(), core.gather_options())
4326    };
4327    // Two-phase: the binds wait for the gate (ready at once with a gate
4328    // that decides, which then gathers here, as before).
4329    let finish = Box::pin(Self::finish_gathering(self.clone(), net, opts));
4330    if let Err(pending) = crate::rt::poll_now(finish) {
4331      crate::rt::spawn(pending.or_cancel(self.cancel.clone()));
4332    }
4333  }
4334
4335  /// [`Peer::start_gathering`] once the gate answered for the binds.
4336  async fn finish_gathering(
4337    self: Rc<Self>,
4338    net: Option<Rc<Network>>,
4339    opts: NetworkOptions,
4340  ) {
4341    let plan = match net.as_ref().filter(|n| n.is_shared()) {
4342      Some(_) => None,
4343      None => Some(
4344        crate::net::bind_plan(
4345          &opts,
4346          &crate::gate_cache::Verdicts::Cache(self.gate.clone()),
4347          Proto::Udp,
4348        )
4349        .await,
4350      ),
4351    };
4352    if self.closed.get() {
4353      return;
4354    }
4355    let specs = {
4356      let mut core = self.core.borrow_mut();
4357      core.binds_pending = false;
4358      // (socket, bound address, host candidate addresses, own reader)
4359      let mut planned: Vec<(Rc<EcnUdpSocket>, SocketAddr, Vec<IpAddr>, bool)> =
4360        Vec::new();
4361      match (net.as_ref().filter(|n| n.is_shared()), plan) {
4362        (Some(net), _) => {
4363          for e in &net.shared {
4364            planned.push((e.socket.clone(), e.bound, e.hosts.clone(), false));
4365          }
4366        }
4367        (None, None) => {}
4368        (None, Some(plan)) => match plan {
4369          Ok((plan, notes)) => {
4370            for note in notes {
4371              core.report_error("", None, ERROR_CODE_UNREACHABLE, note);
4372            }
4373            for (bind, hosts, token) in plan {
4374              let socket = match opts.port_range {
4375                Some(range) => {
4376                  crate::net::bind_in_range(&*core.io, &token, bind, range)
4377                }
4378                None => {
4379                  let addr = SocketAddr::new(bind, 0);
4380                  core.io.bind_udp(&token, addr, UdpOpts::for_addr(addr))
4381                }
4382              };
4383              let socket = match socket {
4384                Ok(s) => Rc::new(EcnUdpSocket::new(s)),
4385                Err(e) => {
4386                  core.report_error(
4387                    "",
4388                    Some(SocketAddr::new(bind, 0)),
4389                    ERROR_CODE_UNREACHABLE,
4390                    e.to_string(),
4391                  );
4392                  continue;
4393                }
4394              };
4395              let Ok(bound) = socket.local_addr() else {
4396                continue;
4397              };
4398              planned.push((socket, bound, hosts, true));
4399            }
4400          }
4401          Err(e) => {
4402            core.report_error("", None, ERROR_CODE_UNREACHABLE, e.to_string())
4403          }
4404        },
4405      }
4406
4407      let mut advertised: HashSet<SocketAddr> = HashSet::new();
4408      let gather_names = core.mdns_mode == MdnsMode::Gather;
4409      for (socket, bound, hosts, own_reader) in planned {
4410        if own_reader {
4411          spawn_udp_reader(
4412            socket.clone(),
4413            bound,
4414            core.recv_tx.clone(),
4415            self.cancel.clone(),
4416          );
4417        }
4418        core.announce_udp_hosts(
4419          &opts,
4420          bound,
4421          &hosts,
4422          gather_names,
4423          &mut advertised,
4424        );
4425        core.endpoints.push(UdpEndpoint {
4426          socket,
4427          bound,
4428          hosts,
4429        });
4430      }
4431      if !core.options.relay_only {
4432        core.gather_tcp(&opts, gather_names);
4433      }
4434      core.resolving = core.options.ice_servers.len();
4435      core.options.ice_servers.clone()
4436    };
4437    for spec in specs {
4438      let peer = self.clone();
4439      let cancel = self.cancel.clone();
4440      crate::rt::spawn(async move {
4441        let _ = add_server(peer, spec).or_cancel(cancel).await;
4442      });
4443    }
4444    self.poke();
4445  }
4446}
4447
4448/// The host addresses candidates are gathered on: all of them, except that a
4449/// connection publishing mDNS names leaves out loopback when it has another
4450/// address (a name for 127.0.0.1 would send a LAN peer to itself).
4451fn published_hosts(hosts: &[IpAddr], gather_names: bool) -> Vec<IpAddr> {
4452  if gather_names && hosts.iter().any(|ip| !ip.is_loopback()) {
4453    hosts
4454      .iter()
4455      .copied()
4456      .filter(|ip| !ip.is_loopback())
4457      .collect()
4458  } else {
4459    hosts.to_vec()
4460  }
4461}
4462
4463/// Dials a remote passive ICE-TCP candidate, from `bind` when given.
4464async fn connect_tcp(
4465  io: &dyn NetIo,
4466  token: &GateToken,
4467  bind: Option<IpAddr>,
4468  to: SocketAddr,
4469) -> std::io::Result<tokio::net::TcpStream> {
4470  let bind = bind.filter(|ip| ip.is_ipv4() == to.is_ipv4());
4471  let stream = io.connect_tcp(token, bind, to, None).await?;
4472  let _ = stream.set_nodelay(true);
4473  Ok(stream)
4474}
4475
4476/// Reads RFC 4571 frames off an ICE-TCP connection into the driver's queue
4477/// (waiting when it is full: a stream pushes back instead of dropping), then
4478/// tells the driver the connection ended.
4479async fn read_ice_tcp<R: tokio::io::AsyncRead + Unpin>(
4480  mut reader: R,
4481  local: SocketAddr,
4482  remote: SocketAddr,
4483  id: u64,
4484  mut decoder: TcpFrameDecoder,
4485  first: Option<Vec<u8>>,
4486  tx: mpsc::Sender<Datagram>,
4487) {
4488  let datagram = |data: BytesMut, closed: Option<String>| Datagram {
4489    local,
4490    from: remote,
4491    stream: None,
4492    via: Via::IceTcp(id),
4493    data,
4494    closed,
4495    ecn: None,
4496  };
4497  if let Some(frame) = first
4498    && tx
4499      .send(datagram(BytesMut::from(&frame[..]), None))
4500      .await
4501      .is_err()
4502  {
4503    return;
4504  }
4505  let mut chunk = vec![0u8; RECV_BUFFER_SIZE];
4506  let reason = 'read: loop {
4507    while let Some(frame) = decoder.next_packet() {
4508      if tx
4509        .send(datagram(BytesMut::from(&frame[..]), None))
4510        .await
4511        .is_err()
4512      {
4513        return;
4514      }
4515    }
4516    let n = match reader.read(&mut chunk).await {
4517      Ok(0) => break 'read "the peer closed the connection".to_string(),
4518      Err(e) => break 'read e.to_string(),
4519      Ok(n) => n,
4520    };
4521    if decoder.push(&chunk[..n]).is_err() {
4522      break 'read "the peer sent more than it framed".to_string();
4523    }
4524  };
4525  let _ = tx.send(datagram(BytesMut::new(), Some(reason))).await;
4526}
4527
4528/// Writes queued RFC 4571 frames to an ICE-TCP connection.
4529async fn write_ice_tcp<W: tokio::io::AsyncWrite + Unpin>(
4530  mut writer: W,
4531  mut rx: mpsc::Receiver<Vec<u8>>,
4532) {
4533  while let Some(frame) = rx.recv().await {
4534    if writer.write_all(&frame).await.is_err() {
4535      let _ = writer.shutdown().await;
4536      return;
4537    }
4538  }
4539}
4540
4541fn spawn_udp_reader(
4542  socket: Rc<EcnUdpSocket>,
4543  local: SocketAddr,
4544  tx: mpsc::Sender<Datagram>,
4545  cancel: Cancel,
4546) {
4547  spawn_udp_reader_via(socket, local, tx, cancel, Via::Socket);
4548}
4549
4550fn spawn_udp_reader_via(
4551  socket: Rc<EcnUdpSocket>,
4552  local: SocketAddr,
4553  tx: mpsc::Sender<Datagram>,
4554  cancel: Cancel,
4555  via: Via,
4556) {
4557  crate::rt::spawn(
4558    async move {
4559      let mut buf = vec![0u8; RECV_BUFFER_SIZE];
4560      loop {
4561        match socket.recv_from(&mut buf).await {
4562          Ok((n, from, ecn)) => {
4563            let dg = Datagram {
4564              local,
4565              from,
4566              stream: None,
4567              via,
4568              data: BytesMut::from(&buf[..n]),
4569              closed: None,
4570              ecn,
4571            };
4572            if let Err(mpsc::error::TrySendError::Closed(_)) = tx.try_send(dg) {
4573              break;
4574            }
4575          }
4576          Err(e) => {
4577            // ICMP port unreachable surfaces as a read error on some
4578            // platforms (Windows' WSAECONNRESET); keep reading.
4579            log::debug!("webrtc: recv on {local}: {e}");
4580            tokio::time::sleep(Duration::from_millis(1)).await;
4581          }
4582        }
4583      }
4584    }
4585    .or_cancel(cancel),
4586  );
4587}
4588
4589/// Reads RFC 6544 frames off a TURN server stream into the driver's queue;
4590/// when the stream ends, tells the driver why.
4591async fn read_stream<R: tokio::io::AsyncRead + Unpin>(
4592  mut reader: R,
4593  local: SocketAddr,
4594  server: SocketAddr,
4595  index: usize,
4596  tx: mpsc::Sender<Datagram>,
4597) {
4598  let mut buf: Vec<u8> = Vec::with_capacity(RECV_BUFFER_SIZE);
4599  let mut chunk = vec![0u8; RECV_BUFFER_SIZE];
4600  let reason = 'read: loop {
4601    let n = match reader.read(&mut chunk).await {
4602      Ok(0) => break 'read "the server closed the connection".to_string(),
4603      Err(e) => break 'read e.to_string(),
4604      Ok(n) => n,
4605    };
4606    buf.extend_from_slice(&chunk[..n]);
4607    loop {
4608      match stream_frame_len(&buf) {
4609        None => break 'read "the server sent a malformed frame".to_string(),
4610        Some(0) => break,
4611        Some(len) => {
4612          let frame: Vec<u8> = buf.drain(..len).collect();
4613          let dg = Datagram {
4614            local,
4615            from: server,
4616            stream: Some(index),
4617            via: Via::Socket,
4618            data: BytesMut::from(&frame[..]),
4619            closed: None,
4620            ecn: None,
4621          };
4622          if tx.send(dg).await.is_err() {
4623            return;
4624          }
4625        }
4626      }
4627    }
4628  };
4629  let _ = tx
4630    .send(Datagram {
4631      local,
4632      from: server,
4633      stream: Some(index),
4634      via: Via::Socket,
4635      data: BytesMut::new(),
4636      closed: Some(reason),
4637      ecn: None,
4638    })
4639    .await;
4640}
4641
4642async fn write_stream<W: tokio::io::AsyncWrite + Unpin>(
4643  mut writer: W,
4644  mut rx: mpsc::UnboundedReceiver<Vec<u8>>,
4645) {
4646  // A failed write also ends the read side, which reports it.
4647  while let Some(frame) = rx.recv().await {
4648    if writer.write_all(&frame).await.is_err() {
4649      let _ = writer.shutdown().await;
4650      return;
4651    }
4652  }
4653}
4654
4655/// Opens the TCP (or TLS) connection to a stream TURN server and starts its
4656/// reader and writer; returns the writer's queue and the local address.
4657async fn connect_stream(
4658  peer: &Rc<Peer>,
4659  token: &GateToken,
4660  spec: &IceServerSpec,
4661  server: SocketAddr,
4662  index: usize,
4663) -> Result<(mpsc::UnboundedSender<Vec<u8>>, SocketAddr), String> {
4664  let io = peer.core.borrow().io.clone();
4665  let tcp = io
4666    .connect_tcp(token, None, server, Some(&spec.host))
4667    .await
4668    .map_err(|e| format!("Could not connect to {}: {e}", spec.url))?;
4669  let _ = tcp.set_nodelay(true);
4670  let local = tcp.local_addr().map_err(|e| e.to_string())?;
4671  let (writer_tx, writer_rx) = mpsc::unbounded_channel();
4672  let recv_tx = peer.core.borrow().recv_tx.clone();
4673  let cancel = peer.cancel.clone();
4674  match spec.transport {
4675    ServerTransport::Tls => {
4676      let config = peer
4677        .core
4678        .borrow()
4679        .options
4680        .tls
4681        .clone()
4682        .ok_or_else(|| "TLS is not available here".to_string())?;
4683      let name = rustls::pki_types::ServerName::try_from(spec.host.clone())
4684        .map_err(|e| e.to_string())?;
4685      let conn = rustls::ClientConnection::new(config, name)
4686        .map_err(|e| e.to_string())?;
4687      let mut stream =
4688        rustls_tokio_stream::TlsStream::new_client_side(tcp, conn, None);
4689      // Handshake first, so a refused certificate is reported now rather
4690      // than as a request timeout.
4691      stream
4692        .handshake()
4693        .await
4694        .map_err(|e| format!("TLS handshake with {} failed: {e}", spec.url))?;
4695      let (r, w) = stream.into_split();
4696      crate::rt::spawn(
4697        read_stream(r, local, server, index, recv_tx).or_cancel(cancel.clone()),
4698      );
4699      crate::rt::spawn(write_stream(w, writer_rx).or_cancel(cancel));
4700    }
4701    _ => {
4702      let (r, w) = tcp.into_split();
4703      crate::rt::spawn(
4704        read_stream(r, local, server, index, recv_tx).or_cancel(cancel.clone()),
4705      );
4706      crate::rt::spawn(write_stream(w, writer_rx).or_cancel(cancel));
4707    }
4708  }
4709  Ok((writer_tx, local))
4710}
4711
4712/// Resolves one ICE server and starts its client.
4713async fn add_server(peer: Rc<Peer>, spec: IceServerSpec) {
4714  let finish = |peer: &Rc<Peer>, error: Option<String>| {
4715    let mut core = peer.core.borrow_mut();
4716    core.resolving = core.resolving.saturating_sub(1);
4717    if let Some(text) = error {
4718      core.report_error(&spec.url, None, ERROR_CODE_UNREACHABLE, text);
4719    }
4720    drop(core);
4721    peer.poke();
4722  };
4723  let proto = match spec.transport {
4724    ServerTransport::Udp => Proto::Udp,
4725    ServerTransport::Tcp => Proto::Tcp,
4726    ServerTransport::Tls => Proto::Tls,
4727  };
4728  // The URL's host before DNS (a front end may have asked already, before
4729  // the constructor: then a cache hit, or the synchronous gate again).
4730  let token = match peer
4731    .gate
4732    .verdict(Reach::ice_server(proto, &spec.host, spec.port))
4733    .await
4734  {
4735    Ok(token) => token,
4736    Err(message) => {
4737      finish(&peer, Some(message));
4738      return;
4739    }
4740  };
4741  let io = peer.core.borrow().io.clone();
4742  let resolved: Vec<SocketAddr> =
4743    match io.resolve(&token, &spec.host, spec.port).await {
4744      Ok(addrs) => addrs,
4745      Err(e) => {
4746        finish(&peer, Some(format!("Could not resolve {}: {e}", spec.host)));
4747        return;
4748      }
4749    };
4750  // A family the connection has a socket for (UDP), or any (TCP/TLS).
4751  let server = {
4752    let core = peer.core.borrow();
4753    resolved.iter().copied().find(|server| {
4754      spec.transport != ServerTransport::Udp
4755        || core.endpoints.iter().any(|e| {
4756          e.bound.is_ipv4() == server.is_ipv4()
4757            && (!e.bound.ip().is_loopback() || server.ip().is_loopback())
4758        })
4759    })
4760  };
4761  let Some(server) = server else {
4762    finish(
4763      &peer,
4764      Some(format!(
4765        "No local address can reach {} (interface enumeration or the \
4766         wildcard listen permission may be denied)",
4767        spec.host
4768      )),
4769    );
4770    return;
4771  };
4772  // The address it resolved to must not be denied either.
4773  let reach = Reach {
4774    resolved_from: Some(spec.host.clone()),
4775    ..Reach::connect(ReachKind::IceServerResolved, proto, server)
4776  };
4777  let token = match peer.gate.verdict(reach).await {
4778    Ok(token) => token,
4779    Err(message) => {
4780      finish(&peer, Some(message));
4781      return;
4782    }
4783  };
4784  if peer.closed.get() {
4785    return;
4786  }
4787  let shared = peer
4788    .core
4789    .borrow()
4790    .options
4791    .network
4792    .as_ref()
4793    .is_some_and(|n| n.is_shared());
4794  if shared && spec.turn && spec.transport == ServerTransport::Udp {
4795    finish(
4796      &peer,
4797      Some(
4798        "TURN over UDP isn't available on a shared-port Deno.webrtc.Network \
4799         (use ?transport=tcp or turns:)"
4800          .to_string(),
4801      ),
4802    );
4803    return;
4804  }
4805  let index = peer.core.borrow().servers.len();
4806  let (link, base) = match spec.transport {
4807    ServerTransport::Udp => {
4808      let base = {
4809        let mut core = peer.core.borrow_mut();
4810        let Some(endpoint) = core
4811          .endpoints
4812          .iter()
4813          .position(|e| e.bound.is_ipv4() == server.is_ipv4())
4814        else {
4815          drop(core);
4816          finish(&peer, Some("No UDP socket for this family".to_string()));
4817          return;
4818        };
4819        // The permission gate allowed `server` above.
4820        core.local_address(endpoint, server, true)
4821      };
4822      (ServerLink::Udp, base)
4823    }
4824    ServerTransport::Tcp | ServerTransport::Tls => {
4825      if !spec.turn {
4826        // A server-reflexive address over TCP describes the TCP mapping,
4827        // useless to a UDP agent.
4828        finish(&peer, None);
4829        return;
4830      }
4831      match connect_stream(&peer, &token, &spec, server, index).await {
4832        Ok((tx, local)) => (ServerLink::Stream(tx), local),
4833        Err(text) => {
4834          finish(&peer, Some(text));
4835          return;
4836        }
4837      }
4838    }
4839  };
4840  if peer.closed.get() {
4841    return;
4842  }
4843  let protocol = match link {
4844    ServerLink::Udp => TransportProtocol::UDP,
4845    ServerLink::Stream(_) => TransportProtocol::TCP,
4846  };
4847  let config = TurnClientConfig {
4848    stun_serv_addr: server.to_string(),
4849    turn_serv_addr: if spec.turn {
4850      server.to_string()
4851    } else {
4852      String::new()
4853    },
4854    local_addr: base,
4855    transport_protocol: protocol,
4856    username: spec.username.clone(),
4857    password: spec.credential.clone(),
4858    realm: String::new(),
4859    software: String::new(),
4860    rto_in_ms: 0,
4861    allocation_refresh_interval_cap: None,
4862    // The default timer (RFC 8489 section 6.2.1) and every password
4863    // algorithm the client implements (SHA-256, and MD5 for RFC 5389
4864    // servers).
4865    ..TurnClientConfig::default()
4866  };
4867  let provider = match rtci::crypto::default_provider() {
4868    Ok(p) => p,
4869    Err(e) => {
4870      finish(&peer, Some(e.to_string()));
4871      return;
4872    }
4873  };
4874  let client = match TurnClient::new(config, provider) {
4875    Ok(c) => c,
4876    Err(e) => {
4877      finish(&peer, Some(e.to_string()));
4878      return;
4879    }
4880  };
4881  {
4882    let mut core = peer.core.borrow_mut();
4883    // A server, not a remote candidate (ICE stays `new` without one).
4884    core.allowed.insert(server);
4885    let now = Instant::now();
4886    let mut entry = ServerClient {
4887      url: spec.url.clone(),
4888      client,
4889      base,
4890      server,
4891      link,
4892      binding: None,
4893      allocate: None,
4894      relay: None,
4895    };
4896    if matches!(entry.link, ServerLink::Udp) {
4897      entry.binding = entry.client.send_binding_request(now).ok();
4898    }
4899    if spec.turn {
4900      entry.allocate = entry.client.allocate(now).ok();
4901    }
4902    core.servers.push(entry);
4903  }
4904  finish(&peer, None);
4905}
4906
4907async fn run_driver(peer: Rc<Peer>, mut rx: mpsc::Receiver<Datagram>) {
4908  loop {
4909    if peer.closed.get() {
4910      break;
4911    }
4912    let pumped = std::panic::catch_unwind(AssertUnwindSafe(|| {
4913      let mut core = peer.core.borrow_mut();
4914      core.pump();
4915      (!core.events.is_empty(), core.next_deadline())
4916    }));
4917    let Ok((has_events, deadline)) = pumped else {
4918      peer.poison();
4919      break;
4920    };
4921    if has_events {
4922      peer.events_ready.notify_one();
4923    }
4924    let sleep = async {
4925      match deadline {
4926        Some(d) => {
4927          tokio::time::sleep_until(tokio::time::Instant::from_std(d)).await
4928        }
4929        None => std::future::pending::<()>().await,
4930      }
4931    };
4932    let step = tokio::select! {
4933      _ = peer.wake.notified() => None,
4934      dg = rx.recv() => match dg {
4935        Some(dg) => Some(Some(dg)),
4936        None => break,
4937      },
4938      _ = sleep => Some(None),
4939    };
4940    let handled = std::panic::catch_unwind(AssertUnwindSafe(|| {
4941      let mut core = peer.core.borrow_mut();
4942      match step {
4943        Some(Some(dg)) => {
4944          core.handle_datagram(dg);
4945          // Whatever else already arrived goes in before the next pump.
4946          while let Ok(dg) = rx.try_recv() {
4947            core.handle_datagram(dg);
4948          }
4949        }
4950        Some(None) => core.handle_timeout(Instant::now()),
4951        None => {}
4952      }
4953    }));
4954    if handled.is_err() {
4955      peer.poison();
4956      break;
4957    }
4958  }
4959}
4960
4961#[cfg(test)]
4962pub(crate) fn frame_len_for_tests(buf: &[u8]) -> Option<usize> {
4963  stream_frame_len(buf)
4964}
4965
4966#[cfg(test)]
4967impl Peer {
4968  pub(crate) fn selected_for_tests(&self) -> Option<(SocketAddr, SocketAddr)> {
4969    self.core.borrow().selected
4970  }
4971
4972  pub(crate) fn selected_is_tcp_for_tests(&self) -> bool {
4973    let core = self.core.borrow();
4974    core.selected.is_some() && core.selected_tcp
4975  }
4976
4977  pub(crate) fn mdns_open_for_tests(&self) -> bool {
4978    self.core.borrow().mdns_socket.is_some()
4979  }
4980}
4981
4982#[cfg(test)]
4983impl Core {
4984  /// Test hook: a wildcard UDP endpoint on `socket` with these host
4985  /// addresses; returns its index.
4986  pub(crate) fn add_endpoint_for_test(
4987    &mut self,
4988    socket: tokio::net::UdpSocket,
4989    hosts: Vec<IpAddr>,
4990  ) -> usize {
4991    let bound = socket.local_addr().unwrap();
4992    self.endpoints.push(UdpEndpoint {
4993      socket: Rc::new(EcnUdpSocket::new(socket)),
4994      bound,
4995      hosts,
4996    });
4997    self.endpoints.len() - 1
4998  }
4999
5000  /// Test hook: one datagram through the driver's receive path.
5001  pub(crate) fn handle_datagram_for_test(&mut self, dg: Datagram) {
5002    self.handle_datagram(dg);
5003  }
5004
5005  /// Test hook: how many peer routes are cached.
5006  pub(crate) fn route_count_for_test(&self) -> usize {
5007    self.routes.len()
5008  }
5009
5010  /// Test hook: a send of `datagram` on `transport` was refused for its
5011  /// size.
5012  pub(crate) fn datagram_too_big_for_test(
5013    &mut self,
5014    transport: TransportContext,
5015    datagram: &[u8],
5016  ) {
5017    self.datagram_too_big(transport, datagram);
5018  }
5019}
5020
5021#[cfg(test)]
5022mod relayed_tests {
5023  use super::*;
5024
5025  fn sent(
5026    relay: SocketAddr,
5027    peer: SocketAddr,
5028    datagram: &[u8],
5029  ) -> RelayedWrite {
5030    let len = datagram.len().min(RELAYED_HEAD);
5031    let mut head = [0; RELAYED_HEAD];
5032    head[..len].copy_from_slice(&datagram[..len]);
5033    RelayedWrite {
5034      relay,
5035      peer,
5036      head,
5037      len,
5038    }
5039  }
5040
5041  // A TURN message refused for its size is traced to the relayed datagram
5042  // it carries (ChannelData: a 4-byte header, then the datagram) and so to
5043  // the path the engine sent it on; a message carrying none of the
5044  // remembered datagrams, or one from another relayed address, to none.
5045  #[test]
5046  fn a_refused_turn_message_names_the_relayed_datagram_it_carried() {
5047    let relay: SocketAddr = "198.51.100.1:50000".parse().unwrap();
5048    let other_relay: SocketAddr = "198.51.100.2:50000".parse().unwrap();
5049    let peer_a: SocketAddr = "203.0.113.1:4000".parse().unwrap();
5050    let peer_b: SocketAddr = "203.0.113.2:4000".parse().unwrap();
5051    let dtls: Vec<u8> = (0..200u32).map(|i| (i * 7 + 23) as u8).collect();
5052    let srtp: Vec<u8> = (0..300u32).map(|i| (i * 13 + 128) as u8).collect();
5053    let mut recent = VecDeque::new();
5054    recent.push_back(sent(relay, peer_a, &dtls));
5055    recent.push_back(sent(relay, peer_b, &srtp));
5056    let mut channel_data = vec![0x40, 0x00, 0x00, 0xc8];
5057    channel_data.extend_from_slice(&dtls);
5058    let found = find_relayed(&recent, relay, &channel_data).unwrap();
5059    assert_eq!(found.peer, peer_a);
5060    assert_eq!(found.head(), &dtls[..RELAYED_HEAD]);
5061    assert!(is_dtls(found.head()));
5062    let mut channel_data = vec![0x40, 0x01, 0x01, 0x2c];
5063    channel_data.extend_from_slice(&srtp);
5064    let found = find_relayed(&recent, relay, &channel_data).unwrap();
5065    assert_eq!(found.peer, peer_b);
5066    assert!(!is_dtls(found.head()));
5067    assert!(find_relayed(&recent, other_relay, &channel_data).is_none());
5068    assert!(
5069      find_relayed(&recent, relay, &[0x40, 0, 0, 4, 1, 2, 3, 4]).is_none()
5070    );
5071  }
5072
5073  // Too short a datagram is not remembered usefully: a match of a few
5074  // octets could be anything in the message.
5075  #[test]
5076  fn a_short_relayed_datagram_matches_nothing() {
5077    let relay: SocketAddr = "198.51.100.1:50000".parse().unwrap();
5078    let peer: SocketAddr = "203.0.113.1:4000".parse().unwrap();
5079    let mut recent = VecDeque::new();
5080    recent.push_back(sent(relay, peer, &[22, 254, 253]));
5081    assert!(
5082      find_relayed(&recent, relay, &[0x40, 0, 0, 3, 22, 254, 253]).is_none()
5083    );
5084  }
5085}