Skip to main content

rtci_stream_driver/
sockets.rs

1//! Server-side socket choices, which belong to the driver and not to the engine: port ranges,
2//! which local addresses get candidates, and one UDP port or one ICE-TCP listening port shared
3//! by many peer connections.
4//!
5//! A shared port works because every ICE connectivity check names its recipient: the USERNAME
6//! of a Binding request is `<receiver's ufrag>:<sender's ufrag>` (RFC 8445 section 7.2.2). The
7//! first request from a remote address says which peer connection it is for
8//! ([`UfragMux::route`]); everything else from that address follows it. Each peer connection
9//! registers its local ufrags (`RTCPeerConnection::ice_username_fragments`: one per transport,
10//! several when sections are not bundled) after each local description, an ICE restart's new
11//! ones included. Inside the peer connection the engine does the same between its transports:
12//! what the shared port brings goes to the transport whose ufrag the first check names.
13
14use std::collections::HashMap;
15use std::hash::Hash;
16use std::io;
17use std::net::{IpAddr, SocketAddr};
18use std::sync::Arc;
19use std::sync::atomic::{AtomicU32, Ordering};
20use std::time::Duration;
21use tokio::io::AsyncReadExt;
22use tokio::net::{TcpListener, TcpStream};
23
24/// An inclusive range of ports for the sockets a peer connection gets.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub struct PortRange {
27    /// The lowest port.
28    pub min: u16,
29    /// The highest port.
30    pub max: u16,
31}
32
33impl PortRange {
34    /// `min..=max`.
35    ///
36    /// # Errors
37    ///
38    /// `InvalidInput` when `min` is 0 or above `max`.
39    pub fn new(min: u16, max: u16) -> io::Result<Self> {
40        if min == 0 || min > max {
41            return Err(io::Error::new(
42                io::ErrorKind::InvalidInput,
43                format!("not a port range: {min}..={max}"),
44            ));
45        }
46        Ok(Self { min, max })
47    }
48
49    fn len(self) -> u32 {
50        u32::from(self.max - self.min) + 1
51    }
52
53    /// The ports of the range, starting at a rotating offset so that successive sockets spread
54    /// over it rather than all trying the first free port.
55    fn ports(self) -> impl Iterator<Item = u16> {
56        static NEXT: AtomicU32 = AtomicU32::new(0);
57        let len = self.len();
58        let start = NEXT.fetch_add(1, Ordering::Relaxed) % len;
59        (0..len).map(move |i| self.min + ((start + i) % len) as u16)
60    }
61}
62
63fn exhausted(range: PortRange) -> io::Error {
64    io::Error::new(
65        io::ErrorKind::AddrInUse,
66        format!("no free port in {}..={}", range.min, range.max),
67    )
68}
69
70/// The first of `ports` that `bind` succeeds on. A port in use is skipped, and so is a port the
71/// host refuses to applications (`PermissionDenied`): on Windows a port inside an excluded port
72/// range (Hyper-V, WinNAT and other reservations; `netsh interface ipv4 show
73/// excludedportrange`) fails with WSAEACCES, and elsewhere a privileged port does; the next
74/// port of the range can still be free. Any other error is the same for every port of the range
75/// (an address that is not local, ...) and comes back at once.
76///
77/// When no port could be bound: `AddrInUse` if some port was in use (the range is full), else
78/// the refusal (no port of the range is usable on this host).
79fn bind_first<T>(
80    range: PortRange,
81    ports: impl Iterator<Item = u16>,
82    mut bind: impl FnMut(u16) -> io::Result<T>,
83) -> io::Result<T> {
84    let mut in_use = false;
85    let mut refused = None;
86    for port in ports {
87        match bind(port) {
88            Ok(socket) => return Ok(socket),
89            Err(e) if e.kind() == io::ErrorKind::AddrInUse => in_use = true,
90            Err(e) if e.kind() == io::ErrorKind::PermissionDenied => refused = Some(e),
91            Err(e) => return Err(e),
92        }
93    }
94    match refused {
95        Some(e) if !in_use => Err(e),
96        _ => Err(exhausted(range)),
97    }
98}
99
100/// A UDP socket on `ip`, on a free port of `range`. Ports the host refuses (an excluded port
101/// range on Windows, a privileged port) are skipped like ports in use.
102///
103/// # Errors
104///
105/// `AddrInUse` when every usable port of the range is taken; `PermissionDenied` when the host
106/// refuses every port of it; another bind error as it came.
107pub fn bind_udp_in_range(ip: IpAddr, range: PortRange) -> io::Result<std::net::UdpSocket> {
108    bind_first(range, range.ports(), |port| {
109        std::net::UdpSocket::bind(SocketAddr::new(ip, port))
110    })
111}
112
113/// A TCP listener on `ip`, on a free port of `range`.
114///
115/// # Errors
116///
117/// As [`bind_udp_in_range`].
118pub fn bind_tcp_listener_in_range(
119    ip: IpAddr,
120    range: PortRange,
121    reuse_address: bool,
122) -> io::Result<TcpListener> {
123    bind_first(range, range.ports(), |port| {
124        crate::bind_listener(SocketAddr::new(ip, port), reuse_address)
125    })
126}
127
128/// Keeps an interface by name.
129pub type InterfaceFilter = Arc<dyn Fn(&str) -> bool + Send + Sync>;
130/// Keeps an address.
131pub type IpFilter = Arc<dyn Fn(IpAddr) -> bool + Send + Sync>;
132
133/// Which local addresses get host candidates.
134#[derive(Clone, Default)]
135pub struct AddressFilter {
136    /// Only these addresses (bind addresses); empty: every address of every interface.
137    pub bind_addresses: Vec<IpAddr>,
138    /// Loopback addresses too (off by default: RFC 8445 section 5.1.1.1 says they SHOULD NOT
139    /// be included unless needed).
140    pub include_loopback: bool,
141    /// IPv6 link-local addresses too (off by default).
142    pub include_link_local: bool,
143    /// Keep an interface by name (`eth0`, `en0`, ...).
144    pub interface_filter: Option<InterfaceFilter>,
145    /// Keep an address.
146    pub ip_filter: Option<IpFilter>,
147}
148
149impl std::fmt::Debug for AddressFilter {
150    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151        f.debug_struct("AddressFilter")
152            .field("bind_addresses", &self.bind_addresses)
153            .field("include_loopback", &self.include_loopback)
154            .field("include_link_local", &self.include_link_local)
155            .field("interface_filter", &self.interface_filter.is_some())
156            .field("ip_filter", &self.ip_filter.is_some())
157            .finish()
158    }
159}
160
161impl AddressFilter {
162    /// Whether `ip`, on the interface named `interface` (when known), passes.
163    pub fn keeps(&self, interface: Option<&str>, ip: IpAddr) -> bool {
164        if ip.is_unspecified() || ip.is_multicast() {
165            return false;
166        }
167        if ip.is_loopback() && !self.include_loopback {
168            return false;
169        }
170        if let IpAddr::V6(v6) = ip
171            && v6.is_unicast_link_local()
172            && !self.include_link_local
173        {
174            return false;
175        }
176        if let (Some(filter), Some(name)) = (&self.interface_filter, interface)
177            && !filter(name)
178        {
179            return false;
180        }
181        self.ip_filter.as_ref().is_none_or(|filter| filter(ip))
182    }
183
184    /// The addresses to gather on: the bind addresses that pass, or every interface address
185    /// that passes.
186    ///
187    /// # Errors
188    ///
189    /// The interfaces could not be listed.
190    pub fn local_addresses(&self) -> io::Result<Vec<IpAddr>> {
191        if !self.bind_addresses.is_empty() {
192            return Ok(self
193                .bind_addresses
194                .iter()
195                .copied()
196                .filter(|ip| self.keeps(None, *ip))
197                .collect());
198        }
199        let mut out = Vec::new();
200        for interface in shared::ifaces::ifaces()? {
201            let Some(addr) = interface.addr else {
202                continue;
203            };
204            let ip = addr.ip();
205            if self.keeps(Some(&interface.name), ip) && !out.contains(&ip) {
206                out.push(ip);
207            }
208        }
209        Ok(out)
210    }
211}
212
213/// The ufrags of a STUN Binding request: `(receiver, sender)` from its USERNAME (RFC 8445
214/// section 7.2.2). `None` for anything else.
215pub fn binding_request_ufrags(datagram: &[u8]) -> Option<(&str, &str)> {
216    const BINDING_REQUEST: u16 = 0x0001;
217    const MAGIC_COOKIE: [u8; 4] = [0x21, 0x12, 0xa4, 0x42];
218    const USERNAME: u16 = 0x0006;
219    if datagram.len() < 20 || datagram[4..8] != MAGIC_COOKIE {
220        return None;
221    }
222    if u16::from_be_bytes([datagram[0], datagram[1]]) != BINDING_REQUEST {
223        return None;
224    }
225    let length = u16::from_be_bytes([datagram[2], datagram[3]]) as usize;
226    let attributes = datagram.get(20..20 + length)?;
227    let mut at = 0;
228    while at + 4 <= attributes.len() {
229        let kind = u16::from_be_bytes([attributes[at], attributes[at + 1]]);
230        let len = u16::from_be_bytes([attributes[at + 2], attributes[at + 3]]) as usize;
231        let value = attributes.get(at + 4..at + 4 + len)?;
232        if kind == USERNAME {
233            let username = std::str::from_utf8(value).ok()?;
234            return username.split_once(':');
235        }
236        at += 4 + len.next_multiple_of(4);
237    }
238    None
239}
240
241/// Routes what arrives on a shared port to the peer connection it is for: by the receiver's
242/// ufrag of the first Binding request from an address, then by that address.
243#[derive(Debug)]
244pub struct UfragMux<K> {
245    by_ufrag: HashMap<String, K>,
246    by_address: HashMap<SocketAddr, K>,
247}
248
249impl<K> Default for UfragMux<K> {
250    fn default() -> Self {
251        Self {
252            by_ufrag: HashMap::new(),
253            by_address: HashMap::new(),
254        }
255    }
256}
257
258impl<K: Clone + Eq + Hash> UfragMux<K> {
259    /// An empty mux.
260    pub fn new() -> Self {
261        Self::default()
262    }
263
264    /// `key`'s peer connection answers to `ufrag` (its local ICE username fragment).
265    pub fn register(&mut self, ufrag: &str, key: K) {
266        self.by_ufrag.insert(ufrag.to_owned(), key);
267    }
268
269    /// Forgets `key`: its ufrags and its remote addresses.
270    pub fn unregister(&mut self, key: &K) {
271        self.by_ufrag.retain(|_, k| k != key);
272        self.by_address.retain(|_, k| k != key);
273    }
274
275    /// The peer connection that registered `ufrag`.
276    pub fn lookup_ufrag(&self, ufrag: &str) -> Option<&K> {
277        self.by_ufrag.get(ufrag)
278    }
279
280    /// The peer connection a datagram from `from` is for: the one this address was routed to
281    /// before, or the one the datagram (a Binding request) names. `None`: no one's; drop it.
282    pub fn route(&mut self, from: SocketAddr, datagram: &[u8]) -> Option<K> {
283        if let Some(key) = self.by_address.get(&from) {
284            // A request naming another registered ufrag moves the address (a peer that
285            // restarted ICE with the same address talks to another connection now).
286            if let Some((receiver, _)) = binding_request_ufrags(datagram)
287                && let Some(other) = self.by_ufrag.get(receiver)
288                && other != key
289            {
290                let other = other.clone();
291                self.by_address.insert(from, other.clone());
292                return Some(other);
293            }
294            return Some(key.clone());
295        }
296        let (receiver, _) = binding_request_ufrags(datagram)?;
297        let key = self.by_ufrag.get(receiver)?.clone();
298        self.by_address.insert(from, key.clone());
299        Some(key)
300    }
301}
302
303/// A connection accepted on an ICE-TCP listening port shared by many peer connections, with
304/// the ufrag its first check names.
305#[derive(Debug)]
306pub struct SharedAccept {
307    /// The connection.
308    pub stream: TcpStream,
309    /// Its local address (the shared port).
310    pub local: SocketAddr,
311    /// The peer's address.
312    pub remote: SocketAddr,
313    /// The receiver's ufrag of its first Binding request.
314    pub ufrag: String,
315    /// What was read to find it, to hand to the engine first
316    /// ([`StreamDriver::adopt_shared`](crate::StreamDriver::adopt_shared)).
317    pub read: Vec<u8>,
318}
319
320/// Accepts the next connection on a shared ICE-TCP port and reads its first RFC 4571 frame
321/// (for `timeout` at most) to learn which peer connection it is for. Connections whose first
322/// frame is not a Binding request with a USERNAME are dropped and the next one is awaited.
323///
324/// # Errors
325///
326/// An accept error.
327pub async fn accept_by_ufrag(
328    listener: &TcpListener,
329    timeout: Duration,
330) -> io::Result<SharedAccept> {
331    loop {
332        let (mut stream, remote) = listener.accept().await?;
333        let local = stream.local_addr()?;
334        let mut read = Vec::new();
335        let first = tokio::time::timeout(timeout, async {
336            let mut buf = [0u8; 4096];
337            loop {
338                if read.len() >= 2 {
339                    let len = u16::from_be_bytes([read[0], read[1]]) as usize;
340                    if read.len() >= 2 + len {
341                        return Some(read[2..2 + len].to_vec());
342                    }
343                }
344                match stream.read(&mut buf).await {
345                    Ok(0) | Err(_) => return None,
346                    Ok(n) => read.extend_from_slice(&buf[..n]),
347                }
348                if read.len() > 2 + 65535 {
349                    return None;
350                }
351            }
352        })
353        .await
354        .ok()
355        .flatten();
356        let Some(frame) = first else {
357            continue;
358        };
359        let Some((ufrag, _)) = binding_request_ufrags(&frame) else {
360            continue;
361        };
362        let ufrag = ufrag.to_owned();
363        let _ = stream.set_nodelay(true);
364        return Ok(SharedAccept {
365            stream,
366            local,
367            remote,
368            ufrag,
369            read,
370        });
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377
378    /// A Binding request with USERNAME `username` (no integrity: the mux reads, never trusts).
379    pub(crate) fn binding_request(username: &str) -> Vec<u8> {
380        let mut attrs = Vec::new();
381        attrs.extend_from_slice(&0x0006u16.to_be_bytes());
382        attrs.extend_from_slice(&(username.len() as u16).to_be_bytes());
383        attrs.extend_from_slice(username.as_bytes());
384        while attrs.len() % 4 != 0 {
385            attrs.push(0);
386        }
387        let mut m = vec![0x00, 0x01];
388        m.extend_from_slice(&(attrs.len() as u16).to_be_bytes());
389        m.extend_from_slice(&[0x21, 0x12, 0xa4, 0x42]);
390        m.extend_from_slice(&[9; 12]);
391        m.extend(attrs);
392        m
393    }
394
395    #[test]
396    fn the_ufrags_of_a_binding_request_are_read_and_nothing_else_is_taken_for_one() {
397        assert_eq!(
398            binding_request_ufrags(&binding_request("abcd:wxyz")),
399            Some(("abcd", "wxyz"))
400        );
401        // A Binding response, a DTLS record, a short datagram.
402        let mut response = binding_request("abcd:wxyz");
403        response[1] = 0x01;
404        response[0] = 0x01;
405        assert_eq!(binding_request_ufrags(&response), None);
406        assert_eq!(binding_request_ufrags(&[22, 254, 253, 0, 0]), None);
407        assert_eq!(binding_request_ufrags(&[0; 10]), None);
408        // An attribute running past the message.
409        let mut cut = binding_request("abcd:wxyz");
410        cut.truncate(26);
411        assert_eq!(binding_request_ufrags(&cut), None);
412    }
413
414    #[test]
415    fn a_mux_routes_by_the_first_request_then_by_the_address() {
416        let mut mux = UfragMux::new();
417        mux.register("aaaa", 1);
418        mux.register("bbbb", 2);
419        let x: SocketAddr = "198.51.100.1:5000".parse().unwrap();
420        let y: SocketAddr = "198.51.100.2:5000".parse().unwrap();
421        // DTLS from an address no request came from: nobody's.
422        assert_eq!(mux.route(x, &[22, 254, 253]), None);
423        assert_eq!(mux.route(x, &binding_request("bbbb:peer")), Some(2));
424        assert_eq!(mux.route(x, &[22, 254, 253]), Some(2), "then by address");
425        assert_eq!(mux.route(y, &binding_request("aaaa:peer")), Some(1));
426        assert_eq!(mux.route(y, &binding_request("zzzz:peer")), Some(1));
427        // A request for an unknown ufrag from a new address is dropped.
428        let z: SocketAddr = "198.51.100.3:5000".parse().unwrap();
429        assert_eq!(mux.route(z, &binding_request("zzzz:peer")), None);
430        // A known address naming another connection moves to it.
431        assert_eq!(mux.route(y, &binding_request("bbbb:peer")), Some(2));
432        mux.unregister(&2);
433        assert_eq!(mux.route(x, &[22]), None);
434        assert_eq!(mux.lookup_ufrag("aaaa"), Some(&1));
435    }
436
437    #[test]
438    fn port_ranges_are_checked_and_cover_every_port() {
439        assert!(PortRange::new(0, 10).is_err());
440        assert!(PortRange::new(20, 10).is_err());
441        let range = PortRange::new(40000, 40003).unwrap();
442        let mut ports: Vec<u16> = range.ports().collect();
443        ports.sort();
444        assert_eq!(ports, vec![40000, 40001, 40002, 40003]);
445    }
446
447    /// A stand-in for the host: ports in use, and ports it refuses (Windows' excluded port
448    /// ranges answer WSAEACCES, which std reports as `PermissionDenied`).
449    struct Host {
450        in_use: Vec<u16>,
451        refused: Vec<u16>,
452    }
453
454    impl Host {
455        fn bind(&mut self, port: u16) -> io::Result<u16> {
456            if self.refused.contains(&port) {
457                Err(io::Error::from(io::ErrorKind::PermissionDenied))
458            } else if self.in_use.contains(&port) {
459                Err(io::Error::from(io::ErrorKind::AddrInUse))
460            } else {
461                self.in_use.push(port);
462                Ok(port)
463            }
464        }
465    }
466
467    #[test]
468    fn a_port_the_host_refuses_inside_the_range_is_skipped_like_one_in_use() {
469        let range = PortRange::new(40000, 40003).unwrap();
470        let mut host = Host {
471            in_use: vec![],
472            refused: vec![40000, 40001],
473        };
474        // Starting at a refused port, then another: the free ports after them are used.
475        let order = || [40000, 40001, 40002, 40003].into_iter();
476        assert_eq!(bind_first(range, order(), |p| host.bind(p)).unwrap(), 40002);
477        assert_eq!(bind_first(range, order(), |p| host.bind(p)).unwrap(), 40003);
478        // Every usable port taken: the range is full.
479        let full = bind_first(range, order(), |p| host.bind(p)).unwrap_err();
480        assert_eq!(full.kind(), io::ErrorKind::AddrInUse);
481    }
482
483    #[test]
484    fn a_range_the_host_refuses_entirely_says_so_rather_than_full() {
485        let range = PortRange::new(40000, 40001).unwrap();
486        let mut host = Host {
487            in_use: vec![],
488            refused: vec![40000, 40001],
489        };
490        let err = bind_first(range, range.ports(), |p| host.bind(p)).unwrap_err();
491        assert_eq!(err.kind(), io::ErrorKind::PermissionDenied);
492        // Another error is the same for every port and is not retried.
493        let mut tried = 0;
494        let err = bind_first(range, range.ports(), |_| -> io::Result<()> {
495            tried += 1;
496            Err(io::Error::from(io::ErrorKind::AddrNotAvailable))
497        })
498        .unwrap_err();
499        assert_eq!((err.kind(), tried), (io::ErrorKind::AddrNotAvailable, 1));
500    }
501
502    #[test]
503    fn the_address_filter_drops_loopback_link_local_and_what_the_filters_refuse() {
504        let v4: IpAddr = "192.0.2.7".parse().unwrap();
505        let lo: IpAddr = "127.0.0.1".parse().unwrap();
506        let ll: IpAddr = "fe80::1".parse().unwrap();
507        let filter = AddressFilter {
508            bind_addresses: vec![v4, lo, ll],
509            ..Default::default()
510        };
511        assert_eq!(filter.local_addresses().unwrap(), vec![v4]);
512        let all = AddressFilter {
513            include_loopback: true,
514            include_link_local: true,
515            ..filter.clone()
516        };
517        assert_eq!(all.local_addresses().unwrap(), vec![v4, lo, ll]);
518        let only_v6 = AddressFilter {
519            ip_filter: Some(Arc::new(|ip: IpAddr| ip.is_ipv6())),
520            ..all.clone()
521        };
522        assert_eq!(only_v6.local_addresses().unwrap(), vec![ll]);
523        let no_eth = AddressFilter {
524            interface_filter: Some(Arc::new(|name: &str| !name.starts_with("eth"))),
525            ..Default::default()
526        };
527        assert!(!no_eth.keeps(Some("eth0"), v4));
528        assert!(no_eth.keeps(Some("wlan0"), v4));
529    }
530}