rtci-stream-driver 0.4.1

A socket driver for a sans-I/O WebRTC engine (ICE-TCP, TURN over TCP and TLS, whole peer connections) on an async runtime of your choice
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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
//! The reference driver for the stream half of WebRTC.rs's sans-I/O engine
//! (`rtci_shared::stream`): it owns the TCP sockets, on the async runtime it is given
//! ([`runtime`]), and does what the engine asks.
//!
//! # Engine and driver
//!
//! The engine (`rtci::peer_connection::RTCPeerConnection`) performs no I/O. For its datagrams
//! the application reads and writes its own UDP sockets (`handle_read` / `poll_write`). For
//! TCP it is the engine that **decides** — which ICE-TCP candidates to gather (RFC 6544), which
//! connections to open and close, the RFC 4571 framing, TURN over TCP, TLS and DTLS, relayed
//! TCP candidates (RFC 6062), server-reflexive gathering over TCP, the Happy Eyeballs race
//! (RFC 8305) — and names every listener and connection by id. This driver only **carries
//! out** what it is told:
//!
//! | The engine says ([`StreamCommand`]) | The driver |
//! | --- | --- |
//! | `Listen { local, reuse_address }` | binds a listener (port 0: any, or one of [`DriverConfig::tcp_port_range`]), reports `Listening` or `ListenFailed`, then `Accepted` for each connection |
//! | `Connect { local, remote, reuse_address }` | connects (within [`DriverConfig::connect_timeout`]), reports `Connected` or `ConnectFailed` |
//! | `Close` / `Reset` | ends the connection with FIN (waiting [`DriverConfig::close_linger`]) or RST |
//! | `Resolve { host, port }` | looks the name up (both families at once, or AAAA and A apart with the `dns-records` feature) |
//! | `ResolveRecords { name, kind }` | SRV / NAPTR records with `dns-records`, none without |
//!
//! Bytes go both ways untouched: what the engine transmits ([`StreamDriver::write`]) is
//! already framed and encrypted, and what the socket reads goes back in whatever pieces it
//! came ([`DriverInput::Read`]); each write is reported with `StreamEvent::Written`, the
//! engine's back-pressure signal.
//!
//! # The loop
//!
//! ```text
//! while let Some(command) = pc.poll_stream_command() { driver.execute(command) }
//! while let Some(transmit) = pc.poll_stream_transmit() { driver.write(transmit) }
//! match driver.next().await {                      // or try_next() in a polling loop
//!     DriverInput::Event(event) => pc.handle_stream_event(now, event)?,
//!     DriverInput::Read { id, data } => pc.handle_stream_read(now, id, &data)?,
//!     DriverInput::Accepted(accepted) => match pc.handle_stream_accepted(
//!         now, accepted.listener, accepted.local, accepted.remote) {
//!         Some(id) => driver.adopt(id, accepted),
//!         None => drop(accepted),                  // refused: the socket closes
//!     },
//! }
//! ```
//!
//! A complete program, two peer connections over loopback TCP with a data channel, is the
//! `stream-driver-loopback` example of the `rtci` crate (`cargo run --example
//! stream-driver-loopback`); the test environment runs it.
//!
//! # Marking (DSCP)
//!
//! Each TCP connection's packets carry the codepoint of its transmits ([`StreamTransmit::dscp`],
//! one per connection, RFC 8837 section 5), and [`peer::PeerDriver`] marks each UDP datagram
//! with the byte `RTCPeerConnection::traffic_class` gives it (RFC 8837 Table 1 with the ECN
//! bits). [`sockets::set_traffic_class`] says what each platform does: Windows leaves the
//! packets unmarked.
//!
//! # Server choices
//!
//! [`sockets`] has what a server decides and the engine does not: port ranges
//! ([`sockets::PortRange`]), which local addresses get candidates ([`sockets::AddressFilter`]),
//! one UDP port for many peer connections ([`sockets::UfragMux`]) and one passive ICE-TCP port
//! for many ([`DriverConfig::shared_passive`], [`sockets::accept_by_ufrag`]).
//!
//! # NAT-assisted candidates
//!
//! [`nat_mapping`] (opt-in, no dependency) asks the gateway for a port mapping with PCP (RFC
//! 6887), falling back to NAT-PMP (RFC 6886); the application adds the mapped address as a
//! server-reflexive candidate ([`nat_mapping::candidate_line`], RFC 6544 section 5.3).
//!
//! # A whole peer connection
//!
//! [`peer::PeerDriver`] (feature `peer`, on by default) drives an `rtci` peer connection over
//! sockets it owns, its UDP host sockets included, and gathers for it: at the first local
//! description, and again on its own when a transport needs a new set of local candidates
//! (`OnLocalCandidatesNeeded`: a new DTLS association runs on a new 3-tuple, RFC 8842 section
//! 5.1), closing the previous sockets once a pair on the new ones is selected.
//!
//! # Runtime
//!
//! The driver's sockets, tasks, timers and name lookups belong to the [`runtime::Runtime`] it
//! is given ([`StreamDriver::with_runtime`], [`peer::PeerDriver::with_runtime`]): there is no
//! global or default runtime. The [`runtime`] module says what is injected and what is not,
//! and how to bring your own.
//!
//! # Features
//!
//! - `runtime-tokio` (default): `runtime::TokioRuntime`, and `StreamDriver::new` /
//!   `default` and `PeerDriver::new` on it.
//! - `runtime-smol`: `runtime::SmolRuntime`.
//! - `runtime-mock`: `runtime::MockRuntime`, virtual time and an in-memory network.
//! - `peer` (default): [`peer`], with a dependency on `rtci`.
//! - `dns-records`: SRV and NAPTR lookups (RFC 5928, RFC 8489 section 8) and AAAA / A answered
//!   apart (RFC 8305 section 3) in `TokioRuntime`, with hickory-resolver (MIT OR Apache-2.0);
//!   it turns `runtime-tokio` on. Without it, names go to the runtime's resolver and record
//!   queries are answered with none (the engine then uses the host and the scheme's default
//!   port).
//!
//! With `default-features = false` and no runtime feature the crate has no async runtime in
//! its dependency tree.
//!
//! Each connection has a reader task and a writer task. With `TokioRuntime::new()` sockets are
//! created on the thread that calls [`StreamDriver::execute`] inside a tokio runtime, so a
//! current-thread runtime on a thread that entered a network namespace keeps them there.

