netcfg/
dhcpv6.rs

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
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::collections::{HashMap, HashSet};

use {
    fidl_fuchsia_net as fnet, fidl_fuchsia_net_dhcpv6 as fnet_dhcpv6,
    fidl_fuchsia_net_dhcpv6_ext as fnet_dhcpv6_ext, fidl_fuchsia_net_ext as fnet_ext,
    fidl_fuchsia_net_name as fnet_name,
};

use anyhow::Context as _;
use async_utils::hanging_get::client::HangingGetStream;
use async_utils::stream::{StreamMap, Tagged};
use dns_server_watcher::{DnsServers, DnsServersUpdateSource};
use futures::future::TryFutureExt as _;
use futures::stream::{Stream, TryStreamExt as _};
use tracing::warn;

use crate::{dns, errors, DnsServerWatchers, InterfaceId};

// TODO(https://fxbug.dev/329099228): Switch to using DUID-LLT and persisting it to disk.
pub(super) fn duid(mac: fnet_ext::MacAddress) -> fnet_dhcpv6::Duid {
    fnet_dhcpv6::Duid::LinkLayerAddress(fnet_dhcpv6::LinkLayerAddress::Ethernet(mac.into()))
}

#[derive(Copy, Clone, Debug, PartialEq)]
pub(super) struct PrefixOnInterface {
    interface_id: InterfaceId,
    prefix: net_types::ip::Subnet<net_types::ip::Ipv6Addr>,
    lifetimes: Lifetimes,
}

pub(super) type Prefixes = HashMap<net_types::ip::Subnet<net_types::ip::Ipv6Addr>, Lifetimes>;
pub(super) type InterfaceIdTaggedPrefixesStream = Tagged<InterfaceId, PrefixesStream>;
pub(super) type PrefixesStreamMap = StreamMap<InterfaceId, InterfaceIdTaggedPrefixesStream>;

#[derive(Debug)]
pub(super) struct ClientState {
    pub(super) sockaddr: fnet::Ipv6SocketAddress,
    pub(super) prefixes: Prefixes,
}

