dhcpv6_client/
client.rs

1// Copyright 2020 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Implements a DHCPv6 client.
6use std::collections::hash_map::DefaultHasher;
7use std::collections::{HashMap, HashSet};
8use std::hash::{Hash, Hasher};
9use std::net::{IpAddr, SocketAddr};
10use std::ops::Add;
11use std::pin::Pin;
12use std::str::FromStr as _;
13use std::time::Duration;
14
15use fidl::endpoints::{ControlHandle as _, ServerEnd};
16use fidl_fuchsia_net_dhcpv6::{
17    ClientMarker, ClientRequest, ClientRequestStream, ClientWatchAddressResponder,
18    ClientWatchPrefixesResponder, ClientWatchServersResponder, Duid, Empty, Lifetimes,
19    LinkLayerAddress, LinkLayerAddressPlusTime, Prefix, PrefixDelegationConfig,
20    RELAY_AGENT_AND_SERVER_LINK_LOCAL_MULTICAST_ADDRESS, RELAY_AGENT_AND_SERVER_PORT,
21};
22use fidl_fuchsia_net_dhcpv6_ext::{
23    AddressConfig, ClientConfig, InformationConfig, NewClientParams,
24};
25use futures::{Future, FutureExt as _, StreamExt as _, TryStreamExt as _, select, stream};
26use {
27    fidl_fuchsia_net as fnet, fidl_fuchsia_net_ext as fnet_ext, fidl_fuchsia_net_name as fnet_name,
28    fuchsia_async as fasync,
29};
30
31use anyhow::{Context as _, Result};
32use assert_matches::assert_matches;
33use byteorder::{NetworkEndian, WriteBytesExt as _};
34use dns_server_watcher::DEFAULT_DNS_PORT;
35use log::{debug, warn};
36use net_types::MulticastAddress as _;
37use net_types::ip::{Ip as _, Ipv6, Ipv6Addr, Subnet, SubnetError};
38use packet::ParsablePacket;
39use packet_formats_dhcp::v6;
40use rand::SeedableRng;
41use rand::rngs::StdRng;
42
43/// A thin wrapper around `zx::MonotonicInstant` that implements `dhcpv6_core::Instant`.
44#[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Debug)]
45pub(crate) struct MonotonicInstant(zx::MonotonicInstant);
46
47impl MonotonicInstant {
48    fn now() -> MonotonicInstant {
49        MonotonicInstant(zx::MonotonicInstant::get())
50    }
51}
52
53impl dhcpv6_core::Instant for MonotonicInstant {
54    fn duration_since(&self, MonotonicInstant(earlier): MonotonicInstant) -> Duration {
55        let Self(this) = *self;
56
57        let diff: zx::MonotonicDuration = this - earlier;
58
59        Duration::from_nanos(diff.into_nanos().try_into().unwrap_or_else(|e| {
60            panic!(
61                "failed to calculate duration since {:?} with instant {:?}: {}",
62                earlier, this, e,
63            )
64        }))
65    }
66
67    fn checked_add(&self, duration: Duration) -> Option<MonotonicInstant> {
68        Some(self.add(duration))
69    }
70}
71
72impl Add<Duration> for MonotonicInstant {
73    type Output = MonotonicInstant;
74
75    fn add(self, duration: Duration) -> MonotonicInstant {
76        let MonotonicInstant(this) = self;
77        MonotonicInstant(this + duration.into())
78    }
79}
80
81#[derive(Debug, thiserror::Error)]
82pub enum ClientError {
83    #[error("fidl error")]
84    Fidl(#[source] fidl::Error),
85    #[error("got watch request while the previous one is pending")]
86    DoubleWatch,
87    #[error("unsupported DHCPv6 configuration")]
88    UnsupportedConfigs,
89    #[error("socket create error")]
90    SocketCreate(std::io::Error),
91    #[error("socket receive error")]
92    SocketRecv(std::io::Error),
93    #[error("unimplemented DHCPv6 functionality: {:?}()", _0)]
94    Unimplemented(String),
95}
96
97/// Theoretical size limit for UDP datagrams.
98///
99/// NOTE: This does not take [jumbograms](https://tools.ietf.org/html/rfc2675) into account.
100const MAX_UDP_DATAGRAM_SIZE: usize = 65_535;
101
102#[pin_project::pin_project]
103struct Timers {
104    #[pin]
105    retransmission: fasync::Timer,
106    #[pin]
107    refresh: fasync::Timer,
108    #[pin]
109    renew: fasync::Timer,
110    #[pin]
111    rebind: fasync::Timer,
112    #[pin]
113    restart_server_discovery: fasync::Timer,
114
115    #[cfg(test)]
116    scheduled: HashSet<dhcpv6_core::client::ClientTimerType>,
117}
118
119impl Default for Timers {
120    fn default() -> Self {
121        let unscheduled = || fasync::Timer::new(fasync::MonotonicInstant::INFINITE);
122        Self {
123            retransmission: unscheduled(),
124            refresh: unscheduled(),
125            renew: unscheduled(),
126            rebind: unscheduled(),
127            restart_server_discovery: unscheduled(),
128            #[cfg(test)]
129            scheduled: Default::default(),
130        }
131    }
132}
133
134/// A DHCPv6 client.
135pub(crate) struct Client<S: for<'a> AsyncSocket<'a>> {
136    /// The interface the client is running on.
137    interface_id: u64,
138    /// Stores the hash of the last observed version of DNS servers by a watcher.
139    ///
140    /// The client uses this hash to determine whether new changes in DNS servers are observed and
141    /// updates should be replied to the watcher.
142    last_observed_dns_hash: u64,
143    /// Stores a responder to send DNS server updates.
144    dns_responder: Option<ClientWatchServersResponder>,
145    /// Stores a responder to send acquired addresses.
146    address_responder: Option<ClientWatchAddressResponder>,
147    /// Holds the discovered prefixes and their lifetimes.
148    prefixes: HashMap<fnet::Ipv6AddressWithPrefix, Lifetimes>,
149    /// Indicates whether or not the prefixes has changed since last yielded.
150    prefixes_changed: bool,
151    /// Stores a responder to send acquired prefixes.
152    prefixes_responder: Option<ClientWatchPrefixesResponder>,
153    /// Maintains the state for the client.
154    state_machine: dhcpv6_core::client::ClientStateMachine<MonotonicInstant, StdRng>,
155    /// The socket used to communicate with DHCPv6 servers.
156    socket: S,
157    /// The address to send outgoing messages to.
158    server_addr: SocketAddr,
159    /// All timers.
160    timers: Pin<Box<Timers>>,
161    /// A stream of FIDL requests to this client.
162    request_stream: ClientRequestStream,
163}
164
165/// A trait that allows stubbing [`fuchsia_async::net::UdpSocket`] in tests.
166pub(crate) trait AsyncSocket<'a> {
167    type RecvFromFut: Future<Output = Result<(usize, SocketAddr), std::io::Error>> + 'a;
168    type SendToFut: Future<Output = Result<usize, std::io::Error>> + 'a;
169
170    fn recv_from(&'a self, buf: &'a mut [u8]) -> Self::RecvFromFut;
171    fn send_to(&'a self, buf: &'a [u8], addr: SocketAddr) -> Self::SendToFut;
172}
173
174impl<'a> AsyncSocket<'a> for fasync::net::UdpSocket {
175    type RecvFromFut = fasync::net::UdpRecvFrom<'a>;
176    type SendToFut = fasync::net::SendTo<'a>;
177
178    fn recv_from(&'a self, buf: &'a mut [u8]) -> Self::RecvFromFut {
179        self.recv_from(buf)
180    }
181    fn send_to(&'a self, buf: &'a [u8], addr: SocketAddr) -> Self::SendToFut {
182        self.send_to(buf, addr)
183    }
184}
185
186/// Converts `InformationConfig` to a collection of `v6::OptionCode`.
187fn to_dhcpv6_option_codes(
188    InformationConfig { dns_servers }: InformationConfig,
189) -> Vec<v6::OptionCode> {
190    dns_servers.then_some(v6::OptionCode::DnsServers).into_iter().collect()
191}
192
193fn to_configured_addresses(
194    AddressConfig { address_count, preferred_addresses }: AddressConfig,
195) -> Result<HashMap<v6::IAID, HashSet<Ipv6Addr>>, ClientError> {
196    let preferred_addresses = preferred_addresses.unwrap_or(Vec::new());
197    if preferred_addresses.len() > address_count.into() {
198        return Err(ClientError::UnsupportedConfigs);
199    }
200
201    // TODO(https://fxbug.dev/42157844): make IAID consistent across
202    // configurations.
203    Ok((0..)
204        .map(v6::IAID::new)
205        .zip(
206            preferred_addresses
207                .into_iter()
208                .map(|fnet::Ipv6Address { addr, .. }| HashSet::from([Ipv6Addr::from(addr)]))
209                .chain(std::iter::repeat_with(HashSet::new)),
210        )
211        .take(address_count.into())
212        .collect())
213}
214
215// The client only supports a single IA_PD.
216//
217// TODO(https://fxbug.dev/42065403): Support multiple IA_PDs.
218const IA_PD_IAID: v6::IAID = v6::IAID::new(0);
219
220/// Creates a state machine for the input client config.
221fn create_state_machine(
222    duid: Option<dhcpv6_core::ClientDuid>,
223    transaction_id: [u8; 3],
224    ClientConfig {
225        information_config,
226        non_temporary_address_config,
227        prefix_delegation_config,
228    }: ClientConfig,
229) -> Result<
230    (
231        dhcpv6_core::client::ClientStateMachine<MonotonicInstant, StdRng>,
232        dhcpv6_core::client::Actions<MonotonicInstant>,
233    ),
234    ClientError,
235> {
236    let information_option_codes = to_dhcpv6_option_codes(information_config);
237    let configured_non_temporary_addresses = to_configured_addresses(non_temporary_address_config)?;
238    let configured_delegated_prefixes = prefix_delegation_config
239        .map(|prefix_delegation_config| {
240            let prefix = match prefix_delegation_config {
241                PrefixDelegationConfig::Empty(Empty {}) => Ok(None),
242                PrefixDelegationConfig::PrefixLength(prefix_len) => {
243                    if prefix_len == 0 {
244                        // Should have used `PrefixDelegationConfig::Empty`.
245                        return Err(ClientError::UnsupportedConfigs);
246                    }
247
248                    Subnet::new(Ipv6::UNSPECIFIED_ADDRESS, prefix_len).map(Some)
249                }
250                PrefixDelegationConfig::Prefix(fnet::Ipv6AddressWithPrefix {
251                    addr: fnet::Ipv6Address { addr, .. },
252                    prefix_len,
253                }) => {
254                    let addr = Ipv6Addr::from_bytes(addr);
255                    if addr == Ipv6::UNSPECIFIED_ADDRESS {
256                        // Should have used `PrefixDelegationConfig::PrefixLength`.
257                        return Err(ClientError::UnsupportedConfigs);
258                    }
259
260                    Subnet::new(addr, prefix_len).map(Some)
261                }
262            };
263
264            match prefix {
265                Ok(o) => Ok(HashMap::from([(IA_PD_IAID, HashSet::from_iter(o.into_iter()))])),
266                Err(SubnetError::PrefixTooLong | SubnetError::HostBitsSet) => {
267                    Err(ClientError::UnsupportedConfigs)
268                }
269            }
270        })
271        .transpose()?;
272
273    let now = MonotonicInstant::now();
274    match (
275        information_option_codes.is_empty(),
276        configured_non_temporary_addresses.is_empty(),
277        configured_delegated_prefixes,
278    ) {
279        (true, true, None) => Err(ClientError::UnsupportedConfigs),
280        (false, true, None) => {
281            if duid.is_some() {
282                Err(ClientError::UnsupportedConfigs)
283            } else {
284                Ok(dhcpv6_core::client::ClientStateMachine::start_stateless(
285                    transaction_id,
286                    information_option_codes,
287                    StdRng::from_os_rng(),
288                    now,
289                ))
290            }
291        }
292        (
293            _request_information,
294            _configure_non_temporary_addresses,
295            configured_delegated_prefixes,
296        ) => Ok(dhcpv6_core::client::ClientStateMachine::start_stateful(
297            transaction_id,
298            if let Some(duid) = duid {
299                duid
300            } else {
301                return Err(ClientError::UnsupportedConfigs);
302            },
303            configured_non_temporary_addresses,
304            configured_delegated_prefixes.unwrap_or_else(Default::default),
305            information_option_codes,
306            StdRng::from_os_rng(),
307            now,
308        )),
309    }
310}
311
312/// Calculates a hash for the input.
313fn hash<H: Hash>(h: &H) -> u64 {
314    let mut dh = DefaultHasher::new();
315    h.hash(&mut dh);
316    dh.finish()
317}
318
319fn subnet_to_address_with_prefix(prefix: Subnet<Ipv6Addr>) -> fnet::Ipv6AddressWithPrefix {
320    fnet::Ipv6AddressWithPrefix {
321        addr: fnet::Ipv6Address { addr: prefix.network().ipv6_bytes() },
322        prefix_len: prefix.prefix(),
323    }
324}
325
326impl<S: for<'a> AsyncSocket<'a>> Client<S> {
327    /// Starts the client in `config`.
328    ///
329    /// Input `transaction_id` is used to label outgoing messages and match incoming ones.
330    pub(crate) async fn start(
331        duid: Option<dhcpv6_core::ClientDuid>,
332        transaction_id: [u8; 3],
333        config: ClientConfig,
334        interface_id: u64,
335        socket_fn: impl FnOnce() -> std::io::Result<S>,
336        server_addr: SocketAddr,
337        request_stream: ClientRequestStream,
338    ) -> Result<Self, ClientError> {
339        let (state_machine, actions) = create_state_machine(duid, transaction_id, config)?;
340        let mut client = Self {
341            state_machine,
342            interface_id,
343            socket: socket_fn().map_err(ClientError::SocketCreate)?,
344            server_addr,
345            request_stream,
346            // Server watcher's API requires blocking iff the first call would return an empty list,
347            // so initialize this field with a hash of an empty list.
348            last_observed_dns_hash: hash(&Vec::<Ipv6Addr>::new()),
349            dns_responder: None,
350            address_responder: None,
351            prefixes: Default::default(),
352            prefixes_changed: false,
353            prefixes_responder: None,
354            timers: Box::pin(Default::default()),
355        };
356        client.run_actions(actions).await?;
357        Ok(client)
358    }
359
360    /// Runs a list of actions sequentially.
361    async fn run_actions(
362        &mut self,
363        actions: dhcpv6_core::client::Actions<MonotonicInstant>,
364    ) -> Result<(), ClientError> {
365        stream::iter(actions)
366            .map(Ok)
367            .try_fold(self, |client, action| async move {
368                match action {
369                    dhcpv6_core::client::Action::SendMessage(buf) => {
370                        match client.socket.send_to(&buf, client.server_addr).await {
371                            Ok(size) => assert_eq!(size, buf.len()),
372                            Err(e) => warn!(
373                                "failed to send message to {}: {}; will retransmit later",
374                                client.server_addr, e
375                            ),
376                        };
377                    }
378                    dhcpv6_core::client::Action::ScheduleTimer(timer_type, timeout) => {
379                        client.schedule_timer(timer_type, timeout)
380                    }
381                    dhcpv6_core::client::Action::CancelTimer(timer_type) => {
382                        client.cancel_timer(timer_type)
383                    }
384                    dhcpv6_core::client::Action::UpdateDnsServers(servers) => {
385                        client.maybe_send_dns_server_updates(servers)?;
386                    }
387                    dhcpv6_core::client::Action::IaNaUpdates(_) => {
388                        // TODO(https://fxbug.dev/42178828): add actions to
389                        // (re)schedule preferred and valid lifetime timers.
390                        // TODO(https://fxbug.dev/42178817): Add
391                        // action to remove the previous address.
392                        // TODO(https://fxbug.dev/42177252): Add action to add
393                        // the new address and cancel timers for old address.
394                    }
395                    dhcpv6_core::client::Action::IaPdUpdates(mut updates) => {
396                        let updates = {
397                            let ret =
398                                updates.remove(&IA_PD_IAID).expect("Update missing for IAID");
399                            debug_assert_eq!(updates, HashMap::new());
400                            ret
401                        };
402
403                        let Self { prefixes, prefixes_changed, .. } = client;
404
405                        let now = zx::MonotonicInstant::get();
406                        let nonzero_timevalue_to_zx_time = |tv| match tv {
407                            v6::NonZeroTimeValue::Finite(tv) => {
408                                now + zx::MonotonicDuration::from_seconds(tv.get().into())
409                            }
410                            v6::NonZeroTimeValue::Infinity => zx::MonotonicInstant::INFINITE,
411                        };
412
413                        let calculate_lifetimes = |dhcpv6_core::client::Lifetimes {
414                            preferred_lifetime,
415                            valid_lifetime,
416                        }| {
417                            Lifetimes {
418                                preferred_until: match preferred_lifetime {
419                                    v6::TimeValue::Zero => zx::MonotonicInstant::ZERO,
420                                    v6::TimeValue::NonZero(preferred_lifetime) => {
421                                        nonzero_timevalue_to_zx_time(preferred_lifetime)
422                                    },
423                                }.into_nanos(),
424                                valid_until: nonzero_timevalue_to_zx_time(valid_lifetime)
425                                    .into_nanos(),
426                            }
427                        };
428
429                        for (prefix, update) in updates.into_iter() {
430                            let fidl_prefix = subnet_to_address_with_prefix(prefix);
431
432                            match update {
433                                dhcpv6_core::client::IaValueUpdateKind::Added(lifetimes) => {
434                                    assert_matches!(
435                                        prefixes.insert(
436                                            fidl_prefix,
437                                            calculate_lifetimes(lifetimes)
438                                        ),
439                                        None,
440                                        "must not know about prefix {} to add it with lifetimes {:?}",
441                                        prefix, lifetimes,
442                                    );
443                                }
444                                dhcpv6_core::client::IaValueUpdateKind::UpdatedLifetimes(updated_lifetimes) => {
445                                    assert_matches!(
446                                        prefixes.get_mut(&fidl_prefix),
447                                        Some(lifetimes) => {
448                                            *lifetimes = calculate_lifetimes(updated_lifetimes);
449                                        },
450                                        "must know about prefix {} to update lifetimes with {:?}",
451                                        prefix, updated_lifetimes,
452                                    );
453                                }
454                                dhcpv6_core::client::IaValueUpdateKind::Removed => {
455                                    assert_matches!(
456                                        prefixes.remove(&fidl_prefix),
457                                        Some(_),
458                                        "must know about prefix {} to remove it",
459                                        prefix
460                                    );
461                                }
462                            }
463                        }
464
465                        // Mark the client has having updated prefixes so that
466                        // callers of `WatchPrefixes` receive the update.
467                        *prefixes_changed = true;
468                        client.maybe_send_prefixes()?;
469                    }
470                };
471                Ok(client)
472            })
473            .await
474            .map(|_: &mut Client<S>| ())
475    }
476
477    /// Sends the latest DNS servers if a watcher is watching, and the latest set of servers are
478    /// different from what the watcher has observed last time.
479    fn maybe_send_dns_server_updates(&mut self, servers: Vec<Ipv6Addr>) -> Result<(), ClientError> {
480        let servers_hash = hash(&servers);
481        if servers_hash == self.last_observed_dns_hash {
482            Ok(())
483        } else {
484            Ok(match self.dns_responder.take() {
485                Some(responder) => {
486                    self.send_dns_server_updates(responder, servers, servers_hash)?
487                }
488                None => (),
489            })
490        }
491    }
492
493    fn maybe_send_prefixes(&mut self) -> Result<(), ClientError> {
494        let Self { prefixes, prefixes_changed, prefixes_responder, .. } = self;
495
496        if !*prefixes_changed {
497            return Ok(());
498        }
499
500        let responder = if let Some(responder) = prefixes_responder.take() {
501            responder
502        } else {
503            return Ok(());
504        };
505
506        let prefixes = prefixes
507            .iter()
508            .map(|(prefix, lifetimes)| Prefix { prefix: *prefix, lifetimes: *lifetimes })
509            .collect::<Vec<_>>();
510
511        responder.send(&prefixes).map_err(ClientError::Fidl)?;
512        *prefixes_changed = false;
513        Ok(())
514    }
515
516    /// Sends a list of DNS servers to a watcher through the input responder and updates the last
517    /// observed hash.
518    fn send_dns_server_updates(
519        &mut self,
520        responder: ClientWatchServersResponder,
521        servers: Vec<Ipv6Addr>,
522        hash: u64,
523    ) -> Result<(), ClientError> {
524        let response: Vec<_> = servers
525            .iter()
526            .map(|addr| {
527                let address = fnet::Ipv6Address { addr: addr.ipv6_bytes() };
528                let zone_index =
529                    if is_unicast_link_local_strict(&address) { self.interface_id } else { 0 };
530
531                fnet_name::DnsServer_ {
532                    address: Some(fnet::SocketAddress::Ipv6(fnet::Ipv6SocketAddress {
533                        address,
534                        zone_index,
535                        port: DEFAULT_DNS_PORT,
536                    })),
537                    source: Some(fnet_name::DnsServerSource::Dhcpv6(
538                        fnet_name::Dhcpv6DnsServerSource {
539                            source_interface: Some(self.interface_id),
540                            ..Default::default()
541                        },
542                    )),
543                    ..Default::default()
544                }
545            })
546            .collect();
547        responder
548            .send(&response)
549            // The channel will be closed on error, so return an error to stop the client.
550            .map_err(ClientError::Fidl)?;
551        self.last_observed_dns_hash = hash;
552        Ok(())
553    }
554
555    /// Schedules a timer for `timer_type` to fire at `instant`.
556    ///
557    /// If a timer for `timer_type` is already scheduled, the timer is
558    /// updated to fire at the new time.
559    fn schedule_timer(
560        &mut self,
561        timer_type: dhcpv6_core::client::ClientTimerType,
562        MonotonicInstant(instant): MonotonicInstant,
563    ) {
564        let timers = self.timers.as_mut().project();
565        let timer = match timer_type {
566            dhcpv6_core::client::ClientTimerType::Retransmission => timers.retransmission,
567            dhcpv6_core::client::ClientTimerType::Refresh => timers.refresh,
568            dhcpv6_core::client::ClientTimerType::Renew => timers.renew,
569            dhcpv6_core::client::ClientTimerType::Rebind => timers.rebind,
570            dhcpv6_core::client::ClientTimerType::RestartServerDiscovery => {
571                timers.restart_server_discovery
572            }
573        };
574        #[cfg(test)]
575        let _: bool = if instant == zx::MonotonicInstant::INFINITE {
576            timers.scheduled.remove(&timer_type)
577        } else {
578            timers.scheduled.insert(timer_type)
579        };
580        timer.reset(fasync::MonotonicInstant::from_zx(instant));
581    }
582
583    /// Cancels a previously scheduled timer for `timer_type`.
584    ///
585    /// If a timer was not previously scheduled for `timer_type`, this
586    /// call is effectively a no-op.
587    fn cancel_timer(&mut self, timer_type: dhcpv6_core::client::ClientTimerType) {
588        self.schedule_timer(timer_type, MonotonicInstant(zx::MonotonicInstant::INFINITE))
589    }
590
591    /// Handles a timeout.
592    async fn handle_timeout(
593        &mut self,
594        timer_type: dhcpv6_core::client::ClientTimerType,
595    ) -> Result<(), ClientError> {
596        // This timer just fired.
597        self.cancel_timer(timer_type);
598
599        let actions = self.state_machine.handle_timeout(timer_type, MonotonicInstant::now());
600        self.run_actions(actions).await
601    }
602
603    /// Handles a received message.
604    async fn handle_message_recv(&mut self, mut msg: &[u8]) -> Result<(), ClientError> {
605        let msg = match v6::Message::parse(&mut msg, ()) {
606            Ok(msg) => msg,
607            Err(e) => {
608                // Discard invalid messages.
609                //
610                // https://tools.ietf.org/html/rfc8415#section-16.
611                warn!("failed to parse received message: {}", e);
612                return Ok(());
613            }
614        };
615        let actions = self.state_machine.handle_message_receive(msg, MonotonicInstant::now());
616        self.run_actions(actions).await
617    }
618
619    /// Handles a FIDL request sent to this client.
620    fn handle_client_request(&mut self, request: ClientRequest) -> Result<(), ClientError> {
621        debug!("handling client request: {:?}", request);
622        match request {
623            ClientRequest::WatchServers { responder } => match self.dns_responder {
624                Some(_) => {
625                    // Drop the previous responder to close the channel.
626                    self.dns_responder = None;
627                    // Return an error to stop the client because the channel is closed.
628                    Err(ClientError::DoubleWatch)
629                }
630                None => {
631                    let dns_servers = self.state_machine.get_dns_servers();
632                    let servers_hash = hash(&dns_servers);
633                    if servers_hash != self.last_observed_dns_hash {
634                        // Something has changed from the last time, update the watcher.
635                        let () =
636                            self.send_dns_server_updates(responder, dns_servers, servers_hash)?;
637                    } else {
638                        // Nothing has changed, update the watcher later.
639                        self.dns_responder = Some(responder);
640                    }
641                    Ok(())
642                }
643            },
644            ClientRequest::WatchAddress { responder } => match self.address_responder.take() {
645                // The responder will be dropped and cause the channel to be closed.
646                Some(ClientWatchAddressResponder { .. }) => Err(ClientError::DoubleWatch),
647                None => {
648                    // TODO(https://fxbug.dev/42152192): Implement the address watcher.
649                    warn!("WatchAddress call will block forever as it is unimplemented");
650                    self.address_responder = Some(responder);
651                    Ok(())
652                }
653            },
654            ClientRequest::WatchPrefixes { responder } => match self.prefixes_responder.take() {
655                // The responder will be dropped and cause the channel to be closed.
656                Some(ClientWatchPrefixesResponder { .. }) => Err(ClientError::DoubleWatch),
657                None => {
658                    self.prefixes_responder = Some(responder);
659                    self.maybe_send_prefixes()
660                }
661            },
662            // TODO(https://fxbug.dev/42152193): Implement Shutdown.
663            ClientRequest::Shutdown { responder: _ } => {
664                Err(ClientError::Unimplemented("Shutdown".to_string()))
665            }
666        }
667    }
668
669    /// Handles the next event and returns the result.
670    ///
671    /// Takes a pre-allocated buffer to avoid repeated allocation.
672    ///
673    /// The returned `Option` is `None` if `request_stream` on the client is closed.
674    async fn handle_next_event(&mut self, buf: &mut [u8]) -> Result<Option<()>, ClientError> {
675        let timers = self.timers.as_mut().project();
676        let timer_type = select! {
677            () = timers.retransmission => {
678                dhcpv6_core::client::ClientTimerType::Retransmission
679            },
680            () = timers.refresh => {
681                dhcpv6_core::client::ClientTimerType::Refresh
682            },
683            () = timers.renew => {
684                dhcpv6_core::client::ClientTimerType::Renew
685            },
686            () = timers.rebind => {
687                dhcpv6_core::client::ClientTimerType::Rebind
688            },
689            () = timers.restart_server_discovery => {
690                dhcpv6_core::client::ClientTimerType::RestartServerDiscovery
691            },
692            recv_from_res = self.socket.recv_from(buf).fuse() => {
693                let (size, _addr) = recv_from_res.map_err(ClientError::SocketRecv)?;
694                self.handle_message_recv(&buf[..size]).await?;
695                return Ok(Some(()));
696            },
697            request = self.request_stream.try_next() => {
698                let request = request.map_err(ClientError::Fidl)?;
699                return request.map(|request| self.handle_client_request(request)).transpose();
700            }
701        };
702        self.handle_timeout(timer_type).await?;
703        Ok(Some(()))
704    }
705
706    #[cfg(test)]
707    fn assert_scheduled(
708        &self,
709        timers: impl IntoIterator<Item = dhcpv6_core::client::ClientTimerType>,
710    ) {
711        assert_eq!(self.timers.as_ref().scheduled, timers.into_iter().collect())
712    }
713}
714
715/// Creates a socket listening on the input address.
716fn create_socket(addr: SocketAddr) -> std::io::Result<fasync::net::UdpSocket> {
717    let socket = socket2::Socket::new(
718        socket2::Domain::IPV6,
719        socket2::Type::DGRAM,
720        Some(socket2::Protocol::UDP),
721    )?;
722    // It is possible to run multiple clients on the same address.
723    socket.set_reuse_port(true)?;
724    socket.bind(&addr.into())?;
725    fasync::net::UdpSocket::from_socket(socket.into())
726}
727
728/// Returns `true` if the input address is a link-local address (`fe80::/64`).
729///
730/// TODO(https://github.com/rust-lang/rust/issues/27709): use is_unicast_link_local_strict() in
731/// stable rust when it's available.
732fn is_unicast_link_local_strict(addr: &fnet::Ipv6Address) -> bool {
733    addr.addr[..8] == [0xfe, 0x80, 0, 0, 0, 0, 0, 0]
734}
735
736fn duid_from_fidl(duid: Duid) -> Result<dhcpv6_core::ClientDuid, ()> {
737    /// According to [RFC 8415, section 11.2], DUID of type DUID-LLT has a type value of 1
738    ///
739    /// [RFC 8415, section 11.2]: https://datatracker.ietf.org/doc/html/rfc8415#section-11.2
740    const DUID_TYPE_LLT: [u8; 2] = [0, 1];
741    /// According to [RFC 8415, section 11.4], DUID of type DUID-LL has a type value of 3
742    ///
743    /// [RFC 8415, section 11.4]: https://datatracker.ietf.org/doc/html/rfc8415#section-11.4
744    const DUID_TYPE_LL: [u8; 2] = [0, 3];
745    /// According to [RFC 8415, section 11.5], DUID of type DUID-UUID has a type value of 4.
746    ///
747    /// [RFC 8415, section 11.5]: https://datatracker.ietf.org/doc/html/rfc8415#section-11.5
748    const DUID_TYPE_UUID: [u8; 2] = [0, 4];
749    /// According to [RFC 8415, section 11.2], the hardware type of Ethernet as assigned by
750    /// [IANA] is 1.
751    ///
752    /// [RFC 8415, section 11.2]: https://datatracker.ietf.org/doc/html/rfc8415#section-11.2
753    /// [IANA]: https://www.iana.org/assignments/arp-parameters/arp-parameters.xhtml
754    const HARDWARE_TYPE_ETHERNET: [u8; 2] = [0, 1];
755    match duid {
756        // DUID-LLT with a MAC address is 14 bytes (2 bytes for the type + 2
757        // bytes for the hardware type + 4 bytes for the timestamp + 6 bytes
758        // for the MAC address), which is guaranteed to fit in the 18-byte limit
759        // of `ClientDuid`.
760        Duid::LinkLayerAddressPlusTime(LinkLayerAddressPlusTime {
761            time,
762            link_layer_address: LinkLayerAddress::Ethernet(mac),
763        }) => {
764            let mut duid = dhcpv6_core::ClientDuid::new();
765            duid.try_extend_from_slice(&DUID_TYPE_LLT).unwrap();
766            duid.try_extend_from_slice(&HARDWARE_TYPE_ETHERNET).unwrap();
767            duid.write_u32::<NetworkEndian>(time).unwrap();
768            duid.try_extend_from_slice(&mac.octets).unwrap();
769            Ok(duid)
770        }
771        // DUID-LL with a MAC address is 10 bytes (2 bytes for the type + 2
772        // bytes for the hardware type + 6 bytes for the MAC address), which
773        // is guaranteed to fit in the 18-byte limit of `ClientDuid`.
774        Duid::LinkLayerAddress(LinkLayerAddress::Ethernet(mac)) => Ok(DUID_TYPE_LL
775            .into_iter()
776            .chain(HARDWARE_TYPE_ETHERNET.into_iter())
777            .chain(mac.octets.into_iter())
778            .collect()),
779        // DUID-UUID is 18 bytes (2 bytes for the type + 16 bytes for the UUID),
780        // which is guaranteed to fit in the 18-byte limit of `ClientDuid`.
781        Duid::Uuid(uuid) => Ok(DUID_TYPE_UUID.into_iter().chain(uuid.into_iter()).collect()),
782        _ => Err(()),
783    }
784}
785
786/// Starts a client based on `params`.
787///
788/// `request` will be serviced by the client.
789pub(crate) async fn serve_client(
790    NewClientParams { interface_id, address, duid, config }: NewClientParams,
791    request: ServerEnd<ClientMarker>,
792) -> Result<()> {
793    if Ipv6Addr::from(address.address.addr).is_multicast()
794        || (is_unicast_link_local_strict(&address.address) && address.zone_index != interface_id)
795    {
796        return request
797            .close_with_epitaph(zx::Status::INVALID_ARGS)
798            .context("closing request channel with epitaph");
799    }
800
801    let fnet_ext::SocketAddress(addr) = fnet::SocketAddress::Ipv6(address).into();
802    let servers_addr = IpAddr::from_str(RELAY_AGENT_AND_SERVER_LINK_LOCAL_MULTICAST_ADDRESS)
803        .with_context(|| {
804            format!(
805                "{} should be a valid IPv6 address",
806                RELAY_AGENT_AND_SERVER_LINK_LOCAL_MULTICAST_ADDRESS,
807            )
808        })?;
809    let duid = match duid.map(|fidl| duid_from_fidl(fidl)).transpose() {
810        Ok(duid) => duid,
811        Err(()) => {
812            return request
813                .close_with_epitaph(zx::Status::INVALID_ARGS)
814                .context("closing request channel with epitaph");
815        }
816    };
817    let (request_stream, control_handle) = request.into_stream_and_control_handle();
818    let mut client = match Client::<fasync::net::UdpSocket>::start(
819        duid,
820        dhcpv6_core::client::transaction_id(),
821        config,
822        interface_id,
823        || create_socket(addr),
824        SocketAddr::new(servers_addr, RELAY_AGENT_AND_SERVER_PORT),
825        request_stream,
826    )
827    .await
828    {
829        Ok(client) => client,
830        Err(ClientError::UnsupportedConfigs) => {
831            control_handle.shutdown_with_epitaph(zx::Status::INVALID_ARGS);
832            return Ok(());
833        }
834        Err(e) => {
835            return Err(e.into());
836        }
837    };
838    let mut buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
839    loop {
840        match client.handle_next_event(&mut buf).await? {
841            Some(()) => (),
842            None => break Ok(()),
843        }
844    }
845}
846
847#[cfg(test)]
848mod tests {
849    use std::pin::pin;
850    use std::task::Poll;
851
852    use fidl::endpoints::{
853        ClientEnd, create_proxy, create_proxy_and_stream, create_request_stream,
854    };
855    use fidl_fuchsia_net_dhcpv6::{self as fnet_dhcpv6, ClientProxy, DEFAULT_CLIENT_PORT};
856    use fuchsia_async as fasync;
857    use futures::{TryFutureExt as _, join, poll};
858
859    use assert_matches::assert_matches;
860    use net_declare::{
861        fidl_ip_v6, fidl_ip_v6_with_prefix, fidl_mac, fidl_socket_addr, fidl_socket_addr_v6,
862        net_ip_v6, net_subnet_v6, std_socket_addr,
863    };
864    use net_types::ip::IpAddress as _;
865    use packet::serialize::InnerPacketBuilder;
866    use test_case::test_case;
867
868    use super::*;
869
870    /// Creates a test socket bound to an ephemeral port on localhost.
871    fn create_test_socket() -> (fasync::net::UdpSocket, SocketAddr) {
872        let addr: SocketAddr = std_socket_addr!("[::1]:0");
873        let socket = std::net::UdpSocket::bind(addr).expect("failed to create test socket");
874        let addr = socket.local_addr().expect("failed to get address of test socket");
875        (fasync::net::UdpSocket::from_socket(socket).expect("failed to create test socket"), addr)
876    }
877
878    struct ReceivedMessage {
879        transaction_id: [u8; 3],
880        // Client IDs are optional in Information Request messages.
881        //
882        // Per RFC 8415 section 18.2.6,
883        //
884        //   The client SHOULD include a Client Identifier option (see
885        //   Section 21.2) to identify itself to the server (however, see
886        //   Section 4.3.1 of [RFC7844] for reasons why a client may not want to
887        //   include this option).
888        //
889        // Per RFC 7844 section 4.3.1,
890        //
891        //   According to [RFC3315], a DHCPv6 client includes its client
892        //   identifier in most of the messages it sends. There is one exception,
893        //   however: the client is allowed to omit its client identifier when
894        //   sending Information-request messages.
895        client_id: Option<Vec<u8>>,
896    }
897
898    /// Asserts `socket` receives a message of `msg_type` from
899    /// `want_from_addr`.
900    async fn assert_received_message(
901        socket: &fasync::net::UdpSocket,
902        want_from_addr: SocketAddr,
903        msg_type: v6::MessageType,
904    ) -> ReceivedMessage {
905        let mut buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
906        let (size, from_addr) =
907            socket.recv_from(&mut buf).await.expect("failed to receive on test server socket");
908        assert_eq!(from_addr, want_from_addr);
909        let buf = &mut &buf[..size]; // Implements BufferView.
910        let msg = v6::Message::parse(buf, ()).expect("failed to parse message");
911        assert_eq!(msg.msg_type(), msg_type);
912
913        let mut client_id = None;
914        for opt in msg.options() {
915            match opt {
916                v6::ParsedDhcpOption::ClientId(id) => {
917                    assert_eq!(core::mem::replace(&mut client_id, Some(id.to_vec())), None)
918                }
919                _ => {}
920            }
921        }
922
923        ReceivedMessage { transaction_id: *msg.transaction_id(), client_id: client_id }
924    }
925
926    const TEST_MAC: fnet::MacAddress = fidl_mac!("00:01:02:03:04:05");
927
928    #[test_case(
929        Duid::LinkLayerAddress(LinkLayerAddress::Ethernet(TEST_MAC)),
930        &[0, 3, 0, 1, 0, 1, 2, 3, 4, 5];
931        "ll"
932    )]
933    #[test_case(
934        Duid::LinkLayerAddressPlusTime(LinkLayerAddressPlusTime {
935            time: 0,
936            link_layer_address: LinkLayerAddress::Ethernet(TEST_MAC),
937        }),
938        &[0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5];
939        "llt"
940    )]
941    #[test_case(
942        Duid::Uuid([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]),
943        &[0, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
944        "uuid"
945    )]
946    #[fuchsia::test]
947    fn test_duid_from_fidl(duid: Duid, want: &[u8]) {
948        assert_eq!(duid_from_fidl(duid), Ok(dhcpv6_core::ClientDuid::try_from(want).unwrap()));
949    }
950
951    #[fuchsia::test]
952    fn test_create_client_with_unsupported_config() {
953        let prefix_delegation_configs = [
954            None,
955            // Prefix length config without a non-zero length.
956            Some(PrefixDelegationConfig::PrefixLength(0)),
957            // Prefix length too long.
958            Some(PrefixDelegationConfig::PrefixLength(Ipv6Addr::BYTES * 8 + 1)),
959            // Network-bits unset.
960            Some(PrefixDelegationConfig::Prefix(fidl_ip_v6_with_prefix!("::/64"))),
961            // Host-bits set.
962            Some(PrefixDelegationConfig::Prefix(fidl_ip_v6_with_prefix!("a::1/64"))),
963        ];
964
965        for prefix_delegation_config in prefix_delegation_configs.iter() {
966            assert_matches!(
967                create_state_machine(
968                    prefix_delegation_config.is_some().then(|| CLIENT_ID.into()),
969                    [1, 2, 3],
970                    ClientConfig {
971                        information_config: Default::default(),
972                        non_temporary_address_config: Default::default(),
973                        prefix_delegation_config: prefix_delegation_config.clone(),
974                    }
975                ),
976                Err(ClientError::UnsupportedConfigs),
977                "prefix_delegation_config={:?}",
978                prefix_delegation_config
979            );
980        }
981    }
982
983    const STATELESS_CLIENT_CONFIG: ClientConfig = ClientConfig {
984        information_config: InformationConfig { dns_servers: true },
985        non_temporary_address_config: AddressConfig { address_count: 0, preferred_addresses: None },
986        prefix_delegation_config: None,
987    };
988
989    #[fuchsia::test]
990    async fn test_client_stops_on_channel_close() {
991        let (client_proxy, server_end) = create_proxy::<ClientMarker>();
992
993        let ((), client_res) = join!(
994            async { drop(client_proxy) },
995            serve_client(
996                NewClientParams {
997                    interface_id: 1,
998                    address: fidl_socket_addr_v6!("[::1]:546"),
999                    config: STATELESS_CLIENT_CONFIG,
1000                    duid: None,
1001                },
1002                server_end,
1003            ),
1004        );
1005        client_res.expect("client future should return with Ok");
1006    }
1007
1008    fn client_proxy_watch_servers(
1009        client_proxy: &fnet_dhcpv6::ClientProxy,
1010    ) -> impl Future<Output = Result<(), fidl::Error>> {
1011        client_proxy.watch_servers().map_ok(|_: Vec<fidl_fuchsia_net_name::DnsServer_>| ())
1012    }
1013
1014    fn client_proxy_watch_address(
1015        client_proxy: &fnet_dhcpv6::ClientProxy,
1016    ) -> impl Future<Output = Result<(), fidl::Error>> {
1017        client_proxy.watch_address().map_ok(
1018            |_: (
1019                fnet::Subnet,
1020                fidl_fuchsia_net_interfaces_admin::AddressParameters,
1021                fidl::endpoints::ServerEnd<
1022                    fidl_fuchsia_net_interfaces_admin::AddressStateProviderMarker,
1023                >,
1024            )| (),
1025        )
1026    }
1027
1028    fn client_proxy_watch_prefixes(
1029        client_proxy: &fnet_dhcpv6::ClientProxy,
1030    ) -> impl Future<Output = Result<(), fidl::Error>> {
1031        client_proxy.watch_prefixes().map_ok(|_: Vec<fnet_dhcpv6::Prefix>| ())
1032    }
1033
1034    #[test_case(client_proxy_watch_servers; "watch_servers")]
1035    #[test_case(client_proxy_watch_address; "watch_address")]
1036    #[test_case(client_proxy_watch_prefixes; "watch_prefixes")]
1037    #[fuchsia::test]
1038    async fn test_client_should_return_error_on_double_watch<F>(watch: F)
1039    where
1040        F: AsyncFn(&fnet_dhcpv6::ClientProxy) -> Result<(), fidl::Error>,
1041    {
1042        let (client_proxy, server_end) = create_proxy::<ClientMarker>();
1043
1044        let (caller1_res, caller2_res, client_res) = join!(
1045            watch(&client_proxy),
1046            watch(&client_proxy),
1047            serve_client(
1048                NewClientParams {
1049                    interface_id: 1,
1050                    address: fidl_socket_addr_v6!("[::1]:546"),
1051                    config: STATELESS_CLIENT_CONFIG,
1052                    duid: None,
1053                },
1054                server_end,
1055            )
1056        );
1057
1058        assert_matches!(
1059            caller1_res,
1060            Err(fidl::Error::ClientChannelClosed { status: zx::Status::PEER_CLOSED, .. })
1061        );
1062        assert_matches!(
1063            caller2_res,
1064            Err(fidl::Error::ClientChannelClosed { status: zx::Status::PEER_CLOSED, .. })
1065        );
1066        assert!(
1067            client_res
1068                .expect_err("client should fail with double watch error")
1069                .to_string()
1070                .contains("got watch request while the previous one is pending")
1071        );
1072    }
1073
1074    const VALID_INFORMATION_CONFIGS: [InformationConfig; 2] =
1075        [InformationConfig { dns_servers: false }, InformationConfig { dns_servers: true }];
1076
1077    const VALID_DELEGATED_PREFIX_CONFIGS: [Option<PrefixDelegationConfig>; 4] = [
1078        Some(PrefixDelegationConfig::Empty(Empty {})),
1079        Some(PrefixDelegationConfig::PrefixLength(1)),
1080        Some(PrefixDelegationConfig::PrefixLength(127)),
1081        Some(PrefixDelegationConfig::Prefix(fidl_ip_v6_with_prefix!("a::/64"))),
1082    ];
1083
1084    // Can't be a const variable because we allocate a vector.
1085    fn get_valid_non_temporary_address_configs() -> [AddressConfig; 5] {
1086        [
1087            Default::default(),
1088            AddressConfig { address_count: 1, preferred_addresses: None },
1089            AddressConfig { address_count: 1, preferred_addresses: Some(Vec::new()) },
1090            AddressConfig {
1091                address_count: 1,
1092                preferred_addresses: Some(vec![fidl_ip_v6!("a::1")]),
1093            },
1094            AddressConfig {
1095                address_count: 2,
1096                preferred_addresses: Some(vec![fidl_ip_v6!("a::2")]),
1097            },
1098        ]
1099    }
1100
1101    #[fuchsia::test]
1102    fn test_client_starts_with_valid_args() {
1103        for information_config in VALID_INFORMATION_CONFIGS {
1104            for non_temporary_address_config in get_valid_non_temporary_address_configs() {
1105                for prefix_delegation_config in VALID_DELEGATED_PREFIX_CONFIGS {
1106                    let mut exec = fasync::TestExecutor::new();
1107
1108                    let (client_proxy, server_end) = create_proxy::<ClientMarker>();
1109
1110                    let test_fut = async {
1111                        join!(
1112                            client_proxy.watch_servers(),
1113                            serve_client(
1114                                NewClientParams {
1115                                    interface_id: 1,
1116                                    address: fidl_socket_addr_v6!("[::1]:546"),
1117                                    config: ClientConfig {
1118                                        information_config: information_config.clone(),
1119                                        non_temporary_address_config: non_temporary_address_config
1120                                            .clone(),
1121                                        prefix_delegation_config: prefix_delegation_config.clone(),
1122                                    },
1123                                    duid: (non_temporary_address_config.address_count != 0
1124                                        || prefix_delegation_config.is_some())
1125                                    .then(|| fnet_dhcpv6::Duid::LinkLayerAddress(
1126                                        fnet_dhcpv6::LinkLayerAddress::Ethernet(fidl_mac!(
1127                                            "00:11:22:33:44:55"
1128                                        ))
1129                                    )),
1130                                },
1131                                server_end
1132                            )
1133                        )
1134                    };
1135                    let mut test_fut = pin!(test_fut);
1136                    assert_matches!(
1137                        exec.run_until_stalled(&mut test_fut),
1138                        Poll::Pending,
1139                        "information_config={:?}, non_temporary_address_config={:?}, prefix_delegation_config={:?}",
1140                        information_config,
1141                        non_temporary_address_config,
1142                        prefix_delegation_config
1143                    );
1144                }
1145            }
1146        }
1147    }
1148
1149    const CLIENT_ID: [u8; 18] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17];
1150
1151    #[fuchsia::test]
1152    async fn test_client_starts_in_correct_mode() {
1153        for information_config @ InformationConfig { dns_servers } in VALID_INFORMATION_CONFIGS {
1154            for non_temporary_address_config @ AddressConfig {
1155                address_count,
1156                preferred_addresses: _,
1157            } in get_valid_non_temporary_address_configs()
1158            {
1159                for prefix_delegation_config in VALID_DELEGATED_PREFIX_CONFIGS {
1160                    let (stateful, want_msg_type) =
1161                        if address_count == 0 && prefix_delegation_config.is_none() {
1162                            if !dns_servers {
1163                                continue;
1164                            } else {
1165                                (false, v6::MessageType::InformationRequest)
1166                            }
1167                        } else {
1168                            (true, v6::MessageType::Solicit)
1169                        };
1170
1171                    let (_, client_stream): (ClientEnd<ClientMarker>, _) =
1172                        create_request_stream::<ClientMarker>();
1173
1174                    let (client_socket, client_addr) = create_test_socket();
1175                    let (server_socket, server_addr) = create_test_socket();
1176                    println!(
1177                        "{:?} {:?} {:?}",
1178                        information_config, non_temporary_address_config, prefix_delegation_config
1179                    );
1180                    let _: Client<fasync::net::UdpSocket> = Client::start(
1181                        stateful.then(|| CLIENT_ID.into()),
1182                        [1, 2, 3], /* transaction ID */
1183                        ClientConfig {
1184                            information_config: information_config.clone(),
1185                            non_temporary_address_config: non_temporary_address_config.clone(),
1186                            prefix_delegation_config: prefix_delegation_config.clone(),
1187                        },
1188                        1, /* interface ID */
1189                        || Ok(client_socket),
1190                        server_addr,
1191                        client_stream,
1192                    )
1193                    .await
1194                        .unwrap_or_else(|e| panic!(
1195                            "failed to create test client: {}; information_config={:?}, non_temporary_address_config={:?}, prefix_delegation_config={:?}",
1196                            e, information_config, non_temporary_address_config, prefix_delegation_config
1197                        ));
1198
1199                    let _: ReceivedMessage =
1200                        assert_received_message(&server_socket, client_addr, want_msg_type).await;
1201                }
1202            }
1203        }
1204    }
1205
1206    // TODO(https://fxbug.dev/335656784): Replace this with a netemul test that isn't
1207    // sensitive to implementation details.
1208    #[fuchsia::test]
1209    async fn test_client_fails_to_start_with_invalid_args() {
1210        for params in vec![
1211            // Interface ID and zone index mismatch on link-local address.
1212            NewClientParams {
1213                interface_id: 2,
1214                address: fnet::Ipv6SocketAddress {
1215                    address: fidl_ip_v6!("fe80::1"),
1216                    port: DEFAULT_CLIENT_PORT,
1217                    zone_index: 1,
1218                },
1219                config: STATELESS_CLIENT_CONFIG,
1220                duid: None,
1221            },
1222            // Multicast address is invalid.
1223            NewClientParams {
1224                interface_id: 1,
1225                address: fnet::Ipv6SocketAddress {
1226                    address: fidl_ip_v6!("ff01::1"),
1227                    port: DEFAULT_CLIENT_PORT,
1228                    zone_index: 1,
1229                },
1230                config: STATELESS_CLIENT_CONFIG,
1231                duid: None,
1232            },
1233            // Stateless with DUID.
1234            NewClientParams {
1235                interface_id: 1,
1236                address: fidl_socket_addr_v6!("[2001:db8::1]:12345"),
1237                config: STATELESS_CLIENT_CONFIG,
1238                duid: Some(fnet_dhcpv6::Duid::LinkLayerAddress(
1239                    fnet_dhcpv6::LinkLayerAddress::Ethernet(fidl_mac!("00:11:22:33:44:55")),
1240                )),
1241            },
1242            // Stateful missing DUID.
1243            NewClientParams {
1244                interface_id: 1,
1245                address: fidl_socket_addr_v6!("[2001:db8::1]:12345"),
1246                config: ClientConfig {
1247                    information_config: InformationConfig { dns_servers: true },
1248                    non_temporary_address_config: AddressConfig {
1249                        address_count: 1,
1250                        preferred_addresses: None,
1251                    },
1252                    prefix_delegation_config: None,
1253                },
1254                duid: None,
1255            },
1256        ] {
1257            let (client_proxy, server_end) = create_proxy::<ClientMarker>();
1258            let () =
1259                serve_client(params, server_end).await.expect("start server failed unexpectedly");
1260            // Calling any function on the client proxy should fail due to channel closed with
1261            // `INVALID_ARGS`.
1262            assert_matches!(
1263                client_proxy.watch_servers().await,
1264                Err(fidl::Error::ClientChannelClosed { status: zx::Status::INVALID_ARGS, .. })
1265            );
1266        }
1267    }
1268
1269    #[test]
1270    fn test_is_unicast_link_local_strict() {
1271        assert_eq!(is_unicast_link_local_strict(&fidl_ip_v6!("fe80::")), true);
1272        assert_eq!(is_unicast_link_local_strict(&fidl_ip_v6!("fe80::1")), true);
1273        assert_eq!(is_unicast_link_local_strict(&fidl_ip_v6!("fe80::ffff:1:2:3")), true);
1274        assert_eq!(is_unicast_link_local_strict(&fidl_ip_v6!("fe80::1:0:0:0:0")), false);
1275        assert_eq!(is_unicast_link_local_strict(&fidl_ip_v6!("fe81::")), false);
1276    }
1277
1278    fn create_test_dns_server(
1279        address: fnet::Ipv6Address,
1280        source_interface: u64,
1281        zone_index: u64,
1282    ) -> fnet_name::DnsServer_ {
1283        fnet_name::DnsServer_ {
1284            address: Some(fnet::SocketAddress::Ipv6(fnet::Ipv6SocketAddress {
1285                address,
1286                zone_index,
1287                port: DEFAULT_DNS_PORT,
1288            })),
1289            source: Some(fnet_name::DnsServerSource::Dhcpv6(fnet_name::Dhcpv6DnsServerSource {
1290                source_interface: Some(source_interface),
1291                ..Default::default()
1292            })),
1293            ..Default::default()
1294        }
1295    }
1296
1297    async fn send_msg_with_options(
1298        socket: &fasync::net::UdpSocket,
1299        to_addr: SocketAddr,
1300        transaction_id: [u8; 3],
1301        msg_type: v6::MessageType,
1302        options: &[v6::DhcpOption<'_>],
1303    ) -> Result<()> {
1304        let builder = v6::MessageBuilder::new(msg_type, transaction_id, options);
1305        let mut buf = vec![0u8; builder.bytes_len()];
1306        builder.serialize(&mut buf);
1307        let size = socket.send_to(&buf, to_addr).await?;
1308        assert_eq!(size, buf.len());
1309        Ok(())
1310    }
1311
1312    #[fuchsia::test]
1313    fn test_client_should_respond_to_dns_watch_requests() {
1314        let mut exec = fasync::TestExecutor::new();
1315        let transaction_id = [1, 2, 3];
1316
1317        let (client_proxy, client_stream) = create_proxy_and_stream::<ClientMarker>();
1318
1319        let (client_socket, client_addr) = create_test_socket();
1320        let (server_socket, server_addr) = create_test_socket();
1321        let mut client = exec
1322            .run_singlethreaded(Client::<fasync::net::UdpSocket>::start(
1323                None,
1324                transaction_id,
1325                STATELESS_CLIENT_CONFIG,
1326                1, /* interface ID */
1327                || Ok(client_socket),
1328                server_addr,
1329                client_stream,
1330            ))
1331            .expect("failed to create test client");
1332
1333        type WatchServersResponseFut = <fnet_dhcpv6::ClientProxy as fnet_dhcpv6::ClientProxyInterface>::WatchServersResponseFut;
1334        type WatchServersResponse = <WatchServersResponseFut as Future>::Output;
1335
1336        struct Test<'a> {
1337            client: &'a mut Client<fasync::net::UdpSocket>,
1338            buf: Vec<u8>,
1339            watcher_fut: WatchServersResponseFut,
1340        }
1341
1342        impl<'a> Test<'a> {
1343            fn new(
1344                client: &'a mut Client<fasync::net::UdpSocket>,
1345                client_proxy: &ClientProxy,
1346            ) -> Self {
1347                Self {
1348                    client,
1349                    buf: vec![0u8; MAX_UDP_DATAGRAM_SIZE],
1350                    watcher_fut: client_proxy.watch_servers(),
1351                }
1352            }
1353
1354            async fn handle_next_event(&mut self) {
1355                self.client
1356                    .handle_next_event(&mut self.buf)
1357                    .await
1358                    .expect("test client failed to handle next event")
1359                    .expect("request stream closed");
1360            }
1361
1362            async fn refresh_client(&mut self) {
1363                // Make the client ready for another reply immediately on signal, so it can
1364                // start receiving updates without waiting for the full refresh timeout which is
1365                // unrealistic in tests.
1366                if self
1367                    .client
1368                    .timers
1369                    .as_ref()
1370                    .scheduled
1371                    .contains(&dhcpv6_core::client::ClientTimerType::Refresh)
1372                {
1373                    self.client
1374                        .handle_timeout(dhcpv6_core::client::ClientTimerType::Refresh)
1375                        .await
1376                        .expect("test client failed to handle timeout");
1377                } else {
1378                    panic!("no refresh timer is scheduled and refresh is requested in test");
1379                }
1380            }
1381
1382            // Drive both the DHCPv6 client's event handling logic and the DNS server
1383            // watcher until the DNS server watcher receives an update from the client (or
1384            // the client unexpectedly exits).
1385            fn run(&mut self) -> impl Future<Output = WatchServersResponse> + use<'_, 'a> {
1386                let Self { client, buf, watcher_fut } = self;
1387                async move {
1388                    let client_fut = async {
1389                        loop {
1390                            client
1391                                .handle_next_event(buf)
1392                                .await
1393                                .expect("test client failed to handle next event")
1394                                .expect("request stream closed");
1395                        }
1396                    }
1397                    .fuse();
1398                    let mut client_fut = pin!(client_fut);
1399                    let mut watcher_fut = watcher_fut.fuse();
1400                    select! {
1401                        () = client_fut => panic!("test client returned unexpectedly"),
1402                        r = watcher_fut => r,
1403                    }
1404                }
1405            }
1406        }
1407
1408        {
1409            // No DNS configurations received yet.
1410            let mut test = Test::new(&mut client, &client_proxy);
1411
1412            // Handle the WatchServers request.
1413            exec.run_singlethreaded(test.handle_next_event());
1414            assert!(
1415                test.client.dns_responder.is_some(),
1416                "WatchServers responder should be present"
1417            );
1418
1419            // Send an empty list to the client, should not update watcher.
1420            exec.run_singlethreaded(send_msg_with_options(
1421                &server_socket,
1422                client_addr,
1423                transaction_id,
1424                v6::MessageType::Reply,
1425                &[v6::DhcpOption::ServerId(&[1, 2, 3]), v6::DhcpOption::DnsServers(&[])],
1426            ))
1427            .expect("failed to send test reply");
1428            // Wait for the client to handle the next event (processing the reply we just
1429            // sent). Note that it is not enough to simply drive the client future until it
1430            // is stalled as we do elsewhere in the test, because we have no guarantee that
1431            // the netstack has delivered the UDP packet to the client by the time the
1432            // `send_to` call returned.
1433            exec.run_singlethreaded(test.handle_next_event());
1434            assert_matches!(exec.run_until_stalled(&mut pin!(test.run())), Poll::Pending);
1435
1436            // Send a list of DNS servers, the watcher should be updated accordingly.
1437            exec.run_singlethreaded(test.refresh_client());
1438            let dns_servers = [net_ip_v6!("fe80::1:2")];
1439            exec.run_singlethreaded(send_msg_with_options(
1440                &server_socket,
1441                client_addr,
1442                transaction_id,
1443                v6::MessageType::Reply,
1444                &[v6::DhcpOption::ServerId(&[1, 2, 3]), v6::DhcpOption::DnsServers(&dns_servers)],
1445            ))
1446            .expect("failed to send test reply");
1447            let want_servers = vec![create_test_dns_server(
1448                fidl_ip_v6!("fe80::1:2"),
1449                1, /* source interface */
1450                1, /* zone index */
1451            )];
1452            let servers = exec.run_singlethreaded(test.run()).expect("get servers");
1453            assert_eq!(servers, want_servers);
1454        } // drop `test_fut` so `client_fut` is no longer mutably borrowed.
1455
1456        {
1457            // No new changes, should not update watcher.
1458            let mut test = Test::new(&mut client, &client_proxy);
1459
1460            // Handle the WatchServers request.
1461            exec.run_singlethreaded(test.handle_next_event());
1462            assert!(
1463                test.client.dns_responder.is_some(),
1464                "WatchServers responder should be present"
1465            );
1466
1467            // Send the same list of DNS servers, should not update watcher.
1468            exec.run_singlethreaded(test.refresh_client());
1469            let dns_servers = [net_ip_v6!("fe80::1:2")];
1470            exec.run_singlethreaded(send_msg_with_options(
1471                &server_socket,
1472                client_addr,
1473                transaction_id,
1474                v6::MessageType::Reply,
1475                &[v6::DhcpOption::ServerId(&[1, 2, 3]), v6::DhcpOption::DnsServers(&dns_servers)],
1476            ))
1477            .expect("failed to send test reply");
1478            // Wait for the client to handle the next event (processing the reply we just
1479            // sent). Note that it is not enough to simply drive the client future until it
1480            // is stalled as we do elsewhere in the test, because we have no guarantee that
1481            // the netstack has delivered the UDP packet to the client by the time the
1482            // `send_to` call returned.
1483            exec.run_singlethreaded(test.handle_next_event());
1484            assert_matches!(exec.run_until_stalled(&mut pin!(test.run())), Poll::Pending);
1485
1486            // Send a different list of DNS servers, should update watcher.
1487            exec.run_singlethreaded(test.refresh_client());
1488            let dns_servers = [net_ip_v6!("fe80::1:2"), net_ip_v6!("1234::5:6")];
1489            exec.run_singlethreaded(send_msg_with_options(
1490                &server_socket,
1491                client_addr,
1492                transaction_id,
1493                v6::MessageType::Reply,
1494                &[v6::DhcpOption::ServerId(&[1, 2, 3]), v6::DhcpOption::DnsServers(&dns_servers)],
1495            ))
1496            .expect("failed to send test reply");
1497            let want_servers = vec![
1498                create_test_dns_server(
1499                    fidl_ip_v6!("fe80::1:2"),
1500                    1, /* source interface */
1501                    1, /* zone index */
1502                ),
1503                // Only set zone index for link local addresses.
1504                create_test_dns_server(
1505                    fidl_ip_v6!("1234::5:6"),
1506                    1, /* source interface */
1507                    0, /* zone index */
1508                ),
1509            ];
1510            let servers = exec.run_singlethreaded(test.run()).expect("get servers");
1511            assert_eq!(servers, want_servers);
1512        } // drop `test_fut` so `client_fut` is no longer mutably borrowed.
1513
1514        {
1515            // Send an empty list of DNS servers, should update watcher,
1516            // because this is different from what the watcher has seen
1517            // last time.
1518            let mut test = Test::new(&mut client, &client_proxy);
1519
1520            exec.run_singlethreaded(test.refresh_client());
1521            exec.run_singlethreaded(send_msg_with_options(
1522                &server_socket,
1523                client_addr,
1524                transaction_id,
1525                v6::MessageType::Reply,
1526                &[v6::DhcpOption::ServerId(&[1, 2, 3]), v6::DhcpOption::DnsServers(&[])],
1527            ))
1528            .expect("failed to send test reply");
1529            let want_servers = Vec::<fnet_name::DnsServer_>::new();
1530            assert_eq!(exec.run_singlethreaded(test.run()).expect("get servers"), want_servers);
1531        } // drop `test_fut` so `client_fut` is no longer mutably borrowed.
1532    }
1533
1534    #[fuchsia::test]
1535    async fn test_client_should_respond_with_dns_servers_on_first_watch_if_non_empty() {
1536        let transaction_id = [1, 2, 3];
1537
1538        let (client_proxy, client_stream) = create_proxy_and_stream::<ClientMarker>();
1539
1540        let (client_socket, client_addr) = create_test_socket();
1541        let (server_socket, server_addr) = create_test_socket();
1542        let client = Client::<fasync::net::UdpSocket>::start(
1543            None,
1544            transaction_id,
1545            STATELESS_CLIENT_CONFIG,
1546            1, /* interface ID */
1547            || Ok(client_socket),
1548            server_addr,
1549            client_stream,
1550        )
1551        .await
1552        .expect("failed to create test client");
1553
1554        let dns_servers = [net_ip_v6!("fe80::1:2"), net_ip_v6!("1234::5:6")];
1555        send_msg_with_options(
1556            &server_socket,
1557            client_addr,
1558            transaction_id,
1559            v6::MessageType::Reply,
1560            &[v6::DhcpOption::ServerId(&[4, 5, 6]), v6::DhcpOption::DnsServers(&dns_servers)],
1561        )
1562        .await
1563        .expect("failed to send test message");
1564
1565        let buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
1566        let handle_client_events_fut =
1567            futures::stream::try_unfold((client, buf), |(mut client, mut buf)| async {
1568                client
1569                    .handle_next_event(&mut buf)
1570                    .await
1571                    .map(|res| res.map(|()| ((), (client, buf))))
1572            })
1573            .try_fold((), |(), ()| futures::future::ready(Ok(())))
1574            .fuse();
1575        let mut handle_client_events_fut = pin!(handle_client_events_fut);
1576
1577        let want_servers = vec![
1578            create_test_dns_server(
1579                fidl_ip_v6!("fe80::1:2"),
1580                1, /* source interface */
1581                1, /* zone index */
1582            ),
1583            create_test_dns_server(
1584                fidl_ip_v6!("1234::5:6"),
1585                1, /* source interface */
1586                0, /* zone index */
1587            ),
1588        ];
1589        let found_servers = select!(
1590            status = handle_client_events_fut => panic!("client unexpectedly exited: {status:?}"),
1591            found_servers = client_proxy.watch_servers() => found_servers.expect(
1592                "watch servers should succeed"),
1593        );
1594        assert_eq!(found_servers, want_servers);
1595    }
1596
1597    #[fuchsia::test]
1598    async fn watch_prefixes() {
1599        const SERVER_ID: [u8; 3] = [3, 4, 5];
1600        const PREFERRED_LIFETIME_SECS: u32 = 1000;
1601        const VALID_LIFETIME_SECS: u32 = 2000;
1602        // Use the smallest possible value to enter the Renewing state
1603        // as fast as possible to keep the test's run-time as low as possible.
1604        const T1: u32 = 1;
1605        const T2: u32 = 2000;
1606
1607        let (client_proxy, client_stream) = create_proxy_and_stream::<ClientMarker>();
1608
1609        let (client_socket, client_addr) = create_test_socket();
1610        let (server_socket, server_addr) = create_test_socket();
1611        let mut client = Client::<fasync::net::UdpSocket>::start(
1612            Some(CLIENT_ID.into()),
1613            [1, 2, 3],
1614            ClientConfig {
1615                information_config: Default::default(),
1616                non_temporary_address_config: Default::default(),
1617                prefix_delegation_config: Some(PrefixDelegationConfig::Empty(Empty {})),
1618            },
1619            1, /* interface ID */
1620            || Ok(client_socket),
1621            server_addr,
1622            client_stream,
1623        )
1624        .await
1625        .expect("failed to create test client");
1626
1627        let client_fut = async {
1628            let mut buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
1629            loop {
1630                select! {
1631                    res = client.handle_next_event(&mut buf).fuse() => {
1632                        match res.expect("test client failed to handle next event") {
1633                            Some(()) => (),
1634                            None => break (),
1635                        };
1636                    }
1637                }
1638            }
1639        }
1640        .fuse();
1641        let mut client_fut = pin!(client_fut);
1642
1643        let update_prefix = net_subnet_v6!("a::/64");
1644        let remove_prefix = net_subnet_v6!("b::/64");
1645        let add_prefix = net_subnet_v6!("c::/64");
1646
1647        // Go through the motions to assign a prefix.
1648        let client_id = {
1649            let ReceivedMessage { client_id, transaction_id } =
1650                assert_received_message(&server_socket, client_addr, v6::MessageType::Solicit)
1651                    .await;
1652            // Client IDs are mandatory in stateful DHCPv6.
1653            let client_id = client_id.unwrap();
1654
1655            let ia_prefix = [
1656                v6::DhcpOption::IaPrefix(v6::IaPrefixSerializer::new(
1657                    PREFERRED_LIFETIME_SECS,
1658                    VALID_LIFETIME_SECS,
1659                    update_prefix,
1660                    &[],
1661                )),
1662                v6::DhcpOption::IaPrefix(v6::IaPrefixSerializer::new(
1663                    PREFERRED_LIFETIME_SECS,
1664                    VALID_LIFETIME_SECS,
1665                    remove_prefix,
1666                    &[],
1667                )),
1668            ];
1669            send_msg_with_options(
1670                &server_socket,
1671                client_addr,
1672                transaction_id,
1673                v6::MessageType::Advertise,
1674                &[
1675                    v6::DhcpOption::ServerId(&SERVER_ID),
1676                    v6::DhcpOption::ClientId(&client_id),
1677                    v6::DhcpOption::Preference(u8::MAX),
1678                    v6::DhcpOption::IaPd(v6::IaPdSerializer::new(IA_PD_IAID, T1, T2, &ia_prefix)),
1679                ],
1680            )
1681            .await
1682            .expect("failed to send adv message");
1683
1684            // Wait for the client to send a Request and send Reply so a prefix
1685            // is assigned.
1686            let transaction_id = select! {
1687                () = client_fut => panic!("should never return"),
1688                res = assert_received_message(
1689                    &server_socket,
1690                    client_addr,
1691                    v6::MessageType::Request,
1692                ).fuse() => {
1693                    let ReceivedMessage { client_id: req_client_id, transaction_id } = res;
1694                    assert_eq!(Some(&client_id), req_client_id.as_ref());
1695                    transaction_id
1696                },
1697            };
1698
1699            send_msg_with_options(
1700                &server_socket,
1701                client_addr,
1702                transaction_id,
1703                v6::MessageType::Reply,
1704                &[
1705                    v6::DhcpOption::ServerId(&SERVER_ID),
1706                    v6::DhcpOption::ClientId(&client_id),
1707                    v6::DhcpOption::IaPd(v6::IaPdSerializer::new(IA_PD_IAID, T1, T2, &ia_prefix)),
1708                ],
1709            )
1710            .await
1711            .expect("failed to send reply message");
1712
1713            client_id
1714        };
1715
1716        let check_watch_prefixes_result =
1717            |res: Result<Vec<Prefix>, _>,
1718             before_handling_reply,
1719             preferred_lifetime_secs: u32,
1720             valid_lifetime_secs: u32,
1721             expected_prefixes| {
1722                assert_matches!(
1723                    res.unwrap()[..],
1724                    [
1725                        Prefix {
1726                            prefix: got_prefix1,
1727                            lifetimes: Lifetimes {
1728                                preferred_until: preferred_until1,
1729                                valid_until: valid_until1,
1730                            },
1731                        },
1732                        Prefix {
1733                            prefix: got_prefix2,
1734                            lifetimes: Lifetimes {
1735                                preferred_until: preferred_until2,
1736                                valid_until: valid_until2,
1737                            },
1738                        },
1739                    ] => {
1740                        let now = zx::MonotonicInstant::get();
1741                        let preferred_until = zx::MonotonicInstant::from_nanos(preferred_until1);
1742                        let valid_until = zx::MonotonicInstant::from_nanos(valid_until1);
1743
1744                        let preferred_for = zx::MonotonicDuration::from_seconds(
1745                            preferred_lifetime_secs.into(),
1746                        );
1747                        let valid_for = zx::MonotonicDuration::from_seconds(valid_lifetime_secs.into());
1748
1749                        assert_eq!(
1750                            HashSet::from([got_prefix1, got_prefix2]),
1751                            HashSet::from(expected_prefixes),
1752                        );
1753                        assert!(preferred_until >= before_handling_reply + preferred_for);
1754                        assert!(preferred_until <= now + preferred_for);
1755                        assert!(valid_until >= before_handling_reply + valid_for);
1756                        assert!(valid_until <= now + valid_for);
1757
1758                        assert_eq!(preferred_until1, preferred_until2);
1759                        assert_eq!(valid_until1, valid_until2);
1760                    }
1761                )
1762            };
1763
1764        // Wait for a prefix to become assigned from the perspective of the DHCPv6
1765        // FIDL client.
1766        {
1767            // watch_prefixes should not return before a lease is negotiated. Note
1768            // that the client has not yet handled the Reply message.
1769            let mut watch_prefixes = client_proxy.watch_prefixes().fuse();
1770            assert_matches!(poll!(&mut watch_prefixes), Poll::Pending);
1771            let before_handling_reply = zx::MonotonicInstant::get();
1772            select! {
1773                () = client_fut => panic!("should never return"),
1774                res = watch_prefixes => check_watch_prefixes_result(
1775                    res,
1776                    before_handling_reply,
1777                    PREFERRED_LIFETIME_SECS,
1778                    VALID_LIFETIME_SECS,
1779                    [
1780                        subnet_to_address_with_prefix(update_prefix),
1781                        subnet_to_address_with_prefix(remove_prefix),
1782                    ],
1783                ),
1784            }
1785        }
1786
1787        // Wait for the client to attempt to renew the lease and go through the
1788        // motions to update the lease.
1789        {
1790            let transaction_id = select! {
1791                () = client_fut => panic!("should never return"),
1792                res = assert_received_message(
1793                    &server_socket,
1794                    client_addr,
1795                    v6::MessageType::Renew,
1796                ).fuse() => {
1797                    let ReceivedMessage { client_id: ren_client_id, transaction_id } = res;
1798                    assert_eq!(ren_client_id.as_ref(), Some(&client_id));
1799                    transaction_id
1800                },
1801            };
1802
1803            const NEW_PREFERRED_LIFETIME_SECS: u32 = 2 * PREFERRED_LIFETIME_SECS;
1804            const NEW_VALID_LIFETIME_SECS: u32 = 2 * VALID_LIFETIME_SECS;
1805            let ia_prefix = [
1806                v6::DhcpOption::IaPrefix(v6::IaPrefixSerializer::new(
1807                    NEW_PREFERRED_LIFETIME_SECS,
1808                    NEW_VALID_LIFETIME_SECS,
1809                    update_prefix,
1810                    &[],
1811                )),
1812                v6::DhcpOption::IaPrefix(v6::IaPrefixSerializer::new(
1813                    NEW_PREFERRED_LIFETIME_SECS,
1814                    NEW_VALID_LIFETIME_SECS,
1815                    add_prefix,
1816                    &[],
1817                )),
1818                v6::DhcpOption::IaPrefix(v6::IaPrefixSerializer::new(0, 0, remove_prefix, &[])),
1819            ];
1820
1821            send_msg_with_options(
1822                &server_socket,
1823                client_addr,
1824                transaction_id,
1825                v6::MessageType::Reply,
1826                &[
1827                    v6::DhcpOption::ServerId(&SERVER_ID),
1828                    v6::DhcpOption::ClientId(&client_id),
1829                    v6::DhcpOption::IaPd(v6::IaPdSerializer::new(
1830                        v6::IAID::new(0),
1831                        T1,
1832                        T2,
1833                        &ia_prefix,
1834                    )),
1835                ],
1836            )
1837            .await
1838            .expect("failed to send reply message");
1839
1840            let before_handling_reply = zx::MonotonicInstant::get();
1841            select! {
1842                () = client_fut => panic!("should never return"),
1843                res = client_proxy.watch_prefixes().fuse() => check_watch_prefixes_result(
1844                    res,
1845                    before_handling_reply,
1846                    NEW_PREFERRED_LIFETIME_SECS,
1847                    NEW_VALID_LIFETIME_SECS,
1848                    [
1849                        subnet_to_address_with_prefix(update_prefix),
1850                        subnet_to_address_with_prefix(add_prefix),
1851                    ],
1852                ),
1853            }
1854        }
1855    }
1856
1857    #[fuchsia::test]
1858    async fn test_client_schedule_and_cancel_timers() {
1859        let (_client_end, client_stream) = create_request_stream::<ClientMarker>();
1860
1861        let (client_socket, _client_addr) = create_test_socket();
1862        let (_server_socket, server_addr) = create_test_socket();
1863        let mut client = Client::<fasync::net::UdpSocket>::start(
1864            None,
1865            [1, 2, 3], /* transaction ID */
1866            STATELESS_CLIENT_CONFIG,
1867            1, /* interface ID */
1868            || Ok(client_socket),
1869            server_addr,
1870            client_stream,
1871        )
1872        .await
1873        .expect("failed to create test client");
1874
1875        // Stateless DHCP client starts by scheduling a retransmission timer.
1876        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
1877
1878        client.cancel_timer(dhcpv6_core::client::ClientTimerType::Retransmission);
1879        client.assert_scheduled([]);
1880
1881        let now = MonotonicInstant::now();
1882        client.schedule_timer(
1883            dhcpv6_core::client::ClientTimerType::Refresh,
1884            now + Duration::from_nanos(1),
1885        );
1886        client.schedule_timer(
1887            dhcpv6_core::client::ClientTimerType::Retransmission,
1888            now + Duration::from_nanos(2),
1889        );
1890        client.assert_scheduled([
1891            dhcpv6_core::client::ClientTimerType::Retransmission,
1892            dhcpv6_core::client::ClientTimerType::Refresh,
1893        ]);
1894
1895        // We are allowed to reschedule a timer to fire at a new time.
1896        let now = MonotonicInstant::now();
1897        client.schedule_timer(
1898            dhcpv6_core::client::ClientTimerType::Refresh,
1899            now + Duration::from_nanos(1),
1900        );
1901        client.schedule_timer(
1902            dhcpv6_core::client::ClientTimerType::Retransmission,
1903            now + Duration::from_nanos(2),
1904        );
1905
1906        client.cancel_timer(dhcpv6_core::client::ClientTimerType::Refresh);
1907        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
1908
1909        // Ok to cancel a timer that is not scheduled.
1910        client.cancel_timer(dhcpv6_core::client::ClientTimerType::Refresh);
1911
1912        client.cancel_timer(dhcpv6_core::client::ClientTimerType::Retransmission);
1913        client.assert_scheduled([]);
1914
1915        // Ok to cancel a timer that is not scheduled.
1916        client.cancel_timer(dhcpv6_core::client::ClientTimerType::Retransmission);
1917    }
1918
1919    #[fuchsia::test]
1920    async fn test_handle_next_event_on_stateless_client() {
1921        let (client_proxy, client_stream) = create_proxy_and_stream::<ClientMarker>();
1922
1923        let (client_socket, client_addr) = create_test_socket();
1924        let (server_socket, server_addr) = create_test_socket();
1925        let mut client = Client::<fasync::net::UdpSocket>::start(
1926            None,
1927            [1, 2, 3], /* transaction ID */
1928            STATELESS_CLIENT_CONFIG,
1929            1, /* interface ID */
1930            || Ok(client_socket),
1931            server_addr,
1932            client_stream,
1933        )
1934        .await
1935        .expect("failed to create test client");
1936
1937        // Starting the client in stateless should send an information request out.
1938        let ReceivedMessage { client_id, transaction_id: _ } = assert_received_message(
1939            &server_socket,
1940            client_addr,
1941            v6::MessageType::InformationRequest,
1942        )
1943        .await;
1944        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
1945
1946        let mut buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
1947        // Trigger a retransmission.
1948        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
1949        let ReceivedMessage { client_id: got_client_id, transaction_id: _ } =
1950            assert_received_message(
1951                &server_socket,
1952                client_addr,
1953                v6::MessageType::InformationRequest,
1954            )
1955            .await;
1956        assert_eq!(got_client_id, client_id);
1957        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
1958
1959        // Message targeting another transaction ID should be ignored.
1960        send_msg_with_options(&server_socket, client_addr, [5, 6, 7], v6::MessageType::Reply, &[])
1961            .await
1962            .expect("failed to send test message");
1963        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
1964        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
1965
1966        // Invalid messages should be discarded. Empty buffer is invalid.
1967        let size =
1968            server_socket.send_to(&[], client_addr).await.expect("failed to send test message");
1969        assert_eq!(size, 0);
1970        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
1971        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
1972
1973        // Message targeting this client should cause the client to transition state.
1974        send_msg_with_options(
1975            &server_socket,
1976            client_addr,
1977            [1, 2, 3],
1978            v6::MessageType::Reply,
1979            &[v6::DhcpOption::ServerId(&[4, 5, 6])],
1980        )
1981        .await
1982        .expect("failed to send test message");
1983        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
1984        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Refresh]);
1985
1986        // Reschedule a shorter timer for Refresh so we don't spend time waiting in test.
1987        client.schedule_timer(
1988            dhcpv6_core::client::ClientTimerType::Refresh,
1989            MonotonicInstant::now() + Duration::from_nanos(1),
1990        );
1991
1992        // Trigger a refresh.
1993        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
1994        let ReceivedMessage { client_id, transaction_id: _ } = assert_received_message(
1995            &server_socket,
1996            client_addr,
1997            v6::MessageType::InformationRequest,
1998        )
1999        .await;
2000        assert_eq!(got_client_id, client_id,);
2001        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
2002
2003        let test_fut = async {
2004            assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
2005            client
2006                .dns_responder
2007                .take()
2008                .expect("test client did not get a channel responder")
2009                .send(&[fnet_name::DnsServer_ {
2010                    address: Some(fidl_socket_addr!("[fe01::2:3]:42")),
2011                    source: Some(fnet_name::DnsServerSource::Dhcpv6(
2012                        fnet_name::Dhcpv6DnsServerSource {
2013                            source_interface: Some(42),
2014                            ..Default::default()
2015                        },
2016                    )),
2017                    ..Default::default()
2018                }])
2019                .expect("failed to send response on test channel");
2020        };
2021        let (watcher_res, ()) = join!(client_proxy.watch_servers(), test_fut);
2022        let servers = watcher_res.expect("failed to watch servers");
2023        assert_eq!(
2024            servers,
2025            vec![fnet_name::DnsServer_ {
2026                address: Some(fidl_socket_addr!("[fe01::2:3]:42")),
2027                source: Some(fnet_name::DnsServerSource::Dhcpv6(
2028                    fnet_name::Dhcpv6DnsServerSource {
2029                        source_interface: Some(42),
2030                        ..Default::default()
2031                    },
2032                )),
2033                ..Default::default()
2034            }]
2035        );
2036
2037        // Drop the channel should cause `handle_next_event(&mut buf)` to return `None`.
2038        drop(client_proxy);
2039        assert_matches!(client.handle_next_event(&mut buf).await, Ok(None));
2040    }
2041
2042    #[fuchsia::test]
2043    async fn test_handle_next_event_on_stateful_client() {
2044        let (client_proxy, client_stream) = create_proxy_and_stream::<ClientMarker>();
2045
2046        let (client_socket, client_addr) = create_test_socket();
2047        let (server_socket, server_addr) = create_test_socket();
2048        let mut client = Client::<fasync::net::UdpSocket>::start(
2049            Some(CLIENT_ID.into()),
2050            [1, 2, 3], /* transaction ID */
2051            ClientConfig {
2052                information_config: Default::default(),
2053                non_temporary_address_config: AddressConfig {
2054                    address_count: 1,
2055                    preferred_addresses: None,
2056                },
2057                prefix_delegation_config: None,
2058            },
2059            1, /* interface ID */
2060            || Ok(client_socket),
2061            server_addr,
2062            client_stream,
2063        )
2064        .await
2065        .expect("failed to create test client");
2066
2067        // Starting the client in stateful should send out a solicit.
2068        let _: ReceivedMessage =
2069            assert_received_message(&server_socket, client_addr, v6::MessageType::Solicit).await;
2070        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
2071
2072        let mut buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
2073        // Drop the channel should cause `handle_next_event(&mut buf)` to return `None`.
2074        drop(client_proxy);
2075        assert_matches!(client.handle_next_event(&mut buf).await, Ok(None));
2076    }
2077
2078    #[fuchsia::test]
2079    #[should_panic = "received unexpected refresh timeout in state InformationRequesting"]
2080    async fn test_handle_next_event_respects_timer_order() {
2081        let (_client_end, client_stream) = create_request_stream::<ClientMarker>();
2082
2083        let (client_socket, client_addr) = create_test_socket();
2084        let (server_socket, server_addr) = create_test_socket();
2085        let mut client = Client::<fasync::net::UdpSocket>::start(
2086            None,
2087            [1, 2, 3], /* transaction ID */
2088            STATELESS_CLIENT_CONFIG,
2089            1, /* interface ID */
2090            || Ok(client_socket),
2091            server_addr,
2092            client_stream,
2093        )
2094        .await
2095        .expect("failed to create test client");
2096
2097        let mut buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
2098        // A retransmission timer is scheduled when starting the client in stateless mode. Cancel
2099        // it and create a new one with a longer timeout so the test is not flaky.
2100        client.schedule_timer(
2101            dhcpv6_core::client::ClientTimerType::Retransmission,
2102            MonotonicInstant::now() + Duration::from_secs(1_000_000),
2103        );
2104        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
2105
2106        // Trigger a message receive, the message is later discarded because transaction ID doesn't
2107        // match.
2108        send_msg_with_options(&server_socket, client_addr, [5, 6, 7], v6::MessageType::Reply, &[])
2109            .await
2110            .expect("failed to send test message");
2111        // There are now two pending events, the message receive is handled first because the timer
2112        // is far into the future.
2113        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
2114        // The retransmission timer is still here.
2115        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
2116
2117        // Inserts a refresh timer that precedes the retransmission.
2118        client.schedule_timer(
2119            dhcpv6_core::client::ClientTimerType::Refresh,
2120            MonotonicInstant::now() + Duration::from_nanos(1),
2121        );
2122        // This timer is scheduled.
2123        client.assert_scheduled([
2124            dhcpv6_core::client::ClientTimerType::Retransmission,
2125            dhcpv6_core::client::ClientTimerType::Refresh,
2126        ]);
2127
2128        // Now handle_next_event(&mut buf) should trigger a refresh because it
2129        // precedes retransmission. Refresh is not expected while in
2130        // InformationRequesting state and should lead to a panic.
2131        let unreachable = client.handle_next_event(&mut buf).await;
2132        panic!("{unreachable:?}");
2133    }
2134
2135    #[fuchsia::test]
2136    async fn test_handle_next_event_fails_on_recv_err() {
2137        struct StubSocket {}
2138        impl<'a> AsyncSocket<'a> for StubSocket {
2139            type RecvFromFut = futures::future::Ready<Result<(usize, SocketAddr), std::io::Error>>;
2140            type SendToFut = futures::future::Ready<Result<usize, std::io::Error>>;
2141
2142            fn recv_from(&'a self, _buf: &'a mut [u8]) -> Self::RecvFromFut {
2143                futures::future::ready(Err(std::io::Error::other("test recv error")))
2144            }
2145            fn send_to(&'a self, buf: &'a [u8], _addr: SocketAddr) -> Self::SendToFut {
2146                futures::future::ready(Ok(buf.len()))
2147            }
2148        }
2149
2150        let (_client_end, client_stream) = create_request_stream::<ClientMarker>();
2151
2152        let mut client = Client::<StubSocket>::start(
2153            None,
2154            [1, 2, 3], /* transaction ID */
2155            STATELESS_CLIENT_CONFIG,
2156            1, /* interface ID */
2157            || Ok(StubSocket {}),
2158            std_socket_addr!("[::1]:0"),
2159            client_stream,
2160        )
2161        .await
2162        .expect("failed to create test client");
2163
2164        assert_matches!(
2165            client.handle_next_event(&mut [0u8]).await,
2166            Err(ClientError::SocketRecv(err)) if err.kind() == std::io::ErrorKind::Other
2167        );
2168    }
2169}