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