rtci-stream-driver 0.6.0

A socket driver for a sans-I/O WebRTC engine (ICE-TCP, TURN over TCP and TLS, whole peer connections) on an async runtime of your choice
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
//! The async runtime a driver runs on, injected per driver.
//!
//! The engine is sans-I/O; the driver owns sockets, tasks and timers. Everything of those that
//! touches a reactor or a clock goes through one object-safe trait, [`Runtime`], given to each
//! driver as an `Arc<dyn Runtime>` ([`StreamDriver::with_runtime`](crate::StreamDriver::with_runtime),
//! [`PeerDriver::with_runtime`](crate::peer::PeerDriver::with_runtime)):
//!
//! | Injected (reactor or clock) | Not injected (executor-agnostic, one implementation) |
//! | --- | --- |
//! | spawning a task ([`Runtime::spawn`]) | channels and wake-ups between the driver's tasks |
//! | the clock and timers ([`Runtime::now`], [`Runtime::sleep_until`]) | [`sleep`], [`timeout`], [`yield_now`]: free functions on top |
//! | UDP sockets, multicast included ([`Runtime::bind_udp`], [`Runtime::bind_udp_multicast`]) | |
//! | TCP listeners and connections ([`Runtime::listen_tcp`], [`Runtime::connect_tcp`]) | |
//! | name resolution ([`Runtime::resolve_host`] and the optional record lookups) | |
//! | running a future to completion ([`Runtime::block_on`]) | |
//!
//! There is no global or default runtime in the library, and none can be set: each driver is
//! given its own. Cargo features only decide which built-in runtime *types* exist
//! (`runtime-tokio`, on by default: `TokioRuntime`; `runtime-smol`: `SmolRuntime`;
//! `runtime-mock`: `MockRuntime`, virtual time and an in-memory network); they never
//! decide what the driver uses, and several can be on at once.
//! With `default-features = false` and no built-in runtime the crate builds without any of them,
//! and an application implements [`Runtime`] for its own executor (the `custom-runtime`
//! example).
//!
//! The design follows the upstream project's "Bring Your Own Async Runtime"
//! (webrtc.rs, 2026-07-30), with one addition: the clock ([`Runtime::now`]) is the runtime's,
//! because the driver stamps every engine input with a time and a virtual clock must be the
//! one both the engine and the timers see.

#[cfg(feature = "runtime-mock")]
pub mod mock;
#[cfg(feature = "runtime-smol")]
mod smol_runtime;
#[cfg(feature = "runtime-tokio")]
mod tokio_runtime;
#[cfg(feature = "runtime-mock")]
pub use mock::{MockClock, MockNet, MockRuntime};
#[cfg(feature = "runtime-smol")]
pub use smol_runtime::SmolRuntime;
#[cfg(feature = "runtime-tokio")]
pub use tokio_runtime::TokioRuntime;

use shared::stream::{DnsRecord, RecordKind};
use socket2::{Domain, Protocol, SockRef, Socket, Type};
use std::fmt::Debug;
use std::future::Future;
use std::io::{self, IoSliceMut};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicU16, Ordering};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};

/// A boxed future that can move between threads.
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// What a driver needs from an async runtime: the primitives that touch a reactor or a clock.
///
/// Object safe (`&self` receivers, no generic methods): drivers hold an `Arc<dyn Runtime>`.
/// See the [module documentation](self) for what is and is not here.
pub trait Runtime: Send + Sync + Debug + 'static {
    /// Runs `future` as a task of its own. Dropping the handle detaches the task (it runs on);
    /// [`JoinHandle::abort`] cancels it.
    fn spawn(&self, future: BoxFuture<'static, ()>) -> Box<dyn JoinHandle>;

    /// The runtime's clock. Every time the driver gives the engine comes from here, so a
    /// virtual clock drives the engine's timers too.
    fn now(&self) -> Instant;

    /// A future that completes once [`now`](Self::now) has reached `deadline` (at once when it
    /// has already).
    fn sleep_until(&self, deadline: Instant) -> BoxFuture<'static, ()>;

    /// A UDP socket bound to `local` (port 0: any free port).
    ///
    /// # Errors
    ///
    /// The bind failed: `AddrInUse` for a port in use, `PermissionDenied` for one the host
    /// refuses (both are skipped inside a port range).
    fn bind_udp(&self, local: SocketAddr) -> io::Result<Arc<dyn AsyncUdpSocket>>;

    /// A UDP socket joined to a multicast group (mDNS: 224.0.0.251 or ff02::fb on 5353).
    ///
    /// # Errors
    ///
    /// The bind or the join failed (a host without IPv6, say).
    fn bind_udp_multicast(&self, config: &MulticastConfig) -> io::Result<Arc<dyn AsyncUdpSocket>>;

    /// A TCP listener on `local` (backlog 128). `reuse_address` sets `SO_REUSEADDR` (and
    /// `SO_REUSEPORT` where the platform has it).
    ///
    /// # Errors
    ///
    /// As [`bind_udp`](Self::bind_udp).
    fn listen_tcp(
        &self,
        local: SocketAddr,
        reuse_address: bool,
    ) -> io::Result<Arc<dyn AsyncTcpListener>>;

    /// A TCP connection from `local` (bound first: an ICE-TCP active candidate's address) to
    /// `remote`, with `TCP_NODELAY` set. The driver bounds it with its connect timeout.
    fn connect_tcp(
        &self,
        local: SocketAddr,
        remote: SocketAddr,
        reuse_address: bool,
    ) -> BoxFuture<'static, io::Result<Arc<dyn AsyncTcpStream>>>;

    /// The addresses of `host` with `port`, both families together (the system resolver asks
    /// for AAAA and A at once, RFC 8305 section 3).
    fn resolve_host(
        &self,
        host: &str,
        port: u16,
    ) -> BoxFuture<'static, io::Result<Vec<SocketAddr>>>;

    /// The addresses of one family of `host`, when the runtime can ask for AAAA and A apart
    /// (RFC 8305 section 3: the engine starts on the first answer). `None`, the default: it
    /// cannot, and the driver uses [`resolve_host`](Self::resolve_host).
    fn resolve_family(
        &self,
        host: &str,
        port: u16,
        ipv6: bool,
    ) -> Option<BoxFuture<'static, Vec<SocketAddr>>> {
        let _ = (host, port, ipv6);
        None
    }

    /// The SRV or NAPTR records of `name` (RFC 5928, RFC 8489 section 8). The default answers
    /// none, and the engine then uses the host and the scheme's default port.
    fn resolve_records(&self, name: &str, kind: RecordKind) -> BoxFuture<'static, Vec<DnsRecord>> {
        let _ = (name, kind);
        Box::pin(std::future::ready(Vec::new()))
    }

    /// Runs `future` to completion on the calling thread. The future need not be `Send`.
    fn block_on(&self, future: Pin<Box<dyn Future<Output = ()> + '_>>);

    /// Whether [`now`](Self::now) is a virtual clock (a mock's) rather than the wall clock.
    /// What is kept per process on the wall clock (the mDNS budget,
    /// [`process_mdns_rate_limit`](crate::peer::process_mdns_rate_limit)) is not shared with a
    /// driver on a virtual clock, whose times run elsewhere. `false` by default.
    fn virtual_clock(&self) -> bool {
        false
    }

    /// Every address of every interface of the host that is up, unfiltered: what address
    /// selection ([`crate::sockets::AddressSelection`]) chooses from. The default reads the
    /// operating system's list ([`host_interfaces`]); a runtime with a network of its own (a
    /// mock's) answers with that network's.
    ///
    /// # Errors
    ///
    /// The list could not be read.
    fn interfaces(&self) -> io::Result<Vec<LocalInterface>> {
        host_interfaces()
    }

    /// The source address the system would use towards a global destination of the family
    /// (IPv6 when `ipv6`): the default route's address, `None` without a route. With IPv6
    /// privacy extensions (RFC 8981) it is the temporary address (RFC 6724 rule 7). The
    /// default asks the system with an unconnected UDP socket connected to a documentation
    /// address (RFC 5737, RFC 3849): connecting a UDP socket sends nothing.
    fn preferred_source(&self, ipv6: bool) -> Option<IpAddr> {
        host_preferred_source(ipv6)
    }

    /// The source address the system's routing table picks towards `destination` (`None`
    /// without a route): RFC 8828 section 5.2 Mode 2 "MUST follow the kernel routing table
    /// rules", and with an enterprise TURN server "the preferred route MUST be through" it, so
    /// the interface of the route to that server is the one gathered on. The default asks the
    /// system with a UDP socket connected to `destination` (connecting sends nothing).
    fn route_source(&self, destination: IpAddr) -> Option<IpAddr> {
        host_route_source(destination)
    }
}

