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
//! Which local addresses get a UDP socket and a host candidate ([`AddressSelection`],
//! [`select_addresses`]): the gathering rules of RFC 8445 section 5.1.1.1 that belong to
//! whoever owns the sockets, applied to the interface list of the driver's runtime
//! ([`Runtime::interfaces`]).

use crate::runtime::{LocalInterface, Runtime};
use crate::sockets::AddressFilter;
use std::io;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

/// How a [`PeerDriver`](crate::peer::PeerDriver) chooses its addresses from the host's
/// interfaces, read again at every gathering (an ICE restart gathers on the addresses the host
/// has then). See [`select_addresses`] for the rules.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct AddressSelection {
    /// Which interfaces and addresses may be used at all (bind addresses, loopback, link-local,
    /// name and address filters).
    pub filter: AddressFilter,
    /// At most this many addresses (`None`, the default: no limit). A limit keeps at least one
    /// address of each family that has one. RFC 8445 sets none; each address adds a host
    /// candidate (and a server-reflexive and a relayed one) and multiplies the pairs, so an
    /// application with a small signalling budget may want one.
    pub max_addresses: Option<usize>,
    /// When no address passes, loopback addresses instead (off by default). RFC 8445 section
    /// 5.1.1.1: "Addresses from a loopback interface MUST NOT be included in the candidate
    /// addresses"; on, a host with no network still reaches another process on itself. For
    /// local use and tests.
    pub loopback_when_alone: bool,
    /// The user consented to Mode 1 (RFC 8828 section 5.2): every interface is gathered on.
    /// `false` by default: Mode 2, the default route's interface only. RFC 8828 section 5.2:
    /// Mode 1 "MUST NOT be used unless user consent has been given" (RFC8828-5.2-7), and
    /// without consent Mode 2 is used (RFC8828-5.2-8); section 5.1 names what counts, the
    /// user's grant of camera or microphone access being the browsers' (a call the user placed
    /// or accepted, in an application). Only the application can know, so only it sets this
    /// (`PeerDriver::set_user_consent` during a call: from the next gathering on).
    pub user_consent: bool,
    /// Addresses the routes of Mode 2 are taken towards, an enterprise TURN server's (RFC
    /// 8828 section 5.2: "If an enterprise TURN server is present, the preferred route MUST be
    /// through this TURN server", RFC8828-5.2-3): for each family that has one, the interface
    /// of the routing table's route to it ([`Runtime::route_source`]) is gathered on instead of
    /// the default route's. A `PeerDriver` adds the IP addresses of its connection's `turn:` /
    /// `turns:` servers by itself; a server given by name is added here by the application
    /// once resolved.
    pub route_via: Vec<IpAddr>,
    /// At most one address of each family (off by default). A lite agent's: RFC 8445 section
    /// 5.2, "It is NOT RECOMMENDED to include more than one candidate per address family"
    /// (RFC8445-5.2-2); a `PeerDriver` whose connection is lite applies it by itself.
    pub one_per_family: bool,
}

impl AddressSelection {
    /// The default route's interface (RFC 8828 Mode 2), no limit, no loopback.
    pub fn new() -> Self {
        Self::default()
    }

    /// With the user's consent (RFC 8828 Mode 1: every interface), or without (Mode 2).
    #[must_use]
    pub fn with_user_consent(mut self, consent: bool) -> Self {
        self.user_consent = consent;
        self
    }

    /// With routes taken towards these addresses ([`route_via`](Self::route_via)).
    #[must_use]
    pub fn with_route_via(mut self, addresses: Vec<IpAddr>) -> Self {
        self.route_via = addresses;
        self
    }

    /// One address of each family at most ([`one_per_family`](Self::one_per_family)).
    #[must_use]
    pub fn with_one_per_family(mut self, on: bool) -> Self {
        self.one_per_family = on;
        self
    }

    /// With `filter`.
    #[must_use]
    pub fn with_filter(mut self, filter: AddressFilter) -> Self {
        self.filter = filter;
        self
    }

    /// With a limit on the number of addresses.
    #[must_use]
    pub fn with_max_addresses(mut self, max: usize) -> Self {
        self.max_addresses = Some(max);
        self
    }