#![warn(missing_docs)]

#[cfg(feature = "peer")]
mod mdns_io;
pub mod nat_mapping;
#[cfg(feature = "peer")]
pub mod peer;
pub mod runtime;
pub mod sockets;

use runtime::{AsyncTcpListener, AsyncTcpStream, JoinHandle, Runtime};
use shared::stream::{ListenerId, StreamCommand, StreamEvent, StreamId, StreamTransmit};
use std::collections::HashMap;
use std::future::Future;
use std::io;
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::time::Duration;

/// What the driver has for the engine.
#[derive(Debug)]
pub enum DriverInput {
    /// Pass to the engine's `handle_stream_event`.
    Event(StreamEvent),
    /// Bytes read from a connection: pass to the engine's `handle_stream_read`.
    Read {
        /// The connection.
        id: StreamId,
        /// What was read.
        data: Vec<u8>,
    },
    /// A connection accepted on a listener: ask the engine for its id
    /// (`handle_stream_accepted`) and [`adopt`](StreamDriver::adopt) it, or drop it.
    Accepted(Accepted),
}

/// A connection accepted on a listener, waiting for its id.
#[derive(Debug)]
pub struct Accepted {
    /// The listener it arrived on.
    pub listener: ListenerId,
    /// Its local address.
    pub local: SocketAddr,
    /// The peer's address.
    pub remote: SocketAddr,
    stream: Arc<dyn AsyncTcpStream>,
}

/// The driver's settings.
#[derive(Debug, Clone, Copy)]
pub struct DriverConfig {
    /// How long a connection attempt may take before it is reported failed.
    pub connect_timeout: Duration,
    /// How long a close waits for the peer's end of stream before giving up.
    pub close_linger: Duration,
    /// Listeners asked for on port 0 take a port of this range.
    pub tcp_port_range: Option<sockets::PortRange>,
    /// A passive ICE-TCP listening port shared with other peer connections: a `Listen` without
    /// `reuse_address` is answered with this address and binds nothing; the application
    /// accepts on the shared listener ([`sockets::accept_by_ufrag`]) and hands each connection
    /// to the driver of the peer connection its first check names
    /// ([`StreamDriver::adopt_shared`]). Every transport of the connection is answered with the
    /// same address; the engine gives each connection to the transport its first check names.
    pub shared_passive: Option<SocketAddr>,
}

