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