/// One address of one interface of the host ([`Runtime::interfaces`]).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LocalInterface {
    /// The interface's name (`en0`, `eth0`, an adapter name on Windows).
    pub name: String,
    /// The address.
    pub ip: IpAddr,
    /// The length of its network prefix, when known (IPv6 addresses of one interface in one
    /// prefix are one network: address selection keeps one of them).
    pub prefix_len: Option<u8>,
    /// Whether the system flags it as an RFC 8981 (RFC 4941) temporary IPv6 address.
    pub temporary: bool,
    /// Whether the system flags it as deprecated (RFC 4862 section 5.5.4: past its preferred
    /// lifetime; a temporary address replaced by a newer one, RFC 8981 section 3.4).
    pub deprecated: bool,
}

impl LocalInterface {
    /// `ip` on the interface `name`, prefix unknown, not temporary.
    pub fn new(name: impl Into<String>, ip: IpAddr) -> Self {
        Self {
            name: name.into(),
            ip,
            prefix_len: None,
            temporary: false,
            deprecated: false,
        }
    }

    /// Flagged deprecated or not.
    #[must_use]
    pub fn with_deprecated(mut self, deprecated: bool) -> Self {
        self.deprecated = deprecated;
        self
    }

    /// With a prefix length.
    #[must_use]
    pub fn with_prefix_len(mut self, prefix_len: u8) -> Self {
        self.prefix_len = Some(prefix_len);
        self
    }

    /// Flagged temporary (RFC 8981) or not.
    #[must_use]
    pub fn with_temporary(mut self, temporary: bool) -> Self {
        self.temporary = temporary;
        self
    }
}

/// The operating system's interface addresses, with their prefix lengths and the temporary
/// flag (`shared::ifaces::temporary_ipv6_addresses`: Linux, Android, macOS and iOS report it;
/// elsewhere nothing is marked).
///
/// # Errors
///
/// The list could not be read.
pub fn host_interfaces() -> io::Result<Vec<LocalInterface>> {
    let temporary = shared::ifaces::temporary_ipv6_addresses().unwrap_or_default();
    let deprecated = shared::ifaces::deprecated_ipv6_addresses().unwrap_or_default();
    let mut out: Vec<LocalInterface> = Vec::new();
    for interface in shared::ifaces::ifaces()? {
        let Some(addr) = interface.addr else {
            continue;
        };
        let ip = addr.ip();
        if out.iter().any(|i| i.ip == ip && i.name == interface.name) {
            continue;
        }
        let prefix_len = interface.mask.map(|mask| prefix_length(mask.ip()));
        out.push(LocalInterface {
            name: interface.name,
            ip,
            prefix_len,
            temporary: matches!(ip, IpAddr::V6(v6) if temporary.contains(&v6)),
            deprecated: matches!(ip, IpAddr::V6(v6) if deprecated.contains(&v6)),
        });
    }
    Ok(out)
}

/// The number of leading one bits of a netmask.
fn prefix_length(mask: IpAddr) -> u8 {
    let ones = match mask {
        IpAddr::V4(m) => u32::from(m).leading_ones(),
        IpAddr::V6(m) => u128::from(m).leading_ones(),
    };
    u8::try_from(ones).unwrap_or(u8::MAX)
}

/// [`Runtime::preferred_source`] on the operating system: the route to a documentation
/// address (RFC 5737, RFC 3849), which only a default route covers.
pub fn host_preferred_source(ipv6: bool) -> Option<IpAddr> {
    host_route_source(if ipv6 {
        IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1))
    } else {
        IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1))
    })
}

/// [`Runtime::route_source`] on the operating system.
pub fn host_route_source(destination: IpAddr) -> Option<IpAddr> {
    let bind: SocketAddr = match destination {
        IpAddr::V6(_) => (Ipv6Addr::UNSPECIFIED, 0).into(),
        IpAddr::V4(_) => (Ipv4Addr::UNSPECIFIED, 0).into(),
    };
    let socket = std::net::UdpSocket::bind(bind).ok()?;
    socket.connect(SocketAddr::new(destination, 9)).ok()?;
    let ip = socket.local_addr().ok()?.ip();
    (!ip.is_unspecified()).then_some(ip)
}