impl Default for DriverConfig {
    fn default() -> Self {
        Self {
            connect_timeout: Duration::from_secs(10),
            close_linger: Duration::from_secs(2),
            tcp_port_range: None,
            shared_passive: None,
        }
    }
}

enum WriterMessage {
    Data(Vec<u8>),
    /// Set the socket's TOS / Traffic Class byte to this before the data that follows.
    Mark(u8),
    Close,
    Reset,
}

struct Connection {
    writer: async_channel::Sender<WriterMessage>,
    task: Box<dyn JoinHandle>,
    established: Arc<AtomicBool>,
    /// The DSCP last asked for on this connection (a new socket's is 0).
    dscp: u8,
    /// What the operating system reported for the socket's TOS / Traffic Class after the
    /// writer last set it; [`NO_TRAFFIC_CLASS`] before that, or when it was refused.
    traffic_class: Arc<AtomicU32>,
}

/// [`Connection::traffic_class`] with nothing read back.
const NO_TRAFFIC_CLASS: u32 = u32::MAX;

impl Connection {
    fn new(
        writer: async_channel::Sender<WriterMessage>,
        task: Box<dyn JoinHandle>,
        established: Arc<AtomicBool>,
        traffic_class: Arc<AtomicU32>,
    ) -> Self {
        Self {
            writer,
            task,
            established,
            dscp: 0,
            traffic_class,
        }
    }
}

/// Owns the sockets of one engine (see the [crate documentation](crate)).
pub struct StreamDriver {
    runtime: Arc<dyn Runtime>,
    config: DriverConfig,
    inputs_tx: async_channel::Sender<DriverInput>,
    inputs: async_channel::Receiver<DriverInput>,
    listeners: HashMap<ListenerId, Box<dyn JoinHandle>>,
    connections: HashMap<StreamId, Connection>,
    /// The engine's listener answered with the shared passive address.
    shared_listener: Option<ListenerId>,
}

#[cfg(feature = "runtime-tokio")]
impl Default for StreamDriver {
    fn default() -> Self {
        Self::new(DriverConfig::default())
    }
}

impl Drop for StreamDriver {
    fn drop(&mut self) {
        for (_, task) in self.listeners.drain() {
            task.abort();
        }
        for (_, connection) in self.connections.drain() {
            connection.task.abort();
        }
    }
}

impl StreamDriver {
    /// A driver with no sockets, on tokio ([`runtime::TokioRuntime::new`]: the tokio runtime
    /// [`execute`](Self::execute) is called in). Feature `runtime-tokio` (on by default).
    #[cfg(feature = "runtime-tokio")]
    pub fn new(config: DriverConfig) -> Self {
        Self::with_runtime(Arc::new(runtime::TokioRuntime::new()), config)
    }

    /// A driver with no sockets, on `runtime`.
    pub fn with_runtime(runtime: Arc<dyn Runtime>, config: DriverConfig) -> Self {
        let (inputs_tx, inputs) = async_channel::unbounded();
        Self {
            runtime,
            config,
            inputs_tx,
            inputs,
            listeners: HashMap::new(),
            connections: HashMap::new(),
            shared_listener: None,
        }
    }

    /// The runtime the driver runs on.
    pub fn runtime(&self) -> &Arc<dyn Runtime> {
        &self.runtime
    }