    /// With loopback addresses when nothing else passes.
    #[must_use]
    pub fn with_loopback_when_alone(mut self, on: bool) -> Self {
        self.loopback_when_alone = on;
        self
    }

    /// The addresses `runtime`'s host has now, selected ([`select_addresses`]); `in_use`: the
    /// addresses gathered on now (a deprecated one among them is kept).
    ///
    /// # Errors
    ///
    /// The interfaces could not be listed.
    pub fn select(&self, runtime: &dyn Runtime, in_use: &[IpAddr]) -> io::Result<Vec<IpAddr>> {
        let interfaces = runtime.interfaces()?;
        Ok(select_addresses(
            &interfaces,
            self.routes(runtime),
            in_use,
            self,
        ))
    }

    /// The route source of each family (`[IPv6, IPv4]`): towards the first
    /// [`route_via`](Self::route_via) address of the family that has a route, else the default
    /// route's ([`Runtime::preferred_source`]).
    pub fn routes(&self, runtime: &dyn Runtime) -> [Option<IpAddr>; 2] {
        let route = |ipv6: bool| {
            self.route_via
                .iter()
                .filter(|ip| ip.is_ipv6() == ipv6)
                .find_map(|ip| runtime.route_source(*ip))
                .or_else(|| runtime.preferred_source(ipv6))
        };
        [route(true), route(false)]
    }
}

/// IPv4-compatible IPv6 (`::a.b.c.d`, deprecated by RFC 4291 section 2.5.5.1).
fn is_v4_compatible(ip: Ipv6Addr) -> bool {
    let s = ip.segments();
    s[..6] == [0; 6] && !ip.is_unspecified() && !ip.is_loopback()
}

/// IPv6 site-local (`fec0::/10`, deprecated by RFC 3879).
fn is_site_local(ip: Ipv6Addr) -> bool {
    ip.segments()[0] & 0xffc0 == 0xfec0
}

/// IPv4-mapped IPv6 (`::ffff:a.b.c.d`).
fn is_v4_mapped(ip: Ipv6Addr) -> bool {
    ip.to_ipv4_mapped().is_some()
}

/// An interface identifier derived from a hardware address (modified EUI-64, RFC 4291
/// appendix A: `ff:fe` in the middle): an address that allows location tracking (RFC 7721
/// section 3).
fn is_eui64(ip: Ipv6Addr) -> bool {
    let o = ip.octets();
    o[11] == 0xff && o[12] == 0xfe
}

fn is_v4_link_local(ip: Ipv4Addr) -> bool {
    ip.is_link_local()
}

/// The first `len` bits of `ip` (an IPv6 network prefix).
fn prefix(ip: Ipv6Addr, len: u8) -> u128 {
    let len = u32::from(len.min(128));
    if len == 0 {
        0
    } else {
        u128::from(ip) & (u128::MAX << (128 - len))
    }
}