/// A task spawned with [`Runtime::spawn`]. Dropping it detaches the task.
pub trait JoinHandle: Send + Debug {
    /// Cancels the task (it is dropped at its next await point, or before it starts).
    fn abort(&self);

    /// Whether the task has ended (finished or cancelled).
    fn is_finished(&self) -> bool;

    /// Ready once the task has ended.
    fn poll_join(&mut self, cx: &mut Context<'_>) -> Poll<()>;
}

impl<'a> dyn JoinHandle + 'a {
    /// Waits for the task to end.
    pub fn join(&mut self) -> impl Future<Output = ()> + '_ {
        std::future::poll_fn(move |cx| self.poll_join(cx))
    }
}

/// One datagram (or, with `segment_size`, several of one size back to back) to send.
#[derive(Debug, Clone, Copy)]
pub struct Transmit<'a> {
    /// Where to.
    pub destination: SocketAddr,
    /// The bytes.
    pub contents: &'a [u8],
    /// The byte for the IPv4 TOS / IPv6 Traffic Class field: the DSCP in the upper six bits
    /// (RFC 2474), the ECN codepoint in the lower two (RFC 3168). The engine gives one per
    /// datagram (`RTCPeerConnection::traffic_class`, RFC 8837).
    pub traffic_class: u8,
    /// `Some(n)`: `contents` is several datagrams of `n` bytes (the last may be shorter), for a
    /// socket that sends them in one call (GSO). The driver sends one datagram per transmit.
    pub segment_size: Option<usize>,
    /// The address the datagram is to leave from, for a socket bound to the unspecified
    /// address: the engine names one for each mDNS datagram (an answer leaves from the address
    /// of its record, on that address's interface, RFC 6762 section 14). `None`: the socket's
    /// own address, or the system's choice.
    pub source: Option<IpAddr>,
}

/// What [`AsyncUdpSocket::poll_recv`] says about one buffer it filled.
#[derive(Debug, Clone, Copy)]
pub struct RecvMeta {
    /// The sender.
    pub addr: SocketAddr,
    /// How many bytes of the buffer were filled.
    pub len: usize,
    /// The size of each datagram in the buffer (`len` when it holds one; less when the socket
    /// coalesced several of one sender, GRO).
    pub stride: usize,
    /// The ECN codepoint the datagram arrived with, when the socket reports it.
    pub ecn: Option<u8>,
    /// The local address it was sent to, when the socket reports it.
    pub dst_ip: Option<IpAddr>,
}

impl Default for RecvMeta {
    fn default() -> Self {
        Self {
            addr: SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), 0),
            len: 0,
            stride: 0,
            ecn: None,
            dst_ip: None,
        }
    }
}

/// A UDP socket of a runtime, in the poll form of quinn-udp's so that batched send and receive
/// (`sendmmsg`, `recvmmsg`, GSO, GRO) fit.
pub trait AsyncUdpSocket: Send + Sync + Debug {
    /// Sends `transmit`, marked with its `traffic_class`. `Pending` when the socket cannot take
    /// it now (the driver then counts it lost, as UDP would).
    fn poll_send(&self, cx: &mut Context<'_>, transmit: &Transmit<'_>) -> Poll<io::Result<usize>>;

    /// Receives up to `bufs.len()` datagrams (at most [`max_receive_batch`](Self::max_receive_batch)),
    /// filling `meta` alongside; how many.
    fn poll_recv(
        &self,
        cx: &mut Context<'_>,
        bufs: &mut [IoSliceMut<'_>],
        meta: &mut [RecvMeta],
    ) -> Poll<io::Result<usize>>;

    /// The address it is bound to.
    fn local_addr(&self) -> io::Result<SocketAddr>;

    /// How many buffers one [`poll_recv`](Self::poll_recv) can fill. 1 by default.
    fn max_receive_batch(&self) -> usize {
        1
    }

    /// The TOS / Traffic Class byte the operating system reports for the socket (`getsockopt`
    /// of `IP_TOS` / `IPV6_TCLASS`): what its next datagram carries.
    ///
    /// # Errors
    ///
    /// The option is not offered on this platform.
    fn traffic_class(&self) -> io::Result<u32>;

    /// Whether the platform refused to mark this socket: its datagrams leave with traffic
    /// class 0 whatever the transmit asks (see [`crate::sockets::set_traffic_class`]).
    fn unmarked(&self) -> bool {
        false
    }

    /// Sets whether the socket's next datagrams go with the IPv4 Don't Fragment bit set and,
    /// over IPv6, without local fragmentation (`true`), or may be fragmented (`false`): what
    /// `RTCPeerConnection::dont_fragment` asks per datagram (RFC 8261 section 5, RFC 6347
    /// section 4.1.1.1, RFC 9147 section 4.4; RFC 9260 section 6.9: a fragment made before a
    /// path MTU reduction "MUST" be IP-fragmented). `Unsupported` by default, and where the
    /// platform has no such option: its datagrams keep the system's default.
    ///
    /// # Errors
    ///
    /// The platform refused the option, or has none.
    fn set_dont_fragment(&self, on: bool) -> io::Result<()> {
        let _ = on;
        Err(io::ErrorKind::Unsupported.into())
    }
}

/// A TCP connection of a runtime. `&self` methods: the driver's reader and writer tasks share
/// one `Arc`.
pub trait AsyncTcpStream: Send + Sync + Debug {
    /// Reads into `buf`; 0 at the peer's end of stream.
    fn poll_read(&self, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<io::Result<usize>>;

    /// Writes some of `buf`; how much.
    fn poll_write(&self, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>>;

    /// Ends the sending direction (FIN).
    ///
    /// # Errors
    ///
    /// The socket refused.
    fn shutdown_write(&self) -> io::Result<()>;

    /// Makes the close abortive (`SO_LINGER` 0): when the last reference is dropped the
    /// connection is reset (RST) instead of closed with FIN.
    ///
    /// # Errors
    ///
    /// The socket refused.
    fn reset_on_close(&self) -> io::Result<()>;

    /// Sets the socket's TOS / Traffic Class byte and returns what the operating system reports
    /// for it afterwards.
    ///
    /// # Errors
    ///
    /// The platform refused the option or does not offer it.
    fn set_traffic_class(&self, value: u8) -> io::Result<u32>;

    /// Its local address.
    fn local_addr(&self) -> io::Result<SocketAddr>;

    /// The peer's address.
    fn peer_addr(&self) -> io::Result<SocketAddr>;
}

/// A TCP listener of a runtime.
pub trait AsyncTcpListener: Send + Sync + Debug {
    /// The next connection, with `TCP_NODELAY` set, and its peer's address.
    fn poll_accept(
        &self,
        cx: &mut Context<'_>,
    ) -> Poll<io::Result<(Arc<dyn AsyncTcpStream>, SocketAddr)>>;

    /// The address it listens on.
    fn local_addr(&self) -> io::Result<SocketAddr>;
}

impl<'a> dyn AsyncTcpListener + 'a {
    /// Waits for the next connection.
    pub async fn accept(&self) -> io::Result<(Arc<dyn AsyncTcpStream>, SocketAddr)> {
        std::future::poll_fn(|cx| self.poll_accept(cx)).await
    }
}

impl<'a> dyn AsyncTcpStream + 'a {
    /// Reads into `buf`; 0 at the peer's end of stream.
    pub async fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
        std::future::poll_fn(|cx| self.poll_read(cx, buf)).await
    }

    /// Writes all of `buf`.
    pub async fn write_all(&self, mut buf: &[u8]) -> io::Result<()> {
        while !buf.is_empty() {
            let n = std::future::poll_fn(|cx| self.poll_write(cx, buf)).await?;
            if n == 0 {
                return Err(io::ErrorKind::WriteZero.into());
            }
            buf = &buf[n..];
        }
        Ok(())
    }
}

impl<'a> dyn AsyncUdpSocket + 'a {
    /// Waits for one datagram: its length and sender.
    pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
        std::future::poll_fn(|cx| {
            let mut meta = [RecvMeta::default()];
            let mut bufs = [IoSliceMut::new(&mut *buf)];
            match self.poll_recv(cx, &mut bufs, &mut meta) {
                Poll::Ready(Ok(_)) => Poll::Ready(Ok((meta[0].len, meta[0].addr))),
                Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
                Poll::Pending => Poll::Pending,
            }
        })
        .await
    }

