Skip to main content

rtci_host/
net.rs

1// Copyright 2026 Brainwires. MIT OR Apache-2.0.
2
3//! `Deno.webrtc.Network`: the server-side network settings the standard
4//! doesn't have, shared by the connections that name it in
5//! `RTCConfiguration.denoNetwork`.
6//!
7//! - **One UDP port for every connection** (`port`): the network binds it
8//!   once and its reader hands each datagram to the connection it belongs
9//!   to. A remote address is learned from its first STUN binding request,
10//!   whose USERNAME (`<local ufrag>:<remote ufrag>`) names the connection by
11//!   the ICE username fragment of its local description; responses from STUN
12//!   servers are routed by transaction id. Anything else from an unknown
13//!   address is dropped. TURN over UDP isn't available on a shared port
14//!   (TURN over TCP / TLS is: those clients have their own connections).
15//! - **A port range** (`portRange`): each connection binds its own socket
16//!   on a port from the range.
17//! - **Bind addresses and interfaces** (`bindAddresses`, `interfaces`,
18//!   `includeLoopback`).
19//! - **1:1 NAT** (`publicAddresses`): the public address is advertised in
20//!   place of the private one (`host`) or beside it (`srflx`).
21//! - **ICE over TCP** (`tcpPort`, RFC 6544): one TCP listener per bind
22//!   address, shared by the network's connections. Each connection
23//!   advertises a passive host candidate on it and an active one (port 9) per
24//!   host address, which dials a remote passive candidate. An accepted
25//!   stream belongs to the connection its first frame (RFC 4571), a STUN
26//!   binding request, names by its local ufrag, as on a shared UDP port; a
27//!   stream that sends no such frame within [`TCP_FIRST_FRAME_TIMEOUT`] is
28//!   closed, and at most [`MAX_PENDING_TCP`] wait at once.
29//! - **mDNS** (`mdns`): `true` publishes the host candidates under
30//!   `<uuid>.local` names (and resolves the peer's), `false` neither
31//!   publishes nor resolves; without it a connection resolves the peer's
32//!   `.local` candidates, as browsers do.
33//! - **ICE-lite**, the ICE timers and the data channel message size.
34//!
35//! Every bind needs the listen permission for its address, and listing
36//! interfaces `--allow-sys=networkInterfaces`; datagrams still go only to
37//! addresses the net permission allows.
38
39use std::cell::Cell;
40use std::cell::RefCell;
41use std::collections::HashMap;
42use std::net::IpAddr;
43use std::net::Ipv4Addr;
44use std::net::Ipv6Addr;
45use std::net::SocketAddr;
46use std::rc::Rc;
47use std::rc::Weak;
48use std::time::Duration;
49
50use crate::rt::Cancel;
51use crate::rt::OrCancel;
52use bytes::BytesMut;
53use rtci::shared::tcp_framing::TcpFrameDecoder;
54use serde::Deserialize;
55use tokio::io::AsyncReadExt;
56use tokio::net::TcpListener;
57use tokio::net::TcpStream;
58use tokio::net::UdpSocket;
59
60use crate::ecn::EcnUdpSocket;
61use crate::error::Error;
62use crate::error::ErrorKind;
63use crate::gate::GateToken;
64use crate::gate::NetGate;
65use crate::gate::Proto;
66use crate::gate::Reach;
67use crate::gate::ReachKind;
68use crate::gate_cache::GateCache;
69use crate::gate_cache::Verdicts;
70use crate::net_io::NetIo;
71use crate::net_io::UdpOpts;
72use crate::peer::Datagram;
73use crate::peer::Peer;
74use crate::peer::Via;
75
76/// The most remote addresses (and STUN transactions) a shared port
77/// remembers; a flood of spoofed sources can't grow the maps without limit.
78const MAX_ROUTES: usize = 65536;
79/// Accepted ICE-TCP streams still waiting for their first frame, per
80/// network; more are closed at once.
81pub const MAX_PENDING_TCP: usize = 64;
82/// How long an accepted ICE-TCP stream has to send its first frame.
83pub const TCP_FIRST_FRAME_TIMEOUT: Duration = Duration::from_secs(10);
84/// The most an accepted ICE-TCP stream may send before its first frame is
85/// complete.
86const MAX_FIRST_FRAME: usize = 2048;
87
88#[derive(Deserialize, Default, Clone, Copy, Debug)]
89#[serde(rename_all = "camelCase")]
90pub struct IceTimeoutsArg {
91  pub disconnected: Option<u64>,
92  pub failed: Option<u64>,
93  pub keep_alive: Option<u64>,
94}
95
96#[derive(Deserialize, Clone, Copy, Debug)]
97pub struct PortRangeArg {
98  pub min: u16,
99  pub max: u16,
100}
101
102#[derive(Deserialize, Default, Clone, Debug)]
103#[serde(rename_all = "camelCase")]
104pub struct NetworkArg {
105  pub port: Option<u16>,
106  pub port_range: Option<PortRangeArg>,
107  pub bind_addresses: Option<Vec<String>>,
108  pub interfaces: Option<Vec<String>>,
109  #[serde(default = "yes")]
110  pub include_loopback: bool,
111  #[serde(default)]
112  pub public_addresses: Vec<String>,
113  #[serde(default)]
114  pub public_address_candidate: Option<String>,
115  #[serde(default)]
116  pub ice_lite: bool,
117  pub ice_timeouts: Option<IceTimeoutsArg>,
118  pub max_message_size: Option<u32>,
119  pub tcp_port: Option<u16>,
120  pub mdns: Option<bool>,
121}
122
123fn yes() -> bool {
124  true
125}
126
127/// A public address and the private one it maps to (`None`: every private
128/// address).
129#[derive(Clone, Copy, Debug)]
130pub struct PublicAddress {
131  pub public: IpAddr,
132  pub private: Option<IpAddr>,
133}
134
135#[derive(Clone, Debug, Default)]
136pub struct NetworkOptions {
137  pub port: Option<u16>,
138  pub port_range: Option<(u16, u16)>,
139  pub bind_addresses: Option<Vec<IpAddr>>,
140  pub interfaces: Option<Vec<String>>,
141  pub include_loopback: bool,
142  pub public_addresses: Vec<PublicAddress>,
143  /// `publicAddressCandidate: "srflx"`: advertise the public address as a
144  /// server-reflexive candidate beside the host one.
145  pub public_srflx: bool,
146  pub ice_lite: bool,
147  pub ice_timeouts:
148    Option<(Option<Duration>, Option<Duration>, Option<Duration>)>,
149  pub max_message_size: Option<u32>,
150  /// `tcpPort`: ICE over TCP on a listener on this port (0: one the OS
151  /// picks).
152  pub tcp_port: Option<u16>,
153  pub mdns: MdnsMode,
154}
155
156/// What a connection does with mDNS `.local` host candidates.
157#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
158pub enum MdnsMode {
159  /// Neither publishes nor resolves (`mdns: false`).
160  Off,
161  /// Resolves the peer's (the default, as browsers do).
162  #[default]
163  Resolve,
164  /// Publishes its own host candidates under `.local` names and resolves the
165  /// peer's (`mdns: true`).
166  Gather,
167}
168
169fn parse_ip(s: &str, what: &str) -> Result<IpAddr, Error> {
170  s.trim_matches(['[', ']']).parse().map_err(|_| {
171    Error::new(
172      ErrorKind::Type,
173      format!("'{s}' is not an IP address ({what})"),
174    )
175  })
176}
177
178impl NetworkOptions {
179  pub fn parse(arg: NetworkArg) -> Result<Self, Error> {
180    let bind_addresses = match arg.bind_addresses {
181      Some(list) => Some(
182        list
183          .iter()
184          .map(|a| parse_ip(a, "bindAddresses"))
185          .collect::<Result<Vec<_>, _>>()?,
186      ),
187      None => None,
188    };
189    let mut public_addresses = Vec::new();
190    for entry in &arg.public_addresses {
191      let (public, private) = match entry.split_once('/') {
192        Some((p, q)) => (
193          parse_ip(p, "publicAddresses")?,
194          Some(parse_ip(q, "publicAddresses")?),
195        ),
196        None => (parse_ip(entry, "publicAddresses")?, None),
197      };
198      public_addresses.push(PublicAddress { public, private });
199    }
200    if public_addresses.len() > 1
201      && public_addresses.iter().any(|p| p.private.is_none())
202    {
203      return Err(Error::new(
204        ErrorKind::Type,
205        "With several publicAddresses, each must be 'public/private'"
206          .to_string(),
207      ));
208    }
209    let ms = |v: Option<u64>| v.map(Duration::from_millis);
210    Ok(Self {
211      port: arg.port,
212      port_range: arg.port_range.map(|r| (r.min, r.max)),
213      bind_addresses,
214      interfaces: arg.interfaces,
215      include_loopback: arg.include_loopback,
216      public_addresses,
217      public_srflx: arg.public_address_candidate.as_deref() == Some("srflx"),
218      ice_lite: arg.ice_lite,
219      ice_timeouts: arg
220        .ice_timeouts
221        .map(|t| (ms(t.disconnected), ms(t.failed), ms(t.keep_alive))),
222      max_message_size: arg.max_message_size,
223      tcp_port: arg.tcp_port,
224      mdns: match arg.mdns {
225        None => MdnsMode::Resolve,
226        Some(false) => MdnsMode::Off,
227        Some(true) => MdnsMode::Gather,
228      },
229    })
230  }
231
232  /// The public address a private one is advertised as, if any.
233  pub fn public_for(&self, private: IpAddr) -> Option<IpAddr> {
234    self
235      .public_addresses
236      .iter()
237      .find(|p| {
238        p.public.is_ipv4() == private.is_ipv4()
239          && p.private.is_none_or(|q| q == private)
240      })
241      .map(|p| p.public)
242  }
243
244  /// The private address a public one stands for (host replacement).
245  pub fn private_for(
246    &self,
247    public: IpAddr,
248    hosts: &[IpAddr],
249  ) -> Option<IpAddr> {
250    self
251      .public_addresses
252      .iter()
253      .find(|p| p.public == public)
254      .and_then(|p| {
255        p.private.or_else(|| {
256          hosts
257            .iter()
258            .copied()
259            .find(|h| h.is_ipv4() == public.is_ipv4() && !h.is_loopback())
260        })
261      })
262  }
263}
264
265/// One of a shared port's sockets.
266#[derive(Clone)]
267pub struct SharedEndpoint {
268  pub(crate) socket: Rc<EcnUdpSocket>,
269  pub bound: SocketAddr,
270  pub hosts: Vec<IpAddr>,
271}
272
273/// One of an ICE-TCP network's listeners.
274#[derive(Clone, Debug)]
275pub struct TcpEndpoint {
276  pub bound: SocketAddr,
277  pub hosts: Vec<IpAddr>,
278}
279
280pub struct Network {
281  pub options: NetworkOptions,
282  /// `port` networks: the sockets every connection shares.
283  pub shared: Vec<SharedEndpoint>,
284  /// `tcpPort` networks: the listeners every connection's passive
285  /// candidates are on.
286  pub tcp: Vec<TcpEndpoint>,
287  /// Accepted streams still waiting for their first frame.
288  pending_tcp: Cell<usize>,
289  by_ufrag: RefCell<HashMap<String, Weak<Peer>>>,
290  by_remote: RefCell<HashMap<SocketAddr, Weak<Peer>>>,
291  by_transaction: RefCell<HashMap<[u8; 12], Weak<Peer>>>,
292  cancel: Cancel,
293  closed: Cell<bool>,
294}
295
296/// The STUN message type, transaction id and (for a binding request) the
297/// local ufrag its USERNAME names, if `data` is a STUN message.
298pub(crate) fn stun_info(
299  data: &[u8],
300) -> Option<(u16, [u8; 12], Option<String>)> {
301  if data.len() < 20 || data[0] >= 4 || data[4..8] != [0x21, 0x12, 0xa4, 0x42] {
302    return None;
303  }
304  let typ = u16::from_be_bytes([data[0], data[1]]);
305  let mut tid = [0u8; 12];
306  tid.copy_from_slice(&data[8..20]);
307  let len = u16::from_be_bytes([data[2], data[3]]) as usize;
308  let body = data.get(20..20 + len)?;
309  let mut ufrag = None;
310  if typ == 0x0001 {
311    let mut i = 0;
312    while i + 4 <= body.len() {
313      let attr = u16::from_be_bytes([body[i], body[i + 1]]);
314      let alen = u16::from_be_bytes([body[i + 2], body[i + 3]]) as usize;
315      let value = body.get(i + 4..i + 4 + alen)?;
316      if attr == 0x0006 {
317        let username = std::str::from_utf8(value).ok()?;
318        ufrag = username.split(':').next().map(str::to_string);
319        break;
320      }
321      i += 4 + alen.div_ceil(4) * 4;
322    }
323  }
324  Some((typ, tid, ufrag))
325}
326
327impl Network {
328  /// Binds a `port` network's sockets now (through `io`), so a taken port
329  /// or a refused permission is `createNetwork`'s error.
330  ///
331  /// Asks `guard` synchronously only ([`NetGate::decide`] /
332  /// [`NetGate::interfaces`]; `None` is a refusal). With a gate that may
333  /// answer later, use [`Network::create`].
334  pub fn new(
335    options: NetworkOptions,
336    guard: &dyn NetGate,
337    io: &dyn NetIo,
338  ) -> Result<Rc<Self>, Error> {
339    let verdicts = Verdicts::Sync(guard);
340    match crate::rt::poll_now(Box::pin(Self::build(options, &verdicts, io))) {
341      Ok(result) => result,
342      // `Verdicts::Sync` and the binds never wait.
343      Err(_) => Err(Error::new(
344        ErrorKind::Internal,
345        "the network could not be created synchronously".to_string(),
346      )),
347    }
348  }
349
350  /// [`Network::new`] with a gate that may answer later: the binds wait for
351  /// its answers (an unanswered question is refused after
352  /// [`NetGate::ask_timeout`]). Ready at once with a gate that decides.
353  pub async fn create(
354    options: NetworkOptions,
355    guard: Rc<dyn NetGate>,
356    io: Rc<dyn NetIo>,
357  ) -> Result<Rc<Self>, Error> {
358    let cache = GateCache::new(guard);
359    let verdicts = Verdicts::Cache(cache.clone());
360    let result = Self::build(options, &verdicts, &*io).await;
361    cache.close();
362    result
363  }
364
365  async fn build(
366    options: NetworkOptions,
367    guard: &Verdicts<'_>,
368    io: &dyn NetIo,
369  ) -> Result<Rc<Self>, Error> {
370    let cancel = Cancel::new();
371    let mut shared = Vec::new();
372    if let Some(port) = options.port {
373      for (bind, hosts, token) in
374        bind_plan(&options, guard, Proto::Udp).await?.0
375      {
376        let addr = SocketAddr::new(bind, port);
377        let socket = io
378          .bind_udp(&token, addr, UdpOpts::for_addr(addr))
379          .map_err(|e| {
380            Error::new(
381              ErrorKind::Operation,
382              format!(
383                "Could not bind UDP {}: {e}",
384                SocketAddr::new(bind, port)
385              ),
386            )
387          })?;
388        let bound = socket.local_addr().map_err(crate::peer::rtc_err)?;
389        shared.push(SharedEndpoint {
390          socket: Rc::new(EcnUdpSocket::new(socket)),
391          bound,
392          hosts,
393        });
394      }
395    }
396    let mut listeners = Vec::new();
397    if let Some(port) = options.tcp_port {
398      for (bind, hosts, token) in
399        bind_plan(&options, guard, Proto::Tcp).await?.0
400      {
401        let addr = SocketAddr::new(bind, port);
402        let listener = io.bind_tcp(&token, addr).map_err(|e| {
403          Error::new(
404            ErrorKind::Operation,
405            format!("Could not listen on TCP {addr}: {e}"),
406          )
407        })?;
408        let bound = listener.local_addr().map_err(crate::peer::rtc_err)?;
409        listeners.push((listener, TcpEndpoint { bound, hosts }));
410      }
411    }
412    let network = Rc::new(Self {
413      tcp: listeners.iter().map(|(_, e)| e.clone()).collect(),
414      pending_tcp: Cell::new(0),
415      options,
416      shared,
417      by_ufrag: RefCell::new(HashMap::new()),
418      by_remote: RefCell::new(HashMap::new()),
419      by_transaction: RefCell::new(HashMap::new()),
420      cancel,
421      closed: Cell::new(false),
422    });
423    for endpoint in &network.shared {
424      spawn_shared_reader(Rc::downgrade(&network), endpoint.clone());
425    }
426    for (listener, _) in listeners {
427      spawn_tcp_acceptor(Rc::downgrade(&network), listener);
428    }
429    Ok(network)
430  }
431
432  /// A `tcpPort` network: its connections do ICE over TCP.
433  pub fn has_tcp(&self) -> bool {
434    !self.tcp.is_empty()
435  }
436
437  /// Whether connections route by their local ufrag here (a shared UDP port
438  /// or TCP listeners).
439  pub fn routes_by_ufrag(&self) -> bool {
440    self.is_shared() || self.has_tcp()
441  }
442
443  pub fn tcp_addresses(&self) -> Vec<String> {
444    self.tcp.iter().map(|e| e.bound.to_string()).collect()
445  }
446
447  /// The connection whose local ufrag a binding request names.
448  fn peer_for_ufrag(&self, ufrag: &str) -> Option<Rc<Peer>> {
449    self.by_ufrag.borrow().get(ufrag).and_then(Weak::upgrade)
450  }
451
452  pub fn is_shared(&self) -> bool {
453    self.options.port.is_some()
454  }
455
456  pub fn is_closed(&self) -> bool {
457    self.closed.get()
458  }
459
460  pub fn addresses(&self) -> Vec<String> {
461    self.shared.iter().map(|e| e.bound.to_string()).collect()
462  }
463
464  /// A connection on the shared port answers to this local ufrag.
465  pub fn register_ufrag(&self, ufrag: String, peer: &Weak<Peer>) {
466    let mut map = self.by_ufrag.borrow_mut();
467    map.retain(|_, p| p.strong_count() > 0);
468    map.insert(ufrag, peer.clone());
469  }
470
471  /// A STUN request a connection sends to a STUN server on the shared port:
472  /// its response is routed back by transaction id.
473  pub fn register_transaction(&self, message: &[u8], peer: &Weak<Peer>) {
474    if let Some((_, tid, _)) = stun_info(message) {
475      let mut map = self.by_transaction.borrow_mut();
476      if map.len() >= MAX_ROUTES {
477        map.retain(|_, p| p.strong_count() > 0);
478      }
479      if map.len() < MAX_ROUTES {
480        map.insert(tid, peer.clone());
481      }
482    }
483  }
484
485  pub fn forget(&self, peer: &Peer) {
486    let same = |p: &Weak<Peer>| std::ptr::eq(p.as_ptr(), peer);
487    self.by_ufrag.borrow_mut().retain(|_, p| !same(p));
488    self.by_remote.borrow_mut().retain(|_, p| !same(p));
489    self.by_transaction.borrow_mut().retain(|_, p| !same(p));
490  }
491
492  pub fn close(&self) {
493    if self.closed.replace(true) {
494      return;
495    }
496    self.cancel.cancel();
497    self.by_ufrag.borrow_mut().clear();
498    self.by_remote.borrow_mut().clear();
499    self.by_transaction.borrow_mut().clear();
500  }
501
502  /// The connection a datagram on the shared port belongs to. A binding
503  /// request goes by the ufrag its USERNAME names and (re)maps its source
504  /// address to that connection, so a request forged from someone's address
505  /// can't keep their traffic away from the connection they are checking; a
506  /// STUN server's response goes by transaction id; anything else by the
507  /// source address.
508  fn route(&self, from: SocketAddr, data: &[u8]) -> Option<Rc<Peer>> {
509    if let Some((typ, tid, ufrag)) = stun_info(data) {
510      if typ & 0x0110 != 0 {
511        if let Some(peer) = self
512          .by_transaction
513          .borrow_mut()
514          .remove(&tid)
515          .and_then(|p| p.upgrade())
516        {
517          return Some(peer);
518        }
519      } else if let Some(ufrag) = ufrag {
520        let peer =
521          self.by_ufrag.borrow().get(&ufrag).and_then(Weak::upgrade)?;
522        // ICE authenticates the request itself; a forged one only moves a
523        // route, which the real peer's next check moves back.
524        let mut routes = self.by_remote.borrow_mut();
525        if routes.len() >= MAX_ROUTES {
526          routes.retain(|_, p| p.strong_count() > 0);
527        }
528        if routes.len() < MAX_ROUTES {
529          routes.insert(from, Rc::downgrade(&peer));
530        }
531        return Some(peer);
532      }
533    }
534    self.by_remote.borrow().get(&from).and_then(Weak::upgrade)
535  }
536}
537
538impl Drop for Network {
539  fn drop(&mut self) {
540    self.cancel.cancel();
541  }
542}
543
544fn spawn_shared_reader(network: Weak<Network>, endpoint: SharedEndpoint) {
545  let Some(cancel) = network.upgrade().map(|n| n.cancel.clone()) else {
546    return;
547  };
548  crate::rt::spawn(
549    async move {
550      let mut buf = vec![0u8; 9216];
551      loop {
552        match endpoint.socket.recv_from(&mut buf).await {
553          Ok((n, from, ecn)) => {
554            let Some(net) = network.upgrade() else {
555              break;
556            };
557            let Some(peer) = net.route(from, &buf[..n]) else {
558              continue;
559            };
560            peer.deliver(Datagram {
561              local: endpoint.bound,
562              from,
563              stream: None,
564              via: Via::Socket,
565              data: BytesMut::from(&buf[..n]),
566              closed: None,
567              ecn,
568            });
569          }
570          Err(e) => {
571            log::debug!("webrtc: shared recv on {}: {e}", endpoint.bound);
572            tokio::time::sleep(Duration::from_millis(1)).await;
573          }
574        }
575      }
576    }
577    .or_cancel(cancel),
578  );
579}
580
581fn spawn_tcp_acceptor(network: Weak<Network>, listener: TcpListener) {
582  let Some(cancel) = network.upgrade().map(|n| n.cancel.clone()) else {
583    return;
584  };
585  crate::rt::spawn(
586    async move {
587      loop {
588        let (stream, from) = match listener.accept().await {
589          Ok(accepted) => accepted,
590          Err(e) => {
591            log::debug!("webrtc: ICE-TCP accept: {e}");
592            tokio::time::sleep(Duration::from_millis(10)).await;
593            continue;
594          }
595        };
596        let Some(net) = network.upgrade() else {
597          break;
598        };
599        if net.pending_tcp.get() >= MAX_PENDING_TCP {
600          continue;
601        }
602        net.pending_tcp.set(net.pending_tcp.get() + 1);
603        let weak = network.clone();
604        crate::rt::spawn(
605          async move {
606            let routed = tokio::time::timeout(
607              TCP_FIRST_FRAME_TIMEOUT,
608              first_frame(stream),
609            )
610            .await;
611            let Some(net) = weak.upgrade() else {
612              return;
613            };
614            net.pending_tcp.set(net.pending_tcp.get().saturating_sub(1));
615            let Ok(Some((stream, decoder, frame, ufrag))) = routed else {
616              return;
617            };
618            if let Some(peer) = net.peer_for_ufrag(&ufrag) {
619              peer.adopt_tcp(stream, from, decoder, frame);
620            }
621          }
622          .or_cancel(net.cancel.clone()),
623        );
624      }
625    }
626    .or_cancel(cancel),
627  );
628}
629
630/// Reads an accepted stream up to its first RFC 4571 frame, which must be a
631/// STUN binding request naming a local ufrag; returns the stream, what else
632/// was read, the frame and the ufrag.
633async fn first_frame(
634  mut stream: TcpStream,
635) -> Option<(TcpStream, TcpFrameDecoder, Vec<u8>, String)> {
636  let _ = stream.set_nodelay(true);
637  let mut decoder = TcpFrameDecoder::new();
638  let mut chunk = [0u8; 2048];
639  // A binding request is a few hundred bytes: a stream that sends more
640  // before its first frame completes isn't ICE.
641  let mut read = 0usize;
642  loop {
643    if let Some(frame) = decoder.next_packet() {
644      let (typ, _, ufrag) = stun_info(&frame)?;
645      if typ != 0x0001 {
646        return None;
647      }
648      return Some((stream, decoder, frame, ufrag?));
649    }
650    if read >= MAX_FIRST_FRAME {
651      return None;
652    }
653    let n = stream.read(&mut chunk).await.ok()?;
654    if n == 0 {
655      return None;
656    }
657    read += n;
658    decoder.push(&chunk[..n]).ok()?;
659  }
660}
661
662/// The addresses a connection (or a shared port) binds, each with the host
663/// candidate addresses it stands for and the gate's token for the bind; and
664/// why some were left out (reported as `icecandidateerror`s).
665pub type BindPlan = (Vec<(IpAddr, Vec<IpAddr>, GateToken)>, Vec<String>);
666
667/// What to bind, from the network's options (or the defaults, without one):
668/// the wildcard with every interface address as a host candidate when
669/// interfaces may be listed and the wildcard listened on, else
670/// `127.0.0.1`; `DENO_WEBRTC_LOOPBACK_ONLY=1` always `127.0.0.1`. Waits
671/// for the gate's answers (each question in turn, as the synchronous
672/// checks went).
673pub(crate) async fn bind_plan(
674  options: &NetworkOptions,
675  guard: &Verdicts<'_>,
676  proto: Proto,
677) -> Result<BindPlan, Error> {
678  let listen = async |ip: IpAddr| {
679    guard.reach(Reach::bind(ReachKind::Bind, proto, ip)).await
680  };
681  let loopback = IpAddr::V4(Ipv4Addr::LOCALHOST);
682  let mut notes = Vec::new();
683  // (bind, hosts, the token when the bind was checked already)
684  let mut plan: Vec<(IpAddr, Vec<IpAddr>, Option<GateToken>)> = Vec::new();
685  if crate::peer::loopback_only() {
686    // Checked below, as the fallback's loopback bind is.
687    plan.push((loopback, vec![loopback], None));
688  } else {
689    let mut ifaces: Option<Option<Vec<IpAddr>>> = None;
690    match options.bind_addresses.clone() {
691      Some(binds) => {
692        for bind in binds {
693          let token = match listen(bind).await {
694            Ok(token) => token,
695            Err(message) => {
696              if options.port.is_some() {
697                return Err(Error::new(ErrorKind::NotCapable, message));
698              }
699              notes.push(message);
700              continue;
701            }
702          };
703          let hosts = if bind.is_unspecified() {
704            if ifaces.is_none() {
705              ifaces = Some(interfaces(options, guard, &mut notes).await);
706            }
707            let list = ifaces.clone().flatten();
708            let mut hosts: Vec<IpAddr> = list
709              .unwrap_or_default()
710              .into_iter()
711              .filter(|ip| ip.is_ipv4() == bind.is_ipv4())
712              .collect();
713            if bind.is_ipv4() && options.include_loopback {
714              hosts.insert(0, loopback);
715            }
716            hosts
717          } else {
718            vec![bind]
719          };
720          plan.push((bind, hosts, Some(token)));
721        }
722      }
723      None => match interfaces(options, guard, &mut notes).await {
724        Some(ifaces) => {
725          let mut v4: Vec<IpAddr> =
726            ifaces.iter().copied().filter(IpAddr::is_ipv4).collect();
727          if options.include_loopback {
728            v4.insert(0, loopback);
729          }
730          let v6: Vec<IpAddr> =
731            ifaces.iter().copied().filter(IpAddr::is_ipv6).collect();
732          let any4 = IpAddr::V4(Ipv4Addr::UNSPECIFIED);
733          match listen(any4).await {
734            Ok(token) => plan.push((any4, v4, Some(token))),
735            Err(message) => {
736              notes.push(format!(
737                "Only loopback host candidates were gathered: {message}"
738              ));
739              plan.push((loopback, vec![loopback], None));
740            }
741          }
742          let any6 = IpAddr::V6(Ipv6Addr::UNSPECIFIED);
743          if !v6.is_empty()
744            && let Ok(token) = listen(any6).await
745          {
746            plan.push((any6, v6, Some(token)));
747          }
748        }
749        None => plan.push((loopback, vec![loopback], None)),
750      },
751    }
752  }
753  // The loopback bind of the fallback needs its own listen grant.
754  let mut checked = Vec::new();
755  for (bind, hosts, token) in plan {
756    let token = match token {
757      Some(token) if bind.is_unspecified() => token,
758      _ => match listen(bind).await {
759        Ok(token) => token,
760        Err(message) => {
761          if options.port.is_some() {
762            return Err(Error::new(ErrorKind::NotCapable, message));
763          }
764          notes.push(message);
765          continue;
766        }
767      },
768    };
769    checked.push((bind, hosts, token));
770  }
771  Ok((checked, notes))
772}
773
774/// The interface addresses, when the gate allows listing them (else a note).
775async fn interfaces(
776  options: &NetworkOptions,
777  guard: &Verdicts<'_>,
778  notes: &mut Vec<String>,
779) -> Option<Vec<IpAddr>> {
780  match guard.interfaces().await {
781    Ok(()) => Some(crate::peer::interface_addresses(
782      options.interfaces.as_deref(),
783    )),
784    Err(message) => {
785      notes.push(format!(
786        "Only loopback host candidates were gathered: {message}"
787      ));
788      None
789    }
790  }
791}
792
793/// Binds a UDP socket on `ip` with a port from `range` (tried from a random
794/// start, so concurrent connections spread over it).
795pub fn bind_in_range(
796  io: &dyn NetIo,
797  token: &GateToken,
798  ip: IpAddr,
799  range: (u16, u16),
800) -> std::io::Result<UdpSocket> {
801  let (min, max) = range;
802  let span = (max - min) as u32 + 1;
803  let mut start = [0u8; 4];
804  let _ = aws_lc_rs::rand::fill(&mut start);
805  let start = u32::from_le_bytes(start) % span;
806  let mut last = None;
807  for i in 0..span {
808    let port = min + ((start + i) % span) as u16;
809    let addr = SocketAddr::new(ip, port);
810    match io.bind_udp(token, addr, UdpOpts::for_addr(addr)) {
811      Ok(socket) => return Ok(socket),
812      Err(e) => last = Some(e),
813    }
814  }
815  Err(last.unwrap_or_else(|| {
816    std::io::Error::new(std::io::ErrorKind::AddrInUse, "no free port in range")
817  }))
818}
819
820#[cfg(test)]
821pub(crate) fn stun_info_for_tests(
822  data: &[u8],
823) -> Option<(u16, [u8; 12], Option<String>)> {
824  stun_info(data)
825}