impl ClientState {
    pub(super) fn new(sockaddr: fnet::Ipv6SocketAddress) -> Self {
        Self { sockaddr, prefixes: Default::default() }
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub(super) struct Lifetimes {
    preferred_until: zx::MonotonicInstant,
    valid_until: zx::MonotonicInstant,
}

impl Into<fnet_dhcpv6::Lifetimes> for Lifetimes {
    fn into(self) -> fnet_dhcpv6::Lifetimes {
        let Self { preferred_until, valid_until } = self;
        fnet_dhcpv6::Lifetimes {
            preferred_until: preferred_until.into_nanos(),
            valid_until: valid_until.into_nanos(),
        }
    }
}

pub(super) type PrefixesStream =
    HangingGetStream<fnet_dhcpv6::ClientProxy, Vec<fnet_dhcpv6::Prefix>>;

pub(super) fn from_fidl_prefixes(
    fidl_prefixes: &[fnet_dhcpv6::Prefix],
) -> Result<Prefixes, anyhow::Error> {
    let prefixes = fidl_prefixes
        .iter()
        .map(
            |&fnet_dhcpv6::Prefix {
                 prefix:
                     fnet::Ipv6AddressWithPrefix { addr: fnet::Ipv6Address { addr }, prefix_len },
                 lifetimes: fnet_dhcpv6::Lifetimes { valid_until, preferred_until },
             }| {
                let subnet = net_types::ip::Subnet::new(
                    net_types::ip::Ipv6Addr::from_bytes(addr),
                    prefix_len,
                )
                .map_err(|e| anyhow::anyhow!("subnet parsing error: {:?}", e))?;
                if valid_until == 0 {
                    return Err(anyhow::anyhow!(
                        "received DHCPv6 prefix {:?} with valid-until time of 0",
                        subnet
                    ));
                }
                if preferred_until == 0 {
                    return Err(anyhow::anyhow!(
                        "received DHCPv6 prefix {:?} with preferred-until time of 0",
                        subnet
                    ));
                }
                Ok((
                    subnet,
                    Lifetimes {
                        valid_until: zx::MonotonicInstant::from_nanos(valid_until),
                        preferred_until: zx::MonotonicInstant::from_nanos(preferred_until),
                    },
                ))
            },
        )
        .collect::<Result<Prefixes, _>>()?;
    if prefixes.len() != fidl_prefixes.len() {
        return Err(anyhow::anyhow!(
            "DHCPv6 prefixes {:?} contains duplicate prefix",
            fidl_prefixes
        ));
    }
    Ok(prefixes)
}

/// Start a DHCPv6 client for the specified host interface.
pub(super) fn start_client(
    dhcpv6_client_provider: &fnet_dhcpv6::ClientProviderProxy,
    interface_id: InterfaceId,
    sockaddr: fnet::Ipv6SocketAddress,
    duid: fnet_dhcpv6::Duid,
    prefix_delegation_config: Option<fnet_dhcpv6::PrefixDelegationConfig>,
) -> Result<
    (impl Stream<Item = Result<Vec<fnet_name::DnsServer_>, fidl::Error>>, PrefixesStream),
    errors::Error,
> {
    let stateful = prefix_delegation_config.is_some();
    let params = fnet_dhcpv6_ext::NewClientParams {
        interface_id: interface_id.get(),
        address: sockaddr,
        config: fnet_dhcpv6_ext::ClientConfig {
            information_config: fnet_dhcpv6_ext::InformationConfig { dns_servers: true },
            non_temporary_address_config: Default::default(),
            prefix_delegation_config,
        },
        duid: stateful.then_some(duid),
    };
    let (client, server) = fidl::endpoints::create_proxy::<fnet_dhcpv6::ClientMarker>();

    // Not all environments may have a DHCPv6 client service so we consider this a
    // non-fatal error.
    dhcpv6_client_provider
        .new_client(&params.into(), server)
        .context("error creating new DHCPv6 client")
        .map_err(errors::Error::NonFatal)?;

    let dns_servers_stream = futures::stream::try_unfold(client.clone(), move |proxy| {
        proxy.watch_servers().map_ok(move |s| Some((s, proxy)))
    });
    let prefixes_stream =
        PrefixesStream::new_eager_with_fn_ptr(client, fnet_dhcpv6::ClientProxy::watch_prefixes);

    Ok((dns_servers_stream, prefixes_stream))
}

fn get_suitable_dhcpv6_prefix(
    current_prefix: Option<PrefixOnInterface>,
    interface_states: &HashMap<InterfaceId, crate::InterfaceState>,
    allowed_upstream_device_classes: &HashSet<crate::DeviceClass>,
    interface_config: AcquirePrefixInterfaceConfig,
) -> Option<PrefixOnInterface> {
    if let Some(PrefixOnInterface { interface_id, prefix, lifetimes: _ }) = current_prefix {
        let crate::InterfaceState { config, .. } =
            interface_states.get(&interface_id).unwrap_or_else(|| {
                panic!(
                    "interface {} cannot be found but provides current prefix = {:?}",
                    interface_id, current_prefix,
                )
            });
        match config {
            crate::InterfaceConfigState::Host(crate::HostInterfaceState {
                dhcpv4_client: _,
                dhcpv6_client_state,
                dhcpv6_pd_config: _,
                interface_admin_auth: _,
            }) => {
                let Some(ClientState { prefixes, sockaddr: _ }) = dhcpv6_client_state.as_ref()
                else {
                    // It's surprising that the interface doesn't have an active DHCPv6 client
                    // but has a DHCPv6 prefix, but this can happen during interface teardown.
                    return None;
                };
                if let Some(lifetimes) = prefixes.get(&prefix) {
                    return Some(PrefixOnInterface { interface_id, prefix, lifetimes: *lifetimes });
                }
            }
            crate::InterfaceConfigState::WlanAp(wlan_ap_state) => {
                panic!(
                    "interface {} not expected to be WLAN AP with state: {:?}",
                    interface_id, wlan_ap_state,
                );
            }
        }
    }

    interface_states
        .iter()
        .filter_map(|(interface_id, crate::InterfaceState { config, device_class, .. })| {
            let prefixes = match config {
                crate::InterfaceConfigState::Host(crate::HostInterfaceState {
                    dhcpv4_client: _,
                    dhcpv6_client_state,
                    dhcpv6_pd_config: _,
                    interface_admin_auth: _,
                }) => {
                    if let Some(ClientState { prefixes, sockaddr: _ }) = dhcpv6_client_state {
                        prefixes
                    } else {
                        return None;
                    }
                }
                crate::InterfaceConfigState::WlanAp(crate::WlanApInterfaceState {}) => {
                    return None;
                }
            };
            match interface_config {
                AcquirePrefixInterfaceConfig::Upstreams => {
                    allowed_upstream_device_classes.contains(&device_class)
                }
                AcquirePrefixInterfaceConfig::Id(want_id) => interface_id.get() == want_id,
            }
            .then(|| {
                prefixes.iter().map(|(&prefix, &lifetimes)| PrefixOnInterface {
                    interface_id: *interface_id,
                    prefix,
                    lifetimes,
                })
            })
        })
        .flatten()
        .max_by(
            |PrefixOnInterface {
                 interface_id: _,
                 prefix: _,
                 lifetimes:
                     Lifetimes { preferred_until: preferred_until1, valid_until: valid_until1 },
             },
             PrefixOnInterface {
                 interface_id: _,
                 prefix: _,
                 lifetimes:
                     Lifetimes { preferred_until: preferred_until2, valid_until: valid_until2 },
             }| {
                // Prefer prefixes with the highest preferred lifetime then
                // valid lifetime.
                (preferred_until1, valid_until1).cmp(&(preferred_until2, valid_until2))
            },
        )
}

pub(super) fn maybe_send_watch_prefix_response(
    interface_states: &HashMap<InterfaceId, crate::InterfaceState>,
    allowed_upstream_device_classes: &HashSet<crate::DeviceClass>,
    prefix_provider_handler: Option<&mut PrefixProviderHandler>,
) -> Result<(), anyhow::Error> {
    let PrefixProviderHandler {
        current_prefix,
        interface_config,
        preferred_prefix_len: _,
        watch_prefix_responder,
        prefix_control_request_stream: _,
    } = if let Some(handler) = prefix_provider_handler {
        handler
    } else {
        return Ok(());
    };

    let new_prefix = get_suitable_dhcpv6_prefix(
        *current_prefix,
        interface_states,
        allowed_upstream_device_classes,
        *interface_config,
    );
    if new_prefix == *current_prefix {
        return Ok(());
    }

    if let Some(responder) = watch_prefix_responder.take() {
        responder
            .send(&new_prefix.map_or(
                fnet_dhcpv6::PrefixEvent::Unassigned(fnet_dhcpv6::Empty),
                |PrefixOnInterface { interface_id: _, prefix, lifetimes }| {
                    fnet_dhcpv6::PrefixEvent::Assigned(fnet_dhcpv6::Prefix {
                        prefix: fnet::Ipv6AddressWithPrefix {
                            addr: fnet::Ipv6Address { addr: prefix.network().ipv6_bytes() },
                            prefix_len: prefix.prefix(),
                        },
                        lifetimes: lifetimes.into(),
                    })
                },
            ))
            .context("failed to send PrefixControl.WatchPrefix response")?;
        *current_prefix = new_prefix;
    }

    Ok(())
}

/// Stops the DHCPv6 client running on the specified host interface.
///
/// Any DNS servers learned by the client will be cleared.
pub(super) async fn stop_client(
    lookup_admin: &fnet_name::LookupAdminProxy,
    dns_servers: &mut DnsServers,
    dns_server_watch_responders: &mut dns::DnsServerWatchResponders,
    interface_id: InterfaceId,
    watchers: &mut DnsServerWatchers<'_>,
    prefixes_streams: &mut PrefixesStreamMap,
) {
    let source = DnsServersUpdateSource::Dhcpv6 { interface_id: interface_id.get() };

    // Dropping all fuchsia.net.dhcpv6/Client proxies will stop the DHCPv6 client.
    if let None = watchers.remove(&source) {
        // It's surprising that the DNS Watcher for the interface doesn't exist
        // when the DHCP client is trying to be stopped, but this can happen
        // when multiple futures try to stop the client at the same time.
        warn!(
            "DNS Watcher for key not present; multiple futures stopped DHCPv6 \
            client for key {:?}; interface_id={}",
            source, interface_id
        );
    }
    if let None = prefixes_streams.remove(&interface_id) {
        // It's surprising that the Prefix Stream for the interface doesn't exist
        // when the DHCP client is trying to be stopped, but this can happen
        // when multiple futures try to stop the client at the same time.
        warn!(
            "Prefix Stream for key not present; multiple futures stopped DHCPv6 \
            client for key {:?}; interface_id={}",
            source, interface_id
        );
    }

    dns::update_servers(lookup_admin, dns_servers, dns_server_watch_responders, source, vec![])
        .await
}

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub(super) enum AcquirePrefixInterfaceConfig {
    Upstreams,
    Id(u64),
}

pub(super) struct PrefixProviderHandler {
    pub(super) prefix_control_request_stream: fnet_dhcpv6::PrefixControlRequestStream,
    pub(super) watch_prefix_responder: Option<fnet_dhcpv6::PrefixControlWatchPrefixResponder>,
    pub(super) preferred_prefix_len: Option<u8>,
    /// Interfaces configured to perform PD on.
    pub(super) interface_config: AcquirePrefixInterfaceConfig,
    pub(super) current_prefix: Option<PrefixOnInterface>,
}

impl PrefixProviderHandler {
    pub(super) fn try_next_prefix_control_request(
        &mut self,
    ) -> futures::stream::TryNext<'_, fnet_dhcpv6::PrefixControlRequestStream> {
        self.prefix_control_request_stream.try_next()
    }
}

#[cfg(test)]
mod tests {
    use fidl_fuchsia_net_interfaces_admin as fnet_interfaces_admin;