    /// Sends one datagram, unmarked, waiting for room.
    pub async fn send_to(&self, buf: &[u8], destination: SocketAddr) -> io::Result<usize> {
        let transmit = Transmit {
            destination,
            contents: buf,
            traffic_class: 0,
            segment_size: None,
            source: None,
        };
        std::future::poll_fn(|cx| self.poll_send(cx, &transmit)).await
    }

    /// Sends `transmit` if the socket can take it now: how many bytes, or the system's error
    /// (`WouldBlock` when the socket cannot take it now).
    ///
    /// # Errors
    ///
    /// The send failed, or would block.
    pub fn try_send(&self, transmit: &Transmit<'_>) -> io::Result<usize> {
        let mut cx = Context::from_waker(std::task::Waker::noop());
        match self.poll_send(&mut cx, transmit) {
            Poll::Ready(result) => result,
            Poll::Pending => Err(io::ErrorKind::WouldBlock.into()),
        }
    }
}

/// What a multicast socket is bound and joined to.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct MulticastConfig {
    /// The group (224.0.0.251 or ff02::fb for mDNS).
    pub group: IpAddr,
    /// The port (5353 for mDNS).
    pub port: u16,
    /// The addresses of the interfaces to join the group on: one membership per interface
    /// that has one of them (the addresses of the group's family; an IPv6 address names its
    /// interface by index, [`interface_index`]). Empty: the system's default interface only.
    /// RFC 6762 section 14: a host on several links takes part in mDNS on each of them.
    pub interfaces: Vec<IpAddr>,
    /// TTL / hop limit of what it sends, multicast and unicast (255 for mDNS, RFC 6762
    /// section 11).
    pub hop_limit: u32,
    /// Shares the port with other processes (`SO_REUSEADDR`, and `SO_REUSEPORT` where the
    /// platform has it).
    pub reuse_address: bool,
}

impl MulticastConfig {
    /// `group` on `port`: the default interface, hop limit 1, the port not shared.
    pub fn new(group: IpAddr, port: u16) -> Self {
        Self {
            group,
            port,
            interfaces: Vec::new(),
            hop_limit: 1,
            reuse_address: false,
        }
    }

    /// Joined on these [`interfaces`](Self::interfaces).
    #[must_use]
    pub fn with_interfaces(mut self, interfaces: Vec<IpAddr>) -> Self {
        self.interfaces = interfaces;
        self
    }
    /// With a [`hop_limit`](Self::hop_limit).
    #[must_use]
    pub fn with_hop_limit(mut self, hop_limit: u32) -> Self {
        self.hop_limit = hop_limit;
        self
    }
    /// Sharing the port ([`reuse_address`](Self::reuse_address)) or not.
    #[must_use]
    pub fn with_reuse_address(mut self, reuse_address: bool) -> Self {
        self.reuse_address = reuse_address;
        self
    }
    /// mDNS on `group` (224.0.0.251 or ff02::fb): port 5353, joined on the interfaces of
    /// `interfaces` (the default interface when empty), hop limit 255, the port shared with
    /// the host's other responders.
    pub fn mdns(group: IpAddr, interfaces: Vec<IpAddr>) -> Self {
        Self {
            group,
            port: 5353,
            interfaces,
            hop_limit: 255,
            reuse_address: true,
        }
    }

    /// The addresses of [`interfaces`](Self::interfaces) of the group's family.
    pub fn interfaces_of_family(&self) -> impl Iterator<Item = IpAddr> + '_ {
        let v4 = self.group.is_ipv4();
        self.interfaces
            .iter()
            .copied()
            .filter(move |ip| ip.is_ipv4() == v4 && !ip.is_unspecified())
    }
}

/// The index of the interface that holds the IPv6 address `ip` (what `IPV6_MULTICAST_IF` and
/// an IPv6 group membership name an interface by), `None` when no interface of the host holds
/// it.
pub fn interface_index(ip: Ipv6Addr) -> Option<u32> {
    let interfaces = shared::ifaces::ifaces().ok()?;
    let entry = interfaces
        .iter()
        .find(|i| matches!(i.addr, Some(SocketAddr::V6(a)) if *a.ip() == ip))?;
    if let Some(SocketAddr::V6(a)) = entry.addr
        && a.scope_id() != 0
    {
        return Some(a.scope_id());
    }
    name_to_index(&entry.name)
}