    /// Carries out a command of the engine. With `runtime::TokioRuntime::new()` it must be
    /// called inside a tokio runtime.
    pub fn execute(&mut self, command: StreamCommand) {
        match command {
            StreamCommand::Listen {
                listener,
                local,
                reuse_address,
            } if !reuse_address
                && self.config.shared_passive.is_some_and(|shared| {
                    shared.ip() == local.ip() || local.ip().is_unspecified()
                }) =>
            {
                self.shared_listener = Some(listener);
                let shared = self.config.shared_passive.unwrap_or(local);
                self.send(DriverInput::Event(StreamEvent::Listening {
                    listener,
                    local: shared,
                }));
            }
            StreamCommand::Listen {
                listener,
                local,
                reuse_address,
            } => match match self.config.tcp_port_range {
                Some(range) if local.port() == 0 => sockets::bind_tcp_listener_in_range(
                    self.runtime.as_ref(),
                    local.ip(),
                    range,
                    reuse_address,
                ),
                _ => self.runtime.listen_tcp(local, reuse_address),
            } {
                Ok(socket) => {
                    let bound = socket.local_addr().unwrap_or(local);
                    self.send(DriverInput::Event(StreamEvent::Listening {
                        listener,
                        local: bound,
                    }));
                    let tx = self.inputs_tx.clone();
                    let task = self.runtime.spawn(Box::pin(accept_loop(
                        self.runtime.clone(),
                        listener,
                        socket,
                        tx,
                    )));
                    if let Some(old) = self.listeners.insert(listener, task) {
                        old.abort();
                    }
                }
                Err(_) => self.send(DriverInput::Event(StreamEvent::ListenFailed { listener })),
            },
            StreamCommand::StopListening { listener } => {
                if let Some(task) = self.listeners.remove(&listener) {
                    task.abort();
                }
            }
            StreamCommand::Connect {
                id,
                local,
                remote,
                reuse_address,
            } => {
                let (writer, rx) = async_channel::unbounded();
                let established = Arc::new(AtomicBool::new(false));
                let tx = self.inputs_tx.clone();
                let config = self.config;
                let flag = established.clone();
                let traffic_class = Arc::new(AtomicU32::new(NO_TRAFFIC_CLASS));
                let marked = traffic_class.clone();
                let rt = self.runtime.clone();
                let task = self.runtime.spawn(Box::pin(async move {
                    let connected = runtime::timeout(
                        rt.as_ref(),
                        config.connect_timeout,
                        connect(rt.as_ref(), local, remote, reuse_address),
                    )
                    .await;
                    match connected {
                        Ok(Ok(stream)) => {
                            let local = stream.local_addr().unwrap_or(local);
                            flag.store(true, Ordering::SeqCst);
                            let _ = tx
                                .try_send(DriverInput::Event(StreamEvent::Connected { id, local }));
                            run_connection(rt, id, stream, rx, tx, config, marked).await;
                        }
                        _ => {
                            let _ =
                                tx.try_send(DriverInput::Event(StreamEvent::ConnectFailed { id }));
                        }
                    }
                }));
                self.connections.insert(
                    id,
                    Connection::new(writer, task, established, traffic_class),
                );
            }
            StreamCommand::Close { id } => {
                if let Some(connection) = self.connections.remove(&id) {
                    if connection.established.load(Ordering::SeqCst) {
                        let _ = connection.writer.try_send(WriterMessage::Close);
                    } else {
                        connection.task.abort();
                    }
                }
            }
            StreamCommand::Reset { id } => {
                if let Some(connection) = self.connections.remove(&id) {
                    if connection.established.load(Ordering::SeqCst) {
                        let _ = connection.writer.try_send(WriterMessage::Reset);
                    } else {
                        connection.task.abort();
                    }
                }
            }
            StreamCommand::Resolve { query, host, port } => {
                match (
                    self.runtime.resolve_family(&host, port, true),
                    self.runtime.resolve_family(&host, port, false),
                ) {
                    // AAAA and A asked together, each answered as it arrives (RFC 8305 section
                    // 3): the engine starts on the first.
                    (Some(v6), Some(v4)) => {
                        for (ipv6, lookup) in [(true, v6), (false, v4)] {
                            let tx = self.inputs_tx.clone();
                            self.runtime.spawn(Box::pin(async move {
                                let addresses = lookup.await;
                                let _ =
                                    tx.try_send(DriverInput::Event(StreamEvent::ResolvedFamily {
                                        query,
                                        ipv6,
                                        addresses,
                                    }));
                            }));
                        }
                    }
                    // Both families at once (RFC 8305 section 3): the system resolver asks for
                    // AAAA and A together.
                    _ => {
                        let tx = self.inputs_tx.clone();
                        let lookup = self.runtime.resolve_host(&host, port);
                        self.runtime.spawn(Box::pin(async move {
                            let addresses = lookup.await.unwrap_or_default();
                            let _ = tx.try_send(DriverInput::Event(StreamEvent::Resolved {
                                query,
                                addresses,
                            }));
                        }));
                    }
                }
            }
            StreamCommand::ResolveRecords { query, name, kind } => {
                let tx = self.inputs_tx.clone();
                // Without record lookups (the runtime's default) the answer is none, and the
                // engine takes the host's addresses (RFC 5928 section 3).
                let lookup = self.runtime.resolve_records(&name, kind);
                self.runtime.spawn(Box::pin(async move {
                    let records = lookup.await;
                    let _ = tx.try_send(DriverInput::Event(StreamEvent::ResolvedRecords {
                        query,
                        records,
                    }));
                }));
            }
            _ => {}
        }
    }

