Skip to main content

rtci_stream_driver/
lib.rs

1//! The reference driver for the stream half of WebRTC.rs's sans-I/O engine
2//! (`rtci_shared::stream`): it owns the TCP sockets, on the async runtime it is given
3//! ([`runtime`]), and does what the engine asks.
4//!
5//! # Engine and driver
6//!
7//! The engine (`rtci::peer_connection::RTCPeerConnection`) performs no I/O. For its datagrams
8//! the application reads and writes its own UDP sockets (`handle_read` / `poll_write`). For
9//! TCP it is the engine that **decides** — which ICE-TCP candidates to gather (RFC 6544), which
10//! connections to open and close, the RFC 4571 framing, TURN over TCP, TLS and DTLS, relayed
11//! TCP candidates (RFC 6062), server-reflexive gathering over TCP, the Happy Eyeballs race
12//! (RFC 8305) — and names every listener and connection by id. This driver only **carries
13//! out** what it is told:
14//!
15//! | The engine says ([`StreamCommand`]) | The driver |
16//! | --- | --- |
17//! | `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 |
18//! | `Connect { local, remote, reuse_address }` | connects (within [`DriverConfig::connect_timeout`]), reports `Connected` or `ConnectFailed` |
19//! | `Close` / `Reset` | ends the connection with FIN (waiting [`DriverConfig::close_linger`]) or RST |
20//! | `Resolve { host, port }` | looks the name up (both families at once, or AAAA and A apart with the `dns-records` feature) |
21//! | `ResolveRecords { name, kind }` | SRV / NAPTR records with `dns-records`, none without |
22//!
23//! Bytes go both ways untouched: what the engine transmits ([`StreamDriver::write`]) is
24//! already framed and encrypted, and what the socket reads goes back in whatever pieces it
25//! came ([`DriverInput::Read`]); each write is reported with `StreamEvent::Written`, the
26//! engine's back-pressure signal.
27//!
28//! # The loop
29//!
30//! ```text
31//! while let Some(command) = pc.poll_stream_command() { driver.execute(command) }
32//! while let Some(transmit) = pc.poll_stream_transmit() { driver.write(transmit) }
33//! match driver.next().await {                      // or try_next() in a polling loop
34//!     DriverInput::Event(event) => pc.handle_stream_event(now, event)?,
35//!     DriverInput::Read { id, data } => pc.handle_stream_read(now, id, &data)?,
36//!     DriverInput::Accepted(accepted) => match pc.handle_stream_accepted(
37//!         now, accepted.listener, accepted.local, accepted.remote) {
38//!         Some(id) => driver.adopt(id, accepted),
39//!         None => drop(accepted),                  // refused: the socket closes
40//!     },
41//! }
42//! ```
43//!
44//! A complete program, two peer connections over loopback TCP with a data channel, is the
45//! `stream-driver-loopback` example of the `rtci` crate (`cargo run --example
46//! stream-driver-loopback`); the test environment runs it.
47//!
48//! # Marking (DSCP)
49//!
50//! Each TCP connection's packets carry the codepoint of its transmits ([`StreamTransmit::dscp`],
51//! one per connection, RFC 8837 section 5), and [`peer::PeerDriver`] marks each UDP datagram
52//! with the byte `RTCPeerConnection::traffic_class` gives it (RFC 8837 Table 1 with the ECN
53//! bits). [`sockets::set_traffic_class`] says what each platform does: Windows leaves the
54//! packets unmarked.
55//!
56//! # Server choices
57//!
58//! [`sockets`] has what a server decides and the engine does not: port ranges
59//! ([`sockets::PortRange`]), which local addresses get candidates ([`sockets::AddressFilter`]),
60//! one UDP port for many peer connections ([`sockets::UfragMux`]) and one passive ICE-TCP port
61//! for many ([`DriverConfig::shared_passive`], [`sockets::accept_by_ufrag`]).
62//!
63//! # NAT-assisted candidates
64//!
65//! [`nat_mapping`] (opt-in, no dependency) asks the gateway for a port mapping with PCP (RFC
66//! 6887), falling back to NAT-PMP (RFC 6886); the application adds the mapped address as a
67//! server-reflexive candidate ([`nat_mapping::candidate_line`], RFC 6544 section 5.3).
68//!
69//! # A whole peer connection
70//!
71//! [`peer::PeerDriver`] (feature `peer`, on by default) drives an `rtci` peer connection over
72//! sockets it owns, its UDP host sockets included, and gathers for it: at the first local
73//! description, and again on its own when a transport needs a new set of local candidates
74//! (`OnLocalCandidatesNeeded`: a new DTLS association runs on a new 3-tuple, RFC 8842 section
75//! 5.1), closing the previous sockets once a pair on the new ones is selected.
76//!
77//! # Runtime
78//!
79//! The driver's sockets, tasks, timers and name lookups belong to the [`runtime::Runtime`] it
80//! is given ([`StreamDriver::with_runtime`], [`peer::PeerDriver::with_runtime`]): there is no
81//! global or default runtime. The [`runtime`] module says what is injected and what is not,
82//! and how to bring your own.
83//!
84//! # Features
85//!
86//! - `runtime-tokio` (default): `runtime::TokioRuntime`, and `StreamDriver::new` /
87//!   `default` and `PeerDriver::new` on it.
88//! - `runtime-smol`: `runtime::SmolRuntime`.
89//! - `runtime-mock`: `runtime::MockRuntime`, virtual time and an in-memory network.
90//! - `peer` (default): [`peer`], with a dependency on `rtci`.
91//! - `dns-records`: SRV and NAPTR lookups (RFC 5928, RFC 8489 section 8) and AAAA / A answered
92//!   apart (RFC 8305 section 3) in `TokioRuntime`, with hickory-resolver (MIT OR Apache-2.0);
93//!   it turns `runtime-tokio` on. Without it, names go to the runtime's resolver and record
94//!   queries are answered with none (the engine then uses the host and the scheme's default
95//!   port).
96//!
97//! With `default-features = false` and no runtime feature the crate has no async runtime in
98//! its dependency tree.
99//!
100//! Each connection has a reader task and a writer task. With `TokioRuntime::new()` sockets are
101//! created on the thread that calls [`StreamDriver::execute`] inside a tokio runtime, so a
102//! current-thread runtime on a thread that entered a network namespace keeps them there.
103
104#![warn(missing_docs)]
105
106#[cfg(feature = "peer")]
107mod mdns_io;
108pub mod nat_mapping;
109#[cfg(feature = "peer")]
110pub mod peer;
111pub mod runtime;
112pub mod sockets;
113
114use runtime::{AsyncTcpListener, AsyncTcpStream, JoinHandle, Runtime};
115use shared::stream::{ListenerId, StreamCommand, StreamEvent, StreamId, StreamTransmit};
116use std::collections::HashMap;
117use std::future::Future;
118use std::io;
119use std::net::SocketAddr;
120use std::sync::Arc;
121use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
122use std::time::Duration;
123
124/// What the driver has for the engine.
125#[derive(Debug)]
126pub enum DriverInput {
127    /// Pass to the engine's `handle_stream_event`.
128    Event(StreamEvent),
129    /// Bytes read from a connection: pass to the engine's `handle_stream_read`.
130    Read {
131        /// The connection.
132        id: StreamId,
133        /// What was read.
134        data: Vec<u8>,
135    },
136    /// A connection accepted on a listener: ask the engine for its id
137    /// (`handle_stream_accepted`) and [`adopt`](StreamDriver::adopt) it, or drop it.
138    Accepted(Accepted),
139}
140
141/// A connection accepted on a listener, waiting for its id.
142#[derive(Debug)]
143pub struct Accepted {
144    /// The listener it arrived on.
145    pub listener: ListenerId,
146    /// Its local address.
147    pub local: SocketAddr,
148    /// The peer's address.
149    pub remote: SocketAddr,
150    stream: Arc<dyn AsyncTcpStream>,
151}
152
153/// The driver's settings.
154#[derive(Debug, Clone, Copy)]
155pub struct DriverConfig {
156    /// How long a connection attempt may take before it is reported failed.
157    pub connect_timeout: Duration,
158    /// How long a close waits for the peer's end of stream before giving up.
159    pub close_linger: Duration,
160    /// Listeners asked for on port 0 take a port of this range.
161    pub tcp_port_range: Option<sockets::PortRange>,
162    /// A passive ICE-TCP listening port shared with other peer connections: a `Listen` without
163    /// `reuse_address` is answered with this address and binds nothing; the application
164    /// accepts on the shared listener ([`sockets::accept_by_ufrag`]) and hands each connection
165    /// to the driver of the peer connection its first check names
166    /// ([`StreamDriver::adopt_shared`]). Every transport of the connection is answered with the
167    /// same address; the engine gives each connection to the transport its first check names.
168    pub shared_passive: Option<SocketAddr>,
169}
170
171impl Default for DriverConfig {
172    fn default() -> Self {
173        Self {
174            connect_timeout: Duration::from_secs(10),
175            close_linger: Duration::from_secs(2),
176            tcp_port_range: None,
177            shared_passive: None,
178        }
179    }
180}
181
182enum WriterMessage {
183    Data(Vec<u8>),
184    /// Set the socket's TOS / Traffic Class byte to this before the data that follows.
185    Mark(u8),
186    Close,
187    Reset,
188}
189
190struct Connection {
191    writer: async_channel::Sender<WriterMessage>,
192    task: Box<dyn JoinHandle>,
193    established: Arc<AtomicBool>,
194    /// The DSCP last asked for on this connection (a new socket's is 0).
195    dscp: u8,
196    /// What the operating system reported for the socket's TOS / Traffic Class after the
197    /// writer last set it; [`NO_TRAFFIC_CLASS`] before that, or when it was refused.
198    traffic_class: Arc<AtomicU32>,
199}
200
201/// [`Connection::traffic_class`] with nothing read back.
202const NO_TRAFFIC_CLASS: u32 = u32::MAX;
203
204impl Connection {
205    fn new(
206        writer: async_channel::Sender<WriterMessage>,
207        task: Box<dyn JoinHandle>,
208        established: Arc<AtomicBool>,
209        traffic_class: Arc<AtomicU32>,
210    ) -> Self {
211        Self {
212            writer,
213            task,
214            established,
215            dscp: 0,
216            traffic_class,
217        }
218    }
219}
220
221/// Owns the sockets of one engine (see the [crate documentation](crate)).
222pub struct StreamDriver {
223    runtime: Arc<dyn Runtime>,
224    config: DriverConfig,
225    inputs_tx: async_channel::Sender<DriverInput>,
226    inputs: async_channel::Receiver<DriverInput>,
227    listeners: HashMap<ListenerId, Box<dyn JoinHandle>>,
228    connections: HashMap<StreamId, Connection>,
229    /// The engine's listener answered with the shared passive address.
230    shared_listener: Option<ListenerId>,
231}
232
233#[cfg(feature = "runtime-tokio")]
234impl Default for StreamDriver {
235    fn default() -> Self {
236        Self::new(DriverConfig::default())
237    }
238}
239
240impl Drop for StreamDriver {
241    fn drop(&mut self) {
242        for (_, task) in self.listeners.drain() {
243            task.abort();
244        }
245        for (_, connection) in self.connections.drain() {
246            connection.task.abort();
247        }
248    }
249}
250
251impl StreamDriver {
252    /// A driver with no sockets, on tokio ([`runtime::TokioRuntime::new`]: the tokio runtime
253    /// [`execute`](Self::execute) is called in). Feature `runtime-tokio` (on by default).
254    #[cfg(feature = "runtime-tokio")]
255    pub fn new(config: DriverConfig) -> Self {
256        Self::with_runtime(Arc::new(runtime::TokioRuntime::new()), config)
257    }
258
259    /// A driver with no sockets, on `runtime`.
260    pub fn with_runtime(runtime: Arc<dyn Runtime>, config: DriverConfig) -> Self {
261        let (inputs_tx, inputs) = async_channel::unbounded();
262        Self {
263            runtime,
264            config,
265            inputs_tx,
266            inputs,
267            listeners: HashMap::new(),
268            connections: HashMap::new(),
269            shared_listener: None,
270        }
271    }
272
273    /// The runtime the driver runs on.
274    pub fn runtime(&self) -> &Arc<dyn Runtime> {
275        &self.runtime
276    }
277
278    /// Carries out a command of the engine. With `runtime::TokioRuntime::new()` it must be
279    /// called inside a tokio runtime.
280    pub fn execute(&mut self, command: StreamCommand) {
281        match command {
282            StreamCommand::Listen {
283                listener,
284                local,
285                reuse_address,
286            } if !reuse_address
287                && self.config.shared_passive.is_some_and(|shared| {
288                    shared.ip() == local.ip() || local.ip().is_unspecified()
289                }) =>
290            {
291                self.shared_listener = Some(listener);
292                let shared = self.config.shared_passive.unwrap_or(local);
293                self.send(DriverInput::Event(StreamEvent::Listening {
294                    listener,
295                    local: shared,
296                }));
297            }
298            StreamCommand::Listen {
299                listener,
300                local,
301                reuse_address,
302            } => match match self.config.tcp_port_range {
303                Some(range) if local.port() == 0 => sockets::bind_tcp_listener_in_range(
304                    self.runtime.as_ref(),
305                    local.ip(),
306                    range,
307                    reuse_address,
308                ),
309                _ => self.runtime.listen_tcp(local, reuse_address),
310            } {
311                Ok(socket) => {
312                    let bound = socket.local_addr().unwrap_or(local);
313                    self.send(DriverInput::Event(StreamEvent::Listening {
314                        listener,
315                        local: bound,
316                    }));
317                    let tx = self.inputs_tx.clone();
318                    let task = self.runtime.spawn(Box::pin(accept_loop(
319                        self.runtime.clone(),
320                        listener,
321                        socket,
322                        tx,
323                    )));
324                    if let Some(old) = self.listeners.insert(listener, task) {
325                        old.abort();
326                    }
327                }
328                Err(_) => self.send(DriverInput::Event(StreamEvent::ListenFailed { listener })),
329            },
330            StreamCommand::StopListening { listener } => {
331                if let Some(task) = self.listeners.remove(&listener) {
332                    task.abort();
333                }
334            }
335            StreamCommand::Connect {
336                id,
337                local,
338                remote,
339                reuse_address,
340            } => {
341                let (writer, rx) = async_channel::unbounded();
342                let established = Arc::new(AtomicBool::new(false));
343                let tx = self.inputs_tx.clone();
344                let config = self.config;
345                let flag = established.clone();
346                let traffic_class = Arc::new(AtomicU32::new(NO_TRAFFIC_CLASS));
347                let marked = traffic_class.clone();
348                let rt = self.runtime.clone();
349                let task = self.runtime.spawn(Box::pin(async move {
350                    let connected = runtime::timeout(
351                        rt.as_ref(),
352                        config.connect_timeout,
353                        connect(rt.as_ref(), local, remote, reuse_address),
354                    )
355                    .await;
356                    match connected {
357                        Ok(Ok(stream)) => {
358                            let local = stream.local_addr().unwrap_or(local);
359                            flag.store(true, Ordering::SeqCst);
360                            let _ = tx
361                                .try_send(DriverInput::Event(StreamEvent::Connected { id, local }));
362                            run_connection(rt, id, stream, rx, tx, config, marked).await;
363                        }
364                        _ => {
365                            let _ =
366                                tx.try_send(DriverInput::Event(StreamEvent::ConnectFailed { id }));
367                        }
368                    }
369                }));
370                self.connections.insert(
371                    id,
372                    Connection::new(writer, task, established, traffic_class),
373                );
374            }
375            StreamCommand::Close { id } => {
376                if let Some(connection) = self.connections.remove(&id) {
377                    if connection.established.load(Ordering::SeqCst) {
378                        let _ = connection.writer.try_send(WriterMessage::Close);
379                    } else {
380                        connection.task.abort();
381                    }
382                }
383            }
384            StreamCommand::Reset { id } => {
385                if let Some(connection) = self.connections.remove(&id) {
386                    if connection.established.load(Ordering::SeqCst) {
387                        let _ = connection.writer.try_send(WriterMessage::Reset);
388                    } else {
389                        connection.task.abort();
390                    }
391                }
392            }
393            StreamCommand::Resolve { query, host, port } => {
394                match (
395                    self.runtime.resolve_family(&host, port, true),
396                    self.runtime.resolve_family(&host, port, false),
397                ) {
398                    // AAAA and A asked together, each answered as it arrives (RFC 8305 section
399                    // 3): the engine starts on the first.
400                    (Some(v6), Some(v4)) => {
401                        for (ipv6, lookup) in [(true, v6), (false, v4)] {
402                            let tx = self.inputs_tx.clone();
403                            self.runtime.spawn(Box::pin(async move {
404                                let addresses = lookup.await;
405                                let _ =
406                                    tx.try_send(DriverInput::Event(StreamEvent::ResolvedFamily {
407                                        query,
408                                        ipv6,
409                                        addresses,
410                                    }));
411                            }));
412                        }
413                    }
414                    // Both families at once (RFC 8305 section 3): the system resolver asks for
415                    // AAAA and A together.
416                    _ => {
417                        let tx = self.inputs_tx.clone();
418                        let lookup = self.runtime.resolve_host(&host, port);
419                        self.runtime.spawn(Box::pin(async move {
420                            let addresses = lookup.await.unwrap_or_default();
421                            let _ = tx.try_send(DriverInput::Event(StreamEvent::Resolved {
422                                query,
423                                addresses,
424                            }));
425                        }));
426                    }
427                }
428            }
429            StreamCommand::ResolveRecords { query, name, kind } => {
430                let tx = self.inputs_tx.clone();
431                // Without record lookups (the runtime's default) the answer is none, and the
432                // engine takes the host's addresses (RFC 5928 section 3).
433                let lookup = self.runtime.resolve_records(&name, kind);
434                self.runtime.spawn(Box::pin(async move {
435                    let records = lookup.await;
436                    let _ = tx.try_send(DriverInput::Event(StreamEvent::ResolvedRecords {
437                        query,
438                        records,
439                    }));
440                }));
441            }
442            _ => {}
443        }
444    }
445
446    /// Takes the engine's id for an accepted connection and starts serving it.
447    pub fn adopt(&mut self, id: StreamId, accepted: Accepted) {
448        let (writer, rx) = async_channel::unbounded();
449        let tx = self.inputs_tx.clone();
450        let config = self.config;
451        let traffic_class = Arc::new(AtomicU32::new(NO_TRAFFIC_CLASS));
452        let task = self.runtime.spawn(Box::pin(run_connection(
453            self.runtime.clone(),
454            id,
455            accepted.stream,
456            rx,
457            tx,
458            config,
459            traffic_class.clone(),
460        )));
461        self.connections.insert(
462            id,
463            Connection::new(writer, task, Arc::new(AtomicBool::new(true)), traffic_class),
464        );
465    }
466
467    /// The engine's listener that stands for the shared passive port
468    /// ([`DriverConfig::shared_passive`]), once the engine asked for it.
469    pub fn shared_listener(&self) -> Option<ListenerId> {
470        self.shared_listener
471    }
472
473    /// Serves a connection accepted on the shared passive port, which the engine gave `id`
474    /// (`handle_stream_accepted` with [`shared_listener`](Self::shared_listener)); the bytes
475    /// already read from it to route it are handed to the engine first.
476    pub fn adopt_shared(&mut self, id: StreamId, accepted: sockets::SharedAccept) {
477        if !accepted.read.is_empty() {
478            self.send(DriverInput::Read {
479                id,
480                data: accepted.read,
481            });
482        }
483        self.adopt(
484            id,
485            Accepted {
486                listener: self.shared_listener.unwrap_or(ListenerId(0)),
487                local: accepted.local,
488                remote: accepted.remote,
489                stream: accepted.stream,
490            },
491        );
492    }
493
494    /// Writes a transmit of the engine, after the earlier ones of its connection. When the
495    /// transmit's DSCP ([`StreamTransmit::dscp`]: one per TCP connection, RFC 8837 section 5)
496    /// differs from the connection's, the socket's `IP_TOS` / `IPV6_TCLASS` is set to it first
497    /// ([`sockets::set_traffic_class`], which says what each platform does).
498    pub fn write(&mut self, transmit: StreamTransmit) {
499        if let Some(connection) = self.connections.get_mut(&transmit.id) {
500            if connection.dscp != transmit.dscp {
501                connection.dscp = transmit.dscp;
502                let _ = connection
503                    .writer
504                    .try_send(WriterMessage::Mark(transmit.dscp << 2));
505            }
506            let _ = connection
507                .writer
508                .try_send(WriterMessage::Data(transmit.data));
509        }
510    }
511
512    /// The TOS / Traffic Class byte the operating system reported for connection `id`'s
513    /// socket (`getsockopt` of `IP_TOS` / `IPV6_TCLASS`) after the driver last set it, once it
514    /// has: `None` for an unknown connection, one never marked, or a platform that refused.
515    pub fn socket_traffic_class(&self, id: StreamId) -> Option<u32> {
516        let connection = self.connections.get(&id)?;
517        let value = connection.traffic_class.load(Ordering::SeqCst);
518        (value != NO_TRAFFIC_CLASS).then_some(value)
519    }
520
521    /// The next input for the engine.
522    pub async fn next(&mut self) -> DriverInput {
523        // The driver holds a sender itself, so the channel never closes.
524        self.inputs
525            .recv()
526            .await
527            .expect("the driver keeps its own sender")
528    }
529
530    /// The next input for the engine, if one is ready.
531    pub fn try_next(&mut self) -> Option<DriverInput> {
532        self.inputs.try_recv().ok()
533    }
534
535    /// Connections and listeners open.
536    pub fn sockets(&self) -> (usize, usize) {
537        (self.connections.len(), self.listeners.len())
538    }
539
540    fn send(&self, input: DriverInput) {
541        let _ = self.inputs_tx.try_send(input);
542    }
543}
544
545async fn connect(
546    runtime: &dyn Runtime,
547    local: SocketAddr,
548    remote: SocketAddr,
549    reuse_address: bool,
550) -> io::Result<Arc<dyn AsyncTcpStream>> {
551    let stream = runtime.connect_tcp(local, remote, reuse_address).await?;
552    // A connection whose two ends are the same address is the socket connected to itself, not
553    // to a peer: connecting from an ephemeral port to a loopback port nothing listens on, the
554    // system can pick that very port as the source, and TCP's simultaneous open (RFC 9293
555    // section 3.5) then "connects" the socket to itself. It is a failed connection (an ICE-TCP
556    // check toward a dead loopback candidate would otherwise succeed against its own echo).
557    if is_self_connection(stream.local_addr()?, stream.peer_addr()?) {
558        return Err(io::Error::new(
559            io::ErrorKind::ConnectionRefused,
560            format!("{remote}: the socket connected to itself"),
561        ));
562    }
563    Ok(stream)
564}
565
566/// Whether a connection runs from an address to that same address.
567fn is_self_connection(local: SocketAddr, peer: SocketAddr) -> bool {
568    local == peer
569}
570
571async fn accept_loop(
572    runtime: Arc<dyn Runtime>,
573    listener: ListenerId,
574    socket: Arc<dyn AsyncTcpListener>,
575    tx: async_channel::Sender<DriverInput>,
576) {
577    loop {
578        match socket.accept().await {
579            Ok((stream, remote)) => {
580                let local = match stream.local_addr() {
581                    Ok(local) => local,
582                    Err(_) => continue,
583                };
584                if tx
585                    .try_send(DriverInput::Accepted(Accepted {
586                        listener,
587                        local,
588                        remote,
589                        stream,
590                    }))
591                    .is_err()
592                {
593                    return;
594                }
595            }
596            // Out of descriptors, say: try again shortly rather than spin.
597            Err(_) => runtime::sleep(runtime.as_ref(), Duration::from_millis(50)).await,
598        }
599    }
600}
601
602/// What the writer of a connection waits for next.
603enum Next {
604    Message(Option<WriterMessage>),
605    ReaderEnded,
606}
607
608async fn run_connection(
609    runtime: Arc<dyn Runtime>,
610    id: StreamId,
611    stream: Arc<dyn AsyncTcpStream>,
612    rx: async_channel::Receiver<WriterMessage>,
613    tx: async_channel::Sender<DriverInput>,
614    config: DriverConfig,
615    traffic_class: Arc<AtomicU32>,
616) {
617    let reader_tx = tx.clone();
618    let read_half = stream.clone();
619    let mut reader = runtime.spawn(Box::pin(async move {
620        let mut buf = vec![0u8; 64 * 1024];
621        loop {
622            match read_half.read(&mut buf).await {
623                Ok(0) => {
624                    let _ = reader_tx.try_send(DriverInput::Event(StreamEvent::Closed { id }));
625                    return;
626                }
627                Ok(n) => {
628                    if reader_tx
629                        .try_send(DriverInput::Read {
630                            id,
631                            data: buf[..n].to_vec(),
632                        })
633                        .is_err()
634                    {
635                        return;
636                    }
637                }
638                Err(_) => {
639                    let _ = reader_tx.try_send(DriverInput::Event(StreamEvent::Reset { id }));
640                    return;
641                }
642            }
643        }
644    }));
645    loop {
646        let next = {
647            let mut message = std::pin::pin!(rx.recv());
648            std::future::poll_fn(|cx| {
649                if let std::task::Poll::Ready(message) = message.as_mut().poll(cx) {
650                    return std::task::Poll::Ready(Next::Message(message.ok()));
651                }
652                // The peer closed or the connection broke: the reader has reported it.
653                reader.poll_join(cx).map(|()| Next::ReaderEnded)
654            })
655            .await
656        };
657        match next {
658            Next::Message(Some(WriterMessage::Mark(value))) => {
659                let read_back = stream.set_traffic_class(value).unwrap_or(NO_TRAFFIC_CLASS);
660                traffic_class.store(read_back, Ordering::SeqCst);
661            }
662            Next::Message(Some(WriterMessage::Data(data))) => {
663                if stream.write_all(&data).await.is_err() {
664                    let _ = tx.try_send(DriverInput::Event(StreamEvent::Reset { id }));
665                    reader.abort();
666                    return;
667                }
668                let _ = tx.try_send(DriverInput::Event(StreamEvent::Written {
669                    id,
670                    bytes: data.len(),
671                }));
672            }
673            Next::Message(Some(WriterMessage::Close)) => {
674                let _ = stream.shutdown_write();
675                // The reader reports Closed at the peer's end of stream; one that never
676                // comes is given up on.
677                if runtime::timeout(runtime.as_ref(), config.close_linger, reader.join())
678                    .await
679                    .is_err()
680                {
681                    reader.abort();
682                    let _ = tx.try_send(DriverInput::Event(StreamEvent::Closed { id }));
683                }
684                return;
685            }
686            Next::Message(Some(WriterMessage::Reset) | None) => {
687                // SO_LINGER 0: closing sends RST instead of FIN, once the reader's reference
688                // is dropped with it.
689                let _ = stream.reset_on_close();
690                reader.abort();
691                return;
692            }
693            Next::ReaderEnded => return,
694        }
695    }
696}
697
698/// DNS lookups with hickory-resolver (feature `dns-records`).
699#[cfg(feature = "dns-records")]
700mod dns {
701    use hickory_resolver::TokioResolver;
702    use hickory_resolver::proto::rr::{RData, RecordType};
703    use shared::stream::{DnsRecord, RecordKind};
704    use std::net::{IpAddr, SocketAddr};
705
706    /// The system's resolver (its name servers and search list).
707    fn resolver() -> Option<TokioResolver> {
708        TokioResolver::builder_tokio().ok()?.build().ok()
709    }
710
711    /// The addresses of one family of `host`, with `port`.
712    pub(crate) async fn addresses(host: &str, port: u16, ipv6: bool) -> Vec<SocketAddr> {
713        match resolver() {
714            Some(resolver) => addresses_with(&resolver, host, port, ipv6).await,
715            None => vec![],
716        }
717    }
718
719    async fn addresses_with(
720        resolver: &TokioResolver,
721        host: &str,
722        port: u16,
723        ipv6: bool,
724    ) -> Vec<SocketAddr> {
725        let kind = if ipv6 {
726            RecordType::AAAA
727        } else {
728            RecordType::A
729        };
730        let Ok(found) = resolver.lookup(host, kind).await else {
731            return vec![];
732        };
733        found
734            .answers()
735            .iter()
736            .filter_map(|r| match &r.data {
737                RData::A(a) => Some(IpAddr::V4(a.0)),
738                RData::AAAA(a) => Some(IpAddr::V6(a.0)),
739                _ => None,
740            })
741            .map(|ip| SocketAddr::new(ip, port))
742            .collect()
743    }
744
745    /// The SRV or NAPTR records of `name` (none on any error).
746    pub(crate) async fn records(name: &str, kind: RecordKind) -> Vec<DnsRecord> {
747        match resolver() {
748            Some(resolver) => records_with(&resolver, name, kind).await,
749            None => vec![],
750        }
751    }
752
753    async fn records_with(
754        resolver: &TokioResolver,
755        name: &str,
756        kind: RecordKind,
757    ) -> Vec<DnsRecord> {
758        let record_type = match kind {
759            RecordKind::Srv => RecordType::SRV,
760            RecordKind::Naptr => RecordType::NAPTR,
761            _ => return vec![],
762        };
763        let Ok(found) = resolver.lookup(name, record_type).await else {
764            return vec![];
765        };
766        let text = |b: &[u8]| String::from_utf8_lossy(b).into_owned();
767        found
768            .answers()
769            .iter()
770            .filter_map(|r| match &r.data {
771                RData::SRV(srv) => Some(DnsRecord::Srv {
772                    priority: srv.priority,
773                    weight: srv.weight,
774                    port: srv.port,
775                    target: srv.target.to_utf8(),
776                }),
777                RData::NAPTR(n) => Some(DnsRecord::Naptr {
778                    order: n.order,
779                    preference: n.preference,
780                    flags: text(&n.flags),
781                    services: text(&n.services),
782                    regexp: text(&n.regexp),
783                    replacement: n.replacement.to_utf8(),
784                }),
785                _ => None,
786            })
787            .collect()
788    }
789
790    /// The lookups against a name server on loopback that answers from a fixed zone, through
791    /// the resolver's own UDP client: what the engine's SRV / NAPTR discovery of STUN and TURN
792    /// servers (RFC 5928, RFC 8489 section 8) and its per-family answers (RFC 8305 section 3)
793    /// receive.
794    #[cfg(test)]
795    mod tests {
796        use super::*;
797        use hickory_resolver::config::{NameServerConfig, ResolverConfig};
798        use hickory_resolver::net::runtime::TokioRuntimeProvider;
799        use hickory_resolver::proto::op::{Message, OpCode};
800        use hickory_resolver::proto::rr::rdata::{A, AAAA, NAPTR, SRV};
801        use hickory_resolver::proto::rr::{Name, Record};
802        use std::net::{Ipv4Addr, Ipv6Addr};
803
804        /// A name server on 127.0.0.1 answering `turn.example.`; its port.
805        async fn name_server() -> u16 {
806            let socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
807            let port = socket.local_addr().unwrap().port();
808            tokio::spawn(async move {
809                let mut buf = [0u8; 1500];
810                loop {
811                    let Ok((n, from)) = socket.recv_from(&mut buf).await else {
812                        return;
813                    };
814                    let Ok(query) = Message::from_vec(&buf[..n]) else {
815                        continue;
816                    };
817                    let mut response = Message::response(query.metadata.id, OpCode::Query);
818                    response.metadata.recursion_desired = query.metadata.recursion_desired;
819                    response.metadata.recursion_available = true;
820                    response.metadata.authoritative = true;
821                    for q in &query.queries {
822                        response.add_query(q.clone());
823                        let name = q.name().clone();
824                        let rdata = |r| Record::from_rdata(name.clone(), 60, r);
825                        let host = |s: &str| Name::from_ascii(s).unwrap();
826                        let answers: Vec<Record> = match q.query_type() {
827                            RecordType::A => vec![rdata(RData::A(A(Ipv4Addr::new(192, 0, 2, 7))))],
828                            RecordType::AAAA => vec![rdata(RData::AAAA(AAAA(Ipv6Addr::new(
829                                0x2001, 0xdb8, 0, 0, 0, 0, 0, 7,
830                            ))))],
831                            RecordType::SRV => vec![
832                                rdata(RData::SRV(SRV::new(1, 5, 3478, host("turn1.example.")))),
833                                rdata(RData::SRV(SRV::new(2, 0, 3479, host("turn2.example.")))),
834                            ],
835                            RecordType::NAPTR => vec![rdata(RData::NAPTR(NAPTR::new(
836                                10,
837                                20,
838                                b"s".to_vec().into_boxed_slice(),
839                                b"RELAY:turn.udp".to_vec().into_boxed_slice(),
840                                Vec::new().into_boxed_slice(),
841                                host("_turn._udp.example."),
842                            )))],
843                            _ => vec![],
844                        };
845                        for a in answers {
846                            response.add_answer(a);
847                        }
848                    }
849                    if let Ok(bytes) = response.to_vec() {
850                        let _ = socket.send_to(&bytes, from).await;
851                    }
852                }
853            });
854            port
855        }
856
857        fn resolver_at(port: u16) -> TokioResolver {
858            let mut server = NameServerConfig::udp(IpAddr::V4(Ipv4Addr::LOCALHOST));
859            for connection in &mut server.connections {
860                connection.port = port;
861            }
862            let config = ResolverConfig::from_parts(None, vec![], vec![server]);
863            TokioResolver::builder_with_config(config, TokioRuntimeProvider::default())
864                .build()
865                .unwrap()
866        }
867
868        #[tokio::test]
869        async fn srv_and_naptr_records_and_each_address_family_come_back_whole() {
870            let resolver = resolver_at(name_server().await);
871            let mut srv = records_with(&resolver, "turn.example.", RecordKind::Srv).await;
872            srv.sort_by_key(|r| match r {
873                DnsRecord::Srv { priority, .. } => *priority,
874                _ => u16::MAX,
875            });
876            assert_eq!(
877                srv,
878                vec![
879                    DnsRecord::Srv {
880                        priority: 1,
881                        weight: 5,
882                        port: 3478,
883                        target: "turn1.example.".into(),
884                    },
885                    DnsRecord::Srv {
886                        priority: 2,
887                        weight: 0,
888                        port: 3479,
889                        target: "turn2.example.".into(),
890                    },
891                ]
892            );
893            assert_eq!(
894                records_with(&resolver, "turn.example.", RecordKind::Naptr).await,
895                vec![DnsRecord::Naptr {
896                    order: 10,
897                    preference: 20,
898                    flags: "s".into(),
899                    services: "RELAY:turn.udp".into(),
900                    regexp: String::new(),
901                    replacement: "_turn._udp.example.".into(),
902                }]
903            );
904            assert_eq!(
905                addresses_with(&resolver, "turn.example.", 3478, false).await,
906                vec![SocketAddr::new(Ipv4Addr::new(192, 0, 2, 7).into(), 3478)]
907            );
908            assert_eq!(
909                addresses_with(&resolver, "turn.example.", 3478, true).await,
910                vec![SocketAddr::new(
911                    Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 7).into(),
912                    3478
913                )]
914            );
915        }
916    }
917}
918
919#[cfg(test)]
920mod self_connection_tests {
921    use super::*;
922
923    #[test]
924    fn a_connection_is_to_itself_only_when_both_ends_are_the_same_address() {
925        let a: SocketAddr = "127.0.0.1:45149".parse().unwrap();
926        assert!(is_self_connection(a, a));
927        assert!(!is_self_connection(a, "127.0.0.1:45150".parse().unwrap()));
928        assert!(!is_self_connection(a, "127.0.0.2:45149".parse().unwrap()));
929        let v6: SocketAddr = "[::1]:45149".parse().unwrap();
930        assert!(is_self_connection(v6, v6));
931        assert!(!is_self_connection(v6, "[::1]:9".parse().unwrap()));
932    }
933}