#[cfg(unix)]
fn name_to_index(name: &str) -> Option<u32> {
    let name = std::ffi::CString::new(name).ok()?;
    // SAFETY: `name` is a NUL-terminated string that outlives the call.
    let index = unsafe { libc::if_nametoindex(name.as_ptr()) };
    (index != 0).then_some(index)
}

#[cfg(not(unix))]
fn name_to_index(_: &str) -> Option<u32> {
    None
}

/// The name of the interface that holds `ip`, `None` when no interface of the host holds it.
pub fn interface_name(ip: IpAddr) -> Option<String> {
    shared::ifaces::ifaces()
        .ok()?
        .into_iter()
        .find(|i| i.addr.is_some_and(|a| a.ip() == ip))
        .map(|i| i.name)
}

/// Applies a [`Transmit::source`] to a real multicast socket bound to the unspecified address:
/// before a datagram to a multicast group, it sets the interface the datagram leaves by
/// (`IP_MULTICAST_IF` to the source address, `IPV6_MULTICAST_IF` to the index of the interface
/// that holds it) when it differs from the last one set. The system then sends from that
/// interface's address: on Linux exactly the address given (`IP_MULTICAST_IF` with an address
/// sets the source), on macOS and Windows the interface's address, the same one where the
/// interface has one address of the family. For built-in and third-party runtimes whose sockets
/// have a file descriptor.
#[derive(Debug, Default)]
pub struct MulticastInterfaceSelector {
    last: std::sync::Mutex<Option<IpAddr>>,
}

impl MulticastInterfaceSelector {
    /// Sets the interface of `transmit` on `socket`. A transmit to a unicast destination, or
    /// without a source of the destination's family, changes nothing.
    ///
    /// # Errors
    ///
    /// The source is on no interface of the host, or the system refused the option: the
    /// datagram is not to be sent from another interface instead.
    pub fn apply(&self, socket: SockRef<'_>, transmit: &Transmit<'_>) -> io::Result<()> {
        let destination = transmit.destination.ip();
        let Some(source) = transmit.source.filter(|source| {
            destination.is_multicast()
                && !source.is_unspecified()
                && source.is_ipv4() == destination.is_ipv4()
        }) else {
            return Ok(());
        };
        let mut last = self
            .last
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if *last == Some(source) {
            return Ok(());
        }
        match source {
            IpAddr::V4(source) => socket.set_multicast_if_v4(&source)?,
            IpAddr::V6(source) => {
                let index = interface_index(source).ok_or_else(|| {
                    io::Error::new(
                        io::ErrorKind::AddrNotAvailable,
                        format!("no interface holds {source}"),
                    )
                })?;
                socket.set_multicast_if_v6(index)?;
            }
        }
        *last = Some(source);
        Ok(())
    }
}

/// Waits `duration` on `runtime`'s clock.
pub fn sleep(runtime: &dyn Runtime, duration: Duration) -> BoxFuture<'static, ()> {
    runtime.sleep_until(runtime.now() + duration)
}

/// [`timeout`] ran out.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Elapsed;

impl std::fmt::Display for Elapsed {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("deadline elapsed")
    }
}

impl std::error::Error for Elapsed {}

/// `future`'s output, or [`Elapsed`] if `duration` of `runtime`'s clock passes first.
pub async fn timeout<T>(
    runtime: &dyn Runtime,
    duration: Duration,
    future: impl Future<Output = T>,
) -> Result<T, Elapsed> {
    timeout_at(runtime, runtime.now() + duration, future).await
}

/// `future`'s output, or [`Elapsed`] if `runtime`'s clock reaches `deadline` first.
pub async fn timeout_at<T>(
    runtime: &dyn Runtime,
    deadline: Instant,
    future: impl Future<Output = T>,
) -> Result<T, Elapsed> {
    let mut future = std::pin::pin!(future);
    let mut sleep = runtime.sleep_until(deadline);
    std::future::poll_fn(|cx| {
        if let Poll::Ready(value) = future.as_mut().poll(cx) {
            return Poll::Ready(Ok(value));
        }
        sleep.as_mut().poll(cx).map(|()| Err(Elapsed))
    })
    .await
}

/// Gives other tasks a turn: pending once, with the task woken at once.
pub async fn yield_now() {
    let mut yielded = false;
    std::future::poll_fn(|cx| {
        if yielded {
            return Poll::Ready(());
        }
        yielded = true;
        cx.waker().wake_by_ref();
        Poll::Pending
    })
    .await
}

/// Applies a [`Transmit::traffic_class`] to a real socket: sets `IP_TOS` / `IPV6_TCLASS` when
/// the value differs from the last one set, and stops asking once the platform refused (its
/// datagrams then leave unmarked, [`AsyncUdpSocket::unmarked`]). For built-in and third-party
/// runtimes whose sockets have a file descriptor.
#[derive(Debug)]
pub struct TrafficClassMarker {
    /// The byte last set (a new socket's is 0), or [`Self::REFUSED`].
    state: AtomicU16,
}

impl Default for TrafficClassMarker {
    fn default() -> Self {
        Self {
            state: AtomicU16::new(0),
        }
    }
}

impl TrafficClassMarker {
    const REFUSED: u16 = 0x100;

    /// Marks `socket` (IPv6 when `ipv6`) with `value` before a datagram: what the datagram
    /// carries (0 once the platform refused).
    pub fn apply(&self, socket: SockRef<'_>, ipv6: bool, value: u8) -> u8 {
        let current = self.state.load(Ordering::Relaxed);
        if current == Self::REFUSED {
            return 0;
        }
        if current == u16::from(value) {
            return value;
        }
        match crate::sockets::set_traffic_class(socket, ipv6, value) {
            Ok(()) => {
                self.state.store(u16::from(value), Ordering::Relaxed);
                value
            }
            // The platform does not mark (RFC 8835 4.2: "appropriate to depart ... on platforms
            // where QoS marking is not implemented"): the socket is not asked again.
            Err(_) => {
                self.state.store(Self::REFUSED, Ordering::Relaxed);
                0
            }
        }
    }

