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//! Its addresses are the ones given, or chosen from the host's interfaces at every gathering
78//! ([`sockets::AddressSelection`]: RFC 8445 section 5.1.1.1's rules for whoever owns the
79//! sockets). STUN and TURN over UDP are the engine's own: it sends from the driver's sockets,
80//! and [`peer::PeerDriver::shutdown`] waits for its TURN allocations to be deleted before the
81//! sockets close.
82//!
83//! [`task`] runs a [`peer::PeerDriver`] as a task driven through channels, from any runtime
84//! or an OS thread; [`negotiation`] is W3C perfect negotiation over a peer connection.
85//!
86//! # Runtime
87//!
88//! The driver's sockets, tasks, timers and name lookups belong to the [`runtime::Runtime`] it
89//! is given ([`StreamDriver::with_runtime`], [`peer::PeerDriver::with_runtime`]): there is no
90//! global or default runtime. The [`runtime`] module says what is injected and what is not,
91//! and how to bring your own.
92//!
93//! # Features
94//!
95//! - `runtime-tokio` (default): `runtime::TokioRuntime`, and `StreamDriver::new` /
96//! `default` and `PeerDriver::new` on it.
97//! - `runtime-smol`: `runtime::SmolRuntime`.
98//! - `runtime-mock`: `runtime::MockRuntime`, virtual time and an in-memory network (delay,
99//! loss, jitter, reordering, a rate cap, interfaces for address selection).
100//! - `peer` (default): [`peer`], with a dependency on `rtci`.
101//! - `dns-records`: SRV and NAPTR lookups (RFC 5928, RFC 8489 section 8) and AAAA / A answered
102//! apart (RFC 8305 section 3) in `TokioRuntime`, with hickory-resolver (MIT OR Apache-2.0);
103//! it turns `runtime-tokio` on. Without it, names go to the runtime's resolver and record
104//! queries are answered with none (the engine then uses the host and the scheme's default
105//! port).
106//!
107//! With `default-features = false` and no runtime feature the crate has no async runtime in
108//! its dependency tree.
109//!
110//! Each connection has a reader task and a writer task. With `TokioRuntime::new()` sockets are
111//! created on the thread that calls [`StreamDriver::execute`] inside a tokio runtime, so a
112//! current-thread runtime on a thread that entered a network namespace keeps them there.
113
114#![warn(missing_docs)]
115
116#[cfg(feature = "peer")]
117mod mdns_io;
118pub mod nat_mapping;
119#[cfg(feature = "peer")]
120pub mod negotiation;
121#[cfg(feature = "peer")]
122pub mod peer;
123pub mod runtime;
124mod selection;
125pub mod sockets;
126#[cfg(feature = "peer")]
127pub mod task;
128
129use runtime::{AsyncTcpListener, AsyncTcpStream, JoinHandle, Runtime};
130use shared::stream::{ListenerId, StreamCommand, StreamEvent, StreamId, StreamTransmit};
131use std::collections::HashMap;
132use std::future::Future;
133use std::io;
134use std::net::SocketAddr;
135use std::sync::Arc;
136use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
137use std::time::Duration;
138
139/// What the driver has for the engine.
140#[derive(Debug)]
141pub enum DriverInput {
142 /// Pass to the engine's `handle_stream_event`.
143 Event(StreamEvent),
144 /// Bytes read from a connection: pass to the engine's `handle_stream_read`.
145 Read {
146 /// The connection.
147 id: StreamId,
148 /// What was read.
149 data: Vec<u8>,
150 },
151 /// A connection accepted on a listener: ask the engine for its id
152 /// (`handle_stream_accepted`) and [`adopt`](StreamDriver::adopt) it, or drop it.
153 Accepted(Accepted),
154}
155
156/// A connection accepted on a listener, waiting for its id.
157#[derive(Debug)]
158pub struct Accepted {
159 /// The listener it arrived on.
160 pub listener: ListenerId,
161 /// Its local address.
162 pub local: SocketAddr,
163 /// The peer's address.
164 pub remote: SocketAddr,
165 stream: Arc<dyn AsyncTcpStream>,
166}
167
168/// The driver's settings.
169#[derive(Debug, Clone, Copy)]
170#[non_exhaustive]
171pub struct DriverConfig {
172 /// How long a connection attempt may take before it is reported failed.
173 pub connect_timeout: Duration,
174 /// How long a close waits for the peer's end of stream before giving up.
175 pub close_linger: Duration,
176 /// Listeners asked for on port 0 take a port of this range.
177 pub tcp_port_range: Option<sockets::PortRange>,
178 /// A passive ICE-TCP listening port shared with other peer connections: a `Listen` without
179 /// `reuse_address` is answered with this address and binds nothing; the application
180 /// accepts on the shared listener ([`sockets::accept_by_ufrag`]) and hands each connection
181 /// to the driver of the peer connection its first check names
182 /// ([`StreamDriver::adopt_shared`]). Every transport of the connection is answered with the
183 /// same address; the engine gives each connection to the transport its first check names.
184 pub shared_passive: Option<SocketAddr>,
185}
186
187impl DriverConfig {
188 /// With a [`connect_timeout`](Self::connect_timeout).
189 #[must_use]
190 pub fn with_connect_timeout(mut self, connect_timeout: Duration) -> Self {
191 self.connect_timeout = connect_timeout;
192 self
193 }
194 /// With a [`close_linger`](Self::close_linger).
195 #[must_use]
196 pub fn with_close_linger(mut self, close_linger: Duration) -> Self {
197 self.close_linger = close_linger;
198 self
199 }
200 /// With a [`tcp_port_range`](Self::tcp_port_range).
201 #[must_use]
202 pub fn with_tcp_port_range(mut self, tcp_port_range: sockets::PortRange) -> Self {
203 self.tcp_port_range = Some(tcp_port_range);
204 self
205 }
206 /// With a [`shared_passive`](Self::shared_passive) port.
207 #[must_use]
208 pub fn with_shared_passive(mut self, shared_passive: SocketAddr) -> Self {
209 self.shared_passive = Some(shared_passive);
210 self
211 }
212}
213
214impl Default for DriverConfig {
215 fn default() -> Self {
216 Self {
217 connect_timeout: Duration::from_secs(10),
218 close_linger: Duration::from_secs(2),
219 tcp_port_range: None,
220 shared_passive: None,
221 }
222 }
223}
224
225enum WriterMessage {
226 Data(Vec<u8>),
227 /// Set the socket's TOS / Traffic Class byte to this before the data that follows.
228 Mark(u8),
229 Close,
230 Reset,
231}
232
233struct Connection {
234 writer: async_channel::Sender<WriterMessage>,
235 task: Box<dyn JoinHandle>,
236 established: Arc<AtomicBool>,
237 /// The DSCP last asked for on this connection (a new socket's is 0).
238 dscp: u8,
239 /// What the operating system reported for the socket's TOS / Traffic Class after the
240 /// writer last set it; [`NO_TRAFFIC_CLASS`] before that, or when it was refused.
241 traffic_class: Arc<AtomicU32>,
242}
243
244/// [`Connection::traffic_class`] with nothing read back.
245const NO_TRAFFIC_CLASS: u32 = u32::MAX;
246
247impl Connection {
248 fn new(
249 writer: async_channel::Sender<WriterMessage>,
250 task: Box<dyn JoinHandle>,
251 established: Arc<AtomicBool>,
252 traffic_class: Arc<AtomicU32>,
253 ) -> Self {
254 Self {
255 writer,
256 task,
257 established,
258 dscp: 0,
259 traffic_class,
260 }
261 }
262}
263
264/// Owns the sockets of one engine (see the [crate documentation](crate)).
265pub struct StreamDriver {
266 runtime: Arc<dyn Runtime>,
267 config: DriverConfig,
268 inputs_tx: async_channel::Sender<DriverInput>,
269 inputs: async_channel::Receiver<DriverInput>,
270 listeners: HashMap<ListenerId, Box<dyn JoinHandle>>,
271 connections: HashMap<StreamId, Connection>,
272 /// The engine's listener answered with the shared passive address.
273 shared_listener: Option<ListenerId>,
274}
275
276#[cfg(feature = "runtime-tokio")]
277impl Default for StreamDriver {
278 fn default() -> Self {
279 Self::new(DriverConfig::default())
280 }
281}
282
283impl Drop for StreamDriver {
284 fn drop(&mut self) {
285 for (_, task) in self.listeners.drain() {
286 task.abort();
287 }
288 for (_, connection) in self.connections.drain() {
289 connection.task.abort();
290 }
291 }
292}
293
294impl StreamDriver {
295 /// A driver with no sockets, on tokio ([`runtime::TokioRuntime::new`]: the tokio runtime
296 /// [`execute`](Self::execute) is called in). Feature `runtime-tokio` (on by default).
297 #[cfg(feature = "runtime-tokio")]
298 pub fn new(config: DriverConfig) -> Self {
299 Self::with_runtime(Arc::new(runtime::TokioRuntime::new()), config)
300 }
301
302 /// A driver with no sockets, on `runtime`.
303 pub fn with_runtime(runtime: Arc<dyn Runtime>, config: DriverConfig) -> Self {
304 let (inputs_tx, inputs) = async_channel::unbounded();
305 Self {
306 runtime,
307 config,
308 inputs_tx,
309 inputs,
310 listeners: HashMap::new(),
311 connections: HashMap::new(),
312 shared_listener: None,
313 }
314 }
315
316 /// The runtime the driver runs on.
317 pub fn runtime(&self) -> &Arc<dyn Runtime> {
318 &self.runtime
319 }
320
321 /// Carries out a command of the engine. With `runtime::TokioRuntime::new()` it must be
322 /// called inside a tokio runtime.
323 pub fn execute(&mut self, command: StreamCommand) {
324 match command {
325 StreamCommand::Listen {
326 listener,
327 local,
328 reuse_address,
329 } if !reuse_address
330 && self.config.shared_passive.is_some_and(|shared| {
331 shared.ip() == local.ip() || local.ip().is_unspecified()
332 }) =>
333 {
334 self.shared_listener = Some(listener);
335 let shared = self.config.shared_passive.unwrap_or(local);
336 self.send(DriverInput::Event(StreamEvent::Listening {
337 listener,
338 local: shared,
339 }));
340 }
341 StreamCommand::Listen {
342 listener,
343 local,
344 reuse_address,
345 } => match match self.config.tcp_port_range {
346 Some(range) if local.port() == 0 => sockets::bind_tcp_listener_in_range(
347 self.runtime.as_ref(),
348 local.ip(),
349 range,
350 reuse_address,
351 ),
352 _ => self.runtime.listen_tcp(local, reuse_address),
353 } {
354 Ok(socket) => {
355 let bound = socket.local_addr().unwrap_or(local);
356 self.send(DriverInput::Event(StreamEvent::Listening {
357 listener,
358 local: bound,
359 }));
360 let tx = self.inputs_tx.clone();
361 let task = self.runtime.spawn(Box::pin(accept_loop(
362 self.runtime.clone(),
363 listener,
364 socket,
365 tx,
366 )));
367 if let Some(old) = self.listeners.insert(listener, task) {
368 old.abort();
369 }
370 }
371 Err(_) => self.send(DriverInput::Event(StreamEvent::ListenFailed { listener })),
372 },
373 StreamCommand::StopListening { listener } => {
374 if let Some(task) = self.listeners.remove(&listener) {
375 task.abort();
376 }
377 }
378 StreamCommand::Connect {
379 id,
380 local,
381 remote,
382 reuse_address,
383 } => {
384 let (writer, rx) = async_channel::unbounded();
385 let established = Arc::new(AtomicBool::new(false));
386 let tx = self.inputs_tx.clone();
387 let config = self.config;
388 let flag = established.clone();
389 let traffic_class = Arc::new(AtomicU32::new(NO_TRAFFIC_CLASS));
390 let marked = traffic_class.clone();
391 let rt = self.runtime.clone();
392 let task = self.runtime.spawn(Box::pin(async move {
393 let connected = runtime::timeout(
394 rt.as_ref(),
395 config.connect_timeout,
396 connect(rt.as_ref(), local, remote, reuse_address),
397 )
398 .await;
399 match connected {
400 Ok(Ok(stream)) => {
401 let local = stream.local_addr().unwrap_or(local);
402 flag.store(true, Ordering::SeqCst);
403 let _ = tx
404 .try_send(DriverInput::Event(StreamEvent::Connected { id, local }));
405 run_connection(rt, id, stream, rx, tx, config, marked).await;
406 }
407 _ => {
408 let _ =
409 tx.try_send(DriverInput::Event(StreamEvent::ConnectFailed { id }));
410 }
411 }
412 }));
413 self.connections.insert(
414 id,
415 Connection::new(writer, task, established, traffic_class),
416 );
417 }
418 StreamCommand::Close { id } => {
419 if let Some(connection) = self.connections.remove(&id) {
420 if connection.established.load(Ordering::SeqCst) {
421 let _ = connection.writer.try_send(WriterMessage::Close);
422 } else {
423 connection.task.abort();
424 }
425 }
426 }
427 StreamCommand::Reset { id } => {
428 if let Some(connection) = self.connections.remove(&id) {
429 if connection.established.load(Ordering::SeqCst) {
430 let _ = connection.writer.try_send(WriterMessage::Reset);
431 } else {
432 connection.task.abort();
433 }
434 }
435 }
436 StreamCommand::Resolve { query, host, port } => {
437 match (
438 self.runtime.resolve_family(&host, port, true),
439 self.runtime.resolve_family(&host, port, false),
440 ) {
441 // AAAA and A asked together, each answered as it arrives (RFC 8305 section
442 // 3): the engine starts on the first.
443 (Some(v6), Some(v4)) => {
444 for (ipv6, lookup) in [(true, v6), (false, v4)] {
445 let tx = self.inputs_tx.clone();
446 self.runtime.spawn(Box::pin(async move {
447 let addresses = lookup.await;
448 let _ =
449 tx.try_send(DriverInput::Event(StreamEvent::ResolvedFamily {
450 query,
451 ipv6,
452 addresses,
453 }));
454 }));
455 }
456 }
457 // Both families at once (RFC 8305 section 3): the system resolver asks for
458 // AAAA and A together.
459 _ => {
460 let tx = self.inputs_tx.clone();
461 let lookup = self.runtime.resolve_host(&host, port);
462 self.runtime.spawn(Box::pin(async move {
463 let addresses = lookup.await.unwrap_or_default();
464 let _ = tx.try_send(DriverInput::Event(StreamEvent::Resolved {
465 query,
466 addresses,
467 }));
468 }));
469 }
470 }
471 }
472 StreamCommand::ResolveRecords { query, name, kind } => {
473 let tx = self.inputs_tx.clone();
474 // Without record lookups (the runtime's default) the answer is none, and the
475 // engine takes the host's addresses (RFC 5928 section 3).
476 let lookup = self.runtime.resolve_records(&name, kind);
477 self.runtime.spawn(Box::pin(async move {
478 let records = lookup.await;
479 let _ = tx.try_send(DriverInput::Event(StreamEvent::ResolvedRecords {
480 query,
481 records,
482 }));
483 }));
484 }
485 _ => {}
486 }
487 }
488
489 /// Takes the engine's id for an accepted connection and starts serving it.
490 pub fn adopt(&mut self, id: StreamId, accepted: Accepted) {
491 let (writer, rx) = async_channel::unbounded();
492 let tx = self.inputs_tx.clone();
493 let config = self.config;
494 let traffic_class = Arc::new(AtomicU32::new(NO_TRAFFIC_CLASS));
495 let task = self.runtime.spawn(Box::pin(run_connection(
496 self.runtime.clone(),
497 id,
498 accepted.stream,
499 rx,
500 tx,
501 config,
502 traffic_class.clone(),
503 )));
504 self.connections.insert(
505 id,
506 Connection::new(writer, task, Arc::new(AtomicBool::new(true)), traffic_class),
507 );
508 }
509
510 /// The engine's listener that stands for the shared passive port
511 /// ([`DriverConfig::shared_passive`]), once the engine asked for it.
512 pub fn shared_listener(&self) -> Option<ListenerId> {
513 self.shared_listener
514 }
515
516 /// Serves a connection accepted on the shared passive port, which the engine gave `id`
517 /// (`handle_stream_accepted` with [`shared_listener`](Self::shared_listener)); the bytes
518 /// already read from it to route it are handed to the engine first.
519 pub fn adopt_shared(&mut self, id: StreamId, accepted: sockets::SharedAccept) {
520 if !accepted.read.is_empty() {
521 self.send(DriverInput::Read {
522 id,
523 data: accepted.read,
524 });
525 }
526 self.adopt(
527 id,
528 Accepted {
529 listener: self.shared_listener.unwrap_or(ListenerId(0)),
530 local: accepted.local,
531 remote: accepted.remote,
532 stream: accepted.stream,
533 },
534 );
535 }
536
537 /// Writes a transmit of the engine, after the earlier ones of its connection. When the
538 /// transmit's DSCP ([`StreamTransmit::dscp`]: one per TCP connection, RFC 8837 section 5)
539 /// differs from the connection's, the socket's `IP_TOS` / `IPV6_TCLASS` is set to it first
540 /// ([`sockets::set_traffic_class`], which says what each platform does).
541 pub fn write(&mut self, transmit: StreamTransmit) {
542 if let Some(connection) = self.connections.get_mut(&transmit.id) {
543 if connection.dscp != transmit.dscp {
544 connection.dscp = transmit.dscp;
545 let _ = connection
546 .writer
547 .try_send(WriterMessage::Mark(transmit.dscp << 2));
548 }
549 let _ = connection
550 .writer
551 .try_send(WriterMessage::Data(transmit.data));
552 }
553 }
554
555 /// The TOS / Traffic Class byte the operating system reported for connection `id`'s
556 /// socket (`getsockopt` of `IP_TOS` / `IPV6_TCLASS`) after the driver last set it, once it
557 /// has: `None` for an unknown connection, one never marked, or a platform that refused.
558 pub fn socket_traffic_class(&self, id: StreamId) -> Option<u32> {
559 let connection = self.connections.get(&id)?;
560 let value = connection.traffic_class.load(Ordering::SeqCst);
561 (value != NO_TRAFFIC_CLASS).then_some(value)
562 }
563
564 /// The next input for the engine.
565 pub async fn next(&mut self) -> DriverInput {
566 // The driver holds a sender itself, so the channel never closes.
567 self.inputs
568 .recv()
569 .await
570 .expect("the driver keeps its own sender")
571 }
572
573 /// The next input for the engine, if one is ready.
574 pub fn try_next(&mut self) -> Option<DriverInput> {
575 self.inputs.try_recv().ok()
576 }
577
578 /// Connections and listeners open.
579 pub fn sockets(&self) -> (usize, usize) {
580 (self.connections.len(), self.listeners.len())
581 }
582
583 fn send(&self, input: DriverInput) {
584 let _ = self.inputs_tx.try_send(input);
585 }
586}
587
588async fn connect(
589 runtime: &dyn Runtime,
590 local: SocketAddr,
591 remote: SocketAddr,
592 reuse_address: bool,
593) -> io::Result<Arc<dyn AsyncTcpStream>> {
594 let stream = runtime.connect_tcp(local, remote, reuse_address).await?;
595 // A connection whose two ends are the same address is the socket connected to itself, not
596 // to a peer: connecting from an ephemeral port to a loopback port nothing listens on, the
597 // system can pick that very port as the source, and TCP's simultaneous open (RFC 9293
598 // section 3.5) then "connects" the socket to itself. It is a failed connection (an ICE-TCP
599 // check toward a dead loopback candidate would otherwise succeed against its own echo).
600 if is_self_connection(stream.local_addr()?, stream.peer_addr()?) {
601 return Err(io::Error::new(
602 io::ErrorKind::ConnectionRefused,
603 format!("{remote}: the socket connected to itself"),
604 ));
605 }
606 Ok(stream)
607}
608
609/// Whether a connection runs from an address to that same address.
610fn is_self_connection(local: SocketAddr, peer: SocketAddr) -> bool {
611 local == peer
612}
613
614async fn accept_loop(
615 runtime: Arc<dyn Runtime>,
616 listener: ListenerId,
617 socket: Arc<dyn AsyncTcpListener>,
618 tx: async_channel::Sender<DriverInput>,
619) {
620 loop {
621 match socket.accept().await {
622 Ok((stream, remote)) => {
623 let local = match stream.local_addr() {
624 Ok(local) => local,
625 Err(_) => continue,
626 };
627 if tx
628 .try_send(DriverInput::Accepted(Accepted {
629 listener,
630 local,
631 remote,
632 stream,
633 }))
634 .is_err()
635 {
636 return;
637 }
638 }
639 // Out of descriptors, say: try again shortly rather than spin.
640 Err(_) => runtime::sleep(runtime.as_ref(), Duration::from_millis(50)).await,
641 }
642 }
643}
644
645/// What the writer of a connection waits for next.
646enum Next {
647 Message(Option<WriterMessage>),
648 ReaderEnded,
649}
650
651async fn run_connection(
652 runtime: Arc<dyn Runtime>,
653 id: StreamId,
654 stream: Arc<dyn AsyncTcpStream>,
655 rx: async_channel::Receiver<WriterMessage>,
656 tx: async_channel::Sender<DriverInput>,
657 config: DriverConfig,
658 traffic_class: Arc<AtomicU32>,
659) {
660 let reader_tx = tx.clone();
661 let read_half = stream.clone();
662 let mut reader = runtime.spawn(Box::pin(async move {
663 let mut buf = vec![0u8; 64 * 1024];
664 loop {
665 match read_half.read(&mut buf).await {
666 Ok(0) => {
667 let _ = reader_tx.try_send(DriverInput::Event(StreamEvent::Closed { id }));
668 return;
669 }
670 Ok(n) => {
671 if reader_tx
672 .try_send(DriverInput::Read {
673 id,
674 data: buf[..n].to_vec(),
675 })
676 .is_err()
677 {
678 return;
679 }
680 }
681 Err(_) => {
682 let _ = reader_tx.try_send(DriverInput::Event(StreamEvent::Reset { id }));
683 return;
684 }
685 }
686 }
687 }));
688 loop {
689 let next = {
690 let mut message = std::pin::pin!(rx.recv());
691 std::future::poll_fn(|cx| {
692 if let std::task::Poll::Ready(message) = message.as_mut().poll(cx) {
693 return std::task::Poll::Ready(Next::Message(message.ok()));
694 }
695 // The peer closed or the connection broke: the reader has reported it.
696 reader.poll_join(cx).map(|()| Next::ReaderEnded)
697 })
698 .await
699 };
700 match next {
701 Next::Message(Some(WriterMessage::Mark(value))) => {
702 let read_back = stream.set_traffic_class(value).unwrap_or(NO_TRAFFIC_CLASS);
703 traffic_class.store(read_back, Ordering::SeqCst);
704 }
705 Next::Message(Some(WriterMessage::Data(data))) => {
706 if stream.write_all(&data).await.is_err() {
707 let _ = tx.try_send(DriverInput::Event(StreamEvent::Reset { id }));
708 reader.abort();
709 return;
710 }
711 let _ = tx.try_send(DriverInput::Event(StreamEvent::Written {
712 id,
713 bytes: data.len(),
714 }));
715 }
716 Next::Message(Some(WriterMessage::Close)) => {
717 let _ = stream.shutdown_write();
718 // The reader reports Closed at the peer's end of stream; one that never
719 // comes is given up on.
720 if runtime::timeout(runtime.as_ref(), config.close_linger, reader.join())
721 .await
722 .is_err()
723 {
724 reader.abort();
725 let _ = tx.try_send(DriverInput::Event(StreamEvent::Closed { id }));
726 }
727 return;
728 }
729 Next::Message(Some(WriterMessage::Reset) | None) => {
730 // SO_LINGER 0: closing sends RST instead of FIN, once the reader's reference
731 // is dropped with it.
732 let _ = stream.reset_on_close();
733 reader.abort();
734 return;
735 }
736 Next::ReaderEnded => return,
737 }
738 }
739}
740
741/// DNS lookups with hickory-resolver (feature `dns-records`).
742#[cfg(feature = "dns-records")]
743mod dns {
744 use hickory_resolver::TokioResolver;
745 use hickory_resolver::config::ResolverConfig;
746 use hickory_resolver::net::runtime::TokioRuntimeProvider;
747 use hickory_resolver::proto::rr::{Name, RData, RecordType};
748 use shared::stream::{DnsRecord, RecordKind};
749 use std::net::{IpAddr, SocketAddr};
750
751 /// Whether `name` is in the `.local` domain (RFC 6762 section 3): `local` itself or a name
752 /// under it, with or without the final dot, in any case.
753 pub(crate) fn is_local_name(name: &str) -> bool {
754 let name = name.trim_end_matches('.').to_ascii_lowercase();
755 name == "local" || name.ends_with(".local")
756 }
757
758 /// `config` without a local domain or search domain in `.local`. RFC 6762 section 21: "a
759 /// host MUST NOT append the search suffix ".local.", if present, to any relative
760 /// (partially qualified) host name containing two or more labels". hickory appends the
761 /// domain and every search domain to a name that is not fully qualified (after the name
762 /// itself, when it has more labels than `ndots`), so a `local` search domain from the
763 /// system's configuration is left out altogether: the names the driver resolves are server
764 /// names (STUN / TURN), never single-label `.local` hosts.
765 pub(crate) fn without_local_search(config: ResolverConfig) -> ResolverConfig {
766 let (domain, search, name_servers) = config.into_parts();
767 let keep = |name: &Name| !is_local_name(&name.to_ascii());
768 ResolverConfig::from_parts(
769 domain.filter(keep),
770 search.into_iter().filter(keep).collect(),
771 name_servers,
772 )
773 }
774
775 /// The system's resolver (its name servers and search list).
776 fn resolver() -> Option<TokioResolver> {
777 let (config, options) = hickory_resolver::system_conf::read_system_conf().ok()?;
778 let mut builder = TokioResolver::builder_with_config(
779 without_local_search(config),
780 TokioRuntimeProvider::default(),
781 );
782 *builder.options_mut() = options;
783 builder.build().ok()
784 }
785
786 /// The addresses of one family of `host`, with `port`.
787 pub(crate) async fn addresses(host: &str, port: u16, ipv6: bool) -> Vec<SocketAddr> {
788 match resolver() {
789 Some(resolver) => addresses_with(&resolver, host, port, ipv6).await,
790 None => vec![],
791 }
792 }
793
794 async fn addresses_with(
795 resolver: &TokioResolver,
796 host: &str,
797 port: u16,
798 ipv6: bool,
799 ) -> Vec<SocketAddr> {
800 // RFC 6762 section 22.1: "Name resolution APIs and libraries SHOULD recognize these
801 // names as special and SHOULD NOT send queries for these names to their configured
802 // (unicast) caching DNS server(s)". The engine resolves `.local` candidates itself, by
803 // mDNS; a `.local` server name is answered as none here.
804 if is_local_name(host) {
805 log::debug!("{host}: a .local name is not sent to unicast DNS (RFC 6762 22.1)");
806 return vec![];
807 }
808 let kind = if ipv6 {
809 RecordType::AAAA
810 } else {
811 RecordType::A
812 };
813 let Ok(found) = resolver.lookup(host, kind).await else {
814 return vec![];
815 };
816 found
817 .answers()
818 .iter()
819 .filter_map(|r| match &r.data {
820 RData::A(a) => Some(IpAddr::V4(a.0)),
821 RData::AAAA(a) => Some(IpAddr::V6(a.0)),
822 _ => None,
823 })
824 .map(|ip| SocketAddr::new(ip, port))
825 .collect()
826 }
827
828 /// The SRV or NAPTR records of `name` (none on any error).
829 pub(crate) async fn records(name: &str, kind: RecordKind) -> Vec<DnsRecord> {
830 match resolver() {
831 Some(resolver) => records_with(&resolver, name, kind).await,
832 None => vec![],
833 }
834 }
835
836 async fn records_with(
837 resolver: &TokioResolver,
838 name: &str,
839 kind: RecordKind,
840 ) -> Vec<DnsRecord> {
841 if is_local_name(name) {
842 log::debug!("{name}: a .local name is not sent to unicast DNS (RFC 6762 22.1)");
843 return vec![];
844 }
845 let record_type = match kind {
846 RecordKind::Srv => RecordType::SRV,
847 RecordKind::Naptr => RecordType::NAPTR,
848 _ => return vec![],
849 };
850 let Ok(found) = resolver.lookup(name, record_type).await else {
851 return vec![];
852 };
853 let text = |b: &[u8]| String::from_utf8_lossy(b).into_owned();
854 found
855 .answers()
856 .iter()
857 .filter_map(|r| match &r.data {
858 RData::SRV(srv) => Some(DnsRecord::Srv {
859 priority: srv.priority,
860 weight: srv.weight,
861 port: srv.port,
862 target: srv.target.to_utf8(),
863 }),
864 RData::NAPTR(n) => Some(DnsRecord::Naptr {
865 order: n.order,
866 preference: n.preference,
867 flags: text(&n.flags),
868 services: text(&n.services),
869 regexp: text(&n.regexp),
870 replacement: n.replacement.to_utf8(),
871 }),
872 _ => None,
873 })
874 .collect()
875 }
876
877 /// The lookups against a name server on loopback that answers from a fixed zone, through
878 /// the resolver's own UDP client: what the engine's SRV / NAPTR discovery of STUN and TURN
879 /// servers (RFC 5928, RFC 8489 section 8) and its per-family answers (RFC 8305 section 3)
880 /// receive.
881 #[cfg(test)]
882 mod tests {
883 use super::*;
884 use hickory_resolver::config::{NameServerConfig, ResolverConfig};
885 use hickory_resolver::net::runtime::TokioRuntimeProvider;
886 use hickory_resolver::proto::op::{Message, OpCode};
887 use hickory_resolver::proto::rr::rdata::{A, AAAA, NAPTR, SRV};
888 use hickory_resolver::proto::rr::{Name, Record};
889 use std::net::{Ipv4Addr, Ipv6Addr};
890
891 /// A name server on 127.0.0.1 answering `turn.example.`; its port.
892 async fn name_server() -> u16 {
893 let socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
894 let port = socket.local_addr().unwrap().port();
895 tokio::spawn(async move {
896 let mut buf = [0u8; 1500];
897 loop {
898 let Ok((n, from)) = socket.recv_from(&mut buf).await else {
899 return;
900 };
901 let Ok(query) = Message::from_vec(&buf[..n]) else {
902 continue;
903 };
904 let mut response = Message::response(query.metadata.id, OpCode::Query);
905 response.metadata.recursion_desired = query.metadata.recursion_desired;
906 response.metadata.recursion_available = true;
907 response.metadata.authoritative = true;
908 for q in &query.queries {
909 response.add_query(q.clone());
910 let name = q.name().clone();
911 let rdata = |r| Record::from_rdata(name.clone(), 60, r);
912 let host = |s: &str| Name::from_ascii(s).unwrap();
913 let answers: Vec<Record> = match q.query_type() {
914 RecordType::A => vec![rdata(RData::A(A(Ipv4Addr::new(192, 0, 2, 7))))],
915 RecordType::AAAA => vec![rdata(RData::AAAA(AAAA(Ipv6Addr::new(
916 0x2001, 0xdb8, 0, 0, 0, 0, 0, 7,
917 ))))],
918 RecordType::SRV => vec![
919 rdata(RData::SRV(SRV::new(1, 5, 3478, host("turn1.example.")))),
920 rdata(RData::SRV(SRV::new(2, 0, 3479, host("turn2.example.")))),
921 ],
922 RecordType::NAPTR => vec![rdata(RData::NAPTR(NAPTR::new(
923 10,
924 20,
925 b"s".to_vec().into_boxed_slice(),
926 b"RELAY:turn.udp".to_vec().into_boxed_slice(),
927 Vec::new().into_boxed_slice(),
928 host("_turn._udp.example."),
929 )))],
930 _ => vec![],
931 };
932 for a in answers {
933 response.add_answer(a);
934 }
935 }
936 if let Ok(bytes) = response.to_vec() {
937 let _ = socket.send_to(&bytes, from).await;
938 }
939 }
940 });
941 port
942 }
943
944 fn resolver_at(port: u16) -> TokioResolver {
945 let mut server = NameServerConfig::udp(IpAddr::V4(Ipv4Addr::LOCALHOST));
946 for connection in &mut server.connections {
947 connection.port = port;
948 }
949 let config = ResolverConfig::from_parts(None, vec![], vec![server]);
950 TokioResolver::builder_with_config(config, TokioRuntimeProvider::default())
951 .build()
952 .unwrap()
953 }
954
955 /// A name server that records every name it is asked for and answers an A record for
956 /// names under `example.`, NXDOMAIN for any other.
957 async fn recording_name_server() -> (u16, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
958 use hickory_resolver::proto::op::ResponseCode;
959 let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
960 let socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
961 let port = socket.local_addr().unwrap().port();
962 let log = asked.clone();
963 tokio::spawn(async move {
964 let mut buf = [0u8; 1500];
965 loop {
966 let Ok((n, from)) = socket.recv_from(&mut buf).await else {
967 return;
968 };
969 let Ok(query) = Message::from_vec(&buf[..n]) else {
970 continue;
971 };
972 let mut response = Message::response(query.metadata.id, OpCode::Query);
973 response.metadata.recursion_desired = query.metadata.recursion_desired;
974 response.metadata.recursion_available = true;
975 let mut known = false;
976 for q in &query.queries {
977 let name = q.name().to_ascii().to_ascii_lowercase();
978 log.lock().unwrap().push(name.clone());
979 response.add_query(q.clone());
980 if name.ends_with("example.") && q.query_type() == RecordType::A {
981 known = true;
982 response.add_answer(Record::from_rdata(
983 q.name().clone(),
984 60,
985 RData::A(A(Ipv4Addr::new(192, 0, 2, 9))),
986 ));
987 }
988 }
989 if !known {
990 response.metadata.response_code = ResponseCode::NXDomain;
991 }
992 if let Ok(bytes) = response.to_vec() {
993 let _ = socket.send_to(&bytes, from).await;
994 }
995 }
996 });
997 (port, asked)
998 }
999
1000 /// The resolver the driver builds from a system configuration whose domain is `local`
1001 /// and whose search list is `local`, `example`, asking `port`.
1002 fn resolver_with_local_search(port: u16) -> TokioResolver {
1003 let mut server = NameServerConfig::udp(IpAddr::V4(Ipv4Addr::LOCALHOST));
1004 for connection in &mut server.connections {
1005 connection.port = port;
1006 }
1007 let local = Name::from_ascii("local.").unwrap();
1008 let example = Name::from_ascii("example.").unwrap();
1009 let system =
1010 ResolverConfig::from_parts(Some(local.clone()), vec![local, example], vec![server]);
1011 TokioResolver::builder_with_config(
1012 without_local_search(system),
1013 TokioRuntimeProvider::default(),
1014 )
1015 .build()
1016 .unwrap()
1017 }
1018
1019 /// RFC 6762 section 21: "a host MUST NOT append the search suffix ".local.", if
1020 /// present, to any relative (partially qualified) host name containing two or more
1021 /// labels". With `local` as the system's domain and in its search list, a two-label
1022 /// server name is asked as itself and with the other search domain, never with
1023 /// `.local.` appended.
1024 #[tokio::test]
1025 async fn rfc6762_21_1_no_local_suffix_is_appended_to_a_multi_label_name() {
1026 let (port, asked) = recording_name_server().await;
1027 let resolver = resolver_with_local_search(port);
1028 let found = addresses_with(&resolver, "turn.corp", 3478, false).await;
1029 let asked = asked.lock().unwrap().clone();
1030 assert!(
1031 asked.iter().all(|name| !name.ends_with(".local.")),
1032 "asked: {asked:?}"
1033 );
1034 assert!(
1035 asked.contains(&"turn.corp.example.".to_owned()),
1036 "asked: {asked:?}"
1037 );
1038 assert_eq!(
1039 found,
1040 vec![SocketAddr::new(Ipv4Addr::new(192, 0, 2, 9).into(), 3478)]
1041 );
1042 }
1043
1044 /// RFC 6762 section 22.1: name resolution libraries "SHOULD NOT send queries for these
1045 /// names to their configured (unicast) caching DNS server(s)". A `.local` server name
1046 /// (addresses or records, any case, with or without the final dot) reaches no name
1047 /// server and is answered as none.
1048 #[tokio::test]
1049 async fn rfc6762_22_1_1_a_local_name_is_never_sent_to_unicast_dns() {
1050 let (port, asked) = recording_name_server().await;
1051 let resolver = resolver_with_local_search(port);
1052 assert!(
1053 addresses_with(&resolver, "turn.local", 3478, false)
1054 .await
1055 .is_empty()
1056 );
1057 assert!(
1058 addresses_with(&resolver, "Turn.LOCAL.", 3478, true)
1059 .await
1060 .is_empty()
1061 );
1062 assert!(
1063 records_with(&resolver, "_turn._udp.office.local.", RecordKind::Srv)
1064 .await
1065 .is_empty()
1066 );
1067 // The name server is reachable: a name outside `.local` is asked.
1068 addresses_with(&resolver, "turn.example.", 3478, false).await;
1069 let asked = asked.lock().unwrap().clone();
1070 assert_eq!(asked, vec!["turn.example.".to_owned()]);
1071 }
1072
1073 #[tokio::test]
1074 async fn srv_and_naptr_records_and_each_address_family_come_back_whole() {
1075 let resolver = resolver_at(name_server().await);
1076 let mut srv = records_with(&resolver, "turn.example.", RecordKind::Srv).await;
1077 srv.sort_by_key(|r| match r {
1078 DnsRecord::Srv { priority, .. } => *priority,
1079 _ => u16::MAX,
1080 });
1081 assert_eq!(
1082 srv,
1083 vec![
1084 DnsRecord::Srv {
1085 priority: 1,
1086 weight: 5,
1087 port: 3478,
1088 target: "turn1.example.".into(),
1089 },
1090 DnsRecord::Srv {
1091 priority: 2,
1092 weight: 0,
1093 port: 3479,
1094 target: "turn2.example.".into(),
1095 },
1096 ]
1097 );
1098 assert_eq!(
1099 records_with(&resolver, "turn.example.", RecordKind::Naptr).await,
1100 vec![DnsRecord::Naptr {
1101 order: 10,
1102 preference: 20,
1103 flags: "s".into(),
1104 services: "RELAY:turn.udp".into(),
1105 regexp: String::new(),
1106 replacement: "_turn._udp.example.".into(),
1107 }]
1108 );
1109 assert_eq!(
1110 addresses_with(&resolver, "turn.example.", 3478, false).await,
1111 vec![SocketAddr::new(Ipv4Addr::new(192, 0, 2, 7).into(), 3478)]
1112 );
1113 assert_eq!(
1114 addresses_with(&resolver, "turn.example.", 3478, true).await,
1115 vec![SocketAddr::new(
1116 Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 7).into(),
1117 3478
1118 )]
1119 );
1120 }
1121 }
1122}
1123
1124#[cfg(test)]
1125mod self_connection_tests {
1126 use super::*;
1127
1128 #[test]
1129 fn a_connection_is_to_itself_only_when_both_ends_are_the_same_address() {
1130 let a: SocketAddr = "127.0.0.1:45149".parse().unwrap();
1131 assert!(is_self_connection(a, a));
1132 assert!(!is_self_connection(a, "127.0.0.1:45150".parse().unwrap()));
1133 assert!(!is_self_connection(a, "127.0.0.2:45149".parse().unwrap()));
1134 let v6: SocketAddr = "[::1]:45149".parse().unwrap();
1135 assert!(is_self_connection(v6, v6));
1136 assert!(!is_self_connection(v6, "[::1]:9".parse().unwrap()));
1137 }
1138}