rtci-host 0.2.0

The host I/O around the sans-I/O rtci WebRTC engine: sockets, timers, STUN/TURN clients, ICE-TCP, mDNS and media, behind a permission gate and a socket factory
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
// Copyright 2026 Brainwires. MIT OR Apache-2.0.

//! `Deno.webrtc.Network`: the server-side network settings the standard
//! doesn't have, shared by the connections that name it in
//! `RTCConfiguration.denoNetwork`.
//!
//! - **One UDP port for every connection** (`port`): the network binds it
//!   once and its reader hands each datagram to the connection it belongs
//!   to. A remote address is learned from its first STUN binding request,
//!   whose USERNAME (`<local ufrag>:<remote ufrag>`) names the connection by
//!   the ICE username fragment of its local description; responses from STUN
//!   servers are routed by transaction id. Anything else from an unknown
//!   address is dropped. TURN over UDP isn't available on a shared port
//!   (TURN over TCP / TLS is: those clients have their own connections).
//! - **A port range** (`portRange`): each connection binds its own socket
//!   on a port from the range.
//! - **Bind addresses and interfaces** (`bindAddresses`, `interfaces`,
//!   `includeLoopback`).
//! - **1:1 NAT** (`publicAddresses`): the public address is advertised in
//!   place of the private one (`host`) or beside it (`srflx`).
//! - **ICE over TCP** (`tcpPort`, RFC 6544): one TCP listener per bind
//!   address, shared by the network's connections. Each connection
//!   advertises a passive host candidate on it and an active one (port 9) per
//!   host address, which dials a remote passive candidate. An accepted
//!   stream belongs to the connection its first frame (RFC 4571), a STUN
//!   binding request, names by its local ufrag, as on a shared UDP port; a
//!   stream that sends no such frame within [`TCP_FIRST_FRAME_TIMEOUT`] is
//!   closed, and at most [`MAX_PENDING_TCP`] wait at once.
//! - **mDNS** (`mdns`): `true` publishes the host candidates under
//!   `<uuid>.local` names (and resolves the peer's), `false` neither
//!   publishes nor resolves; without it a connection resolves the peer's
//!   `.local` candidates, as browsers do.
//! - **ICE-lite**, the ICE timers and the data channel message size.
//!
//! Every bind needs the listen permission for its address, and listing
//! interfaces `--allow-sys=networkInterfaces`; datagrams still go only to
//! addresses the net permission allows.

use std::cell::Cell;
use std::cell::RefCell;
use std::collections::HashMap;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
use std::net::SocketAddr;
use std::rc::Rc;
use std::rc::Weak;
use std::time::Duration;

use crate::rt::Cancel;
use crate::rt::OrCancel;
use bytes::BytesMut;
use rtci::shared::tcp_framing::TcpFrameDecoder;
use serde::Deserialize;
use tokio::io::AsyncReadExt;
use tokio::net::TcpListener;
use tokio::net::TcpStream;
use tokio::net::UdpSocket;

use crate::ecn::EcnUdpSocket;
use crate::error::Error;
use crate::error::ErrorKind;
use crate::gate::GateToken;
use crate::gate::NetGate;
use crate::gate::Proto;
use crate::gate::Reach;
use crate::gate::ReachKind;
use crate::gate_cache::GateCache;
use crate::gate_cache::Verdicts;
use crate::net_io::NetIo;
use crate::net_io::UdpOpts;
use crate::peer::Datagram;
use crate::peer::Peer;
use crate::peer::Via;

/// The most remote addresses (and STUN transactions) a shared port
/// remembers; a flood of spoofed sources can't grow the maps without limit.
const MAX_ROUTES: usize = 65536;
/// Accepted ICE-TCP streams still waiting for their first frame, per
/// network; more are closed at once.
pub const MAX_PENDING_TCP: usize = 64;
/// How long an accepted ICE-TCP stream has to send its first frame.
pub const TCP_FIRST_FRAME_TIMEOUT: Duration = Duration::from_secs(10);
/// The most an accepted ICE-TCP stream may send before its first frame is
/// complete.
const MAX_FIRST_FRAME: usize = 2048;