    use const_unwrap::const_unwrap_option;
    use net_declare::{fidl_socket_addr_v6, net_subnet_v6};
    use test_case::test_case;

    use crate::interface::{generate_identifier, InterfaceNamingIdentifier, ProvisioningAction};
    use crate::{DeviceClass, HostInterfaceState, InterfaceConfigState, InterfaceState};

    use super::*;

    const ALLOWED_UPSTREAM_DEVICE_CLASS: crate::DeviceClass = crate::DeviceClass::Ethernet;
    const DISALLOWED_UPSTREAM_DEVICE_CLASS: crate::DeviceClass = crate::DeviceClass::Virtual;
    const LIFETIMES: Lifetimes = Lifetimes {
        preferred_until: zx::MonotonicInstant::from_nanos(123_000_000_000),
        valid_until: zx::MonotonicInstant::from_nanos(456_000_000_000),
    };
    const RENEWED_LIFETIMES: Lifetimes = Lifetimes {
        preferred_until: zx::MonotonicInstant::from_nanos(777_000_000_000),
        valid_until: zx::MonotonicInstant::from_nanos(888_000_000_000),
    };

    impl InterfaceState {
        fn new_host_with_state(
            interface_naming_id: InterfaceNamingIdentifier,
            control: fidl_fuchsia_net_interfaces_ext::admin::Control,
            device_class: DeviceClass,
            dhcpv6_pd_config: Option<fnet_dhcpv6::PrefixDelegationConfig>,
            dhcpv6_client_state: Option<ClientState>,
            provisioning: ProvisioningAction,
            interface_admin_auth: fnet_interfaces_admin::GrantForInterfaceAuthorization,
        ) -> Self {
            Self {
                interface_naming_id,
                control,
                config: InterfaceConfigState::Host(HostInterfaceState {
                    dhcpv4_client: crate::Dhcpv4ClientState::NotRunning,
                    dhcpv6_client_state,
                    dhcpv6_pd_config,
                    interface_admin_auth,
                }),
                device_class,
                provisioning,
            }
        }
    }