    /// Whether the platform refused.
    pub fn refused(&self) -> bool {
        self.state.load(Ordering::Relaxed) == Self::REFUSED
    }
}

/// A non-blocking std UDP socket on `local`: what the built-in runtimes wrap.
///
/// # Errors
///
/// The bind failed.
pub fn std_udp(local: SocketAddr) -> io::Result<std::net::UdpSocket> {
    let socket = std::net::UdpSocket::bind(local)?;
    socket.set_nonblocking(true)?;
    Ok(socket)
}

/// A non-blocking std UDP socket joined as `config` says: for IPv4 what rtci-mdns'
/// `MulticastSocket` builds (bound to the group on Linux, to 0.0.0.0 elsewhere), for IPv6
/// `[::]:port`, IPv6 only; a membership of the group on every interface of
/// [`MulticastConfig::interfaces`] (the default interface when there is none).
///
/// # Errors
///
/// The bind failed, or no membership could be joined (an interface that refuses one is
/// skipped while another joins).
pub fn std_multicast(config: &MulticastConfig) -> io::Result<std::net::UdpSocket> {
    let domain = match config.group {
        IpAddr::V4(_) => Domain::IPV4,
        IpAddr::V6(_) => Domain::IPV6,
    };
    let socket = Socket::new(domain, Type::DGRAM, Some(Protocol::UDP))?;
    if config.group.is_ipv6() {
        socket.set_only_v6(true)?;
    }
    if config.reuse_address {
        socket.set_reuse_address(true)?;
        #[cfg(all(unix, not(target_os = "solaris"), not(target_os = "illumos")))]
        socket.set_reuse_port(true)?;
    }
    socket.set_nonblocking(true)?;
    let interfaces: Vec<IpAddr> = config.interfaces_of_family().collect();
    match config.group {
        IpAddr::V4(group) => {
            socket.set_multicast_ttl_v4(config.hop_limit)?;
            socket.set_ttl_v4(config.hop_limit)?;
            // The group itself does not bind on macOS and Windows; 0.0.0.0 does.
            let local = if cfg!(target_os = "linux") {
                group
            } else {
                Ipv4Addr::UNSPECIFIED
            };
            socket.bind(&SocketAddr::new(local.into(), config.port).into())?;
            join_each(&interfaces, |interface| match interface {
                Some(IpAddr::V4(interface)) => {
                    if cfg!(windows) && interface.is_loopback() {
                        warn_loopback_join_on_windows(group);
                    }
                    socket.join_multicast_v4(&group, &interface)
                }
                _ => socket.join_multicast_v4(&group, &Ipv4Addr::UNSPECIFIED),
            })?;
        }
        IpAddr::V6(group) => {
            socket.set_multicast_hops_v6(config.hop_limit)?;
            socket.set_unicast_hops_v6(config.hop_limit)?;
            socket.bind(&SocketAddr::new(Ipv6Addr::UNSPECIFIED.into(), config.port).into())?;
            join_each(&interfaces, |interface| {
                let index = match interface {
                    Some(IpAddr::V6(ip)) => interface_index(ip).ok_or_else(|| {
                        io::Error::new(
                            io::ErrorKind::AddrNotAvailable,
                            format!("no interface holds {ip}"),
                        )
                    })?,
                    _ => 0,
                };
                socket.join_multicast_v6(&group, index)
            })?;
        }
    }
    Ok(socket.into())
}

/// On Windows a socket joined on the loopback interface that sends to the group leaves the
/// group's destination-cache entry on loopback after the process has exited, and the system
/// then answers 127.0.0.1 for the group to every process that asks which address reaches it,
/// until the entry is deleted (`peer` module documentation). Said once per process.
fn warn_loopback_join_on_windows(group: Ipv4Addr) {
    static ONCE: std::sync::Once = std::sync::Once::new();
    ONCE.call_once(|| {
        log::warn!(
            "joining {group} on the loopback interface: on Windows mDNS sent there leaves the \
             group's destination-cache route on loopback after this process, for other \
             processes too (netsh interface ipv4 delete destinationcache, as administrator)"
        );
    });
}

/// Joins once per interface (`None`: the default one, when there is no interface): an error
/// only when no membership was made. A second address of an interface already joined is
/// refused by the system (`EADDRINUSE`) and changes nothing.
fn join_each(
    interfaces: &[IpAddr],
    mut join: impl FnMut(Option<IpAddr>) -> io::Result<()>,
) -> io::Result<()> {
    if interfaces.is_empty() {
        return join(None);
    }
    let mut first_error = None;
    let mut joined = false;
    for interface in interfaces {
        match join(Some(*interface)) {
            Ok(()) => joined = true,
            Err(e) if e.kind() == io::ErrorKind::AddrInUse => joined = true,
            Err(e) => {
                first_error.get_or_insert(e);
            }
        }
    }
    match (joined, first_error) {
        (false, Some(e)) => Err(e),
        _ => Ok(()),
    }
}

fn tcp_socket(addr: SocketAddr, reuse_address: bool) -> io::Result<Socket> {
    let socket = Socket::new(Domain::for_address(addr), Type::STREAM, Some(Protocol::TCP))?;
    if reuse_address {
        socket.set_reuse_address(true)?;
        #[cfg(all(unix, not(any(target_os = "solaris", target_os = "illumos"))))]
        socket.set_reuse_port(true)?;
    }
    socket.set_nonblocking(true)?;
    Ok(socket)
}

/// A non-blocking std TCP listener on `local`, backlog 128.
///
/// # Errors
///
/// The bind failed.
pub fn std_tcp_listener(
    local: SocketAddr,
    reuse_address: bool,
) -> io::Result<std::net::TcpListener> {
    let socket = tcp_socket(local, reuse_address)?;
    socket.bind(&local.into())?;
    socket.listen(128)?;
    Ok(socket.into())
}

/// A non-blocking TCP socket bound to `local`, for a runtime to connect to a peer.
///
/// # Errors
///
/// The bind failed.
pub fn std_tcp_bound(local: SocketAddr, reuse_address: bool) -> io::Result<Socket> {
    let socket = tcp_socket(local, reuse_address)?;
    socket.bind(&local.into())?;
    Ok(socket)
}