#[derive(Deserialize, Default, Clone, Copy, Debug)]
#[serde(rename_all = "camelCase")]
pub struct IceTimeoutsArg {
  pub disconnected: Option<u64>,
  pub failed: Option<u64>,
  pub keep_alive: Option<u64>,
}

#[derive(Deserialize, Clone, Copy, Debug)]
pub struct PortRangeArg {
  pub min: u16,
  pub max: u16,
}

#[derive(Deserialize, Default, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct NetworkArg {
  pub port: Option<u16>,
  pub port_range: Option<PortRangeArg>,
  pub bind_addresses: Option<Vec<String>>,
  pub interfaces: Option<Vec<String>>,
  #[serde(default = "yes")]
  pub include_loopback: bool,
  #[serde(default)]
  pub public_addresses: Vec<String>,
  #[serde(default)]
  pub public_address_candidate: Option<String>,
  #[serde(default)]
  pub ice_lite: bool,
  pub ice_timeouts: Option<IceTimeoutsArg>,
  pub max_message_size: Option<u32>,
  pub tcp_port: Option<u16>,
  pub mdns: Option<bool>,
}

fn yes() -> bool {
  true
}

/// A public address and the private one it maps to (`None`: every private
/// address).
#[derive(Clone, Copy, Debug)]
pub struct PublicAddress {
  pub public: IpAddr,
  pub private: Option<IpAddr>,
}

#[derive(Clone, Debug, Default)]
pub struct NetworkOptions {
  pub port: Option<u16>,
  pub port_range: Option<(u16, u16)>,
  pub bind_addresses: Option<Vec<IpAddr>>,
  pub interfaces: Option<Vec<String>>,
  pub include_loopback: bool,
  pub public_addresses: Vec<PublicAddress>,
  /// `publicAddressCandidate: "srflx"`: advertise the public address as a
  /// server-reflexive candidate beside the host one.
  pub public_srflx: bool,
  pub ice_lite: bool,
  pub ice_timeouts:
    Option<(Option<Duration>, Option<Duration>, Option<Duration>)>,
  pub max_message_size: Option<u32>,
  /// `tcpPort`: ICE over TCP on a listener on this port (0: one the OS
  /// picks).
  pub tcp_port: Option<u16>,
  pub mdns: MdnsMode,
}

/// What a connection does with mDNS `.local` host candidates.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum MdnsMode {
  /// Neither publishes nor resolves (`mdns: false`).
  Off,
  /// Resolves the peer's (the default, as browsers do).
  #[default]
  Resolve,
  /// Publishes its own host candidates under `.local` names and resolves the
  /// peer's (`mdns: true`).
  Gather,
}

fn parse_ip(s: &str, what: &str) -> Result<IpAddr, Error> {
  s.trim_matches(['[', ']']).parse().map_err(|_| {
    Error::new(
      ErrorKind::Type,
      format!("'{s}' is not an IP address ({what})"),
    )
  })
}

impl NetworkOptions {
  pub fn parse(arg: NetworkArg) -> Result<Self, Error> {
    let bind_addresses = match arg.bind_addresses {
      Some(list) => Some(
        list
          .iter()
          .map(|a| parse_ip(a, "bindAddresses"))
          .collect::<Result<Vec<_>, _>>()?,
      ),
      None => None,
    };
    let mut public_addresses = Vec::new();
    for entry in &arg.public_addresses {
      let (public, private) = match entry.split_once('/') {
        Some((p, q)) => (
          parse_ip(p, "publicAddresses")?,
          Some(parse_ip(q, "publicAddresses")?),
        ),
        None => (parse_ip(entry, "publicAddresses")?, None),
      };
      public_addresses.push(PublicAddress { public, private });
    }
    if public_addresses.len() > 1
      && public_addresses.iter().any(|p| p.private.is_none())
    {
      return Err(Error::new(
        ErrorKind::Type,
        "With several publicAddresses, each must be 'public/private'"
          .to_string(),
      ));
    }
    let ms = |v: Option<u64>| v.map(Duration::from_millis);
    Ok(Self {
      port: arg.port,
      port_range: arg.port_range.map(|r| (r.min, r.max)),
      bind_addresses,
      interfaces: arg.interfaces,
      include_loopback: arg.include_loopback,
      public_addresses,
      public_srflx: arg.public_address_candidate.as_deref() == Some("srflx"),
      ice_lite: arg.ice_lite,
      ice_timeouts: arg
        .ice_timeouts
        .map(|t| (ms(t.disconnected), ms(t.failed), ms(t.keep_alive))),
      max_message_size: arg.max_message_size,
      tcp_port: arg.tcp_port,
      mdns: match arg.mdns {
        None => MdnsMode::Resolve,
        Some(false) => MdnsMode::Off,
        Some(true) => MdnsMode::Gather,
      },
    })
  }