    fn fake_interface_grant() -> fnet_interfaces_admin::GrantForInterfaceAuthorization {
        fnet_interfaces_admin::GrantForInterfaceAuthorization {
            interface_id: 0,
            token: zx::Event::create(),
        }
    }

    #[test_case(
        None,
        [
            (
                DISALLOWED_UPSTREAM_DEVICE_CLASS,
                Some(HashMap::from([(net_subnet_v6!("abcd::/64"), LIFETIMES)])),
            )
        ].into_iter(),
        AcquirePrefixInterfaceConfig::Upstreams,
        None;
        "not_upstream"
    )]
    #[test_case(
        None,
        [
            (
                ALLOWED_UPSTREAM_DEVICE_CLASS,
                Some(HashMap::from([(net_subnet_v6!("abcd::/64"), LIFETIMES)])),
            )
        ].into_iter(),
        AcquirePrefixInterfaceConfig::Upstreams,
        Some(PrefixOnInterface {
            interface_id: const_unwrap_option(InterfaceId::new(1)),
            prefix: net_subnet_v6!("abcd::/64"),
            lifetimes: LIFETIMES,
        });
        "none_to_some"
    )]
    #[test_case(
        Some(PrefixOnInterface {
            interface_id: const_unwrap_option(InterfaceId::new(1)),
            prefix: net_subnet_v6!("abcd::/64"),
            lifetimes: LIFETIMES,
        }),
        [
            (
                ALLOWED_UPSTREAM_DEVICE_CLASS,
                Some(HashMap::from([(net_subnet_v6!("abcd::/64"), LIFETIMES)])),
            )
        ].into_iter(),
        AcquirePrefixInterfaceConfig::Upstreams,
        Some(PrefixOnInterface {
            interface_id: const_unwrap_option(InterfaceId::new(1)),
            prefix: net_subnet_v6!("abcd::/64"),
            lifetimes: LIFETIMES,
        });
        "same"
    )]
    #[test_case(
        Some(PrefixOnInterface {
            interface_id: const_unwrap_option(InterfaceId::new(1)),
            prefix: net_subnet_v6!("abcd::/64"),
            lifetimes: LIFETIMES,
        }),
        [
            (
                ALLOWED_UPSTREAM_DEVICE_CLASS,
                Some(HashMap::from([(net_subnet_v6!("abcd::/64"), RENEWED_LIFETIMES)])),
            )
        ].into_iter(),
        AcquirePrefixInterfaceConfig::Upstreams,
        Some(PrefixOnInterface {
            interface_id: const_unwrap_option(InterfaceId::new(1)),
            prefix: net_subnet_v6!("abcd::/64"),
            lifetimes: RENEWED_LIFETIMES,
        });
        "lifetime_changed"
    )]
    #[test_case(
        Some(PrefixOnInterface {
            interface_id: const_unwrap_option(InterfaceId::new(1)),
            prefix: net_subnet_v6!("abcd::/64"),
            lifetimes: LIFETIMES,
        }),
        [
            (
                ALLOWED_UPSTREAM_DEVICE_CLASS,
                Some(HashMap::new()),
            ),
            (
                ALLOWED_UPSTREAM_DEVICE_CLASS,
                Some(HashMap::from([(net_subnet_v6!("efff::/64"), RENEWED_LIFETIMES)])),
            )
        ].into_iter(),
        AcquirePrefixInterfaceConfig::Upstreams,
        Some(PrefixOnInterface {
            interface_id: const_unwrap_option(InterfaceId::new(2)),
            prefix: net_subnet_v6!("efff::/64"),
            lifetimes: RENEWED_LIFETIMES,
        });
        "different_interface"
    )]
    #[fuchsia::test]
    async fn get_suitable_dhcpv6_prefix(
        current_prefix: Option<PrefixOnInterface>,
        interface_state_iter: impl IntoIterator<Item = (crate::DeviceClass, Option<Prefixes>)>,
        interface_config: AcquirePrefixInterfaceConfig,
        want: Option<PrefixOnInterface>,
    ) {
        let interface_states = (1..)
            .flat_map(InterfaceId::new)
            .zip(interface_state_iter.into_iter().map(|(device_class, prefixes)| {
                let (control, _control_server_end) =
                    fidl_fuchsia_net_interfaces_ext::admin::Control::create_endpoints()
                        .expect("create endpoints");
                InterfaceState::new_host_with_state(
                    generate_identifier(&fidl_fuchsia_net_ext::MacAddress {
                        octets: [0x1, 0x2, 0x3, 0x4, 0x5, 0x6],
                    }),
                    control,
                    device_class,
                    None,
                    prefixes.map(|prefixes| ClientState {
                        sockaddr: fidl_socket_addr_v6!("[fe80::1]:546"),
                        prefixes: prefixes,
                    }),
                    ProvisioningAction::Local,
                    fake_interface_grant(),
                )
            }))
            .collect();
        let allowed_upstream_device_classes = HashSet::from([ALLOWED_UPSTREAM_DEVICE_CLASS]);
        assert_eq!(
            super::get_suitable_dhcpv6_prefix(
                current_prefix,
                &interface_states,
                &allowed_upstream_device_classes,
                interface_config,
            ),
            want
        );
    }
}