    /// Takes the engine's id for an accepted connection and starts serving it.
    pub fn adopt(&mut self, id: StreamId, accepted: Accepted) {
        let (writer, rx) = async_channel::unbounded();
        let tx = self.inputs_tx.clone();
        let config = self.config;
        let traffic_class = Arc::new(AtomicU32::new(NO_TRAFFIC_CLASS));
        let task = self.runtime.spawn(Box::pin(run_connection(
            self.runtime.clone(),
            id,
            accepted.stream,
            rx,
            tx,
            config,
            traffic_class.clone(),
        )));
        self.connections.insert(
            id,
            Connection::new(writer, task, Arc::new(AtomicBool::new(true)), traffic_class),
        );
    }

    /// The engine's listener that stands for the shared passive port
    /// ([`DriverConfig::shared_passive`]), once the engine asked for it.
    pub fn shared_listener(&self) -> Option<ListenerId> {
        self.shared_listener
    }

    /// Serves a connection accepted on the shared passive port, which the engine gave `id`
    /// (`handle_stream_accepted` with [`shared_listener`](Self::shared_listener)); the bytes
    /// already read from it to route it are handed to the engine first.
    pub fn adopt_shared(&mut self, id: StreamId, accepted: sockets::SharedAccept) {
        if !accepted.read.is_empty() {
            self.send(DriverInput::Read {
                id,
                data: accepted.read,
            });
        }
        self.adopt(
            id,
            Accepted {
                listener: self.shared_listener.unwrap_or(ListenerId(0)),
                local: accepted.local,
                remote: accepted.remote,
                stream: accepted.stream,
            },
        );
    }

    /// Writes a transmit of the engine, after the earlier ones of its connection. When the
    /// transmit's DSCP ([`StreamTransmit::dscp`]: one per TCP connection, RFC 8837 section 5)
    /// differs from the connection's, the socket's `IP_TOS` / `IPV6_TCLASS` is set to it first
    /// ([`sockets::set_traffic_class`], which says what each platform does).
    pub fn write(&mut self, transmit: StreamTransmit) {
        if let Some(connection) = self.connections.get_mut(&transmit.id) {
            if connection.dscp != transmit.dscp {
                connection.dscp = transmit.dscp;
                let _ = connection
                    .writer
                    .try_send(WriterMessage::Mark(transmit.dscp << 2));
            }
            let _ = connection
                .writer
                .try_send(WriterMessage::Data(transmit.data));
        }
    }

    /// The TOS / Traffic Class byte the operating system reported for connection `id`'s
    /// socket (`getsockopt` of `IP_TOS` / `IPV6_TCLASS`) after the driver last set it, once it
    /// has: `None` for an unknown connection, one never marked, or a platform that refused.
    pub fn socket_traffic_class(&self, id: StreamId) -> Option<u32> {
        let connection = self.connections.get(&id)?;
        let value = connection.traffic_class.load(Ordering::SeqCst);
        (value != NO_TRAFFIC_CLASS).then_some(value)
    }

    /// The next input for the engine.
    pub async fn next(&mut self) -> DriverInput {
        // The driver holds a sender itself, so the channel never closes.
        self.inputs
            .recv()
            .await
            .expect("the driver keeps its own sender")
    }

    /// The next input for the engine, if one is ready.
    pub fn try_next(&mut self) -> Option<DriverInput> {
        self.inputs.try_recv().ok()
    }

    /// Connections and listeners open.
    pub fn sockets(&self) -> (usize, usize) {
        (self.connections.len(), self.listeners.len())
    }

    fn send(&self, input: DriverInput) {
        let _ = self.inputs_tx.try_send(input);
    }
}

async fn connect(
    runtime: &dyn Runtime,
    local: SocketAddr,
    remote: SocketAddr,
    reuse_address: bool,
) -> io::Result<Arc<dyn AsyncTcpStream>> {
    let stream = runtime.connect_tcp(local, remote, reuse_address).await?;
    // A connection whose two ends are the same address is the socket connected to itself, not
    // to a peer: connecting from an ephemeral port to a loopback port nothing listens on, the
    // system can pick that very port as the source, and TCP's simultaneous open (RFC 9293
    // section 3.5) then "connects" the socket to itself. It is a failed connection (an ICE-TCP
    // check toward a dead loopback candidate would otherwise succeed against its own echo).
    if is_self_connection(stream.local_addr()?, stream.peer_addr()?) {
        return Err(io::Error::new(
            io::ErrorKind::ConnectionRefused,
            format!("{remote}: the socket connected to itself"),
        ));
    }
    Ok(stream)
}