/// The local addresses to gather on, most preferred first, from `interfaces` (the host's,
/// [`crate::runtime::Runtime::interfaces`]), the routing table's source address of each family
/// (`[IPv6, IPv4]`, [`AddressSelection::routes`]: the default route's, or the route towards the
/// enterprise TURN server) and the addresses gathered on now (`in_use`).
///
/// - **Interfaces** (RFC 8828 section 5.2): only those the routing table picks, the interfaces
///   holding the route source addresses (Mode 2), unless [`AddressSelection::user_consent`]
///   (Mode 1). Without a route, Mode 2 finds nothing.
/// - **Filter**: an address must pass [`AddressSelection::filter`] ([`AddressFilter::keeps`]:
///   no unspecified or multicast address; loopback and IPv6 link-local only when the filter
///   asks; its name and address filters; only its bind addresses when it names some). IPv4
///   link-local (169.254/16) follows `include_link_local` too.
/// - **RFC 8445 section 5.1.1.1**: no loopback address (`MUST NOT`, unless the filter asks for
///   them, or [`AddressSelection::loopback_when_alone`] and nothing else passes); no
///   IPv4-compatible IPv6 and no IPv6 site-local address (`MUST NOT`); no IPv4-mapped IPv6
///   address unless the host has no IPv4 address (`SHOULD NOT` "unless ... IPv6-only"); where
///   an interface has a temporary address (RFC 8981, an address that prevents location
///   tracking, RFC 7721) in a prefix, no address of that interface and prefix that allows
///   tracking (`MUST NOT`), and no IPv6 link-local address at all (`MUST NOT`).
/// - **RFC 8835 section 3.3**: no deprecated temporary IPv6 address unless it is in use
///   (`SHOULD`); where the host has a temporary IPv6 address, no permanent IPv6 address of the
///   same (global) scope on any interface or prefix (`SHOULD`).
/// - **One IPv6 address per interface and prefix** (a /64 when the prefix is unknown): the
///   temporary one the system uses as its source, else a temporary one, else one not derived
///   from the hardware address (EUI-64), else the first. libwebrtc does the same: one IPv6
///   address per network (`Network::GetBestIP` in `rtc_base/network.cc`), a temporary one
///   first.
/// - **Order** (it becomes the candidates' local preference, RFC 8445 section 5.1.2.1): the
///   preferred source addresses first, IPv6 before IPv4 (RFC 8421 section 4), then the others
///   in the system's order, the families interleaved (RFC 8421 section 4).
/// - [`AddressSelection::max_addresses`], keeping one of each family that has any;
///   [`AddressSelection::one_per_family`]: the first of each family.
pub fn select_addresses(
    interfaces: &[LocalInterface],
    preferred: [Option<IpAddr>; 2],
    in_use: &[IpAddr],
    selection: &AddressSelection,
) -> Vec<IpAddr> {
    let filter = &selection.filter;
    let passes = |i: &LocalInterface| {
        if !filter.bind_addresses.is_empty() && !filter.bind_addresses.contains(&i.ip) {
            return false;
        }
        if !filter.keeps(Some(&i.name), i.ip) {
            return false;
        }
        match i.ip {
            IpAddr::V4(v4) => !is_v4_link_local(v4) || filter.include_link_local,
            IpAddr::V6(v6) => !is_v4_compatible(v6) && !is_site_local(v6),
        }
    };
    let mut usable: Vec<&LocalInterface> = interfaces.iter().filter(|i| passes(i)).collect();
    if !selection.user_consent {
        // Mode 2: the interfaces of the default route.
        let default_route: Vec<&str> = interfaces
            .iter()
            .filter(|i| preferred.contains(&Some(i.ip)))
            .map(|i| i.name.as_str())
            .collect();
        usable.retain(|i| default_route.contains(&i.name.as_str()));
    }
    if usable.is_empty() && selection.loopback_when_alone {
        let loopback = AddressFilter {
            include_loopback: true,
            ..filter.clone()
        };
        usable = interfaces
            .iter()
            .filter(|i| i.ip.is_loopback() && loopback.keeps(Some(&i.name), i.ip))
            .collect();
    }
    // IPv4-mapped IPv6 only on a host without IPv4.
    let has_v4 = usable.iter().any(|i| i.ip.is_ipv4());
    usable.retain(|i| !matches!(i.ip, IpAddr::V6(v6) if is_v4_mapped(v6) && has_v4));
    // RFC 8835 section 3.3: no deprecated temporary address that is not in use.
    usable.retain(|i| !(i.temporary && i.deprecated && !in_use.contains(&i.ip)));
    // A temporary address anywhere: no IPv6 link-local at all.
    if usable.iter().any(|i| i.temporary) {
        usable.retain(|i| !matches!(i.ip, IpAddr::V6(v6) if v6.is_unicast_link_local()));
        // RFC 8835 section 3.3: no permanent address of the temporary one's scope.
        usable.retain(|i| !i.ip.is_ipv6() || i.temporary);
    }
    // One IPv6 address per interface and prefix.
    let preferred_v6 = preferred[0];
    let mut chosen: Vec<IpAddr> = Vec::new();
    let mut groups_done: Vec<(String, u128)> = Vec::new();
    for i in &usable {
        let IpAddr::V6(v6) = i.ip else {
            if !chosen.contains(&i.ip) {
                chosen.push(i.ip);
            }
            continue;
        };
        let len = i.prefix_len.unwrap_or(64);
        let key = (i.name.clone(), prefix(v6, len));
        if groups_done.contains(&key) {
            continue;
        }
        groups_done.push(key.clone());
        let group: Vec<&LocalInterface> = usable
            .iter()
            .copied()
            .filter(|j| {
                matches!(j.ip, IpAddr::V6(w) if j.name == key.0
                    && prefix(w, j.prefix_len.unwrap_or(64)) == key.1)
            })
            .collect();
        let best = group
            .iter()
            .find(|j| j.temporary && Some(j.ip) == preferred_v6)
            .or_else(|| group.iter().find(|j| j.temporary))
            .or_else(|| {
                group
                    .iter()
                    .find(|j| matches!(j.ip, IpAddr::V6(w) if !is_eui64(w)))
            })
            .or_else(|| group.first());
        if let Some(best) = best {
            chosen.push(best.ip);
        }
    }
    // Order: the preferred sources (IPv6 first), then the rest, families interleaved.
    let mut ordered: Vec<IpAddr> = Vec::new();
    for p in preferred.iter().flatten() {
        if chosen.contains(p) {
            ordered.push(*p);
        }
    }
    let rest: Vec<IpAddr> = chosen
        .into_iter()
        .filter(|ip| !ordered.contains(ip))
        .collect();
    let (mut v6, mut v4): (Vec<IpAddr>, Vec<IpAddr>) = rest.into_iter().partition(IpAddr::is_ipv6);
    v6.reverse();
    v4.reverse();
    loop {
        let a = v6.pop();
        let b = v4.pop();
        if a.is_none() && b.is_none() {
            break;
        }
        ordered.extend(a);
        ordered.extend(b);
    }
    if let Some(max) = selection.max_addresses {
        ordered = cap(ordered, max);
    }
    if selection.one_per_family {
        let mut seen = [false; 2];
        ordered.retain(|ip| !std::mem::replace(&mut seen[usize::from(ip.is_ipv6())], true));
    }
    ordered
}

