Skip to main content

rtci_stream_driver/
selection.rs

1//! Which local addresses get a UDP socket and a host candidate ([`AddressSelection`],
2//! [`select_addresses`]): the gathering rules of RFC 8445 section 5.1.1.1 that belong to
3//! whoever owns the sockets, applied to the interface list of the driver's runtime
4//! ([`Runtime::interfaces`]).
5
6use crate::runtime::{LocalInterface, Runtime};
7use crate::sockets::AddressFilter;
8use std::io;
9use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
10
11/// How a [`PeerDriver`](crate::peer::PeerDriver) chooses its addresses from the host's
12/// interfaces, read again at every gathering (an ICE restart gathers on the addresses the host
13/// has then). See [`select_addresses`] for the rules.
14#[derive(Debug, Clone, Default)]
15#[non_exhaustive]
16pub struct AddressSelection {
17    /// Which interfaces and addresses may be used at all (bind addresses, loopback, link-local,
18    /// name and address filters).
19    pub filter: AddressFilter,
20    /// At most this many addresses (`None`, the default: no limit). A limit keeps at least one
21    /// address of each family that has one. RFC 8445 sets none; each address adds a host
22    /// candidate (and a server-reflexive and a relayed one) and multiplies the pairs, so an
23    /// application with a small signalling budget may want one.
24    pub max_addresses: Option<usize>,
25    /// When no address passes, loopback addresses instead (off by default). RFC 8445 section
26    /// 5.1.1.1: "Addresses from a loopback interface MUST NOT be included in the candidate
27    /// addresses"; on, a host with no network still reaches another process on itself. For
28    /// local use and tests.
29    pub loopback_when_alone: bool,
30    /// The user consented to Mode 1 (RFC 8828 section 5.2): every interface is gathered on.
31    /// `false` by default: Mode 2, the default route's interface only. RFC 8828 section 5.2:
32    /// Mode 1 "MUST NOT be used unless user consent has been given" (RFC8828-5.2-7), and
33    /// without consent Mode 2 is used (RFC8828-5.2-8); section 5.1 names what counts, the
34    /// user's grant of camera or microphone access being the browsers' (a call the user placed
35    /// or accepted, in an application). Only the application can know, so only it sets this
36    /// (`PeerDriver::set_user_consent` during a call: from the next gathering on).
37    pub user_consent: bool,
38    /// Addresses the routes of Mode 2 are taken towards, an enterprise TURN server's (RFC
39    /// 8828 section 5.2: "If an enterprise TURN server is present, the preferred route MUST be
40    /// through this TURN server", RFC8828-5.2-3): for each family that has one, the interface
41    /// of the routing table's route to it ([`Runtime::route_source`]) is gathered on instead of
42    /// the default route's. A `PeerDriver` adds the IP addresses of its connection's `turn:` /
43    /// `turns:` servers by itself; a server given by name is added here by the application
44    /// once resolved.
45    pub route_via: Vec<IpAddr>,
46    /// At most one address of each family (off by default). A lite agent's: RFC 8445 section
47    /// 5.2, "It is NOT RECOMMENDED to include more than one candidate per address family"
48    /// (RFC8445-5.2-2); a `PeerDriver` whose connection is lite applies it by itself.
49    pub one_per_family: bool,
50}
51
52impl AddressSelection {
53    /// The default route's interface (RFC 8828 Mode 2), no limit, no loopback.
54    pub fn new() -> Self {
55        Self::default()
56    }
57
58    /// With the user's consent (RFC 8828 Mode 1: every interface), or without (Mode 2).
59    #[must_use]
60    pub fn with_user_consent(mut self, consent: bool) -> Self {
61        self.user_consent = consent;
62        self
63    }
64
65    /// With routes taken towards these addresses ([`route_via`](Self::route_via)).
66    #[must_use]
67    pub fn with_route_via(mut self, addresses: Vec<IpAddr>) -> Self {
68        self.route_via = addresses;
69        self
70    }
71
72    /// One address of each family at most ([`one_per_family`](Self::one_per_family)).
73    #[must_use]
74    pub fn with_one_per_family(mut self, on: bool) -> Self {
75        self.one_per_family = on;
76        self
77    }
78
79    /// With `filter`.
80    #[must_use]
81    pub fn with_filter(mut self, filter: AddressFilter) -> Self {
82        self.filter = filter;
83        self
84    }
85
86    /// With a limit on the number of addresses.
87    #[must_use]
88    pub fn with_max_addresses(mut self, max: usize) -> Self {
89        self.max_addresses = Some(max);
90        self
91    }
92
93    /// With loopback addresses when nothing else passes.
94    #[must_use]
95    pub fn with_loopback_when_alone(mut self, on: bool) -> Self {
96        self.loopback_when_alone = on;
97        self
98    }
99
100    /// The addresses `runtime`'s host has now, selected ([`select_addresses`]); `in_use`: the
101    /// addresses gathered on now (a deprecated one among them is kept).
102    ///
103    /// # Errors
104    ///
105    /// The interfaces could not be listed.
106    pub fn select(&self, runtime: &dyn Runtime, in_use: &[IpAddr]) -> io::Result<Vec<IpAddr>> {
107        let interfaces = runtime.interfaces()?;
108        Ok(select_addresses(
109            &interfaces,
110            self.routes(runtime),
111            in_use,
112            self,
113        ))
114    }
115
116    /// The route source of each family (`[IPv6, IPv4]`): towards the first
117    /// [`route_via`](Self::route_via) address of the family that has a route, else the default
118    /// route's ([`Runtime::preferred_source`]).
119    pub fn routes(&self, runtime: &dyn Runtime) -> [Option<IpAddr>; 2] {
120        let route = |ipv6: bool| {
121            self.route_via
122                .iter()
123                .filter(|ip| ip.is_ipv6() == ipv6)
124                .find_map(|ip| runtime.route_source(*ip))
125                .or_else(|| runtime.preferred_source(ipv6))
126        };
127        [route(true), route(false)]
128    }
129}
130
131/// IPv4-compatible IPv6 (`::a.b.c.d`, deprecated by RFC 4291 section 2.5.5.1).
132fn is_v4_compatible(ip: Ipv6Addr) -> bool {
133    let s = ip.segments();
134    s[..6] == [0; 6] && !ip.is_unspecified() && !ip.is_loopback()
135}
136
137/// IPv6 site-local (`fec0::/10`, deprecated by RFC 3879).
138fn is_site_local(ip: Ipv6Addr) -> bool {
139    ip.segments()[0] & 0xffc0 == 0xfec0
140}
141
142/// IPv4-mapped IPv6 (`::ffff:a.b.c.d`).
143fn is_v4_mapped(ip: Ipv6Addr) -> bool {
144    ip.to_ipv4_mapped().is_some()
145}
146
147/// An interface identifier derived from a hardware address (modified EUI-64, RFC 4291
148/// appendix A: `ff:fe` in the middle): an address that allows location tracking (RFC 7721
149/// section 3).
150fn is_eui64(ip: Ipv6Addr) -> bool {
151    let o = ip.octets();
152    o[11] == 0xff && o[12] == 0xfe
153}
154
155fn is_v4_link_local(ip: Ipv4Addr) -> bool {
156    ip.is_link_local()
157}
158
159/// The first `len` bits of `ip` (an IPv6 network prefix).
160fn prefix(ip: Ipv6Addr, len: u8) -> u128 {
161    let len = u32::from(len.min(128));
162    if len == 0 {
163        0
164    } else {
165        u128::from(ip) & (u128::MAX << (128 - len))
166    }
167}
168
169/// The local addresses to gather on, most preferred first, from `interfaces` (the host's,
170/// [`crate::runtime::Runtime::interfaces`]), the routing table's source address of each family
171/// (`[IPv6, IPv4]`, [`AddressSelection::routes`]: the default route's, or the route towards the
172/// enterprise TURN server) and the addresses gathered on now (`in_use`).
173///
174/// - **Interfaces** (RFC 8828 section 5.2): only those the routing table picks, the interfaces
175///   holding the route source addresses (Mode 2), unless [`AddressSelection::user_consent`]
176///   (Mode 1). Without a route, Mode 2 finds nothing.
177/// - **Filter**: an address must pass [`AddressSelection::filter`] ([`AddressFilter::keeps`]:
178///   no unspecified or multicast address; loopback and IPv6 link-local only when the filter
179///   asks; its name and address filters; only its bind addresses when it names some). IPv4
180///   link-local (169.254/16) follows `include_link_local` too.
181/// - **RFC 8445 section 5.1.1.1**: no loopback address (`MUST NOT`, unless the filter asks for
182///   them, or [`AddressSelection::loopback_when_alone`] and nothing else passes); no
183///   IPv4-compatible IPv6 and no IPv6 site-local address (`MUST NOT`); no IPv4-mapped IPv6
184///   address unless the host has no IPv4 address (`SHOULD NOT` "unless ... IPv6-only"); where
185///   an interface has a temporary address (RFC 8981, an address that prevents location
186///   tracking, RFC 7721) in a prefix, no address of that interface and prefix that allows
187///   tracking (`MUST NOT`), and no IPv6 link-local address at all (`MUST NOT`).
188/// - **RFC 8835 section 3.3**: no deprecated temporary IPv6 address unless it is in use
189///   (`SHOULD`); where the host has a temporary IPv6 address, no permanent IPv6 address of the
190///   same (global) scope on any interface or prefix (`SHOULD`).
191/// - **One IPv6 address per interface and prefix** (a /64 when the prefix is unknown): the
192///   temporary one the system uses as its source, else a temporary one, else one not derived
193///   from the hardware address (EUI-64), else the first. libwebrtc does the same: one IPv6
194///   address per network (`Network::GetBestIP` in `rtc_base/network.cc`), a temporary one
195///   first.
196/// - **Order** (it becomes the candidates' local preference, RFC 8445 section 5.1.2.1): the
197///   preferred source addresses first, IPv6 before IPv4 (RFC 8421 section 4), then the others
198///   in the system's order, the families interleaved (RFC 8421 section 4).
199/// - [`AddressSelection::max_addresses`], keeping one of each family that has any;
200///   [`AddressSelection::one_per_family`]: the first of each family.
201pub fn select_addresses(
202    interfaces: &[LocalInterface],
203    preferred: [Option<IpAddr>; 2],
204    in_use: &[IpAddr],
205    selection: &AddressSelection,
206) -> Vec<IpAddr> {
207    let filter = &selection.filter;
208    let passes = |i: &LocalInterface| {
209        if !filter.bind_addresses.is_empty() && !filter.bind_addresses.contains(&i.ip) {
210            return false;
211        }
212        if !filter.keeps(Some(&i.name), i.ip) {
213            return false;
214        }
215        match i.ip {
216            IpAddr::V4(v4) => !is_v4_link_local(v4) || filter.include_link_local,
217            IpAddr::V6(v6) => !is_v4_compatible(v6) && !is_site_local(v6),
218        }
219    };
220    let mut usable: Vec<&LocalInterface> = interfaces.iter().filter(|i| passes(i)).collect();
221    if !selection.user_consent {
222        // Mode 2: the interfaces of the default route.
223        let default_route: Vec<&str> = interfaces
224            .iter()
225            .filter(|i| preferred.contains(&Some(i.ip)))
226            .map(|i| i.name.as_str())
227            .collect();
228        usable.retain(|i| default_route.contains(&i.name.as_str()));
229    }
230    if usable.is_empty() && selection.loopback_when_alone {
231        let loopback = AddressFilter {
232            include_loopback: true,
233            ..filter.clone()
234        };
235        usable = interfaces
236            .iter()
237            .filter(|i| i.ip.is_loopback() && loopback.keeps(Some(&i.name), i.ip))
238            .collect();
239    }
240    // IPv4-mapped IPv6 only on a host without IPv4.
241    let has_v4 = usable.iter().any(|i| i.ip.is_ipv4());
242    usable.retain(|i| !matches!(i.ip, IpAddr::V6(v6) if is_v4_mapped(v6) && has_v4));
243    // RFC 8835 section 3.3: no deprecated temporary address that is not in use.
244    usable.retain(|i| !(i.temporary && i.deprecated && !in_use.contains(&i.ip)));
245    // A temporary address anywhere: no IPv6 link-local at all.
246    if usable.iter().any(|i| i.temporary) {
247        usable.retain(|i| !matches!(i.ip, IpAddr::V6(v6) if v6.is_unicast_link_local()));
248        // RFC 8835 section 3.3: no permanent address of the temporary one's scope.
249        usable.retain(|i| !i.ip.is_ipv6() || i.temporary);
250    }
251    // One IPv6 address per interface and prefix.
252    let preferred_v6 = preferred[0];
253    let mut chosen: Vec<IpAddr> = Vec::new();
254    let mut groups_done: Vec<(String, u128)> = Vec::new();
255    for i in &usable {
256        let IpAddr::V6(v6) = i.ip else {
257            if !chosen.contains(&i.ip) {
258                chosen.push(i.ip);
259            }
260            continue;
261        };
262        let len = i.prefix_len.unwrap_or(64);
263        let key = (i.name.clone(), prefix(v6, len));
264        if groups_done.contains(&key) {
265            continue;
266        }
267        groups_done.push(key.clone());
268        let group: Vec<&LocalInterface> = usable
269            .iter()
270            .copied()
271            .filter(|j| {
272                matches!(j.ip, IpAddr::V6(w) if j.name == key.0
273                    && prefix(w, j.prefix_len.unwrap_or(64)) == key.1)
274            })
275            .collect();
276        let best = group
277            .iter()
278            .find(|j| j.temporary && Some(j.ip) == preferred_v6)
279            .or_else(|| group.iter().find(|j| j.temporary))
280            .or_else(|| {
281                group
282                    .iter()
283                    .find(|j| matches!(j.ip, IpAddr::V6(w) if !is_eui64(w)))
284            })
285            .or_else(|| group.first());
286        if let Some(best) = best {
287            chosen.push(best.ip);
288        }
289    }
290    // Order: the preferred sources (IPv6 first), then the rest, families interleaved.
291    let mut ordered: Vec<IpAddr> = Vec::new();
292    for p in preferred.iter().flatten() {
293        if chosen.contains(p) {
294            ordered.push(*p);
295        }
296    }
297    let rest: Vec<IpAddr> = chosen
298        .into_iter()
299        .filter(|ip| !ordered.contains(ip))
300        .collect();
301    let (mut v6, mut v4): (Vec<IpAddr>, Vec<IpAddr>) = rest.into_iter().partition(IpAddr::is_ipv6);
302    v6.reverse();
303    v4.reverse();
304    loop {
305        let a = v6.pop();
306        let b = v4.pop();
307        if a.is_none() && b.is_none() {
308            break;
309        }
310        ordered.extend(a);
311        ordered.extend(b);
312    }
313    if let Some(max) = selection.max_addresses {
314        ordered = cap(ordered, max);
315    }
316    if selection.one_per_family {
317        let mut seen = [false; 2];
318        ordered.retain(|ip| !std::mem::replace(&mut seen[usize::from(ip.is_ipv6())], true));
319    }
320    ordered
321}
322
323/// The first `max` of `ordered`, with one address of each family that has one kept in.
324fn cap(ordered: Vec<IpAddr>, max: usize) -> Vec<IpAddr> {
325    if ordered.len() <= max {
326        return ordered;
327    }
328    let mut kept: Vec<IpAddr> = ordered.iter().copied().take(max).collect();
329    for family_v6 in [true, false] {
330        if !kept.iter().any(|ip| ip.is_ipv6() == family_v6)
331            && let Some(first) = ordered.iter().find(|ip| ip.is_ipv6() == family_v6)
332        {
333            // Replace the last address of the family that has more than one.
334            let other = !family_v6;
335            if kept.iter().filter(|ip| ip.is_ipv6() == other).count() > 1
336                && let Some(at) = kept.iter().rposition(|ip| ip.is_ipv6() == other)
337            {
338                kept[at] = *first;
339            }
340        }
341    }
342    // Keep the original order.
343    ordered.into_iter().filter(|ip| kept.contains(ip)).collect()
344}
345
346#[cfg(test)]
347mod tests {
348    use super::*;
349
350    fn v4(s: &str) -> IpAddr {
351        IpAddr::V4(s.parse().unwrap())
352    }
353    fn v6(s: &str) -> IpAddr {
354        IpAddr::V6(s.parse().unwrap())
355    }
356    fn on(name: &str, ip: IpAddr) -> LocalInterface {
357        LocalInterface::new(name, ip)
358    }
359    fn mode1() -> AddressSelection {
360        AddressSelection::new().with_user_consent(true)
361    }
362    fn select(interfaces: &[LocalInterface]) -> Vec<IpAddr> {
363        select_addresses(interfaces, [None, None], &[], &mode1())
364    }
365
366    // RFC8445-5.1.1.1-4: loopback addresses are not candidate addresses.
367    #[test]
368    fn rfc8445_5_1_1_1_4_loopback_addresses_are_not_selected() {
369        let all = [
370            on("lo", v4("127.0.0.1")),
371            on("lo", v6("::1")),
372            on("eth0", v4("192.168.1.10")),
373        ];
374        assert_eq!(select(&all), vec![v4("192.168.1.10")]);
375        // Only with the setting, and only when nothing else passes.
376        let alone = [on("lo", v4("127.0.0.1"))];
377        assert!(select(&alone).is_empty());
378        let fallback = mode1().with_loopback_when_alone(true);
379        assert_eq!(
380            select_addresses(&alone, [None, None], &[], &fallback),
381            vec![v4("127.0.0.1")]
382        );
383        assert_eq!(
384            select_addresses(&all, [None, None], &[], &fallback),
385            vec![v4("192.168.1.10")]
386        );
387    }
388
389    // RFC8445-5.1.1.1-5: no IPv4-compatible IPv6, no IPv6 site-local.
390    #[test]
391    fn rfc8445_5_1_1_1_5_v4_compatible_and_site_local_ipv6_are_not_selected() {
392        let all = [
393            on("eth0", v6("::192.0.2.33")),
394            on("eth0", v6("fec0::1")),
395            on("eth0", v6("2001:db8:1::10")),
396        ];
397        assert_eq!(select(&all), vec![v6("2001:db8:1::10")]);
398    }
399
400    // RFC8445-5.1.1.1-6: no IPv4-mapped IPv6 unless the host has no IPv4.
401    #[test]
402    fn rfc8445_5_1_1_1_6_v4_mapped_ipv6_only_on_an_ipv6_only_host() {
403        let mapped = on("eth0", v6("::ffff:192.0.2.1"));
404        let dual = [mapped.clone(), on("eth0", v4("192.168.1.10"))];
405        assert_eq!(select(&dual), vec![v4("192.168.1.10")]);
406        assert_eq!(select(&[mapped]), vec![v6("::ffff:192.0.2.1")]);
407    }
408
409    // RFC8445-5.1.1.1-7: with a temporary (privacy) address in a prefix, the trackable
410    // addresses of that interface and prefix are not gathered; RFC8835-3.3-1: nor any
411    // permanent IPv6 address of the same scope elsewhere.
412    #[test]
413    fn rfc8445_5_1_1_1_7_a_temporary_address_hides_the_trackable_ones_of_its_prefix() {
414        let all = [
415            on("eth0", v6("2001:db8:1::211:22ff:fe33:4455")).with_prefix_len(64),
416            on("eth0", v6("2001:db8:1::a1b2:c3d4:e5f6:1234"))
417                .with_prefix_len(64)
418                .with_temporary(true),
419            on("eth0", v4("192.168.1.10")),
420        ];
421        assert_eq!(
422            select(&all),
423            vec![v6("2001:db8:1::a1b2:c3d4:e5f6:1234"), v4("192.168.1.10")]
424        );
425        // Without the temporary address the permanent one is gathered.
426        assert_eq!(
427            select(&[all[0].clone()]),
428            vec![v6("2001:db8:1::211:22ff:fe33:4455")]
429        );
430    }
431
432    // RFC8835-3.3-1: "discard permanent IPv6 addresses where a temporary address of the same
433    // scope exists", on another prefix or interface too.
434    #[test]
435    fn rfc8835_3_3_1_a_temporary_address_hides_every_permanent_global_one() {
436        let all = [
437            on("eth0", v6("2001:db8:1::a1b2:c3d4:e5f6:1234"))
438                .with_prefix_len(64)
439                .with_temporary(true),
440            on("eth0", v6("2001:db8:2::10")).with_prefix_len(64),
441            on("wlan0", v6("2001:db8:9::5")).with_prefix_len(64),
442        ];
443        assert_eq!(select(&all), vec![v6("2001:db8:1::a1b2:c3d4:e5f6:1234")]);
444    }
445
446    // RFC8828-5.2-7, -8, -4: by default (no consent) only the default route's interface, with
447    // its private addresses; every interface only when the application says so.
448    #[test]
449    fn rfc8828_5_2_mode_2_by_default_mode_1_on_request() {
450        let interfaces = [
451            on("eth0", v4("192.168.1.10")),
452            on("eth0", v6("fd00::10")),
453            on("vpn0", v4("10.8.0.2")),
454        ];
455        let preferred = [None, Some(v4("192.168.1.10"))];
456        assert_eq!(
457            select_addresses(&interfaces, preferred, &[], &AddressSelection::new()),
458            vec![v4("192.168.1.10"), v6("fd00::10")]
459        );
460        assert!(
461            select_addresses(&interfaces, [None, None], &[], &AddressSelection::new()).is_empty(),
462            "no default route: nothing"
463        );
464        assert_eq!(
465            select_addresses(&interfaces, preferred, &[], &mode1()),
466            vec![v4("192.168.1.10"), v6("fd00::10"), v4("10.8.0.2")]
467        );
468    }
469
470    // RFC8445-5.1.1.1-8: with privacy addresses, no IPv6 link-local candidates, even when the
471    // filter lets link-local addresses through.
472    #[test]
473    fn rfc8445_5_1_1_1_8_no_link_local_beside_a_temporary_address() {
474        let filter = AddressFilter {
475            include_link_local: true,
476            ..Default::default()
477        };
478        let selection = mode1().with_filter(filter);
479        let link_local = on("eth0", v6("fe80::1"));
480        let temporary = on("eth0", v6("2001:db8:1::abcd")).with_temporary(true);
481        assert_eq!(
482            select_addresses(
483                std::slice::from_ref(&link_local),
484                [None, None],
485                &[],
486                &selection
487            ),
488            vec![v6("fe80::1")]
489        );
490        assert_eq!(
491            select_addresses(&[link_local, temporary], [None, None], &[], &selection),
492            vec![v6("2001:db8:1::abcd")]
493        );
494    }
495
496    // RFC8445-5.1.1.1-1: a host candidate on each address of the host (one per IPv6 network).
497    #[test]
498    fn rfc8445_5_1_1_1_1_every_interface_gets_an_address_one_ipv6_per_prefix() {
499        let all = [
500            on("eth0", v4("192.168.1.10")),
501            on("eth0", v6("2001:db8:1::10")),
502            on("eth0", v6("2001:db8:1::11")),
503            on("wlan0", v4("10.0.0.5")),
504            on("wlan0", v6("2001:db8:9::5")),
505        ];
506        assert_eq!(
507            select(&all),
508            vec![
509                v6("2001:db8:1::10"),
510                v4("192.168.1.10"),
511                v6("2001:db8:9::5"),
512                v4("10.0.0.5"),
513            ]
514        );
515    }
516
517    // RFC 8421 section 4: the default route's addresses first, IPv6 before IPv4.
518    #[test]
519    fn the_preferred_sources_come_first_ipv6_before_ipv4() {
520        let all = [
521            on("eth0", v4("192.168.1.10")),
522            on("wlan0", v4("10.0.0.5")),
523            on("wlan0", v6("2001:db8:9::5")),
524        ];
525        let preferred = [Some(v6("2001:db8:9::5")), Some(v4("10.0.0.5"))];
526        assert_eq!(
527            select_addresses(
528                &all,
529                preferred,
530                &[],
531                &super::AddressSelection::new().with_user_consent(true)
532            ),
533            vec![v6("2001:db8:9::5"), v4("10.0.0.5"), v4("192.168.1.10")]
534        );
535    }
536
537    // RFC8835-3.3-2: a deprecated temporary address is discarded unless it is in use (the
538    // connection gathered on it before it was deprecated).
539    #[test]
540    fn rfc8835_3_3_2_a_deprecated_temporary_address_only_while_in_use() {
541        let old = v6("2001:db8:1::aaaa");
542        let new = v6("2001:db8:1::bbbb");
543        let all = [
544            on("eth0", old)
545                .with_prefix_len(64)
546                .with_temporary(true)
547                .with_deprecated(true),
548            on("eth0", new).with_prefix_len(64).with_temporary(true),
549            on("eth1", v6("2001:db8:2::cccc"))
550                .with_prefix_len(64)
551                .with_temporary(true)
552                .with_deprecated(true),
553        ];
554        assert_eq!(select(&all), vec![new], "deprecated ones are discarded");
555        let picked = select_addresses(&all, [None, None], &[old], &mode1());
556        assert!(picked.contains(&old), "kept while in use: {picked:?}");
557        assert!(!picked.contains(&v6("2001:db8:2::cccc")));
558    }
559
560    // RFC8445-5.2-2: a lite agent includes at most one candidate per address family.
561    #[test]
562    fn rfc8445_5_2_2_one_address_per_family() {
563        let all = [
564            on("eth0", v4("192.168.1.10")),
565            on("eth0", v6("2001:db8:1::10")),
566            on("wlan0", v4("10.0.0.5")),
567            on("wlan0", v6("2001:db8:9::5")),
568        ];
569        assert_eq!(
570            select_addresses(&all, [None, None], &[], &mode1().with_one_per_family(true)),
571            vec![v6("2001:db8:1::10"), v4("192.168.1.10")]
572        );
573    }
574
575    // RFC8828-5.2-2, -3: Mode 2 follows the routing table, towards the enterprise TURN server
576    // when there is one: the interface of the route to it is gathered on, not the default
577    // route's.
578    #[test]
579    fn rfc8828_5_2_2_and_3_mode_2_takes_the_route_towards_the_turn_server() {
580        #[derive(Debug)]
581        struct Routes;
582        impl crate::runtime::Runtime for Routes {
583            fn spawn(
584                &self,
585                _: crate::runtime::BoxFuture<'static, ()>,
586            ) -> Box<dyn crate::runtime::JoinHandle> {
587                unimplemented!()
588            }
589            fn now(&self) -> std::time::Instant {
590                std::time::Instant::now()
591            }
592            fn sleep_until(&self, _: std::time::Instant) -> crate::runtime::BoxFuture<'static, ()> {
593                unimplemented!()
594            }
595            fn bind_udp(
596                &self,
597                _: std::net::SocketAddr,
598            ) -> io::Result<std::sync::Arc<dyn crate::runtime::AsyncUdpSocket>> {
599                unimplemented!()
600            }
601            fn bind_udp_multicast(
602                &self,
603                _: &crate::runtime::MulticastConfig,
604            ) -> io::Result<std::sync::Arc<dyn crate::runtime::AsyncUdpSocket>> {
605                unimplemented!()
606            }
607            fn listen_tcp(
608                &self,
609                _: std::net::SocketAddr,
610                _: bool,
611            ) -> io::Result<std::sync::Arc<dyn crate::runtime::AsyncTcpListener>> {
612                unimplemented!()
613            }
614            fn connect_tcp(
615                &self,
616                _: std::net::SocketAddr,
617                _: std::net::SocketAddr,
618                _: bool,
619            ) -> crate::runtime::BoxFuture<
620                'static,
621                io::Result<std::sync::Arc<dyn crate::runtime::AsyncTcpStream>>,
622            > {
623                unimplemented!()
624            }
625            fn resolve_host(
626                &self,
627                _: &str,
628                _: u16,
629            ) -> crate::runtime::BoxFuture<'static, io::Result<Vec<std::net::SocketAddr>>>
630            {
631                unimplemented!()
632            }
633            fn block_on(&self, _: std::pin::Pin<Box<dyn std::future::Future<Output = ()> + '_>>) {
634                unimplemented!()
635            }
636            fn interfaces(&self) -> io::Result<Vec<LocalInterface>> {
637                Ok(vec![
638                    on("eth0", v4("192.168.1.10")),
639                    on("corp0", v4("10.20.0.7")),
640                ])
641            }
642            fn preferred_source(&self, ipv6: bool) -> Option<IpAddr> {
643                (!ipv6).then(|| v4("192.168.1.10"))
644            }
645            fn route_source(&self, destination: IpAddr) -> Option<IpAddr> {
646                // The enterprise TURN server is reached over corp0.
647                (destination == v4("10.99.0.1")).then(|| v4("10.20.0.7"))
648            }
649        }
650        let default_route = AddressSelection::new().select(&Routes, &[]).unwrap();
651        assert_eq!(default_route, vec![v4("192.168.1.10")]);
652        let via_turn = AddressSelection::new()
653            .with_route_via(vec![v4("10.99.0.1")])
654            .select(&Routes, &[])
655            .unwrap();
656        assert_eq!(via_turn, vec![v4("10.20.0.7")]);
657        // A TURN server without a route: the default route's.
658        let unreachable = AddressSelection::new()
659            .with_route_via(vec![v4("10.250.0.1")])
660            .select(&Routes, &[])
661            .unwrap();
662        assert_eq!(unreachable, vec![v4("192.168.1.10")]);
663    }
664
665    #[test]
666    fn a_limit_keeps_one_address_of_each_family() {
667        let all = [
668            on("a", v4("10.0.0.1")),
669            on("b", v4("10.0.1.1")),
670            on("c", v4("10.0.2.1")),
671            on("d", v6("2001:db8:4::1")),
672        ];
673        let selection = mode1().with_max_addresses(2);
674        let picked = select_addresses(&all, [Some(v4("10.0.0.1")), None], &[], &selection);
675        assert_eq!(picked.len(), 2);
676        assert!(picked.contains(&v4("10.0.0.1")));
677        assert!(picked.contains(&v6("2001:db8:4::1")));
678    }
679
680    #[test]
681    fn ipv4_link_local_follows_the_filter() {
682        let all = [on("eth0", v4("169.254.3.4"))];
683        assert!(select(&all).is_empty());
684        let selection = super::AddressSelection::new()
685            .with_user_consent(true)
686            .with_filter(AddressFilter {
687                include_link_local: true,
688                ..Default::default()
689            });
690        assert_eq!(
691            select_addresses(&all, [None, None], &[], &selection),
692            vec![v4("169.254.3.4")]
693        );
694    }
695}