/// Whether a connection runs from an address to that same address.
fn is_self_connection(local: SocketAddr, peer: SocketAddr) -> bool {
    local == peer
}

async fn accept_loop(
    runtime: Arc<dyn Runtime>,
    listener: ListenerId,
    socket: Arc<dyn AsyncTcpListener>,
    tx: async_channel::Sender<DriverInput>,
) {
    loop {
        match socket.accept().await {
            Ok((stream, remote)) => {
                let local = match stream.local_addr() {
                    Ok(local) => local,
                    Err(_) => continue,
                };
                if tx
                    .try_send(DriverInput::Accepted(Accepted {
                        listener,
                        local,
                        remote,
                        stream,
                    }))
                    .is_err()
                {
                    return;
                }
            }
            // Out of descriptors, say: try again shortly rather than spin.
            Err(_) => runtime::sleep(runtime.as_ref(), Duration::from_millis(50)).await,
        }
    }
}

/// What the writer of a connection waits for next.
enum Next {
    Message(Option<WriterMessage>),
    ReaderEnded,
}

async fn run_connection(
    runtime: Arc<dyn Runtime>,
    id: StreamId,
    stream: Arc<dyn AsyncTcpStream>,
    rx: async_channel::Receiver<WriterMessage>,
    tx: async_channel::Sender<DriverInput>,
    config: DriverConfig,
    traffic_class: Arc<AtomicU32>,
) {
    let reader_tx = tx.clone();
    let read_half = stream.clone();
    let mut reader = runtime.spawn(Box::pin(async move {
        let mut buf = vec![0u8; 64 * 1024];
        loop {
            match read_half.read(&mut buf).await {
                Ok(0) => {
                    let _ = reader_tx.try_send(DriverInput::Event(StreamEvent::Closed { id }));
                    return;
                }
                Ok(n) => {
                    if reader_tx
                        .try_send(DriverInput::Read {
                            id,
                            data: buf[..n].to_vec(),
                        })
                        .is_err()
                    {
                        return;
                    }
                }
                Err(_) => {
                    let _ = reader_tx.try_send(DriverInput::Event(StreamEvent::Reset { id }));
                    return;
                }
            }
        }
    }));
    loop {
        let next = {
            let mut message = std::pin::pin!(rx.recv());
            std::future::poll_fn(|cx| {
                if let std::task::Poll::Ready(message) = message.as_mut().poll(cx) {
                    return std::task::Poll::Ready(Next::Message(message.ok()));
                }
                // The peer closed or the connection broke: the reader has reported it.
                reader.poll_join(cx).map(|()| Next::ReaderEnded)
            })
            .await
        };
        match next {
            Next::Message(Some(WriterMessage::Mark(value))) => {
                let read_back = stream.set_traffic_class(value).unwrap_or(NO_TRAFFIC_CLASS);
                traffic_class.store(read_back, Ordering::SeqCst);
            }
            Next::Message(Some(WriterMessage::Data(data))) => {
                if stream.write_all(&data).await.is_err() {
                    let _ = tx.try_send(DriverInput::Event(StreamEvent::Reset { id }));
                    reader.abort();
                    return;
                }
                let _ = tx.try_send(DriverInput::Event(StreamEvent::Written {
                    id,
                    bytes: data.len(),
                }));
            }
            Next::Message(Some(WriterMessage::Close)) => {
                let _ = stream.shutdown_write();
                // The reader reports Closed at the peer's end of stream; one that never
                // comes is given up on.
                if runtime::timeout(runtime.as_ref(), config.close_linger, reader.join())
                    .await
                    .is_err()
                {
                    reader.abort();
                    let _ = tx.try_send(DriverInput::Event(StreamEvent::Closed { id }));
                }
                return;
            }
            Next::Message(Some(WriterMessage::Reset) | None) => {
                // SO_LINGER 0: closing sends RST instead of FIN, once the reader's reference
                // is dropped with it.
                let _ = stream.reset_on_close();
                reader.abort();
                return;
            }
            Next::ReaderEnded => return,
        }
    }
}