  /// The public address a private one is advertised as, if any.
  pub fn public_for(&self, private: IpAddr) -> Option<IpAddr> {
    self
      .public_addresses
      .iter()
      .find(|p| {
        p.public.is_ipv4() == private.is_ipv4()
          && p.private.is_none_or(|q| q == private)
      })
      .map(|p| p.public)
  }

  /// The private address a public one stands for (host replacement).
  pub fn private_for(
    &self,
    public: IpAddr,
    hosts: &[IpAddr],
  ) -> Option<IpAddr> {
    self
      .public_addresses
      .iter()
      .find(|p| p.public == public)
      .and_then(|p| {
        p.private.or_else(|| {
          hosts
            .iter()
            .copied()
            .find(|h| h.is_ipv4() == public.is_ipv4() && !h.is_loopback())
        })
      })
  }
}

/// One of a shared port's sockets.
#[derive(Clone)]
pub struct SharedEndpoint {
  pub(crate) socket: Rc<EcnUdpSocket>,
  pub bound: SocketAddr,
  pub hosts: Vec<IpAddr>,
}

/// One of an ICE-TCP network's listeners.
#[derive(Clone, Debug)]
pub struct TcpEndpoint {
  pub bound: SocketAddr,
  pub hosts: Vec<IpAddr>,
}

pub struct Network {
  pub options: NetworkOptions,
  /// `port` networks: the sockets every connection shares.
  pub shared: Vec<SharedEndpoint>,
  /// `tcpPort` networks: the listeners every connection's passive
  /// candidates are on.
  pub tcp: Vec<TcpEndpoint>,
  /// Accepted streams still waiting for their first frame.
  pending_tcp: Cell<usize>,
  by_ufrag: RefCell<HashMap<String, Weak<Peer>>>,
  by_remote: RefCell<HashMap<SocketAddr, Weak<Peer>>>,
  by_transaction: RefCell<HashMap<[u8; 12], Weak<Peer>>>,
  cancel: Cancel,
  closed: Cell<bool>,
}

/// The STUN message type, transaction id and (for a binding request) the
/// local ufrag its USERNAME names, if `data` is a STUN message.
pub(crate) fn stun_info(
  data: &[u8],
) -> Option<(u16, [u8; 12], Option<String>)> {
  if data.len() < 20 || data[0] >= 4 || data[4..8] != [0x21, 0x12, 0xa4, 0x42] {
    return None;
  }
  let typ = u16::from_be_bytes([data[0], data[1]]);
  let mut tid = [0u8; 12];
  tid.copy_from_slice(&data[8..20]);
  let len = u16::from_be_bytes([data[2], data[3]]) as usize;
  let body = data.get(20..20 + len)?;
  let mut ufrag = None;
  if typ == 0x0001 {
    let mut i = 0;
    while i + 4 <= body.len() {
      let attr = u16::from_be_bytes([body[i], body[i + 1]]);
      let alen = u16::from_be_bytes([body[i + 2], body[i + 3]]) as usize;
      let value = body.get(i + 4..i + 4 + alen)?;
      if attr == 0x0006 {
        let username = std::str::from_utf8(value).ok()?;
        ufrag = username.split(':').next().map(str::to_string);
        break;
      }
      i += 4 + alen.div_ceil(4) * 4;
    }
  }
  Some((typ, tid, ufrag))
}