/// Starts a non-blocking TCP connection from `local` to `remote`: the socket is bound, and the
/// handshake runs. A runtime waits for it to become writable, then reads `take_error` and
/// `peer_addr` (what async-io's own `connect` does), for runtimes whose connect cannot bind a
/// local address first.
///
/// # Errors
///
/// The bind failed, or the connection failed at once.
pub fn std_tcp_connect_start(
    local: SocketAddr,
    remote: SocketAddr,
    reuse_address: bool,
) -> io::Result<std::net::TcpStream> {
    let socket = std_tcp_bound(local, reuse_address)?;
    match socket.connect(&remote.into()) {
        Ok(()) => {}
        Err(e) if connect_in_progress(&e) => {}
        Err(e) => return Err(e),
    }
    Ok(socket.into())
}

/// Whether a non-blocking connect's error only says the handshake is under way.
fn connect_in_progress(e: &io::Error) -> bool {
    #[cfg(unix)]
    if e.raw_os_error() == Some(libc::EINPROGRESS) {
        return true;
    }
    // Windows: WSAEWOULDBLOCK.
    e.kind() == io::ErrorKind::WouldBlock
}

/// Makes `socket`'s close abortive (`SO_LINGER` 0: RST instead of FIN), for
/// [`AsyncTcpStream::reset_on_close`].
///
/// # Errors
///
/// The socket refused.
pub fn reset_on_close(socket: SockRef<'_>) -> io::Result<()> {
    socket.set_linger(Some(Duration::ZERO))
}

/// Sets `socket`'s TOS / Traffic Class and reads it back (for [`AsyncTcpStream::set_traffic_class`]).
///
/// # Errors
///
/// The platform refused the option or does not offer it.
pub fn set_and_read_traffic_class(socket: SockRef<'_>, ipv6: bool, value: u8) -> io::Result<u32> {
    crate::sockets::set_traffic_class(SockRef::from(&*socket), ipv6, value)?;
    crate::sockets::traffic_class(socket, ipv6)
}

/// Asks the system to report each received datagram's TOS / Traffic Class byte
/// (`IP_RECVTOS`, `IPV6_RECVTCLASS`), from which [`recv_from_with_ecn`] reads the ECN field
/// (RFC 3168; RFC 6679 section 7.2.1: receivers "listen for ECT/CE"). Unix only; elsewhere
/// `Unsupported`, and received datagrams carry no ECN.
///
/// # Errors
///
/// The system refused the option.
#[cfg(unix)]
pub fn enable_ecn_receive(socket: SockRef<'_>, ipv6: bool) -> io::Result<()> {
    use std::os::fd::AsRawFd;
    let on: libc::c_int = 1;
    let (level, name) = if ipv6 {
        (libc::IPPROTO_IPV6, libc::IPV6_RECVTCLASS)
    } else {
        (libc::IPPROTO_IP, libc::IP_RECVTOS)
    };
    // SAFETY: a valid descriptor, a c_int option value of the size given.
    let r = unsafe {
        libc::setsockopt(
            socket.as_raw_fd(),
            level,
            name,
            (&on as *const libc::c_int).cast(),
            std::mem::size_of::<libc::c_int>() as libc::socklen_t,
        )
    };
    if r == 0 {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}

/// See the unix version: no ECN is read on this system.
///
/// # Errors
///
/// Always `Unsupported`.
#[cfg(not(unix))]
pub fn enable_ecn_receive(socket: SockRef<'_>, ipv6: bool) -> io::Result<()> {
    let _ = (socket, ipv6);
    Err(io::ErrorKind::Unsupported.into())
}

/// Receives one datagram into `buf` (`recvmsg`): its length, its sender, and the ECN codepoint
/// of its IP header (the two low bits of the TOS / Traffic Class byte) when the system reports
/// it ([`enable_ecn_receive`]). A datagram longer than `buf` is truncated, as `recv_from`
/// truncates it.
///
/// # Errors
///
/// As `recv_from` (`WouldBlock` on a non-blocking socket with nothing to read).
#[cfg(unix)]
pub fn recv_from_with_ecn(
    socket: SockRef<'_>,
    buf: &mut [u8],
) -> io::Result<(usize, SocketAddr, Option<u8>)> {
    use std::os::fd::AsRawFd;
    // SAFETY: zeroed plain-old-data C structures.
    let mut name: libc::sockaddr_storage = unsafe { std::mem::zeroed() };
    let mut iov = libc::iovec {
        iov_base: buf.as_mut_ptr().cast(),
        iov_len: buf.len(),
    };
    // Room for one TOS / Traffic Class control message and more, aligned for cmsghdr.
    let mut control = [0u64; 16];
    // SAFETY: as above.
    let mut msg: libc::msghdr = unsafe { std::mem::zeroed() };
    msg.msg_name = (&mut name as *mut libc::sockaddr_storage).cast();
    msg.msg_namelen = std::mem::size_of::<libc::sockaddr_storage>() as libc::socklen_t;
    msg.msg_iov = &mut iov;
    msg.msg_iovlen = 1 as _;
    msg.msg_control = control.as_mut_ptr().cast();
    msg.msg_controllen = std::mem::size_of_val(&control) as _;
    // SAFETY: every pointer in `msg` is to a live buffer of the length given.
    let n = unsafe { libc::recvmsg(socket.as_raw_fd(), &mut msg, 0) };
    if n < 0 {
        return Err(io::Error::last_os_error());
    }
    let mut ecn = None;
    // SAFETY: the control messages are the ones recvmsg wrote into `control`, walked with the
    // system's macros; each value is read unaligned.
    unsafe {
        let mut cmsg = libc::CMSG_FIRSTHDR(&msg);
        while !cmsg.is_null() {
            let header = &*cmsg;
            let data = libc::CMSG_DATA(cmsg);
            // Linux reports IPv4's byte as IP_TOS, Apple systems and the BSDs as IP_RECVTOS;
            // IPv6's is an int under IPV6_TCLASS everywhere.
            let byte = if header.cmsg_level == libc::IPPROTO_IP
                && (header.cmsg_type == libc::IP_TOS || header.cmsg_type == libc::IP_RECVTOS)
            {
                Some(std::ptr::read_unaligned(data))
            } else if header.cmsg_level == libc::IPPROTO_IPV6
                && header.cmsg_type == libc::IPV6_TCLASS
            {
                Some(std::ptr::read_unaligned(data.cast::<libc::c_int>()) as u8)
            } else {
                None
            };
            if let Some(byte) = byte {
                ecn = Some(byte & 0b11);
            }
            cmsg = libc::CMSG_NXTHDR(&msg, cmsg);
        }
    }
    let from = socket_addr_of(&name)
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "no sender address"))?;
    Ok((n as usize, from, ecn))
}