/// DNS lookups with hickory-resolver (feature `dns-records`).
#[cfg(feature = "dns-records")]
mod dns {
    use hickory_resolver::TokioResolver;
    use hickory_resolver::proto::rr::{RData, RecordType};
    use shared::stream::{DnsRecord, RecordKind};
    use std::net::{IpAddr, SocketAddr};

    /// The system's resolver (its name servers and search list).
    fn resolver() -> Option<TokioResolver> {
        TokioResolver::builder_tokio().ok()?.build().ok()
    }

    /// The addresses of one family of `host`, with `port`.
    pub(crate) async fn addresses(host: &str, port: u16, ipv6: bool) -> Vec<SocketAddr> {
        match resolver() {
            Some(resolver) => addresses_with(&resolver, host, port, ipv6).await,
            None => vec![],
        }
    }

    async fn addresses_with(
        resolver: &TokioResolver,
        host: &str,
        port: u16,
        ipv6: bool,
    ) -> Vec<SocketAddr> {
        let kind = if ipv6 {
            RecordType::AAAA
        } else {
            RecordType::A
        };
        let Ok(found) = resolver.lookup(host, kind).await else {
            return vec![];
        };
        found
            .answers()
            .iter()
            .filter_map(|r| match &r.data {
                RData::A(a) => Some(IpAddr::V4(a.0)),
                RData::AAAA(a) => Some(IpAddr::V6(a.0)),
                _ => None,
            })
            .map(|ip| SocketAddr::new(ip, port))
            .collect()
    }

    /// The SRV or NAPTR records of `name` (none on any error).
    pub(crate) async fn records(name: &str, kind: RecordKind) -> Vec<DnsRecord> {
        match resolver() {
            Some(resolver) => records_with(&resolver, name, kind).await,
            None => vec![],
        }
    }

    async fn records_with(
        resolver: &TokioResolver,
        name: &str,
        kind: RecordKind,
    ) -> Vec<DnsRecord> {
        let record_type = match kind {
            RecordKind::Srv => RecordType::SRV,
            RecordKind::Naptr => RecordType::NAPTR,
            _ => return vec![],
        };
        let Ok(found) = resolver.lookup(name, record_type).await else {
            return vec![];
        };
        let text = |b: &[u8]| String::from_utf8_lossy(b).into_owned();
        found
            .answers()
            .iter()
            .filter_map(|r| match &r.data {
                RData::SRV(srv) => Some(DnsRecord::Srv {
                    priority: srv.priority,
                    weight: srv.weight,
                    port: srv.port,
                    target: srv.target.to_utf8(),
                }),
                RData::NAPTR(n) => Some(DnsRecord::Naptr {
                    order: n.order,
                    preference: n.preference,
                    flags: text(&n.flags),
                    services: text(&n.services),
                    regexp: text(&n.regexp),
                    replacement: n.replacement.to_utf8(),
                }),
                _ => None,
            })
            .collect()
    }

    /// The lookups against a name server on loopback that answers from a fixed zone, through
    /// the resolver's own UDP client: what the engine's SRV / NAPTR discovery of STUN and TURN
    /// servers (RFC 5928, RFC 8489 section 8) and its per-family answers (RFC 8305 section 3)
    /// receive.
    #[cfg(test)]
    mod tests {
        use super::*;
        use hickory_resolver::config::{NameServerConfig, ResolverConfig};
        use hickory_resolver::net::runtime::TokioRuntimeProvider;
        use hickory_resolver::proto::op::{Message, OpCode};
        use hickory_resolver::proto::rr::rdata::{A, AAAA, NAPTR, SRV};
        use hickory_resolver::proto::rr::{Name, Record};
        use std::net::{Ipv4Addr, Ipv6Addr};