impl Network {
  /// Binds a `port` network's sockets now (through `io`), so a taken port
  /// or a refused permission is `createNetwork`'s error.
  ///
  /// Asks `guard` synchronously only ([`NetGate::decide`] /
  /// [`NetGate::interfaces`]; `None` is a refusal). With a gate that may
  /// answer later, use [`Network::create`].
  pub fn new(
    options: NetworkOptions,
    guard: &dyn NetGate,
    io: &dyn NetIo,
  ) -> Result<Rc<Self>, Error> {
    let verdicts = Verdicts::Sync(guard);
    match crate::rt::poll_now(Box::pin(Self::build(options, &verdicts, io))) {
      Ok(result) => result,
      // `Verdicts::Sync` and the binds never wait.
      Err(_) => Err(Error::new(
        ErrorKind::Internal,
        "the network could not be created synchronously".to_string(),
      )),
    }
  }

  /// [`Network::new`] with a gate that may answer later: the binds wait for
  /// its answers (an unanswered question is refused after
  /// [`NetGate::ask_timeout`]). Ready at once with a gate that decides.
  pub async fn create(
    options: NetworkOptions,
    guard: Rc<dyn NetGate>,
    io: Rc<dyn NetIo>,
  ) -> Result<Rc<Self>, Error> {
    let cache = GateCache::new(guard);
    let verdicts = Verdicts::Cache(cache.clone());
    let result = Self::build(options, &verdicts, &*io).await;
    cache.close();
    result
  }

  async fn build(
    options: NetworkOptions,
    guard: &Verdicts<'_>,
    io: &dyn NetIo,
  ) -> Result<Rc<Self>, Error> {
    let cancel = Cancel::new();
    let mut shared = Vec::new();
    if let Some(port) = options.port {
      for (bind, hosts, token) in
        bind_plan(&options, guard, Proto::Udp).await?.0
      {
        let addr = SocketAddr::new(bind, port);
        let socket = io
          .bind_udp(&token, addr, UdpOpts::for_addr(addr))
          .map_err(|e| {
            Error::new(
              ErrorKind::Operation,
              format!(
                "Could not bind UDP {}: {e}",
                SocketAddr::new(bind, port)
              ),
            )
          })?;
        let bound = socket.local_addr().map_err(crate::peer::rtc_err)?;
        shared.push(SharedEndpoint {
          socket: Rc::new(EcnUdpSocket::new(socket)),
          bound,
          hosts,
        });
      }
    }
    let mut listeners = Vec::new();
    if let Some(port) = options.tcp_port {
      for (bind, hosts, token) in
        bind_plan(&options, guard, Proto::Tcp).await?.0
      {
        let addr = SocketAddr::new(bind, port);
        let listener = io.bind_tcp(&token, addr).map_err(|e| {
          Error::new(
            ErrorKind::Operation,
            format!("Could not listen on TCP {addr}: {e}"),
          )
        })?;
        let bound = listener.local_addr().map_err(crate::peer::rtc_err)?;
        listeners.push((listener, TcpEndpoint { bound, hosts }));
      }
    }
    let network = Rc::new(Self {
      tcp: listeners.iter().map(|(_, e)| e.clone()).collect(),
      pending_tcp: Cell::new(0),
      options,
      shared,
      by_ufrag: RefCell::new(HashMap::new()),
      by_remote: RefCell::new(HashMap::new()),
      by_transaction: RefCell::new(HashMap::new()),
      cancel,
      closed: Cell::new(false),
    });
    for endpoint in &network.shared {
      spawn_shared_reader(Rc::downgrade(&network), endpoint.clone());
    }
    for (listener, _) in listeners {
      spawn_tcp_acceptor(Rc::downgrade(&network), listener);
    }
    Ok(network)
  }

  /// A `tcpPort` network: its connections do ICE over TCP.
  pub fn has_tcp(&self) -> bool {
    !self.tcp.is_empty()
  }

  /// Whether connections route by their local ufrag here (a shared UDP port
  /// or TCP listeners).
  pub fn routes_by_ufrag(&self) -> bool {
    self.is_shared() || self.has_tcp()
  }

  pub fn tcp_addresses(&self) -> Vec<String> {
    self.tcp.iter().map(|e| e.bound.to_string()).collect()
  }

  /// The connection whose local ufrag a binding request names.
  fn peer_for_ufrag(&self, ufrag: &str) -> Option<Rc<Peer>> {
    self.by_ufrag.borrow().get(ufrag).and_then(Weak::upgrade)
  }

  pub fn is_shared(&self) -> bool {
    self.options.port.is_some()
  }