/// The first `max` of `ordered`, with one address of each family that has one kept in.
fn cap(ordered: Vec<IpAddr>, max: usize) -> Vec<IpAddr> {
    if ordered.len() <= max {
        return ordered;
    }
    let mut kept: Vec<IpAddr> = ordered.iter().copied().take(max).collect();
    for family_v6 in [true, false] {
        if !kept.iter().any(|ip| ip.is_ipv6() == family_v6)
            && let Some(first) = ordered.iter().find(|ip| ip.is_ipv6() == family_v6)
        {
            // Replace the last address of the family that has more than one.
            let other = !family_v6;
            if kept.iter().filter(|ip| ip.is_ipv6() == other).count() > 1
                && let Some(at) = kept.iter().rposition(|ip| ip.is_ipv6() == other)
            {
                kept[at] = *first;
            }
        }
    }
    // Keep the original order.
    ordered.into_iter().filter(|ip| kept.contains(ip)).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn v4(s: &str) -> IpAddr {
        IpAddr::V4(s.parse().unwrap())
    }
    fn v6(s: &str) -> IpAddr {
        IpAddr::V6(s.parse().unwrap())
    }
    fn on(name: &str, ip: IpAddr) -> LocalInterface {
        LocalInterface::new(name, ip)
    }
    fn mode1() -> AddressSelection {
        AddressSelection::new().with_user_consent(true)
    }
    fn select(interfaces: &[LocalInterface]) -> Vec<IpAddr> {
        select_addresses(interfaces, [None, None], &[], &mode1())
    }

    // RFC8445-5.1.1.1-4: loopback addresses are not candidate addresses.
    #[test]
    fn rfc8445_5_1_1_1_4_loopback_addresses_are_not_selected() {
        let all = [
            on("lo", v4("127.0.0.1")),
            on("lo", v6("::1")),
            on("eth0", v4("192.168.1.10")),
        ];
        assert_eq!(select(&all), vec![v4("192.168.1.10")]);
        // Only with the setting, and only when nothing else passes.
        let alone = [on("lo", v4("127.0.0.1"))];
        assert!(select(&alone).is_empty());
        let fallback = mode1().with_loopback_when_alone(true);
        assert_eq!(
            select_addresses(&alone, [None, None], &[], &fallback),
            vec![v4("127.0.0.1")]
        );
        assert_eq!(
            select_addresses(&all, [None, None], &[], &fallback),
            vec![v4("192.168.1.10")]
        );
    }

    // RFC8445-5.1.1.1-5: no IPv4-compatible IPv6, no IPv6 site-local.
    #[test]
    fn rfc8445_5_1_1_1_5_v4_compatible_and_site_local_ipv6_are_not_selected() {
        let all = [
            on("eth0", v6("::192.0.2.33")),
            on("eth0", v6("fec0::1")),
            on("eth0", v6("2001:db8:1::10")),
        ];
        assert_eq!(select(&all), vec![v6("2001:db8:1::10")]);
    }

    // RFC8445-5.1.1.1-6: no IPv4-mapped IPv6 unless the host has no IPv4.
    #[test]
    fn rfc8445_5_1_1_1_6_v4_mapped_ipv6_only_on_an_ipv6_only_host() {
        let mapped = on("eth0", v6("::ffff:192.0.2.1"));
        let dual = [mapped.clone(), on("eth0", v4("192.168.1.10"))];
        assert_eq!(select(&dual), vec![v4("192.168.1.10")]);
        assert_eq!(select(&[mapped]), vec![v6("::ffff:192.0.2.1")]);
    }

    // RFC8445-5.1.1.1-7: with a temporary (privacy) address in a prefix, the trackable
    // addresses of that interface and prefix are not gathered; RFC8835-3.3-1: nor any
    // permanent IPv6 address of the same scope elsewhere.
    #[test]
    fn rfc8445_5_1_1_1_7_a_temporary_address_hides_the_trackable_ones_of_its_prefix() {
        let all = [
            on("eth0", v6("2001:db8:1::211:22ff:fe33:4455")).with_prefix_len(64),
            on("eth0", v6("2001:db8:1::a1b2:c3d4:e5f6:1234"))
                .with_prefix_len(64)
                .with_temporary(true),
            on("eth0", v4("192.168.1.10")),
        ];
        assert_eq!(
            select(&all),
            vec![v6("2001:db8:1::a1b2:c3d4:e5f6:1234"), v4("192.168.1.10")]
        );
        // Without the temporary address the permanent one is gathered.
        assert_eq!(
            select(&[all[0].clone()]),
            vec![v6("2001:db8:1::211:22ff:fe33:4455")]
        );
    }

    // RFC8835-3.3-1: "discard permanent IPv6 addresses where a temporary address of the same
    // scope exists", on another prefix or interface too.
    #[test]
    fn rfc8835_3_3_1_a_temporary_address_hides_every_permanent_global_one() {
        let all = [
            on("eth0", v6("2001:db8:1::a1b2:c3d4:e5f6:1234"))
                .with_prefix_len(64)
                .with_temporary(true),
            on("eth0", v6("2001:db8:2::10")).with_prefix_len(64),
            on("wlan0", v6("2001:db8:9::5")).with_prefix_len(64),
        ];
        assert_eq!(select(&all), vec![v6("2001:db8:1::a1b2:c3d4:e5f6:1234")]);
    }

    // RFC8828-5.2-7, -8, -4: by default (no consent) only the default route's interface, with
    // its private addresses; every interface only when the application says so.
    #[test]
    fn rfc8828_5_2_mode_2_by_default_mode_1_on_request() {
        let interfaces = [
            on("eth0", v4("192.168.1.10")),
            on("eth0", v6("fd00::10")),
            on("vpn0", v4("10.8.0.2")),
        ];
        let preferred = [None, Some(v4("192.168.1.10"))];
        assert_eq!(
            select_addresses(&interfaces, preferred, &[], &AddressSelection::new()),
            vec![v4("192.168.1.10"), v6("fd00::10")]
        );
        assert!(
            select_addresses(&interfaces, [None, None], &[], &AddressSelection::new()).is_empty(),
            "no default route: nothing"
        );
        assert_eq!(
            select_addresses(&interfaces, preferred, &[], &mode1()),
            vec![v4("192.168.1.10"), v6("fd00::10"), v4("10.8.0.2")]
        );
    }

    // RFC8445-5.1.1.1-8: with privacy addresses, no IPv6 link-local candidates, even when the
    // filter lets link-local addresses through.
    #[test]
    fn rfc8445_5_1_1_1_8_no_link_local_beside_a_temporary_address() {
        let filter = AddressFilter {
            include_link_local: true,
            ..Default::default()
        };
        let selection = mode1().with_filter(filter);
        let link_local = on("eth0", v6("fe80::1"));
        let temporary = on("eth0", v6("2001:db8:1::abcd")).with_temporary(true);
        assert_eq!(
            select_addresses(
                std::slice::from_ref(&link_local),
                [None, None],
                &[],
                &selection
            ),
            vec![v6("fe80::1")]
        );
        assert_eq!(
            select_addresses(&[link_local, temporary], [None, None], &[], &selection),
            vec![v6("2001:db8:1::abcd")]
        );
    }

    // RFC8445-5.1.1.1-1: a host candidate on each address of the host (one per IPv6 network).
    #[test]
    fn rfc8445_5_1_1_1_1_every_interface_gets_an_address_one_ipv6_per_prefix() {
        let all = [
            on("eth0", v4("192.168.1.10")),
            on("eth0", v6("2001:db8:1::10")),
            on("eth0", v6("2001:db8:1::11")),
            on("wlan0", v4("10.0.0.5")),
            on("wlan0", v6("2001:db8:9::5")),
        ];
        assert_eq!(
            select(&all),
            vec![
                v6("2001:db8:1::10"),
                v4("192.168.1.10"),
                v6("2001:db8:9::5"),
                v4("10.0.0.5"),
            ]
        );
    }

    // RFC 8421 section 4: the default route's addresses first, IPv6 before IPv4.
    #[test]
    fn the_preferred_sources_come_first_ipv6_before_ipv4() {
        let all = [
            on("eth0", v4("192.168.1.10")),
            on("wlan0", v4("10.0.0.5")),
            on("wlan0", v6("2001:db8:9::5")),
        ];
        let preferred = [Some(v6("2001:db8:9::5")), Some(v4("10.0.0.5"))];
        assert_eq!(
            select_addresses(
                &all,
                preferred,
                &[],
                &super::AddressSelection::new().with_user_consent(true)
            ),
            vec![v6("2001:db8:9::5"), v4("10.0.0.5"), v4("192.168.1.10")]
        );
    }

    // RFC8835-3.3-2: a deprecated temporary address is discarded unless it is in use (the
    // connection gathered on it before it was deprecated).
    #[test]
    fn rfc8835_3_3_2_a_deprecated_temporary_address_only_while_in_use() {
        let old = v6("2001:db8:1::aaaa");
        let new = v6("2001:db8:1::bbbb");
        let all = [
            on("eth0", old)
                .with_prefix_len(64)
                .with_temporary(true)
                .with_deprecated(true),
            on("eth0", new).with_prefix_len(64).with_temporary(true),
            on("eth1", v6("2001:db8:2::cccc"))
                .with_prefix_len(64)
                .with_temporary(true)
                .with_deprecated(true),
        ];
        assert_eq!(select(&all), vec![new], "deprecated ones are discarded");
        let picked = select_addresses(&all, [None, None], &[old], &mode1());
        assert!(picked.contains(&old), "kept while in use: {picked:?}");
        assert!(!picked.contains(&v6("2001:db8:2::cccc")));
    }

    // RFC8445-5.2-2: a lite agent includes at most one candidate per address family.
    #[test]
    fn rfc8445_5_2_2_one_address_per_family() {
        let all = [
            on("eth0", v4("192.168.1.10")),
            on("eth0", v6("2001:db8:1::10")),
            on("wlan0", v4("10.0.0.5")),
            on("wlan0", v6("2001:db8:9::5")),
        ];
        assert_eq!(
            select_addresses(&all, [None, None], &[], &mode1().with_one_per_family(true)),
            vec![v6("2001:db8:1::10"), v4("192.168.1.10")]
        );
    }

    // RFC8828-5.2-2, -3: Mode 2 follows the routing table, towards the enterprise TURN server
    // when there is one: the interface of the route to it is gathered on, not the default
    // route's.
    #[test]
    fn rfc8828_5_2_2_and_3_mode_2_takes_the_route_towards_the_turn_server() {
        #[derive(Debug)]
        struct Routes;
        impl crate::runtime::Runtime for Routes {
            fn spawn(
                &self,
                _: crate::runtime::BoxFuture<'static, ()>,
            ) -> Box<dyn crate::runtime::JoinHandle> {
                unimplemented!()
            }
            fn now(&self) -> std::time::Instant {
                std::time::Instant::now()
            }
            fn sleep_until(&self, _: std::time::Instant) -> crate::runtime::BoxFuture<'static, ()> {
                unimplemented!()
            }
            fn bind_udp(
                &self,
                _: std::net::SocketAddr,
            ) -> io::Result<std::sync::Arc<dyn crate::runtime::AsyncUdpSocket>> {
                unimplemented!()
            }
            fn bind_udp_multicast(
                &self,
                _: &crate::runtime::MulticastConfig,
            ) -> io::Result<std::sync::Arc<dyn crate::runtime::AsyncUdpSocket>> {
                unimplemented!()
            }
            fn listen_tcp(
                &self,
                _: std::net::SocketAddr,
                _: bool,
            ) -> io::Result<std::sync::Arc<dyn crate::runtime::AsyncTcpListener>> {
                unimplemented!()
            }
            fn connect_tcp(
                &self,
                _: std::net::SocketAddr,
                _: std::net::SocketAddr,
                _: bool,
            ) -> crate::runtime::BoxFuture<
                'static,
                io::Result<std::sync::Arc<dyn crate::runtime::AsyncTcpStream>>,
            > {
                unimplemented!()
            }
            fn resolve_host(
                &self,
                _: &str,
                _: u16,
            ) -> crate::runtime::BoxFuture<'static, io::Result<Vec<std::net::SocketAddr>>>
            {
                unimplemented!()
            }
            fn block_on(&self, _: std::pin::Pin<Box<dyn std::future::Future<Output = ()> + '_>>) {
                unimplemented!()
            }
            fn interfaces(&self) -> io::Result<Vec<LocalInterface>> {
                Ok(vec![
                    on("eth0", v4("192.168.1.10")),
                    on("corp0", v4("10.20.0.7")),
                ])
            }
            fn preferred_source(&self, ipv6: bool) -> Option<IpAddr> {
                (!ipv6).then(|| v4("192.168.1.10"))
            }
            fn route_source(&self, destination: IpAddr) -> Option<IpAddr> {
                // The enterprise TURN server is reached over corp0.
                (destination == v4("10.99.0.1")).then(|| v4("10.20.0.7"))
            }
        }
        let default_route = AddressSelection::new().select(&Routes, &[]).unwrap();
        assert_eq!(default_route, vec![v4("192.168.1.10")]);
        let via_turn = AddressSelection::new()
            .with_route_via(vec![v4("10.99.0.1")])
            .select(&Routes, &[])
            .unwrap();
        assert_eq!(via_turn, vec![v4("10.20.0.7")]);
        // A TURN server without a route: the default route's.
        let unreachable = AddressSelection::new()
            .with_route_via(vec![v4("10.250.0.1")])
            .select(&Routes, &[])
            .unwrap();
        assert_eq!(unreachable, vec![v4("192.168.1.10")]);
    }

    #[test]
    fn a_limit_keeps_one_address_of_each_family() {
        let all = [
            on("a", v4("10.0.0.1")),
            on("b", v4("10.0.1.1")),
            on("c", v4("10.0.2.1")),
            on("d", v6("2001:db8:4::1")),
        ];
        let selection = mode1().with_max_addresses(2);
        let picked = select_addresses(&all, [Some(v4("10.0.0.1")), None], &[], &selection);
        assert_eq!(picked.len(), 2);
        assert!(picked.contains(&v4("10.0.0.1")));
        assert!(picked.contains(&v6("2001:db8:4::1")));
    }

    #[test]
    fn ipv4_link_local_follows_the_filter() {
        let all = [on("eth0", v4("169.254.3.4"))];
        assert!(select(&all).is_empty());
        let selection = super::AddressSelection::new()
            .with_user_consent(true)
            .with_filter(AddressFilter {
                include_link_local: true,
                ..Default::default()
            });
        assert_eq!(
            select_addresses(&all, [None, None], &[], &selection),
            vec![v4("169.254.3.4")]
        );
    }
}