        /// A name server on 127.0.0.1 answering `turn.example.`; its port.
        async fn name_server() -> u16 {
            let socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
            let port = socket.local_addr().unwrap().port();
            tokio::spawn(async move {
                let mut buf = [0u8; 1500];
                loop {
                    let Ok((n, from)) = socket.recv_from(&mut buf).await else {
                        return;
                    };
                    let Ok(query) = Message::from_vec(&buf[..n]) else {
                        continue;
                    };
                    let mut response = Message::response(query.metadata.id, OpCode::Query);
                    response.metadata.recursion_desired = query.metadata.recursion_desired;
                    response.metadata.recursion_available = true;
                    response.metadata.authoritative = true;
                    for q in &query.queries {
                        response.add_query(q.clone());
                        let name = q.name().clone();
                        let rdata = |r| Record::from_rdata(name.clone(), 60, r);
                        let host = |s: &str| Name::from_ascii(s).unwrap();
                        let answers: Vec<Record> = match q.query_type() {
                            RecordType::A => vec![rdata(RData::A(A(Ipv4Addr::new(192, 0, 2, 7))))],
                            RecordType::AAAA => vec![rdata(RData::AAAA(AAAA(Ipv6Addr::new(
                                0x2001, 0xdb8, 0, 0, 0, 0, 0, 7,
                            ))))],
                            RecordType::SRV => vec![
                                rdata(RData::SRV(SRV::new(1, 5, 3478, host("turn1.example.")))),
                                rdata(RData::SRV(SRV::new(2, 0, 3479, host("turn2.example.")))),
                            ],
                            RecordType::NAPTR => vec![rdata(RData::NAPTR(NAPTR::new(
                                10,
                                20,
                                b"s".to_vec().into_boxed_slice(),
                                b"RELAY:turn.udp".to_vec().into_boxed_slice(),
                                Vec::new().into_boxed_slice(),
                                host("_turn._udp.example."),
                            )))],
                            _ => vec![],
                        };
                        for a in answers {
                            response.add_answer(a);
                        }
                    }
                    if let Ok(bytes) = response.to_vec() {
                        let _ = socket.send_to(&bytes, from).await;
                    }
                }
            });
            port
        }

        fn resolver_at(port: u16) -> TokioResolver {
            let mut server = NameServerConfig::udp(IpAddr::V4(Ipv4Addr::LOCALHOST));
            for connection in &mut server.connections {
                connection.port = port;
            }
            let config = ResolverConfig::from_parts(None, vec![], vec![server]);
            TokioResolver::builder_with_config(config, TokioRuntimeProvider::default())
                .build()
                .unwrap()
        }

        #[tokio::test]
        async fn srv_and_naptr_records_and_each_address_family_come_back_whole() {
            let resolver = resolver_at(name_server().await);
            let mut srv = records_with(&resolver, "turn.example.", RecordKind::Srv).await;
            srv.sort_by_key(|r| match r {
                DnsRecord::Srv { priority, .. } => *priority,
                _ => u16::MAX,
            });
            assert_eq!(
                srv,
                vec![
                    DnsRecord::Srv {
                        priority: 1,
                        weight: 5,
                        port: 3478,
                        target: "turn1.example.".into(),
                    },
                    DnsRecord::Srv {
                        priority: 2,
                        weight: 0,
                        port: 3479,
                        target: "turn2.example.".into(),
                    },
                ]
            );
            assert_eq!(
                records_with(&resolver, "turn.example.", RecordKind::Naptr).await,
                vec![DnsRecord::Naptr {
                    order: 10,
                    preference: 20,
                    flags: "s".into(),
                    services: "RELAY:turn.udp".into(),
                    regexp: String::new(),
                    replacement: "_turn._udp.example.".into(),
                }]
            );
            assert_eq!(
                addresses_with(&resolver, "turn.example.", 3478, false).await,
                vec![SocketAddr::new(Ipv4Addr::new(192, 0, 2, 7).into(), 3478)]
            );
            assert_eq!(
                addresses_with(&resolver, "turn.example.", 3478, true).await,
                vec![SocketAddr::new(
                    Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 7).into(),
                    3478
                )]
            );
        }
    }
}

#[cfg(test)]
mod self_connection_tests {
    use super::*;

    #[test]
    fn a_connection_is_to_itself_only_when_both_ends_are_the_same_address() {
        let a: SocketAddr = "127.0.0.1:45149".parse().unwrap();
        assert!(is_self_connection(a, a));
        assert!(!is_self_connection(a, "127.0.0.1:45150".parse().unwrap()));
        assert!(!is_self_connection(a, "127.0.0.2:45149".parse().unwrap()));
        let v6: SocketAddr = "[::1]:45149".parse().unwrap();
        assert!(is_self_connection(v6, v6));
        assert!(!is_self_connection(v6, "[::1]:9".parse().unwrap()));
    }
}