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;
21
22use crate::runtime::{AsyncTcpListener, AsyncTcpStream, AsyncUdpSocket, Runtime};
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 UDP socket of `runtime` on `ip`, on a free port of `range`, skipping refused ports as
114/// [`bind_udp_in_range`] does.
115///
116/// # Errors
117///
118/// As [`bind_udp_in_range`].
119pub fn bind_runtime_udp_in_range(
120    runtime: &dyn Runtime,
121    ip: IpAddr,
122    range: PortRange,
123) -> io::Result<Arc<dyn AsyncUdpSocket>> {
124    bind_first(range, range.ports(), |port| {
125        runtime.bind_udp(SocketAddr::new(ip, port))
126    })
127}
128
129/// A TCP listener of `runtime` on `ip`, on a free port of `range`.
130///
131/// # Errors
132///
133/// As [`bind_udp_in_range`].
134pub fn bind_tcp_listener_in_range(
135    runtime: &dyn Runtime,
136    ip: IpAddr,
137    range: PortRange,
138    reuse_address: bool,
139) -> io::Result<Arc<dyn AsyncTcpListener>> {
140    bind_first(range, range.ports(), |port| {
141        runtime.listen_tcp(SocketAddr::new(ip, port), reuse_address)
142    })
143}
144
145/// Keeps an interface by name.
146pub type InterfaceFilter = Arc<dyn Fn(&str) -> bool + Send + Sync>;
147/// Keeps an address.
148pub type IpFilter = Arc<dyn Fn(IpAddr) -> bool + Send + Sync>;
149
150/// Which local addresses get host candidates.
151#[derive(Clone, Default)]
152pub struct AddressFilter {
153    /// Only these addresses (bind addresses); empty: every address of every interface.
154    pub bind_addresses: Vec<IpAddr>,
155    /// Loopback addresses too (off by default: RFC 8445 section 5.1.1.1 says they SHOULD NOT
156    /// be included unless needed).
157    pub include_loopback: bool,
158    /// IPv6 link-local addresses too (off by default).
159    pub include_link_local: bool,
160    /// Keep an interface by name (`eth0`, `en0`, ...).
161    pub interface_filter: Option<InterfaceFilter>,
162    /// Keep an address.
163    pub ip_filter: Option<IpFilter>,
164}
165
166impl std::fmt::Debug for AddressFilter {
167    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
168        f.debug_struct("AddressFilter")
169            .field("bind_addresses", &self.bind_addresses)
170            .field("include_loopback", &self.include_loopback)
171            .field("include_link_local", &self.include_link_local)
172            .field("interface_filter", &self.interface_filter.is_some())
173            .field("ip_filter", &self.ip_filter.is_some())
174            .finish()
175    }
176}
177
178impl AddressFilter {
179    /// Whether `ip`, on the interface named `interface` (when known), passes.
180    pub fn keeps(&self, interface: Option<&str>, ip: IpAddr) -> bool {
181        if ip.is_unspecified() || ip.is_multicast() {
182            return false;
183        }
184        if ip.is_loopback() && !self.include_loopback {
185            return false;
186        }
187        if let IpAddr::V6(v6) = ip
188            && v6.is_unicast_link_local()
189            && !self.include_link_local
190        {
191            return false;
192        }
193        if let (Some(filter), Some(name)) = (&self.interface_filter, interface)
194            && !filter(name)
195        {
196            return false;
197        }
198        self.ip_filter.as_ref().is_none_or(|filter| filter(ip))
199    }
200
201    /// The addresses to gather on: the bind addresses that pass, or every interface address
202    /// that passes.
203    ///
204    /// # Errors
205    ///
206    /// The interfaces could not be listed.
207    pub fn local_addresses(&self) -> io::Result<Vec<IpAddr>> {
208        if !self.bind_addresses.is_empty() {
209            return Ok(self
210                .bind_addresses
211                .iter()
212                .copied()
213                .filter(|ip| self.keeps(None, *ip))
214                .collect());
215        }
216        let mut out = Vec::new();
217        for interface in shared::ifaces::ifaces()? {
218            let Some(addr) = interface.addr else {
219                continue;
220            };
221            let ip = addr.ip();
222            if self.keeps(Some(&interface.name), ip) && !out.contains(&ip) {
223                out.push(ip);
224            }
225        }
226        Ok(out)
227    }
228}
229
230/// The ufrags of a STUN Binding request: `(receiver, sender)` from its USERNAME (RFC 8445
231/// section 7.2.2). `None` for anything else.
232pub fn binding_request_ufrags(datagram: &[u8]) -> Option<(&str, &str)> {
233    const BINDING_REQUEST: u16 = 0x0001;
234    const MAGIC_COOKIE: [u8; 4] = [0x21, 0x12, 0xa4, 0x42];
235    const USERNAME: u16 = 0x0006;
236    if datagram.len() < 20 || datagram[4..8] != MAGIC_COOKIE {
237        return None;
238    }
239    if u16::from_be_bytes([datagram[0], datagram[1]]) != BINDING_REQUEST {
240        return None;
241    }
242    let length = u16::from_be_bytes([datagram[2], datagram[3]]) as usize;
243    let attributes = datagram.get(20..20 + length)?;
244    let mut at = 0;
245    while at + 4 <= attributes.len() {
246        let kind = u16::from_be_bytes([attributes[at], attributes[at + 1]]);
247        let len = u16::from_be_bytes([attributes[at + 2], attributes[at + 3]]) as usize;
248        let value = attributes.get(at + 4..at + 4 + len)?;
249        if kind == USERNAME {
250            let username = std::str::from_utf8(value).ok()?;
251            return username.split_once(':');
252        }
253        at += 4 + len.next_multiple_of(4);
254    }
255    None
256}
257
258/// Routes what arrives on a shared port to the peer connection it is for: by the receiver's
259/// ufrag of the first Binding request from an address, then by that address.
260#[derive(Debug)]
261pub struct UfragMux<K> {
262    by_ufrag: HashMap<String, K>,
263    by_address: HashMap<SocketAddr, K>,
264}
265
266impl<K> Default for UfragMux<K> {
267    fn default() -> Self {
268        Self {
269            by_ufrag: HashMap::new(),
270            by_address: HashMap::new(),
271        }
272    }
273}
274
275impl<K: Clone + Eq + Hash> UfragMux<K> {
276    /// An empty mux.
277    pub fn new() -> Self {
278        Self::default()
279    }
280
281    /// `key`'s peer connection answers to `ufrag` (its local ICE username fragment).
282    pub fn register(&mut self, ufrag: &str, key: K) {
283        self.by_ufrag.insert(ufrag.to_owned(), key);
284    }
285
286    /// Forgets `key`: its ufrags and its remote addresses.
287    pub fn unregister(&mut self, key: &K) {
288        self.by_ufrag.retain(|_, k| k != key);
289        self.by_address.retain(|_, k| k != key);
290    }
291
292    /// The peer connection that registered `ufrag`.
293    pub fn lookup_ufrag(&self, ufrag: &str) -> Option<&K> {
294        self.by_ufrag.get(ufrag)
295    }
296
297    /// The peer connection a datagram from `from` is for: the one this address was routed to
298    /// before, or the one the datagram (a Binding request) names. `None`: no one's; drop it.
299    pub fn route(&mut self, from: SocketAddr, datagram: &[u8]) -> Option<K> {
300        if let Some(key) = self.by_address.get(&from) {
301            // A request naming another registered ufrag moves the address (a peer that
302            // restarted ICE with the same address talks to another connection now).
303            if let Some((receiver, _)) = binding_request_ufrags(datagram)
304                && let Some(other) = self.by_ufrag.get(receiver)
305                && other != key
306            {
307                let other = other.clone();
308                self.by_address.insert(from, other.clone());
309                return Some(other);
310            }
311            return Some(key.clone());
312        }
313        let (receiver, _) = binding_request_ufrags(datagram)?;
314        let key = self.by_ufrag.get(receiver)?.clone();
315        self.by_address.insert(from, key.clone());
316        Some(key)
317    }
318}
319
320/// A connection accepted on an ICE-TCP listening port shared by many peer connections, with
321/// the ufrag its first check names.
322#[derive(Debug)]
323pub struct SharedAccept {
324    /// The connection.
325    pub stream: Arc<dyn AsyncTcpStream>,
326    /// Its local address (the shared port).
327    pub local: SocketAddr,
328    /// The peer's address.
329    pub remote: SocketAddr,
330    /// The receiver's ufrag of its first Binding request.
331    pub ufrag: String,
332    /// What was read to find it, to hand to the engine first
333    /// ([`StreamDriver::adopt_shared`](crate::StreamDriver::adopt_shared)).
334    pub read: Vec<u8>,
335}
336
337/// Accepts the next connection on a shared ICE-TCP port and reads its first RFC 4571 frame
338/// (for `timeout` at most) to learn which peer connection it is for. Connections whose first
339/// frame is not a Binding request with a USERNAME are dropped and the next one is awaited.
340///
341/// # Errors
342///
343/// An accept error.
344pub async fn accept_by_ufrag(
345    runtime: &dyn Runtime,
346    listener: &dyn AsyncTcpListener,
347    timeout: Duration,
348) -> io::Result<SharedAccept> {
349    loop {
350        let (stream, remote) = listener.accept().await?;
351        let local = stream.local_addr()?;
352        let mut read = Vec::new();
353        let first = crate::runtime::timeout(runtime, timeout, async {
354            let mut buf = [0u8; 4096];
355            loop {
356                if read.len() >= 2 {
357                    let len = u16::from_be_bytes([read[0], read[1]]) as usize;
358                    if read.len() >= 2 + len {
359                        return Some(read[2..2 + len].to_vec());
360                    }
361                }
362                match stream.read(&mut buf).await {
363                    Ok(0) | Err(_) => return None,
364                    Ok(n) => read.extend_from_slice(&buf[..n]),
365                }
366                if read.len() > 2 + 65535 {
367                    return None;
368                }
369            }
370        })
371        .await
372        .ok()
373        .flatten();
374        let Some(frame) = first else {
375            continue;
376        };
377        let Some((ufrag, _)) = binding_request_ufrags(&frame) else {
378            continue;
379        };
380        let ufrag = ufrag.to_owned();
381        return Ok(SharedAccept {
382            stream,
383            local,
384            remote,
385            ufrag,
386            read,
387        });
388    }
389}
390
391#[cfg(test)]
392mod tests {
393    use super::*;
394
395    /// A Binding request with USERNAME `username` (no integrity: the mux reads, never trusts).
396    pub(crate) fn binding_request(username: &str) -> Vec<u8> {
397        let mut attrs = Vec::new();
398        attrs.extend_from_slice(&0x0006u16.to_be_bytes());
399        attrs.extend_from_slice(&(username.len() as u16).to_be_bytes());
400        attrs.extend_from_slice(username.as_bytes());
401        while attrs.len() % 4 != 0 {
402            attrs.push(0);
403        }
404        let mut m = vec![0x00, 0x01];
405        m.extend_from_slice(&(attrs.len() as u16).to_be_bytes());
406        m.extend_from_slice(&[0x21, 0x12, 0xa4, 0x42]);
407        m.extend_from_slice(&[9; 12]);
408        m.extend(attrs);
409        m
410    }
411
412    #[test]
413    fn the_ufrags_of_a_binding_request_are_read_and_nothing_else_is_taken_for_one() {
414        assert_eq!(
415            binding_request_ufrags(&binding_request("abcd:wxyz")),
416            Some(("abcd", "wxyz"))
417        );
418        // A Binding response, a DTLS record, a short datagram.
419        let mut response = binding_request("abcd:wxyz");
420        response[1] = 0x01;
421        response[0] = 0x01;
422        assert_eq!(binding_request_ufrags(&response), None);
423        assert_eq!(binding_request_ufrags(&[22, 254, 253, 0, 0]), None);
424        assert_eq!(binding_request_ufrags(&[0; 10]), None);
425        // An attribute running past the message.
426        let mut cut = binding_request("abcd:wxyz");
427        cut.truncate(26);
428        assert_eq!(binding_request_ufrags(&cut), None);
429    }
430
431    #[test]
432    fn a_mux_routes_by_the_first_request_then_by_the_address() {
433        let mut mux = UfragMux::new();
434        mux.register("aaaa", 1);
435        mux.register("bbbb", 2);
436        let x: SocketAddr = "198.51.100.1:5000".parse().unwrap();
437        let y: SocketAddr = "198.51.100.2:5000".parse().unwrap();
438        // DTLS from an address no request came from: nobody's.
439        assert_eq!(mux.route(x, &[22, 254, 253]), None);
440        assert_eq!(mux.route(x, &binding_request("bbbb:peer")), Some(2));
441        assert_eq!(mux.route(x, &[22, 254, 253]), Some(2), "then by address");
442        assert_eq!(mux.route(y, &binding_request("aaaa:peer")), Some(1));
443        assert_eq!(mux.route(y, &binding_request("zzzz:peer")), Some(1));
444        // A request for an unknown ufrag from a new address is dropped.
445        let z: SocketAddr = "198.51.100.3:5000".parse().unwrap();
446        assert_eq!(mux.route(z, &binding_request("zzzz:peer")), None);
447        // A known address naming another connection moves to it.
448        assert_eq!(mux.route(y, &binding_request("bbbb:peer")), Some(2));
449        mux.unregister(&2);
450        assert_eq!(mux.route(x, &[22]), None);
451        assert_eq!(mux.lookup_ufrag("aaaa"), Some(&1));
452    }
453
454    #[test]
455    fn port_ranges_are_checked_and_cover_every_port() {
456        assert!(PortRange::new(0, 10).is_err());
457        assert!(PortRange::new(20, 10).is_err());
458        let range = PortRange::new(40000, 40003).unwrap();
459        let mut ports: Vec<u16> = range.ports().collect();
460        ports.sort();
461        assert_eq!(ports, vec![40000, 40001, 40002, 40003]);
462    }
463
464    /// A stand-in for the host: ports in use, and ports it refuses (Windows' excluded port
465    /// ranges answer WSAEACCES, which std reports as `PermissionDenied`).
466    struct Host {
467        in_use: Vec<u16>,
468        refused: Vec<u16>,
469    }
470
471    impl Host {
472        fn bind(&mut self, port: u16) -> io::Result<u16> {
473            if self.refused.contains(&port) {
474                Err(io::Error::from(io::ErrorKind::PermissionDenied))
475            } else if self.in_use.contains(&port) {
476                Err(io::Error::from(io::ErrorKind::AddrInUse))
477            } else {
478                self.in_use.push(port);
479                Ok(port)
480            }
481        }
482    }
483
484    #[test]
485    fn a_port_the_host_refuses_inside_the_range_is_skipped_like_one_in_use() {
486        let range = PortRange::new(40000, 40003).unwrap();
487        let mut host = Host {
488            in_use: vec![],
489            refused: vec![40000, 40001],
490        };
491        // Starting at a refused port, then another: the free ports after them are used.
492        let order = || [40000, 40001, 40002, 40003].into_iter();
493        assert_eq!(bind_first(range, order(), |p| host.bind(p)).unwrap(), 40002);
494        assert_eq!(bind_first(range, order(), |p| host.bind(p)).unwrap(), 40003);
495        // Every usable port taken: the range is full.
496        let full = bind_first(range, order(), |p| host.bind(p)).unwrap_err();
497        assert_eq!(full.kind(), io::ErrorKind::AddrInUse);
498    }
499
500    #[test]
501    fn a_range_the_host_refuses_entirely_says_so_rather_than_full() {
502        let range = PortRange::new(40000, 40001).unwrap();
503        let mut host = Host {
504            in_use: vec![],
505            refused: vec![40000, 40001],
506        };
507        let err = bind_first(range, range.ports(), |p| host.bind(p)).unwrap_err();
508        assert_eq!(err.kind(), io::ErrorKind::PermissionDenied);
509        // Another error is the same for every port and is not retried.
510        let mut tried = 0;
511        let err = bind_first(range, range.ports(), |_| -> io::Result<()> {
512            tried += 1;
513            Err(io::Error::from(io::ErrorKind::AddrNotAvailable))
514        })
515        .unwrap_err();
516        assert_eq!((err.kind(), tried), (io::ErrorKind::AddrNotAvailable, 1));
517    }
518
519    #[test]
520    fn the_address_filter_drops_loopback_link_local_and_what_the_filters_refuse() {
521        let v4: IpAddr = "192.0.2.7".parse().unwrap();
522        let lo: IpAddr = "127.0.0.1".parse().unwrap();
523        let ll: IpAddr = "fe80::1".parse().unwrap();
524        let filter = AddressFilter {
525            bind_addresses: vec![v4, lo, ll],
526            ..Default::default()
527        };
528        assert_eq!(filter.local_addresses().unwrap(), vec![v4]);
529        let all = AddressFilter {
530            include_loopback: true,
531            include_link_local: true,
532            ..filter.clone()
533        };
534        assert_eq!(all.local_addresses().unwrap(), vec![v4, lo, ll]);
535        let only_v6 = AddressFilter {
536            ip_filter: Some(Arc::new(|ip: IpAddr| ip.is_ipv6())),
537            ..all.clone()
538        };
539        assert_eq!(only_v6.local_addresses().unwrap(), vec![ll]);
540        let no_eth = AddressFilter {
541            interface_filter: Some(Arc::new(|name: &str| !name.starts_with("eth"))),
542            ..Default::default()
543        };
544        assert!(!no_eth.keeps(Some("eth0"), v4));
545        assert!(no_eth.keeps(Some("wlan0"), v4));
546    }
547}
548
549/// `IPV6_TCLASS`, on the targets where `socket2` has it.
550#[cfg(any(
551    target_os = "android",
552    target_os = "dragonfly",
553    target_os = "freebsd",
554    target_os = "fuchsia",
555    target_os = "linux",
556    target_os = "macos",
557    target_os = "netbsd",
558    target_os = "openbsd",
559    target_os = "illumos",
560))]
561fn set_tclass(socket: &socket2::SockRef<'_>, value: u32) -> io::Result<()> {
562    socket.set_tclass_v6(value)
563}
564
565#[cfg(any(
566    target_os = "android",
567    target_os = "dragonfly",
568    target_os = "freebsd",
569    target_os = "fuchsia",
570    target_os = "linux",
571    target_os = "macos",
572    target_os = "netbsd",
573    target_os = "openbsd",
574    target_os = "illumos",
575))]
576fn tclass(socket: &socket2::SockRef<'_>) -> io::Result<u32> {
577    socket.tclass_v6()
578}
579
580#[cfg(not(any(
581    target_os = "android",
582    target_os = "dragonfly",
583    target_os = "freebsd",
584    target_os = "fuchsia",
585    target_os = "linux",
586    target_os = "macos",
587    target_os = "netbsd",
588    target_os = "openbsd",
589    target_os = "illumos",
590)))]
591fn set_tclass(_: &socket2::SockRef<'_>, _: u32) -> io::Result<()> {
592    Err(io::Error::from(io::ErrorKind::Unsupported))
593}
594
595#[cfg(not(any(
596    target_os = "android",
597    target_os = "dragonfly",
598    target_os = "freebsd",
599    target_os = "fuchsia",
600    target_os = "linux",
601    target_os = "macos",
602    target_os = "netbsd",
603    target_os = "openbsd",
604    target_os = "illumos",
605)))]
606fn tclass(_: &socket2::SockRef<'_>) -> io::Result<u32> {
607    Err(io::Error::from(io::ErrorKind::Unsupported))
608}
609
610/// Sets the byte the socket's packets carry in the IPv4 TOS / IPv6 Traffic Class field: the
611/// DSCP in its upper six bits (RFC 2474 section 3), the ECN codepoint in the lower two (RFC
612/// 3168 section 5). `ipv6` says which option (`IPV6_TCLASS` or `IP_TOS`) the socket's family
613/// takes.
614///
615/// What each platform does:
616/// - **Linux, Android, the BSDs, macOS**: `IP_TOS` / `IPV6_TCLASS` set what every later
617///   packet carries, with no privilege. (Linux keeps the ECN bits of a TCP socket to itself.)
618/// - **Windows**: `IP_TOS` is accepted, and `getsockopt` reads the value back (hosted
619///   `windows-latest`), but Microsoft documents the option as not to be used and the stack as
620///   not applying it unless the host's policy allows applications to set it (it does not by
621///   default): the packets are not known to carry it. Marking needs the qWAVE
622///   API (`QOSAddSocketToFlow`, and `QOSSetFlow` with `QOSSetOutgoingDSCPValue`, which only an
623///   administrator or a member of Network Configuration Operators may call) or a Group Policy
624///   QoS rule. The driver does neither: on Windows its packets leave unmarked whatever the
625///   engine asks, and RFC 8835 section 4.2 allows that ("It is appropriate to depart from this
626///   recommendation when running on platforms where QoS marking is not implemented").
627///   `IPV6_TCLASS` is not offered there (`socket2` has none): `Unsupported`, and the driver
628///   counts the socket in `PeerDriver::unmarked_sockets`.
629/// - Other targets without `IPV6_TCLASS` in `socket2`: an error for IPv6.
630///
631/// # Errors
632///
633/// The option is refused or not offered on this platform.
634pub fn set_traffic_class(socket: socket2::SockRef<'_>, ipv6: bool, value: u8) -> io::Result<()> {
635    if ipv6 {
636        set_tclass(&socket, u32::from(value))
637    } else {
638        socket.set_tos_v4(u32::from(value))
639    }
640}
641
642/// The byte the socket's packets carry in the IPv4 TOS / IPv6 Traffic Class field, as the
643/// operating system reports it (`getsockopt` of `IP_TOS` / `IPV6_TCLASS`).
644///
645/// # Errors
646///
647/// The option is not offered on this platform.
648pub fn traffic_class(socket: socket2::SockRef<'_>, ipv6: bool) -> io::Result<u32> {
649    if ipv6 {
650        tclass(&socket)
651    } else {
652        socket.tos_v4()
653    }
654}