  pub fn is_closed(&self) -> bool {
    self.closed.get()
  }

  pub fn addresses(&self) -> Vec<String> {
    self.shared.iter().map(|e| e.bound.to_string()).collect()
  }

  /// A connection on the shared port answers to this local ufrag.
  pub fn register_ufrag(&self, ufrag: String, peer: &Weak<Peer>) {
    let mut map = self.by_ufrag.borrow_mut();
    map.retain(|_, p| p.strong_count() > 0);
    map.insert(ufrag, peer.clone());
  }

  /// A STUN request a connection sends to a STUN server on the shared port:
  /// its response is routed back by transaction id.
  pub fn register_transaction(&self, message: &[u8], peer: &Weak<Peer>) {
    if let Some((_, tid, _)) = stun_info(message) {
      let mut map = self.by_transaction.borrow_mut();
      if map.len() >= MAX_ROUTES {
        map.retain(|_, p| p.strong_count() > 0);
      }
      if map.len() < MAX_ROUTES {
        map.insert(tid, peer.clone());
      }
    }
  }

  pub fn forget(&self, peer: &Peer) {
    let same = |p: &Weak<Peer>| std::ptr::eq(p.as_ptr(), peer);
    self.by_ufrag.borrow_mut().retain(|_, p| !same(p));
    self.by_remote.borrow_mut().retain(|_, p| !same(p));
    self.by_transaction.borrow_mut().retain(|_, p| !same(p));
  }

  pub fn close(&self) {
    if self.closed.replace(true) {
      return;
    }
    self.cancel.cancel();
    self.by_ufrag.borrow_mut().clear();
    self.by_remote.borrow_mut().clear();
    self.by_transaction.borrow_mut().clear();
  }

  /// The connection a datagram on the shared port belongs to. A binding
  /// request goes by the ufrag its USERNAME names and (re)maps its source
  /// address to that connection, so a request forged from someone's address
  /// can't keep their traffic away from the connection they are checking; a
  /// STUN server's response goes by transaction id; anything else by the
  /// source address.
  fn route(&self, from: SocketAddr, data: &[u8]) -> Option<Rc<Peer>> {
    if let Some((typ, tid, ufrag)) = stun_info(data) {
      if typ & 0x0110 != 0 {
        if let Some(peer) = self
          .by_transaction
          .borrow_mut()
          .remove(&tid)
          .and_then(|p| p.upgrade())
        {
          return Some(peer);
        }
      } else if let Some(ufrag) = ufrag {
        let peer =
          self.by_ufrag.borrow().get(&ufrag).and_then(Weak::upgrade)?;
        // ICE authenticates the request itself; a forged one only moves a
        // route, which the real peer's next check moves back.
        let mut routes = self.by_remote.borrow_mut();
        if routes.len() >= MAX_ROUTES {
          routes.retain(|_, p| p.strong_count() > 0);
        }
        if routes.len() < MAX_ROUTES {
          routes.insert(from, Rc::downgrade(&peer));
        }
        return Some(peer);
      }
    }
    self.by_remote.borrow().get(&from).and_then(Weak::upgrade)
  }
}

impl Drop for Network {
  fn drop(&mut self) {
    self.cancel.cancel();
  }
}

fn spawn_shared_reader(network: Weak<Network>, endpoint: SharedEndpoint) {
  let Some(cancel) = network.upgrade().map(|n| n.cancel.clone()) else {
    return;
  };
  crate::rt::spawn(
    async move {
      let mut buf = vec![0u8; 9216];
      loop {
        match endpoint.socket.recv_from(&mut buf).await {
          Ok((n, from, ecn)) => {
            let Some(net) = network.upgrade() else {
              break;
            };
            let Some(peer) = net.route(from, &buf[..n]) else {
              continue;
            };
            peer.deliver(Datagram {
              local: endpoint.bound,
              from,
              stream: None,
              via: Via::Socket,
              data: BytesMut::from(&buf[..n]),
              closed: None,
              ecn,
            });
          }
          Err(e) => {
            log::debug!("webrtc: shared recv on {}: {e}", endpoint.bound);
            tokio::time::sleep(Duration::from_millis(1)).await;
          }
        }
      }
    }
    .or_cancel(cancel),
  );
}

