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