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 connection itself, for a shared-port network's routes.
850  this: Weak<Peer>,
851  /// The socket factory (every socket the connection opens).
852  pub(crate) io: Rc<dyn NetIo>,
853  /// The permission gate, with the answers it gave this connection.
854  gate: Rc<GateCache>,
855  /// ICE-TCP connections by remote address.
856  tcp_links: HashMap<SocketAddr, TcpLink>,
857  /// Remote passive candidates being dialled, with the frames waiting for
858  /// the connection.
859  tcp_dialing: HashMap<SocketAddr, Vec<Vec<u8>>>,
860  next_tcp_link: u64,
861  /// The selected pair is an ICE-TCP one.
862  selected_tcp: bool,
863  /// What this connection does with `.local` candidates (`Off` when mDNS
864  /// can't be used here: loopback only, or a permission refused).
865  mdns_mode: MdnsMode,
866  /// The mDNS socket, once opened.
867  mdns_socket: Option<Rc<EcnUdpSocket>>,
868  /// Opening the mDNS socket failed (reported once), or the gate refused
869  /// it.
870  mdns_failed: bool,
871  /// The gate's allow for the mDNS socket, once it gave one.
872  mdns_token: Option<GateToken>,
873  /// 1:1 NAT in host mode is the engine's (`with_nat_1to1_ips`): a host
874  /// candidate is added on its private address and announced on the public
875  /// one, its base staying the private socket, so the addresses the engine
876  /// reads and writes on are the sockets' own. Off with mDNS names (the
877  /// engine can't map a name), where the public address is signalled here.
878  engine_nat: bool,
879  /// The remote description's `a=simulcast` lines the engine was given
880  /// without a repeated rid-id, each with the line as signalled
881  /// ([`simulcast_without_repeated_rids`]): `remoteDescription` shows the
882  /// signalled one.
883  remote_simulcast_lines: Vec<(String, String)>,
884}
885
886/// One candidate of [`SelectedPair`], with the fields JavaScript needs to
887/// build the `RTCIceCandidate` (a peer-reflexive remote candidate is exposed
888/// without its address, so it can't be found among the signalled ones).
889#[derive(serde::Serialize, Debug)]
890#[serde(rename_all = "camelCase")]
891pub struct PairCandidate {
892  /// `ip:port` (`[ip]:port` for IPv6), as the signalled candidates are matched.
893  pub addr: String,
894  pub address: String,
895  pub port: u16,
896  pub protocol: String,
897  #[serde(rename = "type")]
898  pub typ: String,
899  pub foundation: String,
900  pub priority: u32,
901  pub related_address: String,
902  pub related_port: u16,
903}
904
905impl PairCandidate {
906  pub(crate) fn of(
907    c: &rtci::peer_connection::transport::RTCIceCandidate,
908  ) -> Self {
909    let addr = match c.address.parse::<IpAddr>() {
910      Ok(IpAddr::V6(ip)) => format!("[{ip}]:{}", c.port),
911      Ok(IpAddr::V4(ip)) => format!("{ip}:{}", c.port),
912      Err(_) => format!("{}:{}", c.address, c.port),
913    };
914    Self {
915      addr,
916      address: c.address.clone(),
917      port: c.port,
918      protocol: c.protocol.to_string(),
919      typ: c.typ.to_string(),
920      foundation: c.foundation.clone(),
921      priority: c.priority,
922      related_address: c.related_address.clone(),
923      related_port: c.related_port,
924    }
925  }
926}
927
928/// The ICE agent's selected candidate pair.
929#[derive(serde::Serialize, Debug)]
930pub struct SelectedPair {
931  pub local: PairCandidate,
932  pub remote: PairCandidate,
933}
934
935/// The four description slots of a connection, each `(type, sdp)`.
936#[derive(serde::Serialize)]
937#[serde(rename_all = "camelCase")]
938pub struct PeerDescriptions {
939  pub current_local: Option<(String, String)>,
940  pub pending_local: Option<(String, String)>,
941  pub current_remote: Option<(String, String)>,
942  pub pending_remote: Option<(String, String)>,
943}
944
945pub struct Peer {
946  pub(crate) core: RefCell<Core>,
947  /// The permission gate, with the answers it gave this connection.
948  gate: Rc<GateCache>,
949  /// `setRemoteDescription` / `addIceCandidate` operations waiting, in
950  /// order, for the gate (or for the one before them).
951  ops: RefCell<VecDeque<(u32, PendingOp)>>,
952  /// The operation the ops task is running, if any.
953  current_op: Cell<Option<u32>>,
954  /// The ops task is running.
955  ops_running: Cell<bool>,
956  last_op: Cell<u32>,
957  /// Ops -> driver: there is something to flush.
958  wake: Notify,
959  /// Driver -> `op_webrtc_pc_next_events`: `core.events` is not empty.
960  events_ready: Notify,
961  cancel: Cancel,
962  closed: Cell<bool>,
963  driver_started: Cell<bool>,
964}
965
966/// A queued two-phase operation (its outcome is the `opdone` event).
967type PendingOp = LocalBoxFuture<'static, Result<(), Error>>;
968
969/// When a remote description's line is given to the engine.
970enum Keep {
971  Always,
972  /// A candidate whose address the gate must allow (else the call fails).
973  Allowed(Reach),
974  /// A `.local` candidate: when the connection can resolve it.
975  Mdns,
976}
977
978pub(crate) fn rtc_err(e: impl std::fmt::Display) -> Error {
979  Error::new(ErrorKind::Operation, e.to_string())
980}
981
982/// The largest session description handed to the engine, in bytes (the
983/// engine's own `MAX_SDP_SIZE`, 1 MiB).
984pub(crate) const MAX_SDP_BYTES: usize = 1 << 20;
985
986/// Refuses an offer, answer or pranswer longer than [`MAX_SDP_BYTES`] before
987/// anything reads it, with the OperationError a description the engine can't
988/// parse gets. A rollback's text is ignored, and an unknown type stays the
989/// TypeError `description` reports.
990pub(crate) fn check_sdp_size(kind: &str, sdp: &str) -> Result<(), Error> {
991  if matches!(kind, "offer" | "answer" | "pranswer")
992    && sdp.len() > MAX_SDP_BYTES
993  {
994    return Err(Error::new(
995      ErrorKind::Operation,
996      format!(
997        "session description of {} bytes exceeds {MAX_SDP_BYTES}",
998        sdp.len()
999      ),
1000    ));
1001  }
1002  Ok(())
1003}
1004
1005/// Whether an SDP has an m-section that isn't rejected: port zero without
1006/// `a=bundle-only` is a rejected one (RFC 8843 ยง6).
1007pub(crate) fn has_live_media_section(sdp: &str) -> bool {
1008  sdp.split("\nm=").skip(1).any(|section| {
1009    let port = section.split_ascii_whitespace().nth(1);
1010    port != Some("0") || section.contains("a=bundle-only")
1011  })
1012}
1013
1014/// An engine error applying a description: a type the signaling state
1015/// doesn't take (RFC 9429 ยง5.5 / ยง5.6) is an InvalidStateError (W3C "set the
1016/// RTCSessionDescription", step 4); anything else an OperationError.
1017fn description_err(e: RtcError) -> Error {
1018  match e {
1019    RtcError::ErrSignalingStateCannotRollback
1020    | RtcError::ErrSignalingStateProposedTransitionInvalid(_) => {
1021      Error::new(ErrorKind::InvalidState, e.to_string())
1022    }
1023    // A description the engine can't apply as written (the legacy
1024    // InvalidAccessError browsers and the WPT keep).
1025    RtcError::ErrSessionDescriptionInvalidIceCredentials => {
1026      Error::new(ErrorKind::InvalidAccess, e.to_string())
1027    }
1028    e => rtc_err(e),
1029  }
1030}
1031
1032/// The candidate's transport, address and port, from a candidate attribute
1033/// value (`candidate:<foundation> <component> <transport> <priority>
1034/// <address> <port> typ ...`).
1035pub fn candidate_address(candidate: &str) -> Option<(String, String, u16)> {
1036  let value = candidate
1037    .trim()
1038    .strip_prefix("a=")
1039    .unwrap_or(candidate.trim());
1040  let value = value.strip_prefix("candidate:").unwrap_or(value);
1041  let mut fields = value.split_ascii_whitespace();
1042  let _foundation = fields.next()?;
1043  let _component = fields.next()?;
1044  let transport = fields.next()?.to_ascii_lowercase();
1045  let _priority = fields.next()?;
1046  let address = fields.next()?.to_string();
1047  let port = fields.next()?.parse().ok()?;
1048  Some((transport, address, port))
1049}
1050
1051/// What to do with a remote candidate before the engine sees it.
1052#[derive(Debug, PartialEq, Eq)]
1053pub enum RemoteCandidate {
1054  /// A UDP candidate with a literal address: check it, then add it.
1055  Udp(SocketAddr),
1056  /// A passive (or simultaneous-open) TCP candidate with a literal address,
1057  /// on a connection doing ICE over TCP: check it, then add it.
1058  Tcp(SocketAddr),
1059  /// An mDNS `.local` host candidate, on a connection that resolves them:
1060  /// the engine resolves it, and the address it resolves to is checked
1061  /// against the net permission before anything is sent there.
1062  Mdns,
1063  /// An active TCP candidate, on a connection doing ICE over TCP: handed
1064  /// to the engine unchecked, since nothing is sent to it (its port is RFC
1065  /// 6544's placeholder 9; the peer dials our passive candidate). The
1066  /// engine's check list then waits at end-of-candidates for that dial
1067  /// rather than failing with no pair (RFC 8838 section 8), until its
1068  /// checking timeout.
1069  Active,
1070  /// Skipped and reported as accepted, as a browser does with a candidate it
1071  /// cannot use: TCP candidates without ICE over TCP (a `tcpPort` network),
1072  /// untyped TCP candidates, and `.local` names when mDNS is off (such a
1073  /// peer is still reached as a peer-reflexive candidate once its checks
1074  /// arrive).
1075  Ignore,
1076}
1077
1078/// The `tcptype` of a candidate attribute value, if it has one.
1079fn candidate_tcp_type(candidate: &str) -> Option<TcpType> {
1080  let mut fields = candidate.split_ascii_whitespace();
1081  while let Some(field) = fields.next() {
1082    if field.eq_ignore_ascii_case("tcptype") {
1083      return fields
1084        .next()
1085        .map(|t| TcpType::from(t.to_ascii_lowercase().as_str()));
1086    }
1087  }
1088  None
1089}
1090
1091/// Classifies a remote candidate for a connection that does (`tcp`) or
1092/// doesn't do ICE over TCP, and does (`mdns`) or doesn't resolve `.local`
1093/// names.
1094pub fn classify_remote_candidate(
1095  candidate: &str,
1096  tcp: bool,
1097  mdns: bool,
1098) -> Result<RemoteCandidate, Error> {
1099  let Some((transport, address, port)) = candidate_address(candidate) else {
1100    return Err(Error::new(
1101      ErrorKind::Operation,
1102      format!("Invalid ICE candidate '{candidate}'"),
1103    ));
1104  };
1105  let is_tcp = match transport.as_str() {
1106    "udp" => false,
1107    "tcp" if tcp => true,
1108    _ => return Ok(RemoteCandidate::Ignore),
1109  };
1110  if is_tcp {
1111    match candidate_tcp_type(candidate) {
1112      Some(TcpType::Passive | TcpType::SimultaneousOpen) => {}
1113      Some(TcpType::Active) => return Ok(RemoteCandidate::Active),
1114      _ => return Ok(RemoteCandidate::Ignore),
1115    }
1116  }
1117  match address.trim_matches(['[', ']']).parse::<IpAddr>() {
1118    Ok(ip) if is_tcp => Ok(RemoteCandidate::Tcp(SocketAddr::new(ip, port))),
1119    Ok(ip) => Ok(RemoteCandidate::Udp(SocketAddr::new(ip, port))),
1120    Err(_) if mdns && is_mdns_name(&address) => Ok(RemoteCandidate::Mdns),
1121    Err(_) => Ok(RemoteCandidate::Ignore),
1122  }
1123}
1124
1125/// A host candidate's `<name>.local` address (RFC 6762 names; WebRTC's are
1126/// `<uuid>.local`).
1127fn is_mdns_name(address: &str) -> bool {
1128  let lower = address.to_ascii_lowercase();
1129  let Some(label) = lower.strip_suffix(".local") else {
1130    return false;
1131  };
1132  !label.is_empty()
1133    && label.len() <= 63
1134    && label
1135      .bytes()
1136      .all(|b| b.is_ascii_alphanumeric() || b == b'-')
1137}
1138
1139/// Whether this connection can use mDNS at all: never with
1140/// `DENO_WEBRTC_LOOPBACK_ONLY=1`, and only with the permissions the socket
1141/// needs (listening on the wildcard address, sending to the mDNS group) and
1142/// interface enumeration, without which the connection is on loopback and
1143/// can't reach a LAN address anyway.
1144///
1145/// Asks in that order, each question once the one before is allowed; the
1146/// token is the bind's.
1147async fn mdns_permitted(gate: Rc<GateCache>) -> Result<GateToken, String> {
1148  if loopback_only() {
1149    return Err("DENO_WEBRTC_LOOPBACK_ONLY=1".to_string());
1150  }
1151  gate.interfaces().await?;
1152  let token = gate
1153    .verdict(Reach::bind(
1154      ReachKind::Mdns,
1155      Proto::Udp,
1156      IpAddr::V4(Ipv4Addr::UNSPECIFIED),
1157    ))
1158    .await?;
1159  gate
1160    .verdict(Reach::connect(ReachKind::Mdns, Proto::Udp, MDNS_DEST_ADDR))
1161    .await?;
1162  Ok(token)
1163}
1164
1165/// An `a=simulcast` value (RFC 8853 section 5.1: `<direction> <alt-list>
1166/// [<direction> <alt-list>]`) without the rid-ids it repeats, or `None` when
1167/// it repeats none. webrtc-pc ignores a repeated rid in a remote offer
1168/// (w3c/webrtc-pc#2780, WPT `simulcast/negotiation-encodings`
1169/// "Duplicate rids in sRD(offer) are ignored"); rtci 0.2 refuses the
1170/// description for it (RFC 8853 section 5.8).
1171pub(crate) fn simulcast_without_repeated_rids(value: &str) -> Option<String> {
1172  let mut seen: Vec<&str> = Vec::new();
1173  let mut repeated = false;
1174  let mut fields: Vec<String> = Vec::new();
1175  for (i, field) in value.split(' ').enumerate() {
1176    // Odd fields are the rid lists; the others the directions.
1177    if i % 2 == 0 {
1178      fields.push(field.to_string());
1179      continue;
1180    }
1181    let mut alternatives: Vec<String> = Vec::new();
1182    for alternative in field.split(';') {
1183      let mut rids: Vec<&str> = Vec::new();
1184      for rid in alternative.split(',') {
1185        let id = rid.strip_prefix('~').unwrap_or(rid);
1186        if seen.contains(&id) {
1187          repeated = true;
1188        } else {
1189          seen.push(id);
1190          rids.push(rid);
1191        }
1192      }
1193      if !rids.is_empty() {
1194        alternatives.push(rids.join(","));
1195      }
1196    }
1197    fields.push(alternatives.join(";"));
1198  }
1199  repeated.then(|| fields.join(" "))
1200}
1201
1202/// Whether an `a=extmap` value (`<id>[/<direction>] <uri> [attributes]`)
1203/// names its extension by an absolute URI, and for RFC 6904's encrypted form
1204/// (`urn:ietf:params:rtp-hdrext:encrypt <uri>`) the one it encrypts too.
1205pub(crate) fn extmap_names_absolute_uris(value: &str) -> bool {
1206  fn absolute(uri: &str) -> bool {
1207    let Some((scheme, rest)) = uri.split_once(':') else {
1208      return false;
1209    };
1210    !rest.is_empty()
1211      && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
1212      && scheme
1213        .chars()
1214        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
1215  }
1216  let mut tokens = value.split_ascii_whitespace().skip(1);
1217  match tokens.next() {
1218    Some("urn:ietf:params:rtp-hdrext:encrypt") => {
1219      tokens.next().is_none_or(absolute)
1220    }
1221    Some(uri) => absolute(uri),
1222    // A line without a URI is malformed, which the engine judges.
1223    None => true,
1224  }
1225}
1226
1227/// Whether `name` is an SDP `attribute-name`, a token (RFC 8866 section 9:
1228/// `token-char = %x21 / %x23-27 / %x2A-2B / %x2D-2E / %x30-39 / %x41-5A /
1229/// %x5E-7E`).
1230pub(crate) fn is_attribute_name(name: &str) -> bool {
1231  !name.is_empty()
1232    && name.bytes().all(|b| {
1233      matches!(b,
1234        0x21 | 0x23..=0x27 | 0x2a..=0x2b | 0x2d..=0x2e | 0x30..=0x39
1235          | 0x41..=0x5a | 0x5e..=0x7e)
1236    })
1237}
1238
1239/// Whether an `a=identity` value has RFC 8827 section 5's form, which the
1240/// engine's SDP parser requires: a base64 assertion, then single-space
1241/// separated extensions.
1242fn is_identity_value(value: &str) -> bool {
1243  let mut fields = value.split(' ');
1244  let assertion = fields.next().unwrap_or_default();
1245  let bytes = assertion.as_bytes();
1246  let pad = bytes.iter().rev().take_while(|b| **b == b'=').count();
1247  !bytes.is_empty()
1248    && bytes.len().is_multiple_of(4)
1249    && pad <= 2
1250    && bytes[..bytes.len() - pad]
1251      .iter()
1252      .all(|b| b.is_ascii_alphanumeric() || *b == b'+' || *b == b'/')
1253    && fields.all(|f| !f.is_empty())
1254}
1255
1256/// Sends one mDNS message to the IPv4 group from `from`, the address the
1257/// engine says it leaves from: an answer leaves from the address its record
1258/// names (rtci-mdns aggregates records per address), on that address's
1259/// interface (RFC 6762 section 14), so that its IP source is that address. A
1260/// resolver takes an A record only from the address it names, and only from
1261/// an on-link source (RFC 6762 section 11, the engine's hardening): sent from
1262/// the wildcard socket's default multicast interface instead, every answer
1263/// left from one address (a cloud host's public one, refused as off-link),
1264/// and no `.local` name resolved. A message from the unspecified address (a
1265/// query) or an IPv6 one (this socket is IPv4) takes the default interface.
1266fn send_mdns(socket: &EcnUdpSocket, message: &[u8], from: IpAddr) {
1267  let interface = match from {
1268    IpAddr::V4(v4) if !v4.is_unspecified() && !v4.is_loopback() => v4,
1269    _ => Ipv4Addr::UNSPECIFIED,
1270  };
1271  if let Err(e) =
1272    socket2::SockRef::from(&**socket).set_multicast_if_v4(&interface)
1273  {
1274    log::debug!("webrtc: mDNS interface {interface}: {e}");
1275    return;
1276  }
1277  if let Err(e) = socket.try_send_to(message, MDNS_DEST_ADDR) {
1278    log::debug!("webrtc: mDNS send from {interface}: {e}");
1279  }
1280}
1281
1282/// Hides the base address a server-reflexive or relay candidate names
1283/// (`raddr` / `rport`) when the host candidates are published under mDNS
1284/// names, as browsers do: it is the host address the name stands for.
1285pub(crate) fn redact_related_address(candidate: &str) -> String {
1286  let mut out = Vec::new();
1287  let mut fields = candidate.split(' ');
1288  while let Some(field) = fields.next() {
1289    out.push(field.to_string());
1290    let hidden = match field {
1291      "raddr" => fields
1292        .next()
1293        .map(|addr| if addr.contains(':') { "::" } else { "0.0.0.0" }),
1294      "rport" => fields.next().map(|_| "0"),
1295      _ => None,
1296    };
1297    if let Some(value) = hidden {
1298      out.push(value.to_string());
1299    }
1300  }
1301  out.join(" ")
1302}
1303
1304/// `DENO_WEBRTC_LOOPBACK_ONLY=1`: gather on `127.0.0.1` alone, never binding
1305/// the wildcard address (test machines whose firewall asks about every
1306/// non-loopback listener; two peers on one machine still connect). Read by
1307/// the runtime like its other `DENO_*` switches, without `--allow-env`.
1308pub(crate) fn loopback_only() -> bool {
1309  std::env::var_os("DENO_WEBRTC_LOOPBACK_ONLY").is_some_and(|v| v == "1")
1310}
1311
1312/// The machine's usable interface addresses (no loopback, no link-local),
1313/// of the named interfaces only when `names` is given.
1314pub(crate) fn interface_addresses(names: Option<&[String]>) -> Vec<IpAddr> {
1315  let Ok(ifaces) = netif::up() else {
1316    return Vec::new();
1317  };
1318  let mut out = Vec::new();
1319  for iface in ifaces {
1320    if names.is_some_and(|names| !names.iter().any(|n| n == iface.name())) {
1321      continue;
1322    }
1323    let ip = *iface.address();
1324    let usable = match ip {
1325      IpAddr::V4(v4) => {
1326        !v4.is_loopback() && !v4.is_link_local() && !v4.is_unspecified()
1327      }
1328      IpAddr::V6(v6) => {
1329        // Link-local addresses need a scope id the candidate grammar can't
1330        // carry; IPv4-mapped ones duplicate the IPv4 candidate.
1331        !v6.is_loopback()
1332          && !v6.is_unspecified()
1333          && (v6.segments()[0] & 0xffc0) != 0xfe80
1334          && v6.to_ipv4_mapped().is_none()
1335      }
1336    };
1337    if usable && !out.contains(&ip) {
1338      out.push(ip);
1339    }
1340  }
1341  out
1342}
1343
1344/// RFC 7983 demultiplexing: a STUN message starts with 0-3.
1345fn is_stun(data: &[u8]) -> bool {
1346  data.first().is_some_and(|b| *b < 4)
1347}
1348
1349fn candidate_line(
1350  candidate: rtci::shared::error::Result<rtci::ice::candidate::Candidate>,
1351) -> Result<String, Error> {
1352  let candidate = candidate.map_err(rtc_err)?;
1353  Ok(
1354    RTCIceCandidate::from(&candidate)
1355      .to_json()
1356      .map_err(rtc_err)?
1357      .candidate,
1358  )
1359}
1360
1361fn base_config(addr: SocketAddr) -> CandidateConfig {
1362  CandidateConfig {
1363    network: "udp".to_owned(),
1364    address: addr.ip().to_string(),
1365    port: addr.port(),
1366    component: 1,
1367    ..Default::default()
1368  }
1369}
1370
1371/// An ICE-TCP host candidate's line.
1372fn tcp_host_line(addr: SocketAddr, tcp_type: TcpType) -> Result<String, Error> {
1373  candidate_line(
1374    CandidateHostConfig {
1375      base_config: CandidateConfig {
1376        network: "tcp".to_owned(),
1377        ..base_config(addr)
1378      },
1379      tcp_type,
1380    }
1381    .new_candidate_host(),
1382  )
1383}
1384
1385/// The length of the first complete RFC 6544 frame in `buf` (a STUN message
1386/// or a padded ChannelData message), `Some(0)` for an incomplete one, `None`
1387/// for garbage.
1388fn stream_frame_len(buf: &[u8]) -> Option<usize> {
1389  if buf.len() < 4 {
1390    return Some(0);
1391  }
1392  let len = u16::from_be_bytes([buf[2], buf[3]]) as usize;
1393  let total = match buf[0] >> 6 {
1394    0 => 20 + len,
1395    1 => 4 + len.div_ceil(4) * 4,
1396    _ => return None,
1397  };
1398  if total > MAX_STREAM_FRAME {
1399    return None;
1400  }
1401  Some(if buf.len() >= total { total } else { 0 })
1402}
1403
1404impl Core {
1405  /// The local description's first media section id, for candidates the
1406  /// engine reports without one (W3C: `sdpMid` of the bundled section).
1407  fn first_mid(&self) -> Option<String> {
1408    let desc = self.pc.local_description()?;
1409    desc.sdp.lines().find_map(|l| {
1410      l.trim_end()
1411        .strip_prefix("a=mid:")
1412        .map(|mid| mid.trim().to_string())
1413    })
1414  }
1415
1416  fn local_ufrag(&self) -> Option<String> {
1417    let desc = self.pc.local_description()?;
1418    desc.sdp.lines().find_map(|l| {
1419      l.trim_end()
1420        .strip_prefix("a=ice-ufrag:")
1421        .map(|u| u.trim().to_string())
1422    })
1423  }
1424
1425  fn add_local(
1426    &mut self,
1427    candidate: String,
1428    url: Option<String>,
1429  ) -> Result<(), Error> {
1430    self
1431      .pc
1432      .add_local_candidate(RTCIceCandidateInit {
1433        candidate,
1434        url,
1435        ..Default::default()
1436      })
1437      .map_err(rtc_err)?;
1438    self.local_gathered += 1;
1439    Ok(())
1440  }
1441
1442  fn remote_ufrag(&self) -> Option<String> {
1443    let desc = self.pc.remote_description()?;
1444    desc.sdp.lines().find_map(|l| {
1445      l.trim_end()
1446        .strip_prefix("a=ice-ufrag:")
1447        .map(|u| u.trim().to_string())
1448    })
1449  }
1450
1451  /// W3C `RTCSctpTransport.state`: `connecting` until the association is
1452  /// up, `connected`, then `closed` for good once it ends (the engine forgets
1453  /// a closed association, so anything after `connected` is `closed`).
1454  fn track_sctp_state(&mut self) {
1455    let Some(engine) = self.pc.sctp().map(|s| s.state()) else {
1456      return;
1457    };
1458    let next = match (self.sctp_state, engine) {
1459      ("closed", _) => "closed",
1460      (_, RTCSctpTransportState::Connected) => "connected",
1461      ("connected", _) | (_, RTCSctpTransportState::Closed) => "closed",
1462      _ => "connecting",
1463    };
1464    if next != self.sctp_state {
1465      self.sctp_state = next;
1466      self.events.push_back(JsEvent::SctpState { state: next });
1467    }
1468  }
1469
1470  /// Reports what each channel's SCTP stream has sent since the last pass.
1471  fn track_sent(&mut self) {
1472    let handles: Vec<u32> = self.sent.keys().copied().collect();
1473    for handle in handles {
1474      let Some(now) = self
1475        .pc
1476        .data_channel(handle as RTCDataChannelId)
1477        .map(|c| c.bytes_dequeued())
1478      else {
1479        self.sent.remove(&handle);
1480        continue;
1481      };
1482      let last = self.sent.insert(handle, now).unwrap_or(0);
1483      if now > last {
1484        self.events.push_back(JsEvent::DataChannelSent {
1485          channel: handle,
1486          bytes: (now - last) as f64,
1487        });
1488      }
1489    }
1490  }
1491
1492  /// The DTLS transport's state: reached through the SCTP transport, else
1493  /// through a receiver (all of them share the one bundled transport).
1494  fn track_dtls_state(&mut self) {
1495    let state = match self.pc.sctp() {
1496      Some(sctp) => Some(sctp.transport().state()),
1497      None => {
1498        let receivers: Vec<_> = self.pc.get_receivers().collect();
1499        receivers.into_iter().find_map(|id| {
1500          self
1501            .pc
1502            .rtp_receiver(id)
1503            .and_then(|r| r.transport().map(|t| t.state()))
1504        })
1505      }
1506    };
1507    let Some(state) = state.map(|s| s.to_string()) else {
1508      return;
1509    };
1510    if state != self.dtls_state {
1511      self.dtls_state.clone_from(&state);
1512      self.events.push_back(JsEvent::DtlsState { state });
1513    }
1514  }
1515
1516  /// The engine's ICE transport's selected pair, reached through the SCTP
1517  /// transport, else through a receiver or a sender (all of them share the one
1518  /// bundled transport; a receiver or sender has one once it has a mid).
1519  fn ice_selected_pair(&mut self) -> Option<SelectedPair> {
1520    let to_pair =
1521      |p: rtci::peer_connection::transport::RTCIceCandidatePair| SelectedPair {
1522        local: PairCandidate::of(p.local()),
1523        remote: PairCandidate::of(p.remote()),
1524      };
1525    if let Some(sctp) = self.pc.sctp() {
1526      return sctp
1527        .transport()
1528        .ice_transport()
1529        .get_selected_candidate_pair()
1530        .map(to_pair);
1531    }
1532    let receivers: Vec<_> = self.pc.get_receivers().collect();
1533    for id in receivers {
1534      let pair = self.pc.rtp_receiver(id).and_then(|r| {
1535        r.transport()
1536          .map(|t| t.ice_transport().get_selected_candidate_pair())
1537      });
1538      match pair {
1539        Some(pair) => return pair.map(to_pair),
1540        None => continue,
1541      }
1542    }
1543    let senders: Vec<_> = self.pc.get_senders().collect();
1544    for id in senders {
1545      let pair = self.pc.rtp_sender(id).and_then(|s| {
1546        s.transport()
1547          .map(|t| t.ice_transport().get_selected_candidate_pair())
1548      });
1549      match pair {
1550        Some(pair) => return pair.map(to_pair),
1551        None => continue,
1552      }
1553    }
1554    None
1555  }
1556
1557  /// W3C webrtc-pc 5.6.4 "failed" ("either zero local candidates were
1558  /// gathered or the PAC timer has expired"): with gathering complete on
1559  /// both sides and no local candidate at all (a relay-only policy without
1560  /// a TURN server), nothing can ever connect, so ICE is `failed` rather
1561  /// than left `checking` until the timeout.
1562  ///
1563  /// A connection with local candidates and none from the remote side is
1564  /// left to the engine: the peer, which has ours, can still check us and
1565  /// form a peer-reflexive pair, and rtci 0.3's RFC 8863 PAC timer holds the
1566  /// check list (39.5 s with the defaults) for that check before failing it.
1567  fn fail_without_pairs(&mut self) {
1568    if self.failed
1569      || self.gathering != GatherPhase::Complete
1570      || !self.remote_gathered
1571      || self.pc.remote_description().is_none()
1572    {
1573      return;
1574    }
1575    if self.local_gathered == 0 {
1576      self.fail("no local candidates, and gathering is complete");
1577    }
1578  }
1579
1580  fn report_error(
1581    &mut self,
1582    url: &str,
1583    base: Option<SocketAddr>,
1584    error_code: u16,
1585    error_text: String,
1586  ) {
1587    self.events.push_back(JsEvent::IceCandidateError {
1588      address: base.map(|b| b.ip().to_string()),
1589      port: base.map(|b| b.port()),
1590      url: url.to_string(),
1591      error_code,
1592      error_text,
1593    });
1594  }
1595
1596  /// Reports `failed` on the engine's behalf (watchdog, panic).
1597  fn fail(&mut self, why: &str) {
1598    if self.failed {
1599      return;
1600    }
1601    log::debug!("webrtc: connection failed: {why}");
1602    self.failed = true;
1603    self.events.push_back(JsEvent::IceConnectionState {
1604      state: "failed".to_string(),
1605    });
1606    self.events.push_back(JsEvent::ConnectionState {
1607      state: "failed".to_string(),
1608    });
1609  }
1610
1611  /// The send-side permission gate: once per destination address. A
1612  /// question still being asked drops the datagram (counted as discarded
1613  /// on send; ICE and DTLS retransmit, and the answer pokes the driver).
1614  fn permit(
1615    &mut self,
1616    addr: SocketAddr,
1617    kind: ReachKind,
1618    proto: Proto,
1619    len: usize,
1620  ) -> bool {
1621    if self.allowed.contains(&addr) {
1622      return true;
1623    }
1624    if self.refused.contains(&addr) {
1625      return false;
1626    }
1627    match self.gate.lookup(&Reach::connect(kind, proto, addr)) {
1628      None => {
1629        self.media.pacer_refusals.add(len);
1630        false
1631      }
1632      Some(Ok(_)) => {
1633        self.allowed.insert(addr);
1634        true
1635      }
1636      Some(Err(message)) => {
1637        self.refused.insert(addr);
1638        self.events.push_back(JsEvent::IceCandidateError {
1639          address: Some(addr.ip().to_string()),
1640          port: Some(addr.port()),
1641          url: String::new(),
1642          error_code: ERROR_CODE_UNREACHABLE,
1643          error_text: message,
1644        });
1645        false
1646      }
1647    }
1648  }
1649
1650  /// Marks a remote address as already checked (by `addIceCandidate` /
1651  /// `setRemoteDescription`, which reject when it is refused).
1652  pub(crate) fn mark_allowed(&mut self, addr: SocketAddr) {
1653    self.allowed.insert(addr);
1654    self.remote_known = true;
1655  }
1656
1657  /// The UDP socket a datagram from `local` (a host candidate address or a
1658  /// base) goes out on.
1659  fn endpoint_for(&self, local: SocketAddr) -> Option<Rc<EcnUdpSocket>> {
1660    self
1661      .endpoints
1662      .iter()
1663      .find(|e| {
1664        e.bound.port() == local.port() && e.bound.is_ipv4() == local.is_ipv4()
1665      })
1666      .map(|e| e.socket.clone())
1667  }
1668
1669  /// The local address a datagram on `endpoint` from `from` arrived on.
1670  /// The OS route is probed and cached only for an address ICE or the
1671  /// permission gate vouched for ([`Core::is_known_remote`]).
1672  fn local_for(&mut self, endpoint: usize, from: SocketAddr) -> SocketAddr {
1673    let known = self.is_known_remote(from.ip());
1674    self.local_address(endpoint, from, known)
1675  }
1676
1677  /// Whether `ip` is a remote address ICE or the permission gate vouched for:
1678  /// a signalled remote candidate, a STUN/TURN server, a destination the
1679  /// engine sent to (which it does only for a signalled candidate or after
1680  /// authenticating a check), or the selected pair's.
1681  fn is_known_remote(&self, ip: IpAddr) -> bool {
1682    self.selected.is_some_and(|(_, r)| r.ip() == ip)
1683      || self.allowed.iter().any(|a| a.ip() == ip)
1684  }
1685
1686  /// [`Core::local_for`] with the trust decided by the caller. With `probe`,
1687  /// the OS route to `from` (a connected probe socket) is resolved and
1688  /// cached. Without it the first host address stands in and nothing is
1689  /// opened or kept, so a datagram from an address nobody vouched for costs
1690  /// neither a socket nor memory.
1691  fn local_address(
1692    &mut self,
1693    endpoint: usize,
1694    from: SocketAddr,
1695    probe: bool,
1696  ) -> SocketAddr {
1697    let e = &self.endpoints[endpoint];
1698    let port = e.bound.port();
1699    let ip = if !e.bound.ip().is_unspecified() {
1700      e.bound.ip()
1701    } else if let Some(ip) = self.routes.get(&from.ip()) {
1702      *ip
1703    } else if !probe || e.hosts.len() <= 1 {
1704      // With one host address (or none) a probe could give no other answer.
1705      e.hosts.first().copied().unwrap_or(from.ip())
1706    } else {
1707      let ip = self
1708        .io
1709        .route_probe(from.ip())
1710        .filter(|ip| e.hosts.contains(ip))
1711        .or_else(|| e.hosts.first().copied())
1712        .unwrap_or(from.ip());
1713      // A cache: once full it starts over rather than grow.
1714      if self.routes.len() >= MAX_ROUTES {
1715        self.routes.clear();
1716      }
1717      self.routes.insert(from.ip(), ip);
1718      ip
1719    };
1720    // 1:1 NAT in host mode: the host candidate is the public address (unless
1721    // the engine maps it, keeping the private socket as the base).
1722    let ip = match self.options.network.as_ref().map(|n| &n.options) {
1723      Some(net) if !net.public_srflx && !self.engine_nat => {
1724        net.public_for(ip).unwrap_or(ip)
1725      }
1726      _ => ip,
1727    };
1728    SocketAddr::new(ip, port)
1729  }
1730
1731  /// Whether a non-STUN packet on (`local`, `from`) belongs to the selected
1732  /// pair. The engine sends DTLS (and everything inside it) only on the
1733  /// selected pair, so the pair is the one its last non-STUN datagram went
1734  /// out on. Until it has sent one (the DTLS server waiting for the client's
1735  /// first flight), a packet is accepted only while ICE is connected and only
1736  /// from an address ICE has exchanged STUN with. The local side is compared
1737  /// by family and port (exactly for a relay): a wildcard socket's local
1738  /// address is the routed one.
1739  fn is_from_selected_pair(
1740    &self,
1741    local: SocketAddr,
1742    from: SocketAddr,
1743    relayed: bool,
1744  ) -> bool {
1745    match self.selected {
1746      Some(_) if self.selected_tcp => false,
1747      Some((l, r)) => {
1748        r == from
1749          && if relayed {
1750            l == local
1751          } else {
1752            l.port() == local.port() && l.is_ipv4() == local.is_ipv4()
1753          }
1754      }
1755      None => self.ice_up && self.stun_peers.contains(&from),
1756    }
1757  }
1758
1759  /// Remembers a remote address that sent STUN (bounded: a flood of
1760  /// spoofed sources can't grow it without limit).
1761  fn saw_stun(&mut self, from: SocketAddr) {
1762    self.remote_known = true;
1763    if self.stun_peers.len() < MAX_STUN_PEERS {
1764      self.stun_peers.insert(from);
1765    }
1766  }
1767
1768  /// ICE over TCP (a `tcpPort` network): a passive candidate on each of the
1769  /// network's listeners per host address, and an active one (port 9) per
1770  /// host address, which dials the peer's passive candidates.
1771  /// Signals the host (and 1:1 NAT server-reflexive) candidates of one UDP
1772  /// endpoint, unless the policy is relay-only; `advertised` keeps an address
1773  /// shared by two endpoints from being signalled twice.
1774  fn announce_udp_hosts(
1775    &mut self,
1776    opts: &NetworkOptions,
1777    bound: SocketAddr,
1778    hosts: &[IpAddr],
1779    gather_names: bool,
1780    advertised: &mut HashSet<SocketAddr>,
1781  ) {
1782    if !self.options.relay_only {
1783      for ip in &published_hosts(hosts, gather_names) {
1784        let private = SocketAddr::new(*ip, bound.port());
1785        let public = opts
1786          .public_for(*ip)
1787          .map(|p| SocketAddr::new(p, bound.port()));
1788        let (host, srflx) = match public {
1789          Some(p) if opts.public_srflx => (private, Some(p)),
1790          // The engine announces it on the public address.
1791          Some(_) if self.engine_nat => (private, None),
1792          Some(p) => (p, None),
1793          None => (private, None),
1794        };
1795        if advertised.insert(host) {
1796          let line = candidate_line(
1797            CandidateHostConfig {
1798              base_config: base_config(host),
1799              ..Default::default()
1800            }
1801            .new_candidate_host(),
1802          );
1803          if let Err(e) = line.and_then(|line| self.add_local(line, None)) {
1804            self.report_error(
1805              "",
1806              Some(host),
1807              ERROR_CODE_UNREACHABLE,
1808              e.to_string(),
1809            );
1810          }
1811        }
1812        if let Some(srflx) = srflx
1813          && advertised.insert(srflx)
1814        {
1815          let line = candidate_line(
1816            CandidateServerReflexiveConfig {
1817              base_config: base_config(srflx),
1818              rel_addr: private.ip().to_string(),
1819              rel_port: private.port(),
1820              url: None,
1821            }
1822            .new_candidate_server_reflexive(),
1823          );
1824          if let Err(e) = line.and_then(|line| self.add_local(line, None)) {
1825            self.report_error(
1826              "",
1827              Some(srflx),
1828              ERROR_CODE_UNREACHABLE,
1829              e.to_string(),
1830            );
1831          }
1832        }
1833      }
1834    }
1835  }
1836
1837  /// What candidates are gathered on: the network's options, or loopback
1838  /// included by default.
1839  fn gather_options(&self) -> NetworkOptions {
1840    match self.options.network.as_ref() {
1841      Some(n) => n.options.clone(),
1842      None => NetworkOptions {
1843        include_loopback: true,
1844        ..Default::default()
1845      },
1846    }
1847  }
1848
1849  fn gather_tcp(&mut self, opts: &NetworkOptions, gather_names: bool) {
1850    let Some(net) = self.options.network.clone().filter(|n| n.has_tcp()) else {
1851      return;
1852    };
1853    let mut lines: Vec<(SocketAddr, TcpType)> = Vec::new();
1854    let mut active: Vec<IpAddr> = Vec::new();
1855    for endpoint in &net.tcp {
1856      for ip in published_hosts(&endpoint.hosts, gather_names) {
1857        // 1:1 NAT: the public address in place of the private one (host
1858        // mode), as for UDP; in srflx mode, or when the engine maps it, the
1859        // host address itself.
1860        let advertised = match opts.public_for(ip) {
1861          Some(public) if !opts.public_srflx && !self.engine_nat => public,
1862          _ => ip,
1863        };
1864        let passive = SocketAddr::new(advertised, endpoint.bound.port());
1865        if !lines.contains(&(passive, TcpType::Passive)) {
1866          lines.push((passive, TcpType::Passive));
1867        }
1868        if !active.contains(&advertised) {
1869          active.push(advertised);
1870        }
1871      }
1872    }
1873    for ip in active {
1874      lines.push((SocketAddr::new(ip, ACTIVE_TCP_PORT), TcpType::Active));
1875    }
1876    for (addr, tcp_type) in lines {
1877      if let Err(e) = tcp_host_line(addr, tcp_type)
1878        .and_then(|line| self.add_local(line, None))
1879      {
1880        self.report_error(
1881          "",
1882          Some(addr),
1883          ERROR_CODE_UNREACHABLE,
1884          e.to_string(),
1885        );
1886      }
1887    }
1888  }
1889
1890  /// Sends an ICE-TCP frame: on the connection to `to`, or, from an active
1891  /// candidate, by dialling `to` (a remote passive candidate) first. A
1892  /// passive candidate only answers on connections it accepted.
1893  fn send_tcp(&mut self, local: SocketAddr, to: SocketAddr, data: &[u8]) {
1894    let Some(frame) = try_frame_packet(data) else {
1895      return;
1896    };
1897    if let Some(link) = self.tcp_links.get(&to) {
1898      if link.writer.try_send(frame).is_err() {
1899        log::debug!("webrtc: ICE-TCP queue to {to} is full");
1900      }
1901      return;
1902    }
1903    if local.port() != ACTIVE_TCP_PORT {
1904      return;
1905    }
1906    if let Some(queue) = self.tcp_dialing.get_mut(&to) {
1907      if queue.len() < MAX_DIAL_QUEUE {
1908        queue.push(frame);
1909      }
1910      return;
1911    }
1912    if self.tcp_links.len() + self.tcp_dialing.len() >= MAX_TCP_LINKS {
1913      return;
1914    }
1915    // `permit` asked this dial's question (as a `TcpDial`): this is a cache
1916    // hit, or the synchronous gate asked again.
1917    let Some(Ok(token)) =
1918      self
1919        .gate
1920        .lookup(&Reach::connect(ReachKind::TcpDial, Proto::Tcp, to))
1921    else {
1922      return;
1923    };
1924    self.tcp_dialing.insert(to, vec![frame]);
1925    let bind = self.tcp_bind_ip(local.ip());
1926    if let Some(peer) = self.this.upgrade() {
1927      let cancel = peer.cancel.clone();
1928      let weak = self.this.clone();
1929      let io = self.io.clone();
1930      crate::rt::spawn(
1931        async move {
1932          let stream = tokio::time::timeout(
1933            TCP_CONNECT_TIMEOUT,
1934            connect_tcp(&*io, &token, bind, to),
1935          )
1936          .await;
1937          let Some(peer) = weak.upgrade() else {
1938            return;
1939          };
1940          match stream {
1941            Ok(Ok(stream)) => {
1942              peer.attach_tcp(stream, to, TcpFrameDecoder::new(), None)
1943            }
1944            Ok(Err(e)) => {
1945              log::debug!("webrtc: ICE-TCP connect to {to}: {e}");
1946              peer.core.borrow_mut().tcp_dialing.remove(&to);
1947            }
1948            Err(_) => {
1949              log::debug!("webrtc: ICE-TCP connect to {to} timed out");
1950              peer.core.borrow_mut().tcp_dialing.remove(&to);
1951            }
1952          }
1953        }
1954        .or_cancel(cancel),
1955      );
1956    }
1957  }
1958
1959  /// The local address an outbound ICE-TCP connection binds for an active
1960  /// candidate on `ip`: that host address itself (a public one in 1:1 NAT
1961  /// host mode stands for its private address), or none (the OS picks).
1962  fn tcp_bind_ip(&self, ip: IpAddr) -> Option<IpAddr> {
1963    let net = self.options.network.as_ref()?;
1964    let hosts: Vec<IpAddr> = net
1965      .tcp
1966      .iter()
1967      .flat_map(|e| e.hosts.iter().copied())
1968      .collect();
1969    if hosts.contains(&ip) {
1970      return Some(ip);
1971    }
1972    net
1973      .options
1974      .private_for(ip, &hosts)
1975      .filter(|private| hosts.contains(private))
1976  }
1977
1978  /// The local address the engine knows an ICE-TCP connection's local
1979  /// address by: in 1:1 NAT host mode the public address stands for the
1980  /// private one, as for UDP.
1981  fn tcp_local(&self, local: SocketAddr) -> SocketAddr {
1982    match self.options.network.as_ref().map(|n| &n.options) {
1983      Some(net) if !net.public_srflx && !self.engine_nat => SocketAddr::new(
1984        net.public_for(local.ip()).unwrap_or(local.ip()),
1985        local.port(),
1986      ),
1987      _ => local,
1988    }
1989  }
1990
1991  /// Opens the mDNS socket once (on first need): `false` when it can't be.
1992  fn open_mdns(&mut self) -> bool {
1993    if self.mdns_socket.is_some() {
1994      return true;
1995    }
1996    if self.mdns_failed || self.mdns_mode == MdnsMode::Off {
1997      return false;
1998    }
1999    let hosts = if self.endpoints.is_empty() {
2000      interface_addresses(
2001        self
2002          .options
2003          .network
2004          .as_ref()
2005          .and_then(|n| n.options.interfaces.as_deref()),
2006      )
2007    } else {
2008      self
2009        .endpoints
2010        .iter()
2011        .flat_map(|e| e.hosts.clone())
2012        .collect()
2013    };
2014    let Some(token) = self.mdns_token.clone() else {
2015      return false;
2016    };
2017    let socket = match self.io.bind_mdns(&token, &hosts) {
2018      Ok(socket) => Rc::new(EcnUdpSocket::plain(socket)),
2019      Err(e) => {
2020        self.mdns_failed = true;
2021        self.report_error(
2022          "",
2023          None,
2024          ERROR_CODE_UNREACHABLE,
2025          format!("mDNS is unavailable: {e}"),
2026        );
2027        return false;
2028      }
2029    };
2030    if let Some(peer) = self.this.upgrade() {
2031      spawn_udp_reader_via(
2032        socket.clone(),
2033        SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), MDNS_PORT),
2034        self.recv_tx.clone(),
2035        peer.cancel.clone(),
2036        Via::Mdns,
2037      );
2038    }
2039    self.mdns_socket = Some(socket);
2040    true
2041  }
2042
2043  /// Whether a remote `.local` candidate can be resolved here (opening the
2044  /// mDNS socket if it isn't yet).
2045  fn resolves_mdns(&mut self) -> bool {
2046    self.mdns_mode != MdnsMode::Off && self.open_mdns()
2047  }
2048
2049  /// Whether this connection does ICE over TCP (a `tcpPort` network).
2050  fn ice_tcp(&self) -> bool {
2051    self.options.network.as_ref().is_some_and(|n| n.has_tcp())
2052  }
2053
2054  /// A candidate line as JavaScript sees it: with the host candidates
2055  /// published under mDNS names, the base address a server-reflexive or
2056  /// relay candidate names is hidden too.
2057  fn public_candidate(&self, line: String) -> String {
2058    if self.mdns_mode == MdnsMode::Gather && line.contains(" raddr ") {
2059      redact_related_address(&line)
2060    } else {
2061      line
2062    }
2063  }
2064
2065  /// Sends what the engine wants sent, through the socket or a TURN relay.
2066  fn flush_engine_writes(&mut self) -> bool {
2067    let mut progressed = false;
2068    while let Some(msg) = self.pc.poll_write() {
2069      progressed = true;
2070      let local = msg.transport.local_addr;
2071      let to = msg.transport.peer_addr;
2072      // mDNS queries and answers (permitted when the socket was opened).
2073      if to == MDNS_DEST_ADDR {
2074        if let Some(socket) = &self.mdns_socket {
2075          send_mdns(socket, &msg.message, local.ip());
2076        }
2077        continue;
2078      }
2079      let tcp = msg.transport.transport_protocol == TransportProtocol::TCP;
2080      // The first frame to a remote passive candidate from an active one
2081      // dials it: an ICE-TCP dial.
2082      let (kind, proto) = if !tcp {
2083        (ReachKind::SendTo, Proto::Udp)
2084      } else if local.port() == ACTIVE_TCP_PORT
2085        && !self.tcp_links.contains_key(&to)
2086      {
2087        (ReachKind::TcpDial, Proto::Tcp)
2088      } else {
2089        (ReachKind::SendTo, Proto::Tcp)
2090      };
2091      if !self.permit(to, kind, proto, msg.message.len()) {
2092        continue;
2093      }
2094      if !is_stun(&msg.message) {
2095        self.selected = Some((local, to));
2096        self.selected_tcp = tcp;
2097      }
2098      if tcp {
2099        self.send_tcp(local, to, &msg.message);
2100        continue;
2101      }
2102      if let Some(server) =
2103        self.servers.iter_mut().find(|s| s.relay == Some(local))
2104      {
2105        let now = Instant::now();
2106        let sent = server
2107          .client
2108          .relay(local)
2109          .and_then(|mut relay| relay.send_to(now, &msg.message, to));
2110        if sent.is_err() {
2111          // No permission for this peer on the relay yet: ask for it and
2112          // drop the datagram (ICE retransmits its checks).
2113          if let Ok(mut relay) = server.client.relay(local) {
2114            let _ = relay.create_permission(now, to);
2115          }
2116        }
2117        continue;
2118      }
2119      // The codepoint the engine chose (ECT(1) on the RTP of a stream
2120      // that negotiated `ack ccfb`, with ECN on), per datagram.
2121      if let Some(socket) = self.endpoint_for(local)
2122        && let Err(e) =
2123          socket.try_send_to_ecn(&msg.message, to, msg.transport.ecn)
2124      {
2125        log::debug!("webrtc: send {local} -> {to}: {e}");
2126      }
2127    }
2128    progressed
2129  }
2130
2131  /// Runs the STUN/TURN clients: their datagrams out, their results in.
2132  fn service_servers(&mut self, now: Instant) -> bool {
2133    let mut progressed = false;
2134    let mut found: Vec<(String, SocketAddr, SocketAddr)> = Vec::new();
2135    let mut relays: Vec<(String, SocketAddr, SocketAddr)> = Vec::new();
2136    let mut errors: Vec<(String, SocketAddr, String)> = Vec::new();
2137    let mut relayed_in: Vec<(SocketAddr, SocketAddr, BytesMut)> = Vec::new();
2138    for server in &mut self.servers {
2139      while let Some(tx) = server.client.poll_write() {
2140        progressed = true;
2141        match &server.link {
2142          ServerLink::Stream(writer) => {
2143            let _ = writer.send(tx.message.to_vec());
2144          }
2145          ServerLink::Udp => {
2146            if let Some(net) =
2147              self.options.network.as_ref().filter(|n| n.is_shared())
2148            {
2149              net.register_transaction(&tx.message, &self.this);
2150            }
2151            if let Some(e) = self.endpoints.iter().find(|e| {
2152              e.bound.port() == tx.transport.local_addr.port()
2153                && e.bound.is_ipv4() == tx.transport.local_addr.is_ipv4()
2154            }) && let Err(err) =
2155              e.socket.try_send_to(&tx.message, tx.transport.peer_addr)
2156            {
2157              log::debug!("webrtc: STUN/TURN send: {err}");
2158            }
2159          }
2160        }
2161      }
2162      while let Some(event) = server.client.poll_event() {
2163        progressed = true;
2164        let url = server.url.clone();
2165        match event {
2166          TurnEvent::BindingResponse(tid, addr) => {
2167            if server.binding == Some(tid) {
2168              server.binding = None;
2169              if matches!(server.link, ServerLink::Udp) {
2170                found.push((url, server.base, addr));
2171              }
2172            }
2173          }
2174          TurnEvent::BindingError(tid, e) => {
2175            if server.binding == Some(tid) {
2176              server.binding = None;
2177              errors.push((url, server.base, e.to_string()));
2178            }
2179          }
2180          TurnEvent::AllocateResponse(tid, relay) => {
2181            if server.allocate == Some(tid) {
2182              server.allocate = None;
2183              server.relay = Some(relay);
2184              relays.push((url, server.base, relay));
2185            }
2186          }
2187          TurnEvent::AllocateError(tid, e) => {
2188            if server.allocate == Some(tid) {
2189              server.allocate = None;
2190              errors.push((url, server.base, e.to_string()));
2191            }
2192          }
2193          TurnEvent::TransactionTimeout(tid) => {
2194            if server.binding == Some(tid) {
2195              server.binding = None;
2196              errors.push((
2197                url,
2198                server.base,
2199                "STUN binding request timed out".to_string(),
2200              ));
2201            } else if server.allocate == Some(tid) {
2202              server.allocate = None;
2203              errors.push((
2204                url,
2205                server.base,
2206                "TURN allocate request timed out".to_string(),
2207              ));
2208            }
2209          }
2210          TurnEvent::DataIndicationOrChannelData(_, from, data) => {
2211            if let Some(relay) = server.relay {
2212              relayed_in.push((relay, from, data));
2213            }
2214          }
2215          _ => {}
2216        }
2217      }
2218    }
2219    for (url, base, addr) in found {
2220      let host = self
2221        .endpoints
2222        .iter()
2223        .any(|e| e.bound.port() == addr.port() && e.hosts.contains(&addr.ip()));
2224      if host || self.options.relay_only || !self.srflx_seen.insert(addr) {
2225        continue;
2226      }
2227      let line = candidate_line(
2228        CandidateServerReflexiveConfig {
2229          base_config: base_config(addr),
2230          rel_addr: base.ip().to_string(),
2231          rel_port: base.port(),
2232          url: Some(url.clone()),
2233        }
2234        .new_candidate_server_reflexive(),
2235      );
2236      if let Err(e) =
2237        line.and_then(|line| self.add_local(line, Some(url.clone())))
2238      {
2239        self.report_error(
2240          &url,
2241          Some(base),
2242          ERROR_CODE_UNREACHABLE,
2243          e.to_string(),
2244        );
2245      }
2246    }
2247    for (url, base, relay) in relays {
2248      let line = candidate_line(
2249        CandidateRelayConfig {
2250          base_config: base_config(relay),
2251          rel_addr: base.ip().to_string(),
2252          rel_port: base.port(),
2253          url: Some(url.clone()),
2254        }
2255        .new_candidate_relay(),
2256      );
2257      if let Err(e) =
2258        line.and_then(|line| self.add_local(line, Some(url.clone())))
2259      {
2260        self.report_error(
2261          &url,
2262          Some(base),
2263          ERROR_CODE_UNREACHABLE,
2264          e.to_string(),
2265        );
2266      }
2267    }
2268    for (url, base, text) in errors {
2269      self.report_error(&url, Some(base), ERROR_CODE_UNREACHABLE, text);
2270    }
2271    for (relay, from, data) in relayed_in {
2272      if self.refused.contains(&from) {
2273        continue;
2274      }
2275      if is_stun(&data) {
2276        self.saw_stun(from);
2277      } else if !self.is_from_selected_pair(relay, from, true) {
2278        continue;
2279      }
2280      let _ = self.pc.handle_read(TaggedBytesMut {
2281        now,
2282        transport: TransportContext {
2283          local_addr: relay,
2284          peer_addr: from,
2285          ecn: None,
2286          transport_protocol: TransportProtocol::UDP,
2287        },
2288        message: data,
2289      });
2290    }
2291    progressed
2292  }
2293
2294  /// Moves the engine's events and received messages to the JS queue.
2295  pub(crate) fn collect_events(&mut self, now: Instant) {
2296    if self.checking_held && self.remote_known {
2297      self.checking_held = false;
2298      if !self.failed {
2299        self.checking_since = Some(now);
2300        self.events.push_back(JsEvent::IceConnectionState {
2301          state: "checking".to_string(),
2302        });
2303      }
2304    }
2305    let mut mid = None::<String>;
2306    // A channel's closing, error and close come after the messages the engine
2307    // delivered with them: the engine queues messages apart from events, and
2308    // a close the peer started follows its data on the wire (RFC 8831
2309    // section 6.7), so none of it may be dropped as arriving "after" close.
2310    let mut closes = Vec::new();
2311    while let Some(event) = self.pc.poll_event() {
2312      match event {
2313        RTCPeerConnectionEvent::OnNegotiationNeededEvent => {
2314          self.events.push_back(JsEvent::NegotiationNeeded)
2315        }
2316        RTCPeerConnectionEvent::OnIceCandidateEvent(e) => {
2317          // The engine's end-of-candidates (a "" candidate) and its null
2318          // candidate: the JS side fires both itself, from the gathering
2319          // state this driver ends (`maybe_complete_gathering`).
2320          let Some(candidate) = e.candidate.filter(|c| !c.end_of_candidates)
2321          else {
2322            continue;
2323          };
2324          if self.options.relay_only
2325            && candidate.typ != RTCIceCandidateType::Relay
2326          {
2327            continue;
2328          }
2329          let Ok(init) = candidate.to_json() else {
2330            continue;
2331          };
2332          if mid.is_none() {
2333            mid = Some(self.first_mid().unwrap_or_else(|| "0".to_string()));
2334          }
2335          let ufrag = self.local_ufrag();
2336          let candidate = self.public_candidate(init.candidate);
2337          self.events.push_back(JsEvent::IceCandidate {
2338            candidate,
2339            sdp_mid: mid.clone(),
2340            sdp_m_line_index: Some(0),
2341            username_fragment: ufrag,
2342            url: e.url.filter(|u| !u.is_empty()),
2343          });
2344        }
2345        RTCPeerConnectionEvent::OnIceCandidateErrorEvent(e) => {
2346          self.events.push_back(JsEvent::IceCandidateError {
2347            address: Some(e.address.clone()).filter(|a| !a.is_empty()),
2348            port: Some(e.port).filter(|p| *p != 0),
2349            url: e.url.clone(),
2350            error_code: e.error_code,
2351            error_text: e.error_text.clone(),
2352          })
2353        }
2354        RTCPeerConnectionEvent::OnSignalingStateChangeEvent(s) => {
2355          self.events.push_back(JsEvent::SignalingState {
2356            state: s.to_string(),
2357          })
2358        }
2359        RTCPeerConnectionEvent::OnIceConnectionStateChangeEvent(s) => {
2360          // rtci 0.2's agent goes `completed` once both sides have ended
2361          // their candidates (`Agent::healthy_state`); the 0.22 engine
2362          // stayed `connected`, as Chromium and WebKit do for these
2363          // connections. It is reported as `connected`: WPT
2364          // RTCRtpTransceiver.https.html's `iceConnected(pc)` resolves only
2365          // on `connected`, so the side it waits for second, already
2366          // `completed`, never resolved and the file timed out
2367          // (`checkSendrecvWithNoSendTrack`, `checkStopAfterCreateAnswer`).
2368          let mut state = s.to_string();
2369          if state == "completed" {
2370            state = "connected".to_string();
2371          }
2372          // An ICE restart on a connected transport keeps its selected pair
2373          // (the engine's previous media path) until the new generation
2374          // selects one, so the transport stays connected: W3C webrtc-pc
2375          // 4.3.3 has `checking` only for a transport with no working pair.
2376          // Its `checking` (and the connection's `connecting`) is not
2377          // reported; a restart from `disconnected` or `failed` is.
2378          if state == "checking" && self.ice_up {
2379            self.restart_masked = true;
2380            continue;
2381          }
2382          if state != "checking" {
2383            self.restart_masked = false;
2384          }
2385          if state == "checking" && !self.remote_known {
2386            self.checking_held = true;
2387            continue;
2388          }
2389          self.checking_held = false;
2390          if state == "connected" || state == "completed" {
2391            self.ice_up = true;
2392            if !self.dtls_connected && self.ice_up_at.is_none() {
2393              self.ice_up_at = Some(now);
2394            }
2395          } else {
2396            self.ice_up = false;
2397            self.ice_up_at = None;
2398          }
2399          self.checking_since =
2400            (state == "checking" && !self.failed).then_some(now);
2401          if !self.failed || state == "closed" {
2402            self.events.push_back(JsEvent::IceConnectionState { state });
2403          }
2404        }
2405        RTCPeerConnectionEvent::OnIceGatheringStateChangeEvent(s) => {
2406          let state = s.to_string();
2407          // W3C webrtc-pc 4.4.4 "update the ICE gathering state": with no
2408          // transport to gather for (a local description without a live
2409          // media section) the state stays where it is; rtci 0.2 still
2410          // reports gathering for one (WPT
2411          // RTCPeerConnection-iceGatheringState "setLocalDescription() with
2412          // no transports should not cause iceGatheringState to change").
2413          // Its `new` (transports closed) is passed on.
2414          if state != "new"
2415            && !self
2416              .pc
2417              .local_description()
2418              .is_some_and(|d| has_live_media_section(&d.sdp))
2419          {
2420            continue;
2421          }
2422          self.events.push_back(JsEvent::IceGatheringState { state })
2423        }
2424        RTCPeerConnectionEvent::OnConnectionStateChangeEvent(s) => {
2425          let state = s.to_string();
2426          if state == "connecting" && self.restart_masked {
2427            continue;
2428          }
2429          if state == "connected" {
2430            self.dtls_connected = true;
2431            self.ice_up_at = None;
2432          }
2433          if !self.failed || state == "closed" {
2434            self.events.push_back(JsEvent::ConnectionState { state });
2435          }
2436        }
2437        RTCPeerConnectionEvent::OnDataChannel(dc) => {
2438          let event = match dc {
2439            RTCDataChannelEvent::OnOpen(handle) => {
2440              self.sent.entry(handle as u32).or_insert(0);
2441              let Some(channel) = self.pc.data_channel(handle) else {
2442                continue;
2443              };
2444              JsEvent::DataChannelOpen {
2445                channel: handle as u32,
2446                id: channel.stream_id(),
2447                label: channel.label().to_string(),
2448                protocol: channel.protocol().to_string(),
2449                ordered: channel.ordered(),
2450                max_packet_life_time: channel.max_packet_life_time(),
2451                max_retransmits: channel.max_retransmits(),
2452                negotiated: channel.negotiated(),
2453                priority: channel.priority(),
2454              }
2455            }
2456            RTCDataChannelEvent::OnClosing(handle) => {
2457              JsEvent::DataChannelClosing {
2458                channel: handle as u32,
2459              }
2460            }
2461            RTCDataChannelEvent::OnClose(handle) => JsEvent::DataChannelClose {
2462              channel: handle as u32,
2463            },
2464            RTCDataChannelEvent::OnError(handle) => {
2465              let error = self.pc.data_channel_error(handle).cloned();
2466              let channel = self.pc.data_channel(handle);
2467              JsEvent::DataChannelError {
2468                channel: handle as u32,
2469                error_detail: error.as_ref().map_or_else(
2470                  || "data-channel-failure".to_string(),
2471                  |e| e.error_detail.to_string(),
2472                ),
2473                message: error
2474                  .as_ref()
2475                  .map(|e| e.message.clone())
2476                  .filter(|m| !m.is_empty())
2477                  .unwrap_or_default(),
2478                sctp_cause_code: error.as_ref().and_then(|e| e.sctp_cause_code),
2479                label: channel.as_ref().map(|c| c.label().to_string()),
2480                id: channel.as_ref().and_then(|c| c.stream_id()),
2481              }
2482            }
2483            // `bufferedamountlow` follows what is sent, not what is
2484            // acknowledged (`track_sent`).
2485            _ => continue,
2486          };
2487          if matches!(event, JsEvent::DataChannelOpen { .. }) {
2488            self.events.push_back(event);
2489          } else {
2490            closes.push(event);
2491          }
2492        }
2493        RTCPeerConnectionEvent::OnTrack(RTCTrackEvent::OnOpen(init)) => {
2494          let index: usize = init.receiver_id.into();
2495          if let Some(key) = self.key_for_receiver_index(index) {
2496            self.media.track_keys.insert(init.track_id.clone(), key);
2497          }
2498        }
2499        _ => {}
2500      }
2501    }
2502    while let Some(message) = self.pc.poll_read() {
2503      match message.message {
2504        RTCMessage::DataChannelMessage(handle, message) => {
2505          self.events.push_back(JsEvent::DataChannelMessage {
2506            channel: handle as u32,
2507            text: message.is_string,
2508            data: Payload::new(message.data.to_vec()),
2509          });
2510        }
2511        RTCMessage::RtpPacket(track_id, packet) => {
2512          let Some(key) = self.key_for_track(&track_id) else {
2513            continue;
2514          };
2515          // A packet unmutes only once this side's negotiation receives on
2516          // the section (`currentDirection`): one the remote sent before it
2517          // stopped (a pacer's queue, a datagram read late) and that is read
2518          // while a renegotiation is still under way is no media of the new
2519          // state.
2520          if !self.media.flowing.contains(&key) && self.receives_now(key) {
2521            self.media.flowing.insert(key);
2522            let generation =
2523              self.media.unmute_generation.get(&key).copied().unwrap_or(0);
2524            self.events.push_back(JsEvent::TrackUnmute {
2525              transceiver: key,
2526              generation,
2527            });
2528          }
2529          self.media.saw_rtp(key, &packet.header);
2530          self.count_received_frame(key, &packet);
2531          // wpt100:mediasink
2532          let sink = self.sink_packet(key, &packet, now);
2533          if let Some((width, height)) = sink.resize {
2534            self.events.push_back(JsEvent::TrackResize {
2535              transceiver: key,
2536              width,
2537              height,
2538            });
2539          }
2540          if let Some(frame) = sink.frame {
2541            self.events.push_back(JsEvent::MediaFrame {
2542              transceiver: key,
2543              key_frame: frame.key_frame,
2544              mime_type: frame.mime_type,
2545              rtp_timestamp: frame.rtp_timestamp,
2546              width: frame.width_height.map(|(w, _)| w),
2547              height: frame.width_height.map(|(_, h)| h),
2548              data: Payload::new(frame.data),
2549            });
2550          }
2551          if let Some(frame) = self.receive_for_transform(key, &packet) {
2552            self.events.push_back(JsEvent::EncodedFrame {
2553              transceiver: key,
2554              data: Payload::new(frame.data),
2555              key_frame: frame.key_frame,
2556              width: frame.width_height.map(|(w, _)| w),
2557              height: frame.width_height.map(|(_, h)| h),
2558              info: frame.info,
2559            });
2560          }
2561          // A frame assembler that lost a frame stays broken until a key
2562          // frame: ask the sender for one (rate-limited per stream).
2563          if self.sink_needs_key_frame(key)
2564            || self.transform_needs_key_frame(key)
2565          {
2566            self.request_key_frame_after_loss(key, packet.header.ssrc, now);
2567          }
2568          if self.media.reading.contains(&key)
2569            && let Ok(bytes) = packet.marshal()
2570          {
2571            self.events.push_back(JsEvent::Rtp {
2572              transceiver: key,
2573              data: Payload::new(bytes.to_vec()),
2574            });
2575          }
2576        }
2577        RTCMessage::RtcpPacket(track_id, packets) => {
2578          if crate::media::wants_key_frame(&packets)
2579            && let Some(key) = self.key_for_track(&track_id)
2580          {
2581            // A fake device's video starts over on its key frame.
2582            if let Some(cursor) = self.media.fake.get_mut(&key) {
2583              cursor.next = 0;
2584            }
2585            self
2586              .events
2587              .push_back(JsEvent::KeyFrameRequest { transceiver: key });
2588          }
2589        }
2590        _ => {}
2591      }
2592    }
2593    self.events.extend(closes);
2594  }
2595
2596  /// Ends gathering once every server answered or gave up.
2597  fn maybe_complete_gathering(&mut self) {
2598    if self.gathering != GatherPhase::Running
2599      || self.binds_pending
2600      || self.resolving > 0
2601      || self.servers.iter().any(ServerClient::pending)
2602    {
2603      return;
2604    }
2605    self.gathering = GatherPhase::Complete;
2606    // An empty candidate is the engine's end-of-candidates: it sets the
2607    // gathering state to "complete" and emits the state change.
2608    let _ = self.pc.add_local_candidate(RTCIceCandidateInit::default());
2609  }
2610
2611  /// One driver pass: loop until the engine and the clients are idle.
2612  fn pump(&mut self) {
2613    let now = Instant::now();
2614    if self
2615      .ice_up_at
2616      .is_some_and(|t| now.duration_since(t) >= DTLS_TIMEOUT)
2617    {
2618      self.ice_up_at = None;
2619      self.fail("DTLS did not connect after ICE did");
2620    }
2621    if let Some(since) = self.checking_since
2622      && now.duration_since(since) >= CHECKING_STALL
2623    {
2624      self.checking_since = None;
2625      if !self.failed && !self.remote_gathered {
2626        self.events.push_back(JsEvent::IceConnectionState {
2627          state: "disconnected".to_string(),
2628        });
2629        self.events.push_back(JsEvent::ConnectionState {
2630          state: "disconnected".to_string(),
2631        });
2632      }
2633    }
2634    for _ in 0..MAX_PUMP_ROUNDS {
2635      let a = self.flush_engine_writes();
2636      let b = self.service_servers(now);
2637      self.maybe_complete_gathering();
2638      self.fail_without_pairs();
2639      // The transports' states before the events they come with (a channel's
2640      // open after its SCTP transport is connected).
2641      self.track_sctp_state();
2642      self.track_dtls_state();
2643      self.collect_events(now);
2644      self.track_sent();
2645      // wpt100:mediasink
2646      self.check_silence(now);
2647      let c = std::mem::take(&mut self.wrote_rtcp);
2648      if !a && !b && !c {
2649        break;
2650      }
2651    }
2652  }
2653
2654  fn next_deadline(&mut self) -> Option<Instant> {
2655    let mut deadline = self.pc.poll_timeout();
2656    for server in &mut self.servers {
2657      if let Some(t) = server.client.poll_timeout() {
2658        deadline = Some(deadline.map_or(t, |d| d.min(t)));
2659      }
2660    }
2661    if let Some(up) = self.ice_up_at {
2662      let t = up + DTLS_TIMEOUT;
2663      deadline = Some(deadline.map_or(t, |d| d.min(t)));
2664    }
2665    if let Some(since) = self.checking_since {
2666      let t = since + CHECKING_STALL;
2667      deadline = Some(deadline.map_or(t, |d| d.min(t)));
2668    }
2669    // wpt100:mediasink
2670    if let Some(t) = self.sinks.silence_deadline() {
2671      deadline = Some(deadline.map_or(t, |d| d.min(t)));
2672    }
2673    deadline
2674  }
2675
2676  fn handle_timeout(&mut self, now: Instant) {
2677    let _ = self.pc.handle_timeout(now);
2678    for server in &mut self.servers {
2679      let _ = server.client.handle_timeout(now);
2680    }
2681  }
2682
2683  fn handle_datagram(&mut self, dg: Datagram) {
2684    if self.refused.contains(&dg.from) {
2685      return;
2686    }
2687    let now = Instant::now();
2688    match dg.via {
2689      Via::Socket => {}
2690      Via::Mdns => {
2691        // Only what a responder sends from its mDNS port; the engine takes
2692        // answers only from the mDNS socket (local port 5353).
2693        if dg.from.port() == MDNS_PORT {
2694          let _ = self.pc.handle_read(TaggedBytesMut {
2695            now,
2696            transport: TransportContext {
2697              local_addr: dg.local,
2698              peer_addr: dg.from,
2699              ecn: None,
2700              transport_protocol: TransportProtocol::UDP,
2701            },
2702            message: dg.data,
2703          });
2704        }
2705        return;
2706      }
2707      Via::IceTcp(id) => {
2708        if dg.closed.is_some() {
2709          if self.tcp_links.get(&dg.from).is_some_and(|l| l.id == id) {
2710            self.tcp_links.remove(&dg.from);
2711          }
2712          return;
2713        }
2714        if !self.tcp_links.get(&dg.from).is_some_and(|l| l.id == id) {
2715          return;
2716        }
2717        if is_stun(&dg.data) {
2718          self.saw_stun(dg.from);
2719        } else {
2720          let from_selected = match self.selected {
2721            Some((_, r)) => self.selected_tcp && r == dg.from,
2722            None => self.ice_up && self.stun_peers.contains(&dg.from),
2723          };
2724          if !from_selected {
2725            return;
2726          }
2727        }
2728        let local = self.tcp_local(dg.local);
2729        let _ = self.pc.handle_read(TaggedBytesMut {
2730          now,
2731          transport: TransportContext {
2732            local_addr: local,
2733            peer_addr: dg.from,
2734            ecn: None,
2735            transport_protocol: TransportProtocol::TCP,
2736          },
2737          message: dg.data,
2738        });
2739        return;
2740      }
2741    }
2742    if let (Some(index), Some(reason)) = (dg.stream, dg.closed.as_ref()) {
2743      if let Some(server) = self.servers.get_mut(index) {
2744        let (url, base) = (server.url.clone(), server.base);
2745        server.binding = None;
2746        server.allocate = None;
2747        server.relay = None;
2748        self.report_error(
2749          &url,
2750          Some(base),
2751          ERROR_CODE_UNREACHABLE,
2752          format!("The TURN connection ended: {reason}"),
2753        );
2754      }
2755      return;
2756    }
2757    if let Some(index) = dg.stream {
2758      if let Some(server) = self.servers.get_mut(index) {
2759        let protocol = server.protocol();
2760        let _ = server.client.handle_read(TaggedBytesMut {
2761          now,
2762          transport: TransportContext {
2763            local_addr: server.base,
2764            peer_addr: dg.from,
2765            ecn: None,
2766            transport_protocol: protocol,
2767          },
2768          message: dg.data,
2769        });
2770      }
2771      return;
2772    }
2773    // A reply from a STUN/TURN server on the UDP socket.
2774    if let Some(server) = self.servers.iter_mut().find(|s| {
2775      matches!(s.link, ServerLink::Udp)
2776        && s.server == dg.from
2777        && s.base.port() == dg.local.port()
2778    }) {
2779      let base = server.base;
2780      let _ = server.client.handle_read(TaggedBytesMut {
2781        now,
2782        transport: TransportContext {
2783          local_addr: base,
2784          peer_addr: dg.from,
2785          ecn: None,
2786          transport_protocol: TransportProtocol::UDP,
2787        },
2788        message: dg.data,
2789      });
2790      return;
2791    }
2792    let Some(endpoint) = self
2793      .endpoints
2794      .iter()
2795      .position(|e| e.bound.port() == dg.local.port())
2796    else {
2797      return;
2798    };
2799    let local = self.local_for(endpoint, dg.from);
2800    if is_stun(&dg.data) {
2801      self.saw_stun(dg.from);
2802    } else if !self.is_from_selected_pair(local, dg.from, false) {
2803      return;
2804    }
2805    let _ = self.pc.handle_read(TaggedBytesMut {
2806      now,
2807      transport: TransportContext {
2808        local_addr: local,
2809        peer_addr: dg.from,
2810        ecn: dg.ecn,
2811        transport_protocol: TransportProtocol::UDP,
2812      },
2813      message: dg.data,
2814    });
2815  }
2816}
2817
2818impl Peer {
2819  pub fn new(
2820    options: PeerOptions,
2821    guard: Rc<dyn NetGate>,
2822    io: Rc<dyn NetIo>,
2823  ) -> Result<Rc<Self>, Error> {
2824    let config = RTCConfigurationBuilder::new()
2825      .with_certificates(options.certificates.clone())
2826      .with_bundle_policy(options.bundle_policy)
2827      .build();
2828    let pacer_refusals = Arc::<crate::media::PacerRefusals>::default();
2829    let (media_engine, registry) =
2830      crate::media::media_stack_counting(pacer_refusals.clone())?;
2831    // Messages up to 256 KiB, as browsers take (the engine's own default is
2832    // RFC 8841's 64 KiB); the connection's maxMessageSize is the smaller of
2833    // this and the peer's.
2834    let net = options.network.as_ref().map(|n| &n.options);
2835    // An ICE restart starts a new gathering phase (`regather`), so the
2836    // previous generation's local candidates go with the old credentials.
2837    let mut settings = SettingEngineBuilder::new()
2838      .with_discard_local_candidates_during_ice_restart(true)
2839      // A new DTLS association (a peer's new `a=tls-id`, the engine's SRTP
2840      // re-keying) keeps the sockets this driver has: one per family, or a
2841      // network's shared port, which can't move to new ports (RFC 8842
2842      // section 5.1's new 3-tuple is left to the peer). The engine's default
2843      // would refuse their addresses and wait for candidates on new ports.
2844      .with_dtls_new_association_on_previous_addresses(true)
2845      .with_sctp_max_message_size(SctpMaxMessageSize::Bounded(
2846        net
2847          .and_then(|n| n.max_message_size)
2848          .unwrap_or(SctpMaxMessageSize::MAX_MESSAGE_SIZE),
2849      ))
2850      // ECN (L4S): the engine marks the RTP of a stream that negotiated
2851      // `ack ccfb` ECT(1) and counts the codepoints datagrams arrive with,
2852      // which the UDP sockets carry both ways where the platform lets them
2853      // (`crate::ecn`). Over ICE-TCP and TURN relays nothing is marked on
2854      // the wire, which the remote's feedback reports as bleached.
2855      .with_ecn(crate::ecn::supported())
2856      // A bundle-only section of an initial offer (every section but the
2857      // first under `max-bundle`, a second section of one media type under
2858      // `balanced`) in the form browsers take: `a=rtcp-mux` and the group's
2859      // ICE credentials in it (rtci's `Chrome` profile value). Chromium,
2860      // WebKit and Firefox refuse the RFC 9143 / RFC 9429 section 5.2.1 form
2861      // ("rtcp-mux must be enabled when BUNDLE is enabled."), and this side
2862      // offers to browsers.
2863      .with_bundle_only_sections_in_browser_form(true)
2864      // An app that never relays the peer's end-of-candidates (the common
2865      // `if (e.candidate) pc.addIceCandidate(e.candidate)`) still reaches
2866      // `failed` once the RFC 8863 PAC timer runs out, as Chrome, Safari and
2867      // Firefox do, instead of staying `disconnected` for ever.
2868      .with_ice_failed_without_end_of_candidates(true);
2869    if let Some(net) = net {
2870      settings = settings.with_lite(net.ice_lite);
2871      if let Some((disconnected, failed, keep_alive)) = net.ice_timeouts {
2872        settings = settings.with_ice_timeouts(disconnected, failed, keep_alive);
2873      }
2874    }
2875    // mDNS: what the network asks for (resolving the peer's `.local`
2876    // candidates by default, as browsers do), when it can be used here.
2877    // A gate that hasn't answered yet leaves the connection resolving names
2878    // only, once it allows (publishing them needs the socket now).
2879    let gate = GateCache::new(guard);
2880    let mut mdns_note = None;
2881    let mut mdns_token = None;
2882    let mdns_mode = match net.map(|n| n.mdns).unwrap_or_default() {
2883      MdnsMode::Off => MdnsMode::Off,
2884      wanted => {
2885        match crate::rt::poll_now(Box::pin(mdns_permitted(gate.clone()))) {
2886          Ok(Ok(token)) => {
2887            mdns_token = Some(token);
2888            wanted
2889          }
2890          Ok(Err(why)) => {
2891            if wanted == MdnsMode::Gather {
2892              mdns_note = Some(format!(
2893                "Host candidates are not published under mDNS names: {why}"
2894              ));
2895            }
2896            MdnsMode::Off
2897          }
2898          Err(_asked) => {
2899            if wanted == MdnsMode::Gather {
2900              mdns_note = Some(
2901                "Host candidates are not published under mDNS names: the \
2902                 permission gate has not answered yet"
2903                  .to_string(),
2904              );
2905            }
2906            MdnsMode::Resolve
2907          }
2908        }
2909      }
2910    };
2911    // Publishing names nobody could resolve would hide the host candidates
2912    // for nothing: the socket is opened first, and a failure keeps them
2913    // literal.
2914    let mut mdns_socket = None;
2915    let mdns_mode = if mdns_mode == MdnsMode::Gather
2916      && let Some(token) = &mdns_token
2917    {
2918      match io.bind_mdns(
2919        token,
2920        &interface_addresses(net.and_then(|n| n.interfaces.as_deref())),
2921      ) {
2922        Ok(socket) => {
2923          mdns_socket = Some(Rc::new(EcnUdpSocket::plain(socket)));
2924          MdnsMode::Gather
2925        }
2926        Err(e) => {
2927          mdns_note = Some(format!(
2928            "Host candidates are not published under mDNS names: {e}"
2929          ));
2930          MdnsMode::Resolve
2931        }
2932      }
2933    } else {
2934      mdns_mode
2935    };
2936    // 1:1 NAT in host mode: the engine announces a mapped host candidate on
2937    // the public address and keeps its private socket as the base, which is
2938    // what its remote-address policy pairs (a loopback remote only from a
2939    // loopback base). It can't map an mDNS name.
2940    let engine_nat = mdns_mode != MdnsMode::Gather
2941      && net.is_some_and(|n| !n.public_srflx && !n.public_addresses.is_empty());
2942    if engine_nat && let Some(net) = net {
2943      settings = settings.with_nat_1to1_ips(
2944        net
2945          .public_addresses
2946          .iter()
2947          .map(|p| match p.private {
2948            Some(private) => format!("{}/{private}", p.public),
2949            None => p.public.to_string(),
2950          })
2951          .collect(),
2952        RTCIceCandidateType::Host,
2953      );
2954    }
2955    settings = settings
2956      .with_multicast_dns_mode(match mdns_mode {
2957        MdnsMode::Off => MulticastDnsMode::Disabled,
2958        MdnsMode::Resolve => MulticastDnsMode::QueryOnly,
2959        MdnsMode::Gather => MulticastDnsMode::QueryAndGather,
2960      })
2961      .with_multicast_dns_timeout(Some(MDNS_QUERY_TIMEOUT));
2962    let settings = settings.build();
2963    let pc = RTCPeerConnectionBuilder::new()
2964      .with_configuration(config)
2965      .with_setting_engine(settings)
2966      .with_media_engine(media_engine)
2967      .with_interceptor_registry(registry)
2968      .build(Instant::now())
2969      .map_err(rtc_err)?;
2970    let (recv_tx, recv_rx) = mpsc::channel(RECV_QUEUE);
2971    let mut events = VecDeque::new();
2972    if let Some(note) = mdns_note {
2973      events.push_back(JsEvent::IceCandidateError {
2974        address: None,
2975        port: None,
2976        url: String::new(),
2977        error_code: ERROR_CODE_UNREACHABLE,
2978        error_text: note,
2979      });
2980    }
2981    let peer = Rc::new_cyclic(|this| Self {
2982      core: RefCell::new(Core {
2983        pc,
2984        options,
2985        endpoints: Vec::new(),
2986        servers: Vec::new(),
2987        gathering: GatherPhase::NotStarted,
2988        resolving: 0,
2989        binds_pending: false,
2990        srflx_seen: HashSet::new(),
2991        events,
2992        allowed: HashSet::new(),
2993        refused: HashSet::new(),
2994        routes: HashMap::new(),
2995        selected: None,
2996        stun_peers: HashSet::new(),
2997        ice_up: false,
2998        ice_up_at: None,
2999        dtls_connected: false,
3000        failed: false,
3001        recv_tx,
3002        recv_rx: Some(recv_rx),
3003        media: MediaState {
3004          pacer_refusals,
3005          ..Default::default()
3006        },
3007        transforms: Default::default(),
3008        sinks: Default::default(),
3009        remote_known: false,
3010        wrote_rtcp: false,
3011        sent: HashMap::new(),
3012        sctp_state: "",
3013        dtls_state: String::new(),
3014        local_gathered: 0,
3015        remote_gathered: false,
3016        checking_held: false,
3017        restart_masked: false,
3018        checking_since: None,
3019        this: this.clone(),
3020        io: io.clone(),
3021        gate: gate.clone(),
3022        tcp_links: HashMap::new(),
3023        tcp_dialing: HashMap::new(),
3024        next_tcp_link: 0,
3025        selected_tcp: false,
3026        mdns_mode,
3027        mdns_socket: mdns_socket.clone(),
3028        mdns_failed: false,
3029        mdns_token,
3030        engine_nat,
3031        remote_simulcast_lines: Vec::new(),
3032      }),
3033      gate,
3034      ops: RefCell::new(VecDeque::new()),
3035      current_op: Cell::new(None),
3036      ops_running: Cell::new(false),
3037      last_op: Cell::new(0),
3038      wake: Notify::new(),
3039      events_ready: Notify::new(),
3040      cancel: Cancel::new(),
3041      closed: Cell::new(false),
3042      driver_started: Cell::new(false),
3043    });
3044    // An answer lets held-back sends go (the driver tries them again).
3045    // Operations waiting on it hold their own futures.
3046    let weak = Rc::downgrade(&peer);
3047    peer.gate.set_on_answer(move || {
3048      if let Some(peer) = weak.upgrade() {
3049        peer.poke();
3050      }
3051    });
3052    if let Some(socket) = mdns_socket {
3053      spawn_udp_reader_via(
3054        socket,
3055        SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), MDNS_PORT),
3056        peer.core.borrow().recv_tx.clone(),
3057        peer.cancel.clone(),
3058        Via::Mdns,
3059      );
3060    }
3061    Ok(peer)
3062  }
3063
3064  pub fn is_closed(&self) -> bool {
3065    self.closed.get()
3066  }
3067
3068  /// The panic boundary: runs `f` on the engine; a panic poisons the
3069  /// connection (`failed`, then closed) and becomes an `OperationError`.
3070  fn guarded<T>(
3071    &self,
3072    f: impl FnOnce(&mut Core) -> Result<T, Error>,
3073  ) -> Result<T, Error> {
3074    if self.closed.get() {
3075      return Err(Error::new(
3076        ErrorKind::InvalidState,
3077        "RTCPeerConnection is closed".to_string(),
3078      ));
3079    }
3080    let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
3081      f(&mut self.core.borrow_mut())
3082    }));
3083    match result {
3084      Ok(r) => r,
3085      Err(_) => {
3086        self.poison();
3087        Err(Error::new(
3088          ErrorKind::Operation,
3089          "the WebRTC engine failed; the connection is closed".to_string(),
3090        ))
3091      }
3092    }
3093  }
3094
3095  fn poison(&self) {
3096    if let Ok(mut core) = self.core.try_borrow_mut() {
3097      core.fail("engine panic");
3098    }
3099    self.shutdown(false);
3100  }
3101
3102  /// Ops call this after changing the engine: the driver flushes what the
3103  /// change produced and JavaScript gets the resulting events.
3104  pub fn poke(&self) {
3105    self.wake.notify_one();
3106  }
3107
3108  /// The next batch of events, or `None` once the connection is closed and
3109  /// the queue is drained.
3110  pub async fn next_events(&self) -> Option<Vec<JsEvent>> {
3111    loop {
3112      {
3113        let mut core = self.core.borrow_mut();
3114        if !core.events.is_empty() {
3115          return Some(core.events.drain(..).collect());
3116        }
3117        if self.closed.get() {
3118          return None;
3119        }
3120      }
3121      self.events_ready.notified().await;
3122    }
3123  }
3124
3125  pub fn create_offer(
3126    self: &Rc<Self>,
3127    ice_restart: bool,
3128  ) -> Result<String, Error> {
3129    let sdp = self.guarded(|core| {
3130      if ice_restart {
3131        core.pc.restart_ice();
3132      }
3133      Ok(core.pc.create_offer(None).map_err(rtc_err)?.sdp)
3134    })?;
3135    Ok(sdp)
3136  }
3137
3138  /// `setConfiguration`: the ICE servers and policy the next gathering
3139  /// (an ICE restart) uses.
3140  pub fn set_ice_servers(
3141    &self,
3142    specs: Vec<IceServerSpec>,
3143    relay_only: bool,
3144    tls: Option<Arc<rustls::ClientConfig>>,
3145  ) {
3146    let mut core = self.core.borrow_mut();
3147    core.options.ice_servers = specs;
3148    core.options.relay_only = relay_only;
3149    if tls.is_some() {
3150      core.options.tls = tls;
3151    }
3152  }
3153
3154  pub fn selected_pair(&self) -> Option<(SocketAddr, SocketAddr)> {
3155    self.core.borrow().selected
3156  }
3157
3158  /// The ICE agent's selected candidate pair (W3C webrtc-pc 5.6
3159  /// `getSelectedCandidatePair()`): the nominated pair as soon as ICE has
3160  /// one, on the controlled side too, before either side sent anything on it.
3161  /// `None` before that, or when the connection is closed.
3162  pub fn ice_selected_pair(&self) -> Option<SelectedPair> {
3163    if self.closed.get() {
3164      return None;
3165    }
3166    self
3167      .guarded(|core| Ok(core.ice_selected_pair()))
3168      .ok()
3169      .flatten()
3170  }
3171
3172  /// Whether the selected pair is an ICE-TCP one.
3173  pub fn selected_is_tcp(&self) -> bool {
3174    self.core.borrow().selected_tcp
3175  }
3176
3177  /// The engine's answer. It lists only the formats the remote offer has
3178  /// (rtci 0.3's default, `with_answer_offered_formats_only`), so a peer
3179  /// can't switch to a format its offer lacked (DENEXT.md item 565).
3180  pub fn create_answer(&self) -> Result<String, Error> {
3181    self.guarded(|core| Ok(core.pc.create_answer(None).map_err(rtc_err)?.sdp))
3182  }
3183
3184  fn description(
3185    kind: &str,
3186    sdp: String,
3187  ) -> Result<RTCSessionDescription, Error> {
3188    match kind {
3189      "offer" => RTCSessionDescription::offer(sdp),
3190      "answer" => RTCSessionDescription::answer(sdp),
3191      "pranswer" => RTCSessionDescription::pranswer(sdp),
3192      "rollback" => RTCSessionDescription::rollback(None),
3193      other => {
3194        return Err(Error::new(
3195          ErrorKind::Type,
3196          format!("'{other}' is not a valid RTCSdpType"),
3197        ));
3198      }
3199    }
3200    .map_err(rtc_err)
3201  }
3202
3203  pub fn set_local_description(
3204    self: &Rc<Self>,
3205    kind: &str,
3206    sdp: String,
3207  ) -> Result<(), Error> {
3208    check_sdp_size(kind, &sdp)?;
3209    // Gathering starts with the first description that has a transport to
3210    // gather for (W3C: an m-section that isn't rejected).
3211    let has_transport = has_live_media_section(&sdp);
3212    let desc = Self::description(kind, sdp)?;
3213    let restarted = self.guarded(|core| {
3214      let ufrag_before = core.local_ufrag();
3215      let applied = core.pc.set_local_description(Instant::now(), desc);
3216      // The engine may have removed transceivers (a rollback, an answer
3217      // rejecting a stopped one's section), even on the way to an error.
3218      core.sync_removed_transceivers();
3219      applied.map_err(|e| match e {
3220        // JSEP: an offer or answer other than the last one created.
3221        RtcError::ErrSDPDoesNotMatchOffer
3222        | RtcError::ErrSDPDoesNotMatchAnswer => {
3223          Error::new(ErrorKind::InvalidModification, e.to_string())
3224        }
3225        e => description_err(e),
3226      })?;
3227      Ok(
3228        kind != "rollback"
3229          && ufrag_before.is_some()
3230          && core.local_ufrag() != ufrag_before,
3231      )
3232    })?;
3233    if kind != "rollback" && has_transport {
3234      if restarted {
3235        self.regather();
3236      } else {
3237        self.start_gathering();
3238      }
3239      self.register_on_shared_port();
3240    }
3241    self.ensure_driver();
3242    self.poke();
3243    Ok(())
3244  }
3245
3246  /// On a shared-port network, the local ufrag routes the remote peer's
3247  /// checks to this connection (registered again after an ICE restart).
3248  fn register_on_shared_port(&self) {
3249    let core = self.core.borrow();
3250    if let Some(net) = core
3251      .options
3252      .network
3253      .as_ref()
3254      .filter(|n| n.routes_by_ufrag())
3255      && let Some(ufrag) = core.local_ufrag()
3256    {
3257      net.register_ufrag(ufrag, &core.this);
3258    }
3259  }
3260
3261  /// A datagram a shared-port network routed to this connection.
3262  pub(crate) fn deliver(&self, dg: Datagram) {
3263    if self.closed.get() {
3264      return;
3265    }
3266    if let Ok(core) = self.core.try_borrow() {
3267      let _ = core.recv_tx.try_send(dg);
3268    }
3269  }
3270
3271  /// Runs `op` here when no operation is waiting and the gate answers at
3272  /// once (its `opdone` is queued before this returns), else queues it
3273  /// behind the others; returns its id.
3274  fn submit_op(self: &Rc<Self>, op: PendingOp) -> u32 {
3275    let id = self.last_op.get().wrapping_add(1);
3276    self.last_op.set(id);
3277    if self.ops_running.get() || !self.ops.borrow().is_empty() {
3278      self.ops.borrow_mut().push_back((id, op));
3279      return id;
3280    }
3281    match crate::rt::poll_now(op) {
3282      Ok(result) => self.op_done(id, result),
3283      Err(op) => {
3284        self.ops.borrow_mut().push_back((id, op));
3285        self.ops_running.set(true);
3286        let peer = self.clone();
3287        let cancel = self.cancel.clone();
3288        crate::rt::spawn(async move {
3289          let _ = Self::run_ops(peer).or_cancel(cancel).await;
3290        });
3291      }
3292    }
3293    id
3294  }
3295
3296  /// Runs the queued operations in order (closing the connection cancels
3297  /// this; `shutdown` reports the ones left).
3298  async fn run_ops(peer: Rc<Self>) {
3299    loop {
3300      let next = peer.ops.borrow_mut().pop_front();
3301      let Some((id, op)) = next else {
3302        break;
3303      };
3304      peer.current_op.set(Some(id));
3305      let result = op.await;
3306      if peer.current_op.take() == Some(id) {
3307        peer.op_done(id, result);
3308      }
3309    }
3310    peer.ops_running.set(false);
3311  }
3312
3313  /// Queues the `opdone` event for operation `op`.
3314  fn op_done(&self, op: u32, result: Result<(), Error>) {
3315    self.core.borrow_mut().events.push_back(JsEvent::OpDone {
3316      op,
3317      error: result.err(),
3318    });
3319    self.events_ready.notify_one();
3320  }
3321
3322  fn check_open(&self) -> Result<(), Error> {
3323    if self.closed.get() {
3324      return Err(Error::new(
3325        ErrorKind::InvalidState,
3326        "RTCPeerConnection is closed".to_string(),
3327      ));
3328    }
3329    Ok(())
3330  }
3331
3332  /// Whether the connection can resolve `.local` candidates now, waiting
3333  /// for the gate's answer for the mDNS socket if it was asked (and
3334  /// opening the socket on the first allow).
3335  async fn mdns_ready(self: &Rc<Self>) -> bool {
3336    {
3337      let core = self.core.borrow();
3338      if core.mdns_socket.is_some() {
3339        return true;
3340      }
3341      if core.mdns_mode == MdnsMode::Off || core.mdns_failed {
3342        return false;
3343      }
3344    }
3345    if self.core.borrow().mdns_token.is_none() {
3346      match mdns_permitted(self.gate.clone()).await {
3347        Ok(token) => self.core.borrow_mut().mdns_token = Some(token),
3348        Err(why) => {
3349          log::debug!("webrtc: mDNS is not used: {why}");
3350          self.core.borrow_mut().mdns_failed = true;
3351          return false;
3352        }
3353      }
3354    }
3355    if self.closed.get() {
3356      return false;
3357    }
3358    self.core.borrow_mut().resolves_mdns()
3359  }
3360
3361  /// Checks every candidate the remote description carries and hands the
3362  /// engine a copy without the ones it can't use (see
3363  /// [`RemoteCandidate::Ignore`]). A refused address fails the whole call.
3364  ///
3365  /// Two-phase: an `Err` here is an argument error (a closed connection, an
3366  /// oversized description, an invalid type, a malformed candidate). The
3367  /// rest happens once the gate answered for every candidate (at once with
3368  /// a gate that decides, before this returns), and its outcome is the
3369  /// `opdone` event whose `op` is the id returned: no `error` when the
3370  /// description was applied, else a [`ErrorKind::NotCapable`] refusal or
3371  /// the engine's error. Operations complete in the order they were made.
3372  pub fn set_remote_description(
3373    self: &Rc<Self>,
3374    kind: &str,
3375    sdp: String,
3376  ) -> Result<u32, Error> {
3377    self.check_open()?;
3378    check_sdp_size(kind, &sdp)?;
3379    if !matches!(kind, "offer" | "answer" | "pranswer" | "rollback") {
3380      return Err(Error::new(
3381        ErrorKind::Type,
3382        format!("'{kind}' is not a valid RTCSdpType"),
3383      ));
3384    }
3385    // The lines the engine is given, each with the condition it is kept on.
3386    let mut lines: Vec<(String, Keep)> = Vec::new();
3387    let mut simulcast_lines = Vec::new();
3388    let mut section_rids: Vec<String> = Vec::new();
3389    // A candidate kept without an address to check: an active TCP one.
3390    let mut unchecked = false;
3391    let (tcp, mdns) = {
3392      let core = self.core.borrow();
3393      (core.ice_tcp(), core.mdns_mode != MdnsMode::Off)
3394    };
3395    for line in sdp.split_inclusive('\n') {
3396      // webrtc-identity: JavaScript validates the a=identity assertion
3397      // (06_identity.js), and a malformed one rejects `peerIdentity`, not the
3398      // description; the engine's RFC 8827 grammar would refuse the whole
3399      // description, so it isn't given one it can't parse.
3400      if let Some(value) = line.trim_end().strip_prefix("a=identity:")
3401        && !is_identity_value(value)
3402      {
3403        continue;
3404      }
3405      // RFC 8866 section 9's `attribute-name` is a token: a line such as
3406      // `a=notssrc1 cname:x` (WPT RTCPeerConnection-connectionState munges
3407      // `a=ssrc:` so, to hide the SSRCs) names no attribute anyone knows,
3408      // which browsers ignore as an attribute they don't understand (RFC
3409      // 9429 section 5.8); rtci 0.2's parser refuses the description for it.
3410      if let Some(attribute) = line.trim_end().strip_prefix("a=")
3411        && !is_attribute_name(
3412          attribute
3413            .split_once(':')
3414            .map_or(attribute, |(name, _)| name),
3415        )
3416      {
3417        continue;
3418      }
3419      // An `a=extmap` line whose extension is not named by an absolute URI
3420      // (RFC 8285 section 5: "The URI ... MUST be absolute") is one no
3421      // endpoint understands, which an answerer leaves out (section 7, WPT
3422      // `protocol/rtp-headerextensions` "Negotiates the subset of supported
3423      // extensions offered" offers `bogus`). rtci 0.2 takes it into its
3424      // negotiated extensions and then fails to write the answer ("url
3425      // parse: relative URL without a base"), so it isn't given the line.
3426      if let Some(value) = line.trim_end().strip_prefix("a=extmap:")
3427        && !extmap_names_absolute_uris(value)
3428      {
3429        continue;
3430      }
3431      // A media section's rids are its own (RFC 8851 section 4).
3432      if line.starts_with("m=") {
3433        section_rids.clear();
3434      }
3435      // A second `a=rid` line for a rid-id the section declared already
3436      // (WPT `simulcast/negotiation-encodings` writes one per entry of
3437      // `a=simulcast:recv foo;bar;foo`): the engine is given the first one
3438      // only, as the repeated rid in `a=simulcast` is dropped below; with
3439      // both it negotiated no simulcast in its answer.
3440      if let Some(value) = line.trim_end().strip_prefix("a=rid:") {
3441        let id = value.split(' ').next().unwrap_or_default().to_string();
3442        if section_rids.contains(&id) {
3443          continue;
3444        }
3445        section_rids.push(id);
3446      }
3447      if let Some(value) = line.trim_end().strip_prefix("a=simulcast:")
3448        && let Some(deduped) = simulcast_without_repeated_rids(value)
3449      {
3450        let end = &line[line.trim_end().len()..];
3451        let engine_line = format!("a=simulcast:{deduped}");
3452        lines.push((format!("{engine_line}{end}"), Keep::Always));
3453        simulcast_lines.push((engine_line, line.trim_end().to_string()));
3454        continue;
3455      }
3456      if let Some(value) = line.trim_end().strip_prefix("a=candidate:") {
3457        let keep = match classify_remote_candidate(value, tcp, mdns)? {
3458          RemoteCandidate::Ignore => continue,
3459          RemoteCandidate::Active => {
3460            unchecked = true;
3461            Keep::Always
3462          }
3463          RemoteCandidate::Udp(addr) => Keep::Allowed(Reach::connect(
3464            ReachKind::RemoteCandidate,
3465            Proto::Udp,
3466            addr,
3467          )),
3468          RemoteCandidate::Tcp(addr) => Keep::Allowed(Reach::connect(
3469            ReachKind::RemoteCandidate,
3470            Proto::Tcp,
3471            addr,
3472          )),
3473          RemoteCandidate::Mdns => Keep::Mdns,
3474        };
3475        lines.push((line.to_string(), keep));
3476        continue;
3477      }
3478      lines.push((line.to_string(), Keep::Always));
3479    }
3480    let kind = kind.to_string();
3481    let peer = self.clone();
3482    Ok(self.submit_op(Box::pin(async move {
3483      // Each candidate's address in order; the first refusal fails the call.
3484      let mut checked = Vec::new();
3485      for (_, keep) in &lines {
3486        if let Keep::Allowed(reach) = keep {
3487          peer
3488            .gate
3489            .verdict(reach.clone())
3490            .await
3491            .map_err(Error::not_capable)?;
3492          checked.extend(reach.socket_addr());
3493        }
3494      }
3495      // `.local` candidates, all kept or all skipped.
3496      let mdns = if lines.iter().any(|(_, k)| matches!(k, Keep::Mdns)) {
3497        let ready = peer.mdns_ready().await;
3498        unchecked |= ready;
3499        ready
3500      } else {
3501        false
3502      };
3503      let kept: String = lines
3504        .iter()
3505        .filter(|(_, k)| mdns || !matches!(k, Keep::Mdns))
3506        .map(|(l, _)| l.as_str())
3507        .collect();
3508      let end_of_candidates =
3509        kept.lines().any(|l| l.trim_end() == "a=end-of-candidates");
3510      let desc = Self::description(&kind, kept)?;
3511      peer.guarded(|core| {
3512        let ufrag_before = core.remote_ufrag();
3513        let applied = core.pc.set_remote_description(Instant::now(), desc);
3514        core.sync_removed_transceivers();
3515        applied.map_err(description_err)?;
3516        core.remote_simulcast_lines = simulcast_lines;
3517        // An ICE restart by the remote side: its candidates, and its
3518        // end-of-candidates, start over.
3519        if ufrag_before.is_some() && core.remote_ufrag() != ufrag_before {
3520          core.remote_known = false;
3521          core.remote_gathered = false;
3522        }
3523        if end_of_candidates {
3524          core.remote_gathered = true;
3525        }
3526        for addr in checked {
3527          core.mark_allowed(addr);
3528        }
3529        if unchecked {
3530          core.remote_known = true;
3531        }
3532        Ok(())
3533      })?;
3534      peer.ensure_driver();
3535      peer.poke();
3536      Ok(())
3537    })))
3538  }
3539
3540  /// Two-phase, as [`Peer::set_remote_description`]: an `Err` is an
3541  /// argument error (a closed connection, a malformed candidate); the
3542  /// outcome (a refused address, the engine's error, or none) is the
3543  /// `opdone` event for the id returned.
3544  pub fn add_ice_candidate(
3545    &self,
3546    candidate: String,
3547    sdp_mid: Option<String>,
3548    sdp_m_line_index: Option<u16>,
3549    username_fragment: Option<String>,
3550  ) -> Result<u32, Error> {
3551    self.check_open()?;
3552    let Some(peer) = self.core.borrow().this.upgrade() else {
3553      return Err(Error::new(
3554        ErrorKind::InvalidState,
3555        "RTCPeerConnection is closed".to_string(),
3556      ));
3557    };
3558    let init = |candidate: String| RTCIceCandidateInit {
3559      candidate,
3560      sdp_mid: sdp_mid.clone(),
3561      sdp_mline_index: sdp_m_line_index,
3562      username_fragment: username_fragment.clone(),
3563      url: None,
3564      relay_protocol: None,
3565    };
3566    if candidate.trim().is_empty() {
3567      // End-of-candidates: the engine checks the media section and the
3568      // usernameFragment and marks the remote description; then the
3569      // remote's current generation is complete.
3570      let init = init(String::new());
3571      let this = peer.clone();
3572      return Ok(peer.submit_op(Box::pin(async move {
3573        this.guarded(|core| {
3574          core.pc.add_remote_candidate(init).map_err(rtc_err)?;
3575          core.remote_gathered = true;
3576          Ok(())
3577        })?;
3578        this.poke();
3579        Ok(())
3580      })));
3581    }
3582    let (tcp, mdns) = {
3583      let core = self.core.borrow();
3584      (core.ice_tcp(), core.mdns_mode != MdnsMode::Off)
3585    };
3586    let class = classify_remote_candidate(&candidate, tcp, mdns)?;
3587    let init = init(candidate);
3588    let this = peer.clone();
3589    Ok(peer.submit_op(Box::pin(async move {
3590      let addr = match class {
3591        RemoteCandidate::Ignore => return Ok(()),
3592        RemoteCandidate::Active => None,
3593        RemoteCandidate::Mdns => {
3594          if !this.mdns_ready().await {
3595            return Ok(());
3596          }
3597          None
3598        }
3599        RemoteCandidate::Udp(addr) => Some((addr, Proto::Udp)),
3600        RemoteCandidate::Tcp(addr) => Some((addr, Proto::Tcp)),
3601      };
3602      if let Some((addr, proto)) = addr {
3603        this
3604          .gate
3605          .verdict(Reach::connect(ReachKind::RemoteCandidate, proto, addr))
3606          .await
3607          .map_err(Error::not_capable)?;
3608      }
3609      this.guarded(|core| {
3610        core.pc.add_remote_candidate(init).map_err(rtc_err)?;
3611        match addr {
3612          Some((addr, _)) => core.mark_allowed(addr),
3613          None => core.remote_known = true,
3614        }
3615        Ok(())
3616      })?;
3617      this.poke();
3618      Ok(())
3619    })))
3620  }
3621
3622  /// Returns the channel's engine handle and its SCTP stream id when it
3623  /// already has one (a negotiated channel).
3624  pub fn create_data_channel(
3625    self: &Rc<Self>,
3626    label: &str,
3627    init: RTCDataChannelInit,
3628  ) -> Result<(u32, Option<u16>), Error> {
3629    let created = self.guarded(|core| {
3630      let channel = core
3631        .pc
3632        .create_data_channel(label, Some(init))
3633        .map_err(rtc_err)?;
3634      let handle = channel.id() as u32;
3635      let id = channel.stream_id();
3636      core.sent.insert(handle, 0);
3637      // A negotiated channel created on a live association is open at once
3638      // and the engine reports no open for it; JavaScript still gets its
3639      // `open` event (asynchronously, as the spec has it).
3640      if channel.ready_state() == RTCDataChannelState::Open {
3641        let open = JsEvent::DataChannelOpen {
3642          channel: handle,
3643          id,
3644          label: channel.label().to_string(),
3645          protocol: channel.protocol().to_string(),
3646          ordered: channel.ordered(),
3647          max_packet_life_time: channel.max_packet_life_time(),
3648          max_retransmits: channel.max_retransmits(),
3649          negotiated: channel.negotiated(),
3650          priority: channel.priority(),
3651        };
3652        core.events.push_back(open);
3653      }
3654      Ok((handle, id))
3655    })?;
3656    self.events_ready.notify_one();
3657    self.poke();
3658    Ok(created)
3659  }
3660
3661  /// Sends one message and returns the channel's buffered amount after it.
3662  pub fn send(
3663    &self,
3664    handle: u32,
3665    text: bool,
3666    data: &[u8],
3667  ) -> Result<u32, Error> {
3668    let buffered = self.guarded(|core| {
3669      let Some(mut channel) = core.pc.data_channel(handle as RTCDataChannelId)
3670      else {
3671        return Err(Error::new(ErrorKind::InvalidState,
3672          "RTCDataChannel is closed".to_string(),
3673        ));
3674      };
3675      let now = Instant::now();
3676      let sent = if text {
3677        let s = std::str::from_utf8(data)
3678          .map_err(|e| Error::new(ErrorKind::Type, e.to_string()))?;
3679        channel.send_text(now, s)
3680      } else {
3681        channel.send(now, BytesMut::from(data))
3682      };
3683      match sent {
3684        Ok(()) => {}
3685        // W3C: a message over the SCTP transport's maxMessageSize is a
3686        // TypeError; a channel that isn't open an InvalidStateError.
3687        Err(RtcError::ErrOutboundPacketTooLarge) => {
3688          return Err(Error::new(ErrorKind::Type, format!(
3689            "The message ({} bytes) is larger than the connection's maxMessageSize",
3690            data.len()
3691          )));
3692        }
3693        Err(
3694          e @ (RtcError::ErrDataChannelNotOpen | RtcError::ErrDataChannelClosed),
3695        ) => {
3696          return Err(Error::new(ErrorKind::InvalidState, e.to_string()));
3697        }
3698        Err(e) => return Err(rtc_err(e)),
3699      }
3700      Ok(u32::try_from(channel.outstanding_bytes()).unwrap_or(u32::MAX))
3701    })?;
3702    self.poke();
3703    Ok(buffered)
3704  }
3705
3706  /// Bytes sent that SCTP hasn't released (acknowledged or abandoned): the
3707  /// engine's send back-pressure, which the tests watch drain.
3708  #[cfg(test)]
3709  pub fn buffered_amount(&self, handle: u32) -> u32 {
3710    let mut core = self.core.borrow_mut();
3711    core
3712      .pc
3713      .data_channel(handle as RTCDataChannelId)
3714      .map(|c| u32::try_from(c.outstanding_bytes()).unwrap_or(u32::MAX))
3715      .unwrap_or(0)
3716  }
3717
3718  /// `RTCDataChannel.id`: the SCTP stream id, once the engine has assigned
3719  /// one (when the DTLS role is negotiated, RFC 8832 section 6).
3720  pub fn data_channel_id(&self, handle: u32) -> Option<u16> {
3721    let mut core = self.core.borrow_mut();
3722    core
3723      .pc
3724      .data_channel(handle as RTCDataChannelId)
3725      .and_then(|c| c.stream_id())
3726  }
3727
3728  pub fn set_buffered_amount_low_threshold(&self, handle: u32, threshold: u32) {
3729    let _ = self.guarded(|core| {
3730      if let Some(mut channel) =
3731        core.pc.data_channel(handle as RTCDataChannelId)
3732      {
3733        channel.set_buffered_amount_low_threshold(threshold);
3734      }
3735      Ok(())
3736    });
3737  }
3738
3739  pub fn close_data_channel(&self, handle: u32) {
3740    let _ = self.guarded(|core| {
3741      if let Some(mut channel) =
3742        core.pc.data_channel(handle as RTCDataChannelId)
3743      {
3744        let _ = channel.close();
3745      }
3746      Ok(())
3747    });
3748    self.poke();
3749  }
3750
3751  /// `RTCSctpTransport.maxMessageSize`, once SCTP is up.
3752  pub fn max_message_size(&self) -> Option<u32> {
3753    self
3754      .core
3755      .borrow()
3756      .pc
3757      .sctp()
3758      .and_then(|s| s.max_message_size())
3759  }
3760
3761  /// `localDescription`: the pending local description, else the current
3762  /// one.
3763  pub fn local_description(&self) -> Option<(String, String)> {
3764    let d = self.descriptions();
3765    d.pending_local.or(d.current_local)
3766  }
3767
3768  /// `remoteDescription`: the pending remote description, else the current
3769  /// one.
3770  pub fn remote_description(&self) -> Option<(String, String)> {
3771    let d = self.descriptions();
3772    d.pending_remote.or(d.current_remote)
3773  }
3774
3775  /// The four description slots of the W3C API, each as `(type, sdp)`: a
3776  /// current description stays in place while a new offer is pending, as
3777  /// `currentLocalDescription` / `pendingLocalDescription` (and the remote
3778  /// pair) have it.
3779  pub fn descriptions(&self) -> PeerDescriptions {
3780    let core = self.core.borrow();
3781    let redact = core.mdns_mode == MdnsMode::Gather;
3782    let local = |d: RTCSessionDescription| {
3783      let sdp = if redact {
3784        d.sdp
3785          .split_inclusive('\n')
3786          .map(|line| match line.strip_prefix("a=candidate:") {
3787            Some(_) if line.contains(" raddr ") => {
3788              let end = line.len() - line.trim_end().len();
3789              let (body, tail) = line.split_at(line.len() - end);
3790              redact_related_address(body) + tail
3791            }
3792            _ => line.to_string(),
3793          })
3794          .collect()
3795      } else {
3796        d.sdp
3797      };
3798      (d.sdp_type.to_string(), sdp)
3799    };
3800    let remote = |d: &RTCSessionDescription| {
3801      let sdp = if core.remote_simulcast_lines.is_empty() {
3802        d.sdp.clone()
3803      } else {
3804        d.sdp
3805          .split_inclusive('\n')
3806          .map(|line| {
3807            let body = line.trim_end();
3808            match core.remote_simulcast_lines.iter().find(|(e, _)| e == body) {
3809              Some((_, signalled)) => {
3810                format!("{signalled}{}", &line[body.len()..])
3811              }
3812              None => line.to_string(),
3813            }
3814          })
3815          .collect()
3816      };
3817      (d.sdp_type.to_string(), sdp)
3818    };
3819    PeerDescriptions {
3820      current_local: core.pc.current_local_description().map(local),
3821      pending_local: core.pc.pending_local_description().map(local),
3822      current_remote: core.pc.current_remote_description().map(remote),
3823      pending_remote: core.pc.pending_remote_description().map(remote),
3824    }
3825  }
3826
3827  /// `getStats()`; `selector` is a transceiver key and whether its sender
3828  /// (else its receiver) is the selector.
3829  pub fn stats(
3830    &self,
3831    selector: Option<(u32, bool)>,
3832  ) -> Result<Vec<serde_json::Value>, Error> {
3833    self.guarded(|core| {
3834      let selector = match selector {
3835        None => StatsSelector::None,
3836        Some((key, sender)) => {
3837          let Some(index) = core.media.keys.iter().position(|k| *k == key)
3838          else {
3839            return Ok(Vec::new());
3840          };
3841          if sender {
3842            StatsSelector::Sender(index.into())
3843          } else {
3844            StatsSelector::Receiver(index.into())
3845          }
3846        }
3847      };
3848      let wall_ms = SystemTime::now()
3849        .duration_since(UNIX_EPOCH)
3850        .unwrap_or_default()
3851        .as_secs_f64()
3852        * 1000.0;
3853      let now = Instant::now();
3854      core.refresh_media_stats(now);
3855      let report = core.pc.get_stats(now, selector);
3856      use RTCStatsReportEntry as E;
3857      let mut stats: Vec<serde_json::Value> = report
3858        .iter()
3859        .filter_map(|entry| {
3860          match entry {
3861            E::PeerConnection(s) => serde_json::to_value(s),
3862            E::Transport(s) => serde_json::to_value(s),
3863            E::IceCandidatePair(s) => serde_json::to_value(s),
3864            E::LocalCandidate(s) => serde_json::to_value(s),
3865            E::RemoteCandidate(s) => serde_json::to_value(s),
3866            E::Certificate(s) => serde_json::to_value(s),
3867            E::Codec(s) => serde_json::to_value(s),
3868            E::DataChannel(s) => serde_json::to_value(s),
3869            E::InboundRtp(s) => serde_json::to_value(s),
3870            E::OutboundRtp(s) => serde_json::to_value(s),
3871            E::RemoteInboundRtp(s) => serde_json::to_value(s),
3872            E::RemoteOutboundRtp(s) => serde_json::to_value(s),
3873            E::AudioSource(s) => serde_json::to_value(s),
3874            E::VideoSource(s) => serde_json::to_value(s),
3875            E::AudioPlayout(s) => serde_json::to_value(s),
3876            _ => return None,
3877          }
3878          .ok()
3879          .map(|stats| epoch_fields_relative(stats, wall_ms))
3880        })
3881        .collect();
3882      add_pacer_refusals(&mut stats, core.media.pacer_refusals.get());
3883      Ok(stats)
3884    })
3885  }
3886
3887  /// Runs a media operation on the engine (media.rs), then lets the driver
3888  /// flush what it produced.
3889  pub(crate) fn media<T>(
3890    &self,
3891    f: impl FnOnce(&mut Core) -> Result<T, Error>,
3892  ) -> Result<T, Error> {
3893    let out = self.guarded(f)?;
3894    self.events_ready.notify_one();
3895    self.poke();
3896    Ok(out)
3897  }
3898
3899  /// `close()`: stops the engine, the sockets and the driver. Idempotent.
3900  pub fn close(&self) {
3901    self.shutdown(true);
3902  }
3903
3904  fn shutdown(&self, graceful: bool) {
3905    if self.closed.replace(true) {
3906      return;
3907    }
3908    // Operations still waiting (for the gate, or for the one before them)
3909    // fail as the closed connection's.
3910    let mut unfinished: Vec<u32> = self.current_op.take().into_iter().collect();
3911    let dropped: Vec<_> = self.ops.borrow_mut().drain(..).collect();
3912    unfinished.extend(dropped.iter().map(|(id, _)| *id));
3913    drop(dropped);
3914    self.gate.close();
3915    if graceful && let Ok(mut core) = self.core.try_borrow_mut() {
3916      let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
3917        let now = Instant::now();
3918        let _ = core.pc.close();
3919        core.collect_events(now);
3920        for server in &mut core.servers {
3921          if let Some(relay) = server.relay
3922            && let Ok(mut relay) = server.client.relay(relay)
3923          {
3924            let _ = relay.close(now);
3925          }
3926        }
3927        // A last flush so the peer hears the SCTP abort / DTLS close and a
3928        // TURN allocation is released, then the sockets go.
3929        let writes: Vec<_> =
3930          std::iter::from_fn(|| core.pc.poll_write()).collect();
3931        for msg in writes {
3932          if core.allowed.contains(&msg.transport.peer_addr)
3933            && core
3934              .servers
3935              .iter()
3936              .all(|s| s.relay != Some(msg.transport.local_addr))
3937            && let Some(socket) = core.endpoint_for(msg.transport.local_addr)
3938          {
3939            let _ = socket.try_send_to_ecn(
3940              &msg.message,
3941              msg.transport.peer_addr,
3942              msg.transport.ecn,
3943            );
3944          }
3945        }
3946        let mut udp_writes = Vec::new();
3947        for server in &mut core.servers {
3948          while let Some(tx) = server.client.poll_write() {
3949            match &server.link {
3950              ServerLink::Stream(writer) => {
3951                let _ = writer.send(tx.message.to_vec());
3952              }
3953              ServerLink::Udp => udp_writes.push(tx),
3954            }
3955          }
3956        }
3957        for tx in udp_writes {
3958          if let Some(socket) = core.endpoint_for(tx.transport.local_addr) {
3959            let _ = socket.try_send_to(&tx.message, tx.transport.peer_addr);
3960          }
3961        }
3962      }));
3963    }
3964    if let Ok(mut core) = self.core.try_borrow_mut() {
3965      for op in unfinished {
3966        core.events.push_back(JsEvent::OpDone {
3967          op,
3968          error: Some(Error::new(
3969            ErrorKind::InvalidState,
3970            "RTCPeerConnection is closed".to_string(),
3971          )),
3972        });
3973      }
3974      core.servers.clear();
3975      core.endpoints.clear();
3976      core.tcp_links.clear();
3977      core.tcp_dialing.clear();
3978      core.mdns_socket = None;
3979      if let Some(net) = core.options.network.take() {
3980        net.forget(self);
3981      }
3982    }
3983    self.cancel.cancel();
3984    self.wake.notify_one();
3985    self.events_ready.notify_one();
3986  }
3987
3988  /// An ICE-TCP stream the network accepted for this connection (its first
3989  /// frame, a binding request, named our ufrag).
3990  pub(crate) fn adopt_tcp(
3991    self: &Rc<Self>,
3992    stream: tokio::net::TcpStream,
3993    remote: SocketAddr,
3994    decoder: TcpFrameDecoder,
3995    first: Vec<u8>,
3996  ) {
3997    self.attach_tcp(stream, remote, decoder, Some(first));
3998  }
3999
4000  /// Starts an ICE-TCP connection's reader and writer and makes it the one
4001  /// frames to `remote` go out on (with what waited while it was dialled).
4002  fn attach_tcp(
4003    self: &Rc<Self>,
4004    stream: tokio::net::TcpStream,
4005    remote: SocketAddr,
4006    decoder: TcpFrameDecoder,
4007    first: Option<Vec<u8>>,
4008  ) {
4009    if self.closed.get() {
4010      return;
4011    }
4012    let Ok(local) = stream.local_addr() else {
4013      return;
4014    };
4015    let mut core = self.core.borrow_mut();
4016    let queued = core.tcp_dialing.remove(&remote).unwrap_or_default();
4017    if core.tcp_links.len() >= MAX_TCP_LINKS
4018      && !core.tcp_links.contains_key(&remote)
4019    {
4020      return;
4021    }
4022    core.next_tcp_link += 1;
4023    let id = core.next_tcp_link;
4024    let (writer, rx) = mpsc::channel(TCP_WRITE_QUEUE);
4025    for frame in queued {
4026      let _ = writer.try_send(frame);
4027    }
4028    core.tcp_links.insert(remote, TcpLink { id, writer });
4029    let recv_tx = core.recv_tx.clone();
4030    drop(core);
4031    let (r, w) = stream.into_split();
4032    crate::rt::spawn(
4033      read_ice_tcp(r, local, remote, id, decoder, first, recv_tx)
4034        .or_cancel(self.cancel.clone()),
4035    );
4036    crate::rt::spawn(write_ice_tcp(w, rx).or_cancel(self.cancel.clone()));
4037    self.ensure_driver();
4038    self.poke();
4039  }
4040
4041  fn ensure_driver(self: &Rc<Self>) {
4042    if self.driver_started.replace(true) || self.closed.get() {
4043      return;
4044    }
4045    let Some(rx) = self.core.borrow_mut().recv_rx.take() else {
4046      return;
4047    };
4048    let peer = self.clone();
4049    let cancel = self.cancel.clone();
4050    crate::rt::spawn(async move {
4051      let _ = run_driver(peer, rx).or_cancel(cancel).await;
4052    });
4053  }
4054
4055  /// Binds one UDP socket per family and adds the host candidates, then
4056  /// starts one client per ICE server, once (the first
4057  /// `setLocalDescription`).
4058  /// An ICE restart applied by setLocalDescription: a new gathering phase
4059  /// (RFC 8445 section 9, JSEP section 3.5.1) on the sockets already bound,
4060  /// under the current ICE candidate policy and servers. The engine dropped
4061  /// the previous generation's local candidates when it applied the restart.
4062  fn regather(self: &Rc<Self>) {
4063    let specs = {
4064      let mut core = self.core.borrow_mut();
4065      if core.gathering == GatherPhase::NotStarted {
4066        drop(core);
4067        self.start_gathering();
4068        return;
4069      }
4070      // The first gathering hasn't bound yet: it gathers under the current
4071      // policy and servers when it does.
4072      if core.binds_pending {
4073        return;
4074      }
4075      core.gathering = GatherPhase::Running;
4076      core.failed = false;
4077      core.local_gathered = 0;
4078      core.events.push_back(JsEvent::IceGatheringState {
4079        state: "gathering".to_string(),
4080      });
4081      let opts = core.gather_options();
4082      let gather_names = core.mdns_mode == MdnsMode::Gather;
4083      let endpoints: Vec<(SocketAddr, Vec<IpAddr>)> = core
4084        .endpoints
4085        .iter()
4086        .map(|e| (e.bound, e.hosts.clone()))
4087        .collect();
4088      let mut advertised: HashSet<SocketAddr> = HashSet::new();
4089      for (bound, hosts) in endpoints {
4090        core.announce_udp_hosts(
4091          &opts,
4092          bound,
4093          &hosts,
4094          gather_names,
4095          &mut advertised,
4096        );
4097      }
4098      if !core.options.relay_only {
4099        core.gather_tcp(&opts, gather_names);
4100      }
4101      core.servers.clear();
4102      core.resolving = core.options.ice_servers.len();
4103      core.options.ice_servers.clone()
4104    };
4105    for spec in specs {
4106      let peer = self.clone();
4107      let cancel = self.cancel.clone();
4108      crate::rt::spawn(async move {
4109        let _ = add_server(peer, spec).or_cancel(cancel).await;
4110      });
4111    }
4112    self.poke();
4113  }
4114
4115  fn start_gathering(self: &Rc<Self>) {
4116    let (net, opts) = {
4117      let mut core = self.core.borrow_mut();
4118      if core.gathering != GatherPhase::NotStarted {
4119        return;
4120      }
4121      core.gathering = GatherPhase::Running;
4122      core.binds_pending = true;
4123      core.events.push_back(JsEvent::IceGatheringState {
4124        state: "gathering".to_string(),
4125      });
4126      (core.options.network.clone(), core.gather_options())
4127    };
4128    // Two-phase: the binds wait for the gate (ready at once with a gate
4129    // that decides, which then gathers here, as before).
4130    let finish = Box::pin(Self::finish_gathering(self.clone(), net, opts));
4131    if let Err(pending) = crate::rt::poll_now(finish) {
4132      crate::rt::spawn(pending.or_cancel(self.cancel.clone()));
4133    }
4134  }
4135
4136  /// [`Peer::start_gathering`] once the gate answered for the binds.
4137  async fn finish_gathering(
4138    self: Rc<Self>,
4139    net: Option<Rc<Network>>,
4140    opts: NetworkOptions,
4141  ) {
4142    let plan = match net.as_ref().filter(|n| n.is_shared()) {
4143      Some(_) => None,
4144      None => Some(
4145        crate::net::bind_plan(
4146          &opts,
4147          &crate::gate_cache::Verdicts::Cache(self.gate.clone()),
4148          Proto::Udp,
4149        )
4150        .await,
4151      ),
4152    };
4153    if self.closed.get() {
4154      return;
4155    }
4156    let specs = {
4157      let mut core = self.core.borrow_mut();
4158      core.binds_pending = false;
4159      // (socket, bound address, host candidate addresses, own reader)
4160      let mut planned: Vec<(Rc<EcnUdpSocket>, SocketAddr, Vec<IpAddr>, bool)> =
4161        Vec::new();
4162      match (net.as_ref().filter(|n| n.is_shared()), plan) {
4163        (Some(net), _) => {
4164          for e in &net.shared {
4165            planned.push((e.socket.clone(), e.bound, e.hosts.clone(), false));
4166          }
4167        }
4168        (None, None) => {}
4169        (None, Some(plan)) => match plan {
4170          Ok((plan, notes)) => {
4171            for note in notes {
4172              core.report_error("", None, ERROR_CODE_UNREACHABLE, note);
4173            }
4174            for (bind, hosts, token) in plan {
4175              let socket = match opts.port_range {
4176                Some(range) => {
4177                  crate::net::bind_in_range(&*core.io, &token, bind, range)
4178                }
4179                None => {
4180                  let addr = SocketAddr::new(bind, 0);
4181                  core.io.bind_udp(&token, addr, UdpOpts::for_addr(addr))
4182                }
4183              };
4184              let socket = match socket {
4185                Ok(s) => Rc::new(EcnUdpSocket::new(s)),
4186                Err(e) => {
4187                  core.report_error(
4188                    "",
4189                    Some(SocketAddr::new(bind, 0)),
4190                    ERROR_CODE_UNREACHABLE,
4191                    e.to_string(),
4192                  );
4193                  continue;
4194                }
4195              };
4196              let Ok(bound) = socket.local_addr() else {
4197                continue;
4198              };
4199              planned.push((socket, bound, hosts, true));
4200            }
4201          }
4202          Err(e) => {
4203            core.report_error("", None, ERROR_CODE_UNREACHABLE, e.to_string())
4204          }
4205        },
4206      }
4207
4208      let mut advertised: HashSet<SocketAddr> = HashSet::new();
4209      let gather_names = core.mdns_mode == MdnsMode::Gather;
4210      for (socket, bound, hosts, own_reader) in planned {
4211        if own_reader {
4212          spawn_udp_reader(
4213            socket.clone(),
4214            bound,
4215            core.recv_tx.clone(),
4216            self.cancel.clone(),
4217          );
4218        }
4219        core.announce_udp_hosts(
4220          &opts,
4221          bound,
4222          &hosts,
4223          gather_names,
4224          &mut advertised,
4225        );
4226        core.endpoints.push(UdpEndpoint {
4227          socket,
4228          bound,
4229          hosts,
4230        });
4231      }
4232      if !core.options.relay_only {
4233        core.gather_tcp(&opts, gather_names);
4234      }
4235      core.resolving = core.options.ice_servers.len();
4236      core.options.ice_servers.clone()
4237    };
4238    for spec in specs {
4239      let peer = self.clone();
4240      let cancel = self.cancel.clone();
4241      crate::rt::spawn(async move {
4242        let _ = add_server(peer, spec).or_cancel(cancel).await;
4243      });
4244    }
4245    self.poke();
4246  }
4247}
4248
4249/// The host addresses candidates are gathered on: all of them, except that a
4250/// connection publishing mDNS names leaves out loopback when it has another
4251/// address (a name for 127.0.0.1 would send a LAN peer to itself).
4252fn published_hosts(hosts: &[IpAddr], gather_names: bool) -> Vec<IpAddr> {
4253  if gather_names && hosts.iter().any(|ip| !ip.is_loopback()) {
4254    hosts
4255      .iter()
4256      .copied()
4257      .filter(|ip| !ip.is_loopback())
4258      .collect()
4259  } else {
4260    hosts.to_vec()
4261  }
4262}
4263
4264/// Dials a remote passive ICE-TCP candidate, from `bind` when given.
4265async fn connect_tcp(
4266  io: &dyn NetIo,
4267  token: &GateToken,
4268  bind: Option<IpAddr>,
4269  to: SocketAddr,
4270) -> std::io::Result<tokio::net::TcpStream> {
4271  let bind = bind.filter(|ip| ip.is_ipv4() == to.is_ipv4());
4272  let stream = io.connect_tcp(token, bind, to, None).await?;
4273  let _ = stream.set_nodelay(true);
4274  Ok(stream)
4275}
4276
4277/// Reads RFC 4571 frames off an ICE-TCP connection into the driver's queue
4278/// (waiting when it is full: a stream pushes back instead of dropping), then
4279/// tells the driver the connection ended.
4280async fn read_ice_tcp<R: tokio::io::AsyncRead + Unpin>(
4281  mut reader: R,
4282  local: SocketAddr,
4283  remote: SocketAddr,
4284  id: u64,
4285  mut decoder: TcpFrameDecoder,
4286  first: Option<Vec<u8>>,
4287  tx: mpsc::Sender<Datagram>,
4288) {
4289  let datagram = |data: BytesMut, closed: Option<String>| Datagram {
4290    local,
4291    from: remote,
4292    stream: None,
4293    via: Via::IceTcp(id),
4294    data,
4295    closed,
4296    ecn: None,
4297  };
4298  if let Some(frame) = first
4299    && tx
4300      .send(datagram(BytesMut::from(&frame[..]), None))
4301      .await
4302      .is_err()
4303  {
4304    return;
4305  }
4306  let mut chunk = vec![0u8; RECV_BUFFER_SIZE];
4307  let reason = 'read: loop {
4308    while let Some(frame) = decoder.next_packet() {
4309      if tx
4310        .send(datagram(BytesMut::from(&frame[..]), None))
4311        .await
4312        .is_err()
4313      {
4314        return;
4315      }
4316    }
4317    let n = match reader.read(&mut chunk).await {
4318      Ok(0) => break 'read "the peer closed the connection".to_string(),
4319      Err(e) => break 'read e.to_string(),
4320      Ok(n) => n,
4321    };
4322    if decoder.push(&chunk[..n]).is_err() {
4323      break 'read "the peer sent more than it framed".to_string();
4324    }
4325  };
4326  let _ = tx.send(datagram(BytesMut::new(), Some(reason))).await;
4327}
4328
4329/// Writes queued RFC 4571 frames to an ICE-TCP connection.
4330async fn write_ice_tcp<W: tokio::io::AsyncWrite + Unpin>(
4331  mut writer: W,
4332  mut rx: mpsc::Receiver<Vec<u8>>,
4333) {
4334  while let Some(frame) = rx.recv().await {
4335    if writer.write_all(&frame).await.is_err() {
4336      let _ = writer.shutdown().await;
4337      return;
4338    }
4339  }
4340}
4341
4342fn spawn_udp_reader(
4343  socket: Rc<EcnUdpSocket>,
4344  local: SocketAddr,
4345  tx: mpsc::Sender<Datagram>,
4346  cancel: Cancel,
4347) {
4348  spawn_udp_reader_via(socket, local, tx, cancel, Via::Socket);
4349}
4350
4351fn spawn_udp_reader_via(
4352  socket: Rc<EcnUdpSocket>,
4353  local: SocketAddr,
4354  tx: mpsc::Sender<Datagram>,
4355  cancel: Cancel,
4356  via: Via,
4357) {
4358  crate::rt::spawn(
4359    async move {
4360      let mut buf = vec![0u8; RECV_BUFFER_SIZE];
4361      loop {
4362        match socket.recv_from(&mut buf).await {
4363          Ok((n, from, ecn)) => {
4364            let dg = Datagram {
4365              local,
4366              from,
4367              stream: None,
4368              via,
4369              data: BytesMut::from(&buf[..n]),
4370              closed: None,
4371              ecn,
4372            };
4373            if let Err(mpsc::error::TrySendError::Closed(_)) = tx.try_send(dg) {
4374              break;
4375            }
4376          }
4377          Err(e) => {
4378            // ICMP port unreachable surfaces as a read error on some
4379            // platforms (Windows' WSAECONNRESET); keep reading.
4380            log::debug!("webrtc: recv on {local}: {e}");
4381            tokio::time::sleep(Duration::from_millis(1)).await;
4382          }
4383        }
4384      }
4385    }
4386    .or_cancel(cancel),
4387  );
4388}
4389
4390/// Reads RFC 6544 frames off a TURN server stream into the driver's queue;
4391/// when the stream ends, tells the driver why.
4392async fn read_stream<R: tokio::io::AsyncRead + Unpin>(
4393  mut reader: R,
4394  local: SocketAddr,
4395  server: SocketAddr,
4396  index: usize,
4397  tx: mpsc::Sender<Datagram>,
4398) {
4399  let mut buf: Vec<u8> = Vec::with_capacity(RECV_BUFFER_SIZE);
4400  let mut chunk = vec![0u8; RECV_BUFFER_SIZE];
4401  let reason = 'read: loop {
4402    let n = match reader.read(&mut chunk).await {
4403      Ok(0) => break 'read "the server closed the connection".to_string(),
4404      Err(e) => break 'read e.to_string(),
4405      Ok(n) => n,
4406    };
4407    buf.extend_from_slice(&chunk[..n]);
4408    loop {
4409      match stream_frame_len(&buf) {
4410        None => break 'read "the server sent a malformed frame".to_string(),
4411        Some(0) => break,
4412        Some(len) => {
4413          let frame: Vec<u8> = buf.drain(..len).collect();
4414          let dg = Datagram {
4415            local,
4416            from: server,
4417            stream: Some(index),
4418            via: Via::Socket,
4419            data: BytesMut::from(&frame[..]),
4420            closed: None,
4421            ecn: None,
4422          };
4423          if tx.send(dg).await.is_err() {
4424            return;
4425          }
4426        }
4427      }
4428    }
4429  };
4430  let _ = tx
4431    .send(Datagram {
4432      local,
4433      from: server,
4434      stream: Some(index),
4435      via: Via::Socket,
4436      data: BytesMut::new(),
4437      closed: Some(reason),
4438      ecn: None,
4439    })
4440    .await;
4441}
4442
4443async fn write_stream<W: tokio::io::AsyncWrite + Unpin>(
4444  mut writer: W,
4445  mut rx: mpsc::UnboundedReceiver<Vec<u8>>,
4446) {
4447  // A failed write also ends the read side, which reports it.
4448  while let Some(frame) = rx.recv().await {
4449    if writer.write_all(&frame).await.is_err() {
4450      let _ = writer.shutdown().await;
4451      return;
4452    }
4453  }
4454}
4455
4456/// Opens the TCP (or TLS) connection to a stream TURN server and starts its
4457/// reader and writer; returns the writer's queue and the local address.
4458async fn connect_stream(
4459  peer: &Rc<Peer>,
4460  token: &GateToken,
4461  spec: &IceServerSpec,
4462  server: SocketAddr,
4463  index: usize,
4464) -> Result<(mpsc::UnboundedSender<Vec<u8>>, SocketAddr), String> {
4465  let io = peer.core.borrow().io.clone();
4466  let tcp = io
4467    .connect_tcp(token, None, server, Some(&spec.host))
4468    .await
4469    .map_err(|e| format!("Could not connect to {}: {e}", spec.url))?;
4470  let _ = tcp.set_nodelay(true);
4471  let local = tcp.local_addr().map_err(|e| e.to_string())?;
4472  let (writer_tx, writer_rx) = mpsc::unbounded_channel();
4473  let recv_tx = peer.core.borrow().recv_tx.clone();
4474  let cancel = peer.cancel.clone();
4475  match spec.transport {
4476    ServerTransport::Tls => {
4477      let config = peer
4478        .core
4479        .borrow()
4480        .options
4481        .tls
4482        .clone()
4483        .ok_or_else(|| "TLS is not available here".to_string())?;
4484      let name = rustls::pki_types::ServerName::try_from(spec.host.clone())
4485        .map_err(|e| e.to_string())?;
4486      let conn = rustls::ClientConnection::new(config, name)
4487        .map_err(|e| e.to_string())?;
4488      let mut stream =
4489        rustls_tokio_stream::TlsStream::new_client_side(tcp, conn, None);
4490      // Handshake first, so a refused certificate is reported now rather
4491      // than as a request timeout.
4492      stream
4493        .handshake()
4494        .await
4495        .map_err(|e| format!("TLS handshake with {} failed: {e}", spec.url))?;
4496      let (r, w) = stream.into_split();
4497      crate::rt::spawn(
4498        read_stream(r, local, server, index, recv_tx).or_cancel(cancel.clone()),
4499      );
4500      crate::rt::spawn(write_stream(w, writer_rx).or_cancel(cancel));
4501    }
4502    _ => {
4503      let (r, w) = tcp.into_split();
4504      crate::rt::spawn(
4505        read_stream(r, local, server, index, recv_tx).or_cancel(cancel.clone()),
4506      );
4507      crate::rt::spawn(write_stream(w, writer_rx).or_cancel(cancel));
4508    }
4509  }
4510  Ok((writer_tx, local))
4511}
4512
4513/// Resolves one ICE server and starts its client.
4514async fn add_server(peer: Rc<Peer>, spec: IceServerSpec) {
4515  let finish = |peer: &Rc<Peer>, error: Option<String>| {
4516    let mut core = peer.core.borrow_mut();
4517    core.resolving = core.resolving.saturating_sub(1);
4518    if let Some(text) = error {
4519      core.report_error(&spec.url, None, ERROR_CODE_UNREACHABLE, text);
4520    }
4521    drop(core);
4522    peer.poke();
4523  };
4524  let proto = match spec.transport {
4525    ServerTransport::Udp => Proto::Udp,
4526    ServerTransport::Tcp => Proto::Tcp,
4527    ServerTransport::Tls => Proto::Tls,
4528  };
4529  // The URL's host before DNS (a front end may have asked already, before
4530  // the constructor: then a cache hit, or the synchronous gate again).
4531  let token = match peer
4532    .gate
4533    .verdict(Reach::ice_server(proto, &spec.host, spec.port))
4534    .await
4535  {
4536    Ok(token) => token,
4537    Err(message) => {
4538      finish(&peer, Some(message));
4539      return;
4540    }
4541  };
4542  let io = peer.core.borrow().io.clone();
4543  let resolved: Vec<SocketAddr> =
4544    match io.resolve(&token, &spec.host, spec.port).await {
4545      Ok(addrs) => addrs,
4546      Err(e) => {
4547        finish(&peer, Some(format!("Could not resolve {}: {e}", spec.host)));
4548        return;
4549      }
4550    };
4551  // A family the connection has a socket for (UDP), or any (TCP/TLS).
4552  let server = {
4553    let core = peer.core.borrow();
4554    resolved.iter().copied().find(|server| {
4555      spec.transport != ServerTransport::Udp
4556        || core.endpoints.iter().any(|e| {
4557          e.bound.is_ipv4() == server.is_ipv4()
4558            && (!e.bound.ip().is_loopback() || server.ip().is_loopback())
4559        })
4560    })
4561  };
4562  let Some(server) = server else {
4563    finish(
4564      &peer,
4565      Some(format!(
4566        "No local address can reach {} (interface enumeration or the \
4567         wildcard listen permission may be denied)",
4568        spec.host
4569      )),
4570    );
4571    return;
4572  };
4573  // The address it resolved to must not be denied either.
4574  let reach = Reach {
4575    resolved_from: Some(spec.host.clone()),
4576    ..Reach::connect(ReachKind::IceServerResolved, proto, server)
4577  };
4578  let token = match peer.gate.verdict(reach).await {
4579    Ok(token) => token,
4580    Err(message) => {
4581      finish(&peer, Some(message));
4582      return;
4583    }
4584  };
4585  if peer.closed.get() {
4586    return;
4587  }
4588  let shared = peer
4589    .core
4590    .borrow()
4591    .options
4592    .network
4593    .as_ref()
4594    .is_some_and(|n| n.is_shared());
4595  if shared && spec.turn && spec.transport == ServerTransport::Udp {
4596    finish(
4597      &peer,
4598      Some(
4599        "TURN over UDP isn't available on a shared-port Deno.webrtc.Network \
4600         (use ?transport=tcp or turns:)"
4601          .to_string(),
4602      ),
4603    );
4604    return;
4605  }
4606  let index = peer.core.borrow().servers.len();
4607  let (link, base) = match spec.transport {
4608    ServerTransport::Udp => {
4609      let base = {
4610        let mut core = peer.core.borrow_mut();
4611        let Some(endpoint) = core
4612          .endpoints
4613          .iter()
4614          .position(|e| e.bound.is_ipv4() == server.is_ipv4())
4615        else {
4616          drop(core);
4617          finish(&peer, Some("No UDP socket for this family".to_string()));
4618          return;
4619        };
4620        // The permission gate allowed `server` above.
4621        core.local_address(endpoint, server, true)
4622      };
4623      (ServerLink::Udp, base)
4624    }
4625    ServerTransport::Tcp | ServerTransport::Tls => {
4626      if !spec.turn {
4627        // A server-reflexive address over TCP describes the TCP mapping,
4628        // useless to a UDP agent.
4629        finish(&peer, None);
4630        return;
4631      }
4632      match connect_stream(&peer, &token, &spec, server, index).await {
4633        Ok((tx, local)) => (ServerLink::Stream(tx), local),
4634        Err(text) => {
4635          finish(&peer, Some(text));
4636          return;
4637        }
4638      }
4639    }
4640  };
4641  if peer.closed.get() {
4642    return;
4643  }
4644  let protocol = match link {
4645    ServerLink::Udp => TransportProtocol::UDP,
4646    ServerLink::Stream(_) => TransportProtocol::TCP,
4647  };
4648  let config = TurnClientConfig {
4649    stun_serv_addr: server.to_string(),
4650    turn_serv_addr: if spec.turn {
4651      server.to_string()
4652    } else {
4653      String::new()
4654    },
4655    local_addr: base,
4656    transport_protocol: protocol,
4657    username: spec.username.clone(),
4658    password: spec.credential.clone(),
4659    realm: String::new(),
4660    software: String::new(),
4661    rto_in_ms: 0,
4662    allocation_refresh_interval_cap: None,
4663    // The default timer (RFC 8489 section 6.2.1) and every password
4664    // algorithm the client implements (SHA-256, and MD5 for RFC 5389
4665    // servers).
4666    ..TurnClientConfig::default()
4667  };
4668  let provider = match rtci::crypto::default_provider() {
4669    Ok(p) => p,
4670    Err(e) => {
4671      finish(&peer, Some(e.to_string()));
4672      return;
4673    }
4674  };
4675  let client = match TurnClient::new(config, provider) {
4676    Ok(c) => c,
4677    Err(e) => {
4678      finish(&peer, Some(e.to_string()));
4679      return;
4680    }
4681  };
4682  {
4683    let mut core = peer.core.borrow_mut();
4684    // A server, not a remote candidate (ICE stays `new` without one).
4685    core.allowed.insert(server);
4686    let now = Instant::now();
4687    let mut entry = ServerClient {
4688      url: spec.url.clone(),
4689      client,
4690      base,
4691      server,
4692      link,
4693      binding: None,
4694      allocate: None,
4695      relay: None,
4696    };
4697    if matches!(entry.link, ServerLink::Udp) {
4698      entry.binding = entry.client.send_binding_request(now).ok();
4699    }
4700    if spec.turn {
4701      entry.allocate = entry.client.allocate(now).ok();
4702    }
4703    core.servers.push(entry);
4704  }
4705  finish(&peer, None);
4706}
4707
4708async fn run_driver(peer: Rc<Peer>, mut rx: mpsc::Receiver<Datagram>) {
4709  loop {
4710    if peer.closed.get() {
4711      break;
4712    }
4713    let pumped = std::panic::catch_unwind(AssertUnwindSafe(|| {
4714      let mut core = peer.core.borrow_mut();
4715      core.pump();
4716      (!core.events.is_empty(), core.next_deadline())
4717    }));
4718    let Ok((has_events, deadline)) = pumped else {
4719      peer.poison();
4720      break;
4721    };
4722    if has_events {
4723      peer.events_ready.notify_one();
4724    }
4725    let sleep = async {
4726      match deadline {
4727        Some(d) => {
4728          tokio::time::sleep_until(tokio::time::Instant::from_std(d)).await
4729        }
4730        None => std::future::pending::<()>().await,
4731      }
4732    };
4733    let step = tokio::select! {
4734      _ = peer.wake.notified() => None,
4735      dg = rx.recv() => match dg {
4736        Some(dg) => Some(Some(dg)),
4737        None => break,
4738      },
4739      _ = sleep => Some(None),
4740    };
4741    let handled = std::panic::catch_unwind(AssertUnwindSafe(|| {
4742      let mut core = peer.core.borrow_mut();
4743      match step {
4744        Some(Some(dg)) => {
4745          core.handle_datagram(dg);
4746          // Whatever else already arrived goes in before the next pump.
4747          while let Ok(dg) = rx.try_recv() {
4748            core.handle_datagram(dg);
4749          }
4750        }
4751        Some(None) => core.handle_timeout(Instant::now()),
4752        None => {}
4753      }
4754    }));
4755    if handled.is_err() {
4756      peer.poison();
4757      break;
4758    }
4759  }
4760}
4761
4762#[cfg(test)]
4763pub(crate) fn frame_len_for_tests(buf: &[u8]) -> Option<usize> {
4764  stream_frame_len(buf)
4765}
4766
4767#[cfg(test)]
4768impl Peer {
4769  pub(crate) fn selected_for_tests(&self) -> Option<(SocketAddr, SocketAddr)> {
4770    self.core.borrow().selected
4771  }
4772
4773  pub(crate) fn selected_is_tcp_for_tests(&self) -> bool {
4774    let core = self.core.borrow();
4775    core.selected.is_some() && core.selected_tcp
4776  }
4777
4778  pub(crate) fn mdns_open_for_tests(&self) -> bool {
4779    self.core.borrow().mdns_socket.is_some()
4780  }
4781}
4782
4783#[cfg(test)]
4784impl Core {
4785  /// Test hook: a wildcard UDP endpoint on `socket` with these host
4786  /// addresses; returns its index.
4787  pub(crate) fn add_endpoint_for_test(
4788    &mut self,
4789    socket: tokio::net::UdpSocket,
4790    hosts: Vec<IpAddr>,
4791  ) -> usize {
4792    let bound = socket.local_addr().unwrap();
4793    self.endpoints.push(UdpEndpoint {
4794      socket: Rc::new(EcnUdpSocket::new(socket)),
4795      bound,
4796      hosts,
4797    });
4798    self.endpoints.len() - 1
4799  }
4800
4801  /// Test hook: one datagram through the driver's receive path.
4802  pub(crate) fn handle_datagram_for_test(&mut self, dg: Datagram) {
4803    self.handle_datagram(dg);
4804  }
4805
4806  /// Test hook: how many peer routes are cached.
4807  pub(crate) fn route_count_for_test(&self) -> usize {
4808    self.routes.len()
4809  }
4810}