fn spawn_tcp_acceptor(network: Weak<Network>, listener: TcpListener) {
  let Some(cancel) = network.upgrade().map(|n| n.cancel.clone()) else {
    return;
  };
  crate::rt::spawn(
    async move {
      loop {
        let (stream, from) = match listener.accept().await {
          Ok(accepted) => accepted,
          Err(e) => {
            log::debug!("webrtc: ICE-TCP accept: {e}");
            tokio::time::sleep(Duration::from_millis(10)).await;
            continue;
          }
        };
        let Some(net) = network.upgrade() else {
          break;
        };
        if net.pending_tcp.get() >= MAX_PENDING_TCP {
          continue;
        }
        net.pending_tcp.set(net.pending_tcp.get() + 1);
        let weak = network.clone();
        crate::rt::spawn(
          async move {
            let routed = tokio::time::timeout(
              TCP_FIRST_FRAME_TIMEOUT,
              first_frame(stream),
            )
            .await;
            let Some(net) = weak.upgrade() else {
              return;
            };
            net.pending_tcp.set(net.pending_tcp.get().saturating_sub(1));
            let Ok(Some((stream, decoder, frame, ufrag))) = routed else {
              return;
            };
            if let Some(peer) = net.peer_for_ufrag(&ufrag) {
              peer.adopt_tcp(stream, from, decoder, frame);
            }
          }
          .or_cancel(net.cancel.clone()),
        );
      }
    }
    .or_cancel(cancel),
  );
}

/// Reads an accepted stream up to its first RFC 4571 frame, which must be a
/// STUN binding request naming a local ufrag; returns the stream, what else
/// was read, the frame and the ufrag.
async fn first_frame(
  mut stream: TcpStream,
) -> Option<(TcpStream, TcpFrameDecoder, Vec<u8>, String)> {
  let _ = stream.set_nodelay(true);
  let mut decoder = TcpFrameDecoder::new();
  let mut chunk = [0u8; 2048];
  // A binding request is a few hundred bytes: a stream that sends more
  // before its first frame completes isn't ICE.
  let mut read = 0usize;
  loop {
    if let Some(frame) = decoder.next_packet() {
      let (typ, _, ufrag) = stun_info(&frame)?;
      if typ != 0x0001 {
        return None;
      }
      return Some((stream, decoder, frame, ufrag?));
    }
    if read >= MAX_FIRST_FRAME {
      return None;
    }
    let n = stream.read(&mut chunk).await.ok()?;
    if n == 0 {
      return None;
    }
    read += n;
    decoder.push(&chunk[..n]).ok()?;
  }
}

/// The addresses a connection (or a shared port) binds, each with the host
/// candidate addresses it stands for and the gate's token for the bind; and
/// why some were left out (reported as `icecandidateerror`s).
pub type BindPlan = (Vec<(IpAddr, Vec<IpAddr>, GateToken)>, Vec<String>);