/// The address in a `sockaddr_storage` recvmsg filled (IPv4 or IPv6).
#[cfg(unix)]
fn socket_addr_of(name: &libc::sockaddr_storage) -> Option<SocketAddr> {
    match libc::c_int::from(name.ss_family) {
        libc::AF_INET => {
            // SAFETY: the family says the storage holds a sockaddr_in.
            let v4 =
                unsafe { &*(name as *const libc::sockaddr_storage).cast::<libc::sockaddr_in>() };
            Some(SocketAddr::new(
                Ipv4Addr::from(u32::from_be(v4.sin_addr.s_addr)).into(),
                u16::from_be(v4.sin_port),
            ))
        }
        libc::AF_INET6 => {
            // SAFETY: the family says the storage holds a sockaddr_in6.
            let v6 =
                unsafe { &*(name as *const libc::sockaddr_storage).cast::<libc::sockaddr_in6>() };
            Some(SocketAddr::V6(std::net::SocketAddrV6::new(
                Ipv6Addr::from(v6.sin6_addr.s6_addr),
                u16::from_be(v6.sin6_port),
                v6.sin6_flowinfo,
                v6.sin6_scope_id,
            )))
        }
        _ => None,
    }
}

/// Sets the Don't Fragment state of `socket` (IPv6 when `ipv6`): `true` sets the IPv4 DF bit and
/// forbids local fragmentation over IPv6, `false` lets the datagram be fragmented. Linux and
/// Android: `IP_MTU_DISCOVER` / `IPV6_MTU_DISCOVER` to `PMTUDISC_DO` or `PMTUDISC_DONT`; Apple
/// systems and FreeBSD: `IP_DONTFRAG` / `IPV6_DONTFRAG`. Elsewhere `Unsupported`.
///
/// # Errors
///
/// The platform refused the option, or has none.
pub fn set_dont_fragment(socket: SockRef<'_>, ipv6: bool, on: bool) -> io::Result<()> {
    #[cfg(any(target_os = "linux", target_os = "android"))]
    let (level, name, value) = match (ipv6, on) {
        (false, true) => (
            libc::IPPROTO_IP,
            libc::IP_MTU_DISCOVER,
            libc::IP_PMTUDISC_DO,
        ),
        (false, false) => (
            libc::IPPROTO_IP,
            libc::IP_MTU_DISCOVER,
            libc::IP_PMTUDISC_DONT,
        ),
        (true, true) => (
            libc::IPPROTO_IPV6,
            libc::IPV6_MTU_DISCOVER,
            libc::IPV6_PMTUDISC_DO,
        ),
        (true, false) => (
            libc::IPPROTO_IPV6,
            libc::IPV6_MTU_DISCOVER,
            libc::IPV6_PMTUDISC_DONT,
        ),
    };
    #[cfg(any(target_vendor = "apple", target_os = "freebsd"))]
    let (level, name, value) = if ipv6 {
        (
            libc::IPPROTO_IPV6,
            libc::IPV6_DONTFRAG,
            libc::c_int::from(on),
        )
    } else {
        (libc::IPPROTO_IP, libc::IP_DONTFRAG, libc::c_int::from(on))
    };
    #[cfg(any(
        target_os = "linux",
        target_os = "android",
        target_vendor = "apple",
        target_os = "freebsd"
    ))]
    {
        use std::os::fd::AsRawFd;
        // SAFETY: a valid descriptor, a c_int option value of the size given.
        let r = unsafe {
            libc::setsockopt(
                socket.as_raw_fd(),
                level,
                name,
                (&value as *const libc::c_int).cast(),
                std::mem::size_of::<libc::c_int>() as libc::socklen_t,
            )
        };
        if r == 0 {
            Ok(())
        } else {
            Err(io::Error::last_os_error())
        }
    }
    #[cfg(not(any(
        target_os = "linux",
        target_os = "android",
        target_vendor = "apple",
        target_os = "freebsd"
    )))]
    {
        let _ = (socket, ipv6, on);
        Err(io::ErrorKind::Unsupported.into())
    }
}

/// The Don't Fragment state [`set_dont_fragment`] set, as the operating system reports it
/// (`getsockopt`): `true` for DF / no local fragmentation.
///
/// # Errors
///
/// The platform refused the query, or has no such option.
pub fn dont_fragment(socket: SockRef<'_>, ipv6: bool) -> io::Result<bool> {
    #[cfg(any(target_os = "linux", target_os = "android"))]
    let (level, name) = if ipv6 {
        (libc::IPPROTO_IPV6, libc::IPV6_MTU_DISCOVER)
    } else {
        (libc::IPPROTO_IP, libc::IP_MTU_DISCOVER)
    };
    #[cfg(any(target_vendor = "apple", target_os = "freebsd"))]
    let (level, name) = if ipv6 {
        (libc::IPPROTO_IPV6, libc::IPV6_DONTFRAG)
    } else {
        (libc::IPPROTO_IP, libc::IP_DONTFRAG)
    };
    #[cfg(any(
        target_os = "linux",
        target_os = "android",
        target_vendor = "apple",
        target_os = "freebsd"
    ))]
    {
        use std::os::fd::AsRawFd;
        let mut value: libc::c_int = 0;
        let mut len = std::mem::size_of::<libc::c_int>() as libc::socklen_t;
        // SAFETY: a valid descriptor, a c_int buffer of the size given.
        let r = unsafe {
            libc::getsockopt(
                socket.as_raw_fd(),
                level,
                name,
                (&mut value as *mut libc::c_int).cast(),
                &mut len,
            )
        };
        if r != 0 {
            return Err(io::Error::last_os_error());
        }
        #[cfg(any(target_os = "linux", target_os = "android"))]
        let on = value == libc::IP_PMTUDISC_DO;
        #[cfg(any(target_vendor = "apple", target_os = "freebsd"))]
        let on = value != 0;
        Ok(on)
    }
    #[cfg(not(any(
        target_os = "linux",
        target_os = "android",
        target_vendor = "apple",
        target_os = "freebsd"
    )))]
    {
        let _ = (socket, ipv6);
        Err(io::ErrorKind::Unsupported.into())
    }
}