/// What to bind, from the network's options (or the defaults, without one):
/// the wildcard with every interface address as a host candidate when
/// interfaces may be listed and the wildcard listened on, else
/// `127.0.0.1`; `DENO_WEBRTC_LOOPBACK_ONLY=1` always `127.0.0.1`. Waits
/// for the gate's answers (each question in turn, as the synchronous
/// checks went).
pub(crate) async fn bind_plan(
  options: &NetworkOptions,
  guard: &Verdicts<'_>,
  proto: Proto,
) -> Result<BindPlan, Error> {
  let listen = async |ip: IpAddr| {
    guard.reach(Reach::bind(ReachKind::Bind, proto, ip)).await
  };
  let loopback = IpAddr::V4(Ipv4Addr::LOCALHOST);
  let mut notes = Vec::new();
  // (bind, hosts, the token when the bind was checked already)
  let mut plan: Vec<(IpAddr, Vec<IpAddr>, Option<GateToken>)> = Vec::new();
  if crate::peer::loopback_only() {
    // Checked below, as the fallback's loopback bind is.
    plan.push((loopback, vec![loopback], None));
  } else {
    let mut ifaces: Option<Option<Vec<IpAddr>>> = None;
    match options.bind_addresses.clone() {
      Some(binds) => {
        for bind in binds {
          let token = match listen(bind).await {
            Ok(token) => token,
            Err(message) => {
              if options.port.is_some() {
                return Err(Error::new(ErrorKind::NotCapable, message));
              }
              notes.push(message);
              continue;
            }
          };
          let hosts = if bind.is_unspecified() {
            if ifaces.is_none() {
              ifaces = Some(interfaces(options, guard, &mut notes).await);
            }
            let list = ifaces.clone().flatten();
            let mut hosts: Vec<IpAddr> = list
              .unwrap_or_default()
              .into_iter()
              .filter(|ip| ip.is_ipv4() == bind.is_ipv4())
              .collect();
            if bind.is_ipv4() && options.include_loopback {
              hosts.insert(0, loopback);
            }
            hosts
          } else {
            vec![bind]
          };
          plan.push((bind, hosts, Some(token)));
        }
      }
      None => match interfaces(options, guard, &mut notes).await {
        Some(ifaces) => {
          let mut v4: Vec<IpAddr> =
            ifaces.iter().copied().filter(IpAddr::is_ipv4).collect();
          if options.include_loopback {
            v4.insert(0, loopback);
          }
          let v6: Vec<IpAddr> =
            ifaces.iter().copied().filter(IpAddr::is_ipv6).collect();
          let any4 = IpAddr::V4(Ipv4Addr::UNSPECIFIED);
          match listen(any4).await {
            Ok(token) => plan.push((any4, v4, Some(token))),
            Err(message) => {
              notes.push(format!(
                "Only loopback host candidates were gathered: {message}"
              ));
              plan.push((loopback, vec![loopback], None));
            }
          }
          let any6 = IpAddr::V6(Ipv6Addr::UNSPECIFIED);
          if !v6.is_empty()
            && let Ok(token) = listen(any6).await
          {
            plan.push((any6, v6, Some(token)));
          }
        }
        None => plan.push((loopback, vec![loopback], None)),
      },
    }
  }
  // The loopback bind of the fallback needs its own listen grant.
  let mut checked = Vec::new();
  for (bind, hosts, token) in plan {
    let token = match token {
      Some(token) if bind.is_unspecified() => token,
      _ => match listen(bind).await {
        Ok(token) => token,
        Err(message) => {
          if options.port.is_some() {
            return Err(Error::new(ErrorKind::NotCapable, message));
          }
          notes.push(message);
          continue;
        }
      },
    };
    checked.push((bind, hosts, token));
  }
  Ok((checked, notes))
}

/// The interface addresses, when the gate allows listing them (else a note).
async fn interfaces(
  options: &NetworkOptions,
  guard: &Verdicts<'_>,
  notes: &mut Vec<String>,
) -> Option<Vec<IpAddr>> {
  match guard.interfaces().await {
    Ok(()) => Some(crate::peer::interface_addresses(
      options.interfaces.as_deref(),
    )),
    Err(message) => {
      notes.push(format!(
        "Only loopback host candidates were gathered: {message}"
      ));
      None
    }
  }
}

/// Binds a UDP socket on `ip` with a port from `range` (tried from a random
/// start, so concurrent connections spread over it).
pub fn bind_in_range(
  io: &dyn NetIo,
  token: &GateToken,
  ip: IpAddr,
  range: (u16, u16),
) -> std::io::Result<UdpSocket> {
  let (min, max) = range;
  let span = (max - min) as u32 + 1;
  let mut start = [0u8; 4];
  let _ = aws_lc_rs::rand::fill(&mut start);
  let start = u32::from_le_bytes(start) % span;
  let mut last = None;
  for i in 0..span {
    let port = min + ((start + i) % span) as u16;
    let addr = SocketAddr::new(ip, port);
    match io.bind_udp(token, addr, UdpOpts::for_addr(addr)) {
      Ok(socket) => return Ok(socket),
      Err(e) => last = Some(e),
    }
  }
  Err(last.unwrap_or_else(|| {
    std::io::Error::new(std::io::ErrorKind::AddrInUse, "no free port in range")
  }))
}

#[cfg(test)]
pub(crate) fn stun_info_for_tests(
  data: &[u8],
) -> Option<(u16, [u8; 12], Option<String>)> {
  stun_info(data)
}