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::{select, stream, Future, FutureExt as _, StreamExt as _, TryStreamExt as _};
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, error, warn};
36use net_types::ip::{Ip as _, Ipv6, Ipv6Addr, Subnet, SubnetError};
37use net_types::MulticastAddress as _;
38use packet::ParsablePacket;
39use packet_formats_dhcp::v6;
40use rand::rngs::StdRng;
41use rand::SeedableRng;
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_entropy(),
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_entropy(),
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    let () = 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        let () = 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                        let () = 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                        let () = 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        let () = 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                let () = 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        let () = 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    let () = socket.set_reuse_port(true)?;
724    let () = 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        create_proxy, create_proxy_and_stream, create_request_stream, ClientEnd,
854    };
855    use fidl_fuchsia_net_dhcpv6::{self as fnet_dhcpv6, ClientProxy, DEFAULT_CLIENT_PORT};
856    use fuchsia_async as fasync;
857    use futures::{join, poll, TryFutureExt as _};
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!(client_res
1067            .expect_err("client should fail with double watch error")
1068            .to_string()
1069            .contains("got watch request while the previous one is pending"));
1070    }
1071
1072    const VALID_INFORMATION_CONFIGS: [InformationConfig; 2] =
1073        [InformationConfig { dns_servers: false }, InformationConfig { dns_servers: true }];
1074
1075    const VALID_DELEGATED_PREFIX_CONFIGS: [Option<PrefixDelegationConfig>; 4] = [
1076        Some(PrefixDelegationConfig::Empty(Empty {})),
1077        Some(PrefixDelegationConfig::PrefixLength(1)),
1078        Some(PrefixDelegationConfig::PrefixLength(127)),
1079        Some(PrefixDelegationConfig::Prefix(fidl_ip_v6_with_prefix!("a::/64"))),
1080    ];
1081
1082    // Can't be a const variable because we allocate a vector.
1083    fn get_valid_non_temporary_address_configs() -> [AddressConfig; 5] {
1084        [
1085            Default::default(),
1086            AddressConfig { address_count: 1, preferred_addresses: None },
1087            AddressConfig { address_count: 1, preferred_addresses: Some(Vec::new()) },
1088            AddressConfig {
1089                address_count: 1,
1090                preferred_addresses: Some(vec![fidl_ip_v6!("a::1")]),
1091            },
1092            AddressConfig {
1093                address_count: 2,
1094                preferred_addresses: Some(vec![fidl_ip_v6!("a::2")]),
1095            },
1096        ]
1097    }
1098
1099    #[fuchsia::test]
1100    fn test_client_starts_with_valid_args() {
1101        for information_config in VALID_INFORMATION_CONFIGS {
1102            for non_temporary_address_config in get_valid_non_temporary_address_configs() {
1103                for prefix_delegation_config in VALID_DELEGATED_PREFIX_CONFIGS {
1104                    let mut exec = fasync::TestExecutor::new();
1105
1106                    let (client_proxy, server_end) = create_proxy::<ClientMarker>();
1107
1108                    let test_fut = async {
1109                        join!(
1110                            client_proxy.watch_servers(),
1111                            serve_client(
1112                                NewClientParams {
1113                                    interface_id: 1,
1114                                    address: fidl_socket_addr_v6!("[::1]:546"),
1115                                    config: ClientConfig {
1116                                        information_config: information_config.clone(),
1117                                        non_temporary_address_config: non_temporary_address_config
1118                                            .clone(),
1119                                        prefix_delegation_config: prefix_delegation_config.clone(),
1120                                    },
1121                                    duid: (non_temporary_address_config.address_count != 0
1122                                        || prefix_delegation_config.is_some())
1123                                    .then(|| fnet_dhcpv6::Duid::LinkLayerAddress(
1124                                        fnet_dhcpv6::LinkLayerAddress::Ethernet(fidl_mac!(
1125                                            "00:11:22:33:44:55"
1126                                        ))
1127                                    )),
1128                                },
1129                                server_end
1130                            )
1131                        )
1132                    };
1133                    let mut test_fut = pin!(test_fut);
1134                    assert_matches!(
1135                        exec.run_until_stalled(&mut test_fut),
1136                        Poll::Pending,
1137                        "information_config={:?}, non_temporary_address_config={:?}, prefix_delegation_config={:?}",
1138                        information_config, non_temporary_address_config, prefix_delegation_config
1139                    );
1140                }
1141            }
1142        }
1143    }
1144
1145    const CLIENT_ID: [u8; 18] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17];
1146
1147    #[fuchsia::test]
1148    async fn test_client_starts_in_correct_mode() {
1149        for information_config @ InformationConfig { dns_servers } in VALID_INFORMATION_CONFIGS {
1150            for non_temporary_address_config @ AddressConfig {
1151                address_count,
1152                preferred_addresses: _,
1153            } in get_valid_non_temporary_address_configs()
1154            {
1155                for prefix_delegation_config in VALID_DELEGATED_PREFIX_CONFIGS {
1156                    let (stateful, want_msg_type) =
1157                        if address_count == 0 && prefix_delegation_config.is_none() {
1158                            if !dns_servers {
1159                                continue;
1160                            } else {
1161                                (false, v6::MessageType::InformationRequest)
1162                            }
1163                        } else {
1164                            (true, v6::MessageType::Solicit)
1165                        };
1166
1167                    let (_, client_stream): (ClientEnd<ClientMarker>, _) =
1168                        create_request_stream::<ClientMarker>();
1169
1170                    let (client_socket, client_addr) = create_test_socket();
1171                    let (server_socket, server_addr) = create_test_socket();
1172                    println!(
1173                        "{:?} {:?} {:?}",
1174                        information_config, non_temporary_address_config, prefix_delegation_config
1175                    );
1176                    let _: Client<fasync::net::UdpSocket> = Client::start(
1177                        stateful.then(|| CLIENT_ID.into()),
1178                        [1, 2, 3], /* transaction ID */
1179                        ClientConfig {
1180                            information_config: information_config.clone(),
1181                            non_temporary_address_config: non_temporary_address_config.clone(),
1182                            prefix_delegation_config: prefix_delegation_config.clone(),
1183                        },
1184                        1, /* interface ID */
1185                        || Ok(client_socket),
1186                        server_addr,
1187                        client_stream,
1188                    )
1189                    .await
1190                        .unwrap_or_else(|e| panic!(
1191                            "failed to create test client: {}; information_config={:?}, non_temporary_address_config={:?}, prefix_delegation_config={:?}",
1192                            e, information_config, non_temporary_address_config, prefix_delegation_config
1193                        ));
1194
1195                    let _: ReceivedMessage =
1196                        assert_received_message(&server_socket, client_addr, want_msg_type).await;
1197                }
1198            }
1199        }
1200    }
1201
1202    // TODO(https://fxbug.dev/335656784): Replace this with a netemul test that isn't
1203    // sensitive to implementation details.
1204    #[fuchsia::test]
1205    async fn test_client_fails_to_start_with_invalid_args() {
1206        for params in vec![
1207            // Interface ID and zone index mismatch on link-local address.
1208            NewClientParams {
1209                interface_id: 2,
1210                address: fnet::Ipv6SocketAddress {
1211                    address: fidl_ip_v6!("fe80::1"),
1212                    port: DEFAULT_CLIENT_PORT,
1213                    zone_index: 1,
1214                },
1215                config: STATELESS_CLIENT_CONFIG,
1216                duid: None,
1217            },
1218            // Multicast address is invalid.
1219            NewClientParams {
1220                interface_id: 1,
1221                address: fnet::Ipv6SocketAddress {
1222                    address: fidl_ip_v6!("ff01::1"),
1223                    port: DEFAULT_CLIENT_PORT,
1224                    zone_index: 1,
1225                },
1226                config: STATELESS_CLIENT_CONFIG,
1227                duid: None,
1228            },
1229            // Stateless with DUID.
1230            NewClientParams {
1231                interface_id: 1,
1232                address: fidl_socket_addr_v6!("[2001:db8::1]:12345"),
1233                config: STATELESS_CLIENT_CONFIG,
1234                duid: Some(fnet_dhcpv6::Duid::LinkLayerAddress(
1235                    fnet_dhcpv6::LinkLayerAddress::Ethernet(fidl_mac!("00:11:22:33:44:55")),
1236                )),
1237            },
1238            // Stateful missing DUID.
1239            NewClientParams {
1240                interface_id: 1,
1241                address: fidl_socket_addr_v6!("[2001:db8::1]:12345"),
1242                config: ClientConfig {
1243                    information_config: InformationConfig { dns_servers: true },
1244                    non_temporary_address_config: AddressConfig {
1245                        address_count: 1,
1246                        preferred_addresses: None,
1247                    },
1248                    prefix_delegation_config: None,
1249                },
1250                duid: None,
1251            },
1252        ] {
1253            let (client_proxy, server_end) = create_proxy::<ClientMarker>();
1254            let () =
1255                serve_client(params, server_end).await.expect("start server failed unexpectedly");
1256            // Calling any function on the client proxy should fail due to channel closed with
1257            // `INVALID_ARGS`.
1258            assert_matches!(
1259                client_proxy.watch_servers().await,
1260                Err(fidl::Error::ClientChannelClosed { status: zx::Status::INVALID_ARGS, .. })
1261            );
1262        }
1263    }
1264
1265    #[test]
1266    fn test_is_unicast_link_local_strict() {
1267        assert_eq!(is_unicast_link_local_strict(&fidl_ip_v6!("fe80::")), true);
1268        assert_eq!(is_unicast_link_local_strict(&fidl_ip_v6!("fe80::1")), true);
1269        assert_eq!(is_unicast_link_local_strict(&fidl_ip_v6!("fe80::ffff:1:2:3")), true);
1270        assert_eq!(is_unicast_link_local_strict(&fidl_ip_v6!("fe80::1:0:0:0:0")), false);
1271        assert_eq!(is_unicast_link_local_strict(&fidl_ip_v6!("fe81::")), false);
1272    }
1273
1274    fn create_test_dns_server(
1275        address: fnet::Ipv6Address,
1276        source_interface: u64,
1277        zone_index: u64,
1278    ) -> fnet_name::DnsServer_ {
1279        fnet_name::DnsServer_ {
1280            address: Some(fnet::SocketAddress::Ipv6(fnet::Ipv6SocketAddress {
1281                address,
1282                zone_index,
1283                port: DEFAULT_DNS_PORT,
1284            })),
1285            source: Some(fnet_name::DnsServerSource::Dhcpv6(fnet_name::Dhcpv6DnsServerSource {
1286                source_interface: Some(source_interface),
1287                ..Default::default()
1288            })),
1289            ..Default::default()
1290        }
1291    }
1292
1293    async fn send_msg_with_options(
1294        socket: &fasync::net::UdpSocket,
1295        to_addr: SocketAddr,
1296        transaction_id: [u8; 3],
1297        msg_type: v6::MessageType,
1298        options: &[v6::DhcpOption<'_>],
1299    ) -> Result<()> {
1300        let builder = v6::MessageBuilder::new(msg_type, transaction_id, options);
1301        let mut buf = vec![0u8; builder.bytes_len()];
1302        let () = builder.serialize(&mut buf);
1303        let size = socket.send_to(&buf, to_addr).await?;
1304        assert_eq!(size, buf.len());
1305        Ok(())
1306    }
1307
1308    #[fuchsia::test]
1309    fn test_client_should_respond_to_dns_watch_requests() {
1310        let mut exec = fasync::TestExecutor::new();
1311        let transaction_id = [1, 2, 3];
1312
1313        let (client_proxy, client_stream) = create_proxy_and_stream::<ClientMarker>();
1314
1315        let (client_socket, client_addr) = create_test_socket();
1316        let (server_socket, server_addr) = create_test_socket();
1317        let mut client = exec
1318            .run_singlethreaded(Client::<fasync::net::UdpSocket>::start(
1319                None,
1320                transaction_id,
1321                STATELESS_CLIENT_CONFIG,
1322                1, /* interface ID */
1323                || Ok(client_socket),
1324                server_addr,
1325                client_stream,
1326            ))
1327            .expect("failed to create test client");
1328
1329        type WatchServersResponseFut = <fnet_dhcpv6::ClientProxy as fnet_dhcpv6::ClientProxyInterface>::WatchServersResponseFut;
1330        type WatchServersResponse = <WatchServersResponseFut as Future>::Output;
1331
1332        struct Test<'a> {
1333            client: &'a mut Client<fasync::net::UdpSocket>,
1334            buf: Vec<u8>,
1335            watcher_fut: WatchServersResponseFut,
1336        }
1337
1338        impl<'a> Test<'a> {
1339            fn new(
1340                client: &'a mut Client<fasync::net::UdpSocket>,
1341                client_proxy: &ClientProxy,
1342            ) -> Self {
1343                Self {
1344                    client,
1345                    buf: vec![0u8; MAX_UDP_DATAGRAM_SIZE],
1346                    watcher_fut: client_proxy.watch_servers(),
1347                }
1348            }
1349
1350            async fn handle_next_event(&mut self) {
1351                self.client
1352                    .handle_next_event(&mut self.buf)
1353                    .await
1354                    .expect("test client failed to handle next event")
1355                    .expect("request stream closed");
1356            }
1357
1358            async fn refresh_client(&mut self) {
1359                // Make the client ready for another reply immediately on signal, so it can
1360                // start receiving updates without waiting for the full refresh timeout which is
1361                // unrealistic in tests.
1362                if self
1363                    .client
1364                    .timers
1365                    .as_ref()
1366                    .scheduled
1367                    .contains(&dhcpv6_core::client::ClientTimerType::Refresh)
1368                {
1369                    self.client
1370                        .handle_timeout(dhcpv6_core::client::ClientTimerType::Refresh)
1371                        .await
1372                        .expect("test client failed to handle timeout");
1373                } else {
1374                    panic!("no refresh timer is scheduled and refresh is requested in test");
1375                }
1376            }
1377
1378            // Drive both the DHCPv6 client's event handling logic and the DNS server
1379            // watcher until the DNS server watcher receives an update from the client (or
1380            // the client unexpectedly exits).
1381            fn run(&mut self) -> impl Future<Output = WatchServersResponse> + use<'_, 'a> {
1382                let Self { client, buf, watcher_fut } = self;
1383                async move {
1384                    let client_fut = async {
1385                        loop {
1386                            client
1387                                .handle_next_event(buf)
1388                                .await
1389                                .expect("test client failed to handle next event")
1390                                .expect("request stream closed");
1391                        }
1392                    }
1393                    .fuse();
1394                    let mut client_fut = pin!(client_fut);
1395                    let mut watcher_fut = watcher_fut.fuse();
1396                    select! {
1397                        () = client_fut => panic!("test client returned unexpectedly"),
1398                        r = watcher_fut => r,
1399                    }
1400                }
1401            }
1402        }
1403
1404        {
1405            // No DNS configurations received yet.
1406            let mut test = Test::new(&mut client, &client_proxy);
1407
1408            // Handle the WatchServers request.
1409            exec.run_singlethreaded(test.handle_next_event());
1410            assert!(
1411                test.client.dns_responder.is_some(),
1412                "WatchServers responder should be present"
1413            );
1414
1415            // Send an empty list to the client, should not update watcher.
1416            let () = exec
1417                .run_singlethreaded(send_msg_with_options(
1418                    &server_socket,
1419                    client_addr,
1420                    transaction_id,
1421                    v6::MessageType::Reply,
1422                    &[v6::DhcpOption::ServerId(&[1, 2, 3]), v6::DhcpOption::DnsServers(&[])],
1423                ))
1424                .expect("failed to send test reply");
1425            // Wait for the client to handle the next event (processing the reply we just
1426            // sent). Note that it is not enough to simply drive the client future until it
1427            // is stalled as we do elsewhere in the test, because we have no guarantee that
1428            // the netstack has delivered the UDP packet to the client by the time the
1429            // `send_to` call returned.
1430            exec.run_singlethreaded(test.handle_next_event());
1431            assert_matches!(exec.run_until_stalled(&mut pin!(test.run())), Poll::Pending);
1432
1433            // Send a list of DNS servers, the watcher should be updated accordingly.
1434            exec.run_singlethreaded(test.refresh_client());
1435            let dns_servers = [net_ip_v6!("fe80::1:2")];
1436            let () = exec
1437                .run_singlethreaded(send_msg_with_options(
1438                    &server_socket,
1439                    client_addr,
1440                    transaction_id,
1441                    v6::MessageType::Reply,
1442                    &[
1443                        v6::DhcpOption::ServerId(&[1, 2, 3]),
1444                        v6::DhcpOption::DnsServers(&dns_servers),
1445                    ],
1446                ))
1447                .expect("failed to send test reply");
1448            let want_servers = vec![create_test_dns_server(
1449                fidl_ip_v6!("fe80::1:2"),
1450                1, /* source interface */
1451                1, /* zone index */
1452            )];
1453            let servers = exec.run_singlethreaded(test.run()).expect("get servers");
1454            assert_eq!(servers, want_servers);
1455        } // drop `test_fut` so `client_fut` is no longer mutably borrowed.
1456
1457        {
1458            // No new changes, should not update watcher.
1459            let mut test = Test::new(&mut client, &client_proxy);
1460
1461            // Handle the WatchServers request.
1462            exec.run_singlethreaded(test.handle_next_event());
1463            assert!(
1464                test.client.dns_responder.is_some(),
1465                "WatchServers responder should be present"
1466            );
1467
1468            // Send the same list of DNS servers, should not update watcher.
1469            exec.run_singlethreaded(test.refresh_client());
1470            let dns_servers = [net_ip_v6!("fe80::1:2")];
1471            let () = exec
1472                .run_singlethreaded(send_msg_with_options(
1473                    &server_socket,
1474                    client_addr,
1475                    transaction_id,
1476                    v6::MessageType::Reply,
1477                    &[
1478                        v6::DhcpOption::ServerId(&[1, 2, 3]),
1479                        v6::DhcpOption::DnsServers(&dns_servers),
1480                    ],
1481                ))
1482                .expect("failed to send test reply");
1483            // Wait for the client to handle the next event (processing the reply we just
1484            // sent). Note that it is not enough to simply drive the client future until it
1485            // is stalled as we do elsewhere in the test, because we have no guarantee that
1486            // the netstack has delivered the UDP packet to the client by the time the
1487            // `send_to` call returned.
1488            exec.run_singlethreaded(test.handle_next_event());
1489            assert_matches!(exec.run_until_stalled(&mut pin!(test.run())), Poll::Pending);
1490
1491            // Send a different list of DNS servers, should update watcher.
1492            exec.run_singlethreaded(test.refresh_client());
1493            let dns_servers = [net_ip_v6!("fe80::1:2"), net_ip_v6!("1234::5:6")];
1494            let () = exec
1495                .run_singlethreaded(send_msg_with_options(
1496                    &server_socket,
1497                    client_addr,
1498                    transaction_id,
1499                    v6::MessageType::Reply,
1500                    &[
1501                        v6::DhcpOption::ServerId(&[1, 2, 3]),
1502                        v6::DhcpOption::DnsServers(&dns_servers),
1503                    ],
1504                ))
1505                .expect("failed to send test reply");
1506            let want_servers = vec![
1507                create_test_dns_server(
1508                    fidl_ip_v6!("fe80::1:2"),
1509                    1, /* source interface */
1510                    1, /* zone index */
1511                ),
1512                // Only set zone index for link local addresses.
1513                create_test_dns_server(
1514                    fidl_ip_v6!("1234::5:6"),
1515                    1, /* source interface */
1516                    0, /* zone index */
1517                ),
1518            ];
1519            let servers = exec.run_singlethreaded(test.run()).expect("get servers");
1520            assert_eq!(servers, want_servers);
1521        } // drop `test_fut` so `client_fut` is no longer mutably borrowed.
1522
1523        {
1524            // Send an empty list of DNS servers, should update watcher,
1525            // because this is different from what the watcher has seen
1526            // last time.
1527            let mut test = Test::new(&mut client, &client_proxy);
1528
1529            exec.run_singlethreaded(test.refresh_client());
1530            let () = exec
1531                .run_singlethreaded(send_msg_with_options(
1532                    &server_socket,
1533                    client_addr,
1534                    transaction_id,
1535                    v6::MessageType::Reply,
1536                    &[v6::DhcpOption::ServerId(&[1, 2, 3]), v6::DhcpOption::DnsServers(&[])],
1537                ))
1538                .expect("failed to send test reply");
1539            let want_servers = Vec::<fnet_name::DnsServer_>::new();
1540            assert_eq!(exec.run_singlethreaded(test.run()).expect("get servers"), want_servers);
1541        } // drop `test_fut` so `client_fut` is no longer mutably borrowed.
1542    }
1543
1544    #[fuchsia::test]
1545    async fn test_client_should_respond_with_dns_servers_on_first_watch_if_non_empty() {
1546        let transaction_id = [1, 2, 3];
1547
1548        let (client_proxy, client_stream) = create_proxy_and_stream::<ClientMarker>();
1549
1550        let (client_socket, client_addr) = create_test_socket();
1551        let (server_socket, server_addr) = create_test_socket();
1552        let client = Client::<fasync::net::UdpSocket>::start(
1553            None,
1554            transaction_id,
1555            STATELESS_CLIENT_CONFIG,
1556            1, /* interface ID */
1557            || Ok(client_socket),
1558            server_addr,
1559            client_stream,
1560        )
1561        .await
1562        .expect("failed to create test client");
1563
1564        let dns_servers = [net_ip_v6!("fe80::1:2"), net_ip_v6!("1234::5:6")];
1565        let () = send_msg_with_options(
1566            &server_socket,
1567            client_addr,
1568            transaction_id,
1569            v6::MessageType::Reply,
1570            &[v6::DhcpOption::ServerId(&[4, 5, 6]), v6::DhcpOption::DnsServers(&dns_servers)],
1571        )
1572        .await
1573        .expect("failed to send test message");
1574
1575        let buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
1576        let handle_client_events_fut =
1577            futures::stream::try_unfold((client, buf), |(mut client, mut buf)| async {
1578                client
1579                    .handle_next_event(&mut buf)
1580                    .await
1581                    .map(|res| res.map(|()| ((), (client, buf))))
1582            })
1583            .try_fold((), |(), ()| futures::future::ready(Ok(())))
1584            .fuse();
1585        let mut handle_client_events_fut = pin!(handle_client_events_fut);
1586
1587        let want_servers = vec![
1588            create_test_dns_server(
1589                fidl_ip_v6!("fe80::1:2"),
1590                1, /* source interface */
1591                1, /* zone index */
1592            ),
1593            create_test_dns_server(
1594                fidl_ip_v6!("1234::5:6"),
1595                1, /* source interface */
1596                0, /* zone index */
1597            ),
1598        ];
1599        let found_servers = select!(
1600            status = handle_client_events_fut => panic!("client unexpectedly exited: {status:?}"),
1601            found_servers = client_proxy.watch_servers() => found_servers.expect(
1602                "watch servers should succeed"),
1603        );
1604        assert_eq!(found_servers, want_servers);
1605    }
1606
1607    #[fuchsia::test]
1608    async fn watch_prefixes() {
1609        const SERVER_ID: [u8; 3] = [3, 4, 5];
1610        const PREFERRED_LIFETIME_SECS: u32 = 1000;
1611        const VALID_LIFETIME_SECS: u32 = 2000;
1612        // Use the smallest possible value to enter the Renewing state
1613        // as fast as possible to keep the test's run-time as low as possible.
1614        const T1: u32 = 1;
1615        const T2: u32 = 2000;
1616
1617        let (client_proxy, client_stream) = create_proxy_and_stream::<ClientMarker>();
1618
1619        let (client_socket, client_addr) = create_test_socket();
1620        let (server_socket, server_addr) = create_test_socket();
1621        let mut client = Client::<fasync::net::UdpSocket>::start(
1622            Some(CLIENT_ID.into()),
1623            [1, 2, 3],
1624            ClientConfig {
1625                information_config: Default::default(),
1626                non_temporary_address_config: Default::default(),
1627                prefix_delegation_config: Some(PrefixDelegationConfig::Empty(Empty {})),
1628            },
1629            1, /* interface ID */
1630            || Ok(client_socket),
1631            server_addr,
1632            client_stream,
1633        )
1634        .await
1635        .expect("failed to create test client");
1636
1637        let client_fut = async {
1638            let mut buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
1639            loop {
1640                select! {
1641                    res = client.handle_next_event(&mut buf).fuse() => {
1642                        match res.expect("test client failed to handle next event") {
1643                            Some(()) => (),
1644                            None => break (),
1645                        };
1646                    }
1647                }
1648            }
1649        }
1650        .fuse();
1651        let mut client_fut = pin!(client_fut);
1652
1653        let update_prefix = net_subnet_v6!("a::/64");
1654        let remove_prefix = net_subnet_v6!("b::/64");
1655        let add_prefix = net_subnet_v6!("c::/64");
1656
1657        // Go through the motions to assign a prefix.
1658        let client_id = {
1659            let ReceivedMessage { client_id, transaction_id } =
1660                assert_received_message(&server_socket, client_addr, v6::MessageType::Solicit)
1661                    .await;
1662            // Client IDs are mandatory in stateful DHCPv6.
1663            let client_id = client_id.unwrap();
1664
1665            let ia_prefix = [
1666                v6::DhcpOption::IaPrefix(v6::IaPrefixSerializer::new(
1667                    PREFERRED_LIFETIME_SECS,
1668                    VALID_LIFETIME_SECS,
1669                    update_prefix,
1670                    &[],
1671                )),
1672                v6::DhcpOption::IaPrefix(v6::IaPrefixSerializer::new(
1673                    PREFERRED_LIFETIME_SECS,
1674                    VALID_LIFETIME_SECS,
1675                    remove_prefix,
1676                    &[],
1677                )),
1678            ];
1679            let () = send_msg_with_options(
1680                &server_socket,
1681                client_addr,
1682                transaction_id,
1683                v6::MessageType::Advertise,
1684                &[
1685                    v6::DhcpOption::ServerId(&SERVER_ID),
1686                    v6::DhcpOption::ClientId(&client_id),
1687                    v6::DhcpOption::Preference(u8::MAX),
1688                    v6::DhcpOption::IaPd(v6::IaPdSerializer::new(IA_PD_IAID, T1, T2, &ia_prefix)),
1689                ],
1690            )
1691            .await
1692            .expect("failed to send adv message");
1693
1694            // Wait for the client to send a Request and send Reply so a prefix
1695            // is assigned.
1696            let transaction_id = select! {
1697                () = client_fut => panic!("should never return"),
1698                res = assert_received_message(
1699                    &server_socket,
1700                    client_addr,
1701                    v6::MessageType::Request,
1702                ).fuse() => {
1703                    let ReceivedMessage { client_id: req_client_id, transaction_id } = res;
1704                    assert_eq!(Some(&client_id), req_client_id.as_ref());
1705                    transaction_id
1706                },
1707            };
1708
1709            let () = send_msg_with_options(
1710                &server_socket,
1711                client_addr,
1712                transaction_id,
1713                v6::MessageType::Reply,
1714                &[
1715                    v6::DhcpOption::ServerId(&SERVER_ID),
1716                    v6::DhcpOption::ClientId(&client_id),
1717                    v6::DhcpOption::IaPd(v6::IaPdSerializer::new(IA_PD_IAID, T1, T2, &ia_prefix)),
1718                ],
1719            )
1720            .await
1721            .expect("failed to send reply message");
1722
1723            client_id
1724        };
1725
1726        let check_watch_prefixes_result =
1727            |res: Result<Vec<Prefix>, _>,
1728             before_handling_reply,
1729             preferred_lifetime_secs: u32,
1730             valid_lifetime_secs: u32,
1731             expected_prefixes| {
1732                assert_matches!(
1733                    res.unwrap()[..],
1734                    [
1735                        Prefix {
1736                            prefix: got_prefix1,
1737                            lifetimes: Lifetimes {
1738                                preferred_until: preferred_until1,
1739                                valid_until: valid_until1,
1740                            },
1741                        },
1742                        Prefix {
1743                            prefix: got_prefix2,
1744                            lifetimes: Lifetimes {
1745                                preferred_until: preferred_until2,
1746                                valid_until: valid_until2,
1747                            },
1748                        },
1749                    ] => {
1750                        let now = zx::MonotonicInstant::get();
1751                        let preferred_until = zx::MonotonicInstant::from_nanos(preferred_until1);
1752                        let valid_until = zx::MonotonicInstant::from_nanos(valid_until1);
1753
1754                        let preferred_for = zx::MonotonicDuration::from_seconds(
1755                            preferred_lifetime_secs.into(),
1756                        );
1757                        let valid_for = zx::MonotonicDuration::from_seconds(valid_lifetime_secs.into());
1758
1759                        assert_eq!(
1760                            HashSet::from([got_prefix1, got_prefix2]),
1761                            HashSet::from(expected_prefixes),
1762                        );
1763                        assert!(preferred_until >= before_handling_reply + preferred_for);
1764                        assert!(preferred_until <= now + preferred_for);
1765                        assert!(valid_until >= before_handling_reply + valid_for);
1766                        assert!(valid_until <= now + valid_for);
1767
1768                        assert_eq!(preferred_until1, preferred_until2);
1769                        assert_eq!(valid_until1, valid_until2);
1770                    }
1771                )
1772            };
1773
1774        // Wait for a prefix to become assigned from the perspective of the DHCPv6
1775        // FIDL client.
1776        {
1777            // watch_prefixes should not return before a lease is negotiated. Note
1778            // that the client has not yet handled the Reply message.
1779            let mut watch_prefixes = client_proxy.watch_prefixes().fuse();
1780            assert_matches!(poll!(&mut watch_prefixes), Poll::Pending);
1781            let before_handling_reply = zx::MonotonicInstant::get();
1782            select! {
1783                () = client_fut => panic!("should never return"),
1784                res = watch_prefixes => check_watch_prefixes_result(
1785                    res,
1786                    before_handling_reply,
1787                    PREFERRED_LIFETIME_SECS,
1788                    VALID_LIFETIME_SECS,
1789                    [
1790                        subnet_to_address_with_prefix(update_prefix),
1791                        subnet_to_address_with_prefix(remove_prefix),
1792                    ],
1793                ),
1794            }
1795        }
1796
1797        // Wait for the client to attempt to renew the lease and go through the
1798        // motions to update the lease.
1799        {
1800            let transaction_id = select! {
1801                () = client_fut => panic!("should never return"),
1802                res = assert_received_message(
1803                    &server_socket,
1804                    client_addr,
1805                    v6::MessageType::Renew,
1806                ).fuse() => {
1807                    let ReceivedMessage { client_id: ren_client_id, transaction_id } = res;
1808                    assert_eq!(ren_client_id.as_ref(), Some(&client_id));
1809                    transaction_id
1810                },
1811            };
1812
1813            const NEW_PREFERRED_LIFETIME_SECS: u32 = 2 * PREFERRED_LIFETIME_SECS;
1814            const NEW_VALID_LIFETIME_SECS: u32 = 2 * VALID_LIFETIME_SECS;
1815            let ia_prefix = [
1816                v6::DhcpOption::IaPrefix(v6::IaPrefixSerializer::new(
1817                    NEW_PREFERRED_LIFETIME_SECS,
1818                    NEW_VALID_LIFETIME_SECS,
1819                    update_prefix,
1820                    &[],
1821                )),
1822                v6::DhcpOption::IaPrefix(v6::IaPrefixSerializer::new(
1823                    NEW_PREFERRED_LIFETIME_SECS,
1824                    NEW_VALID_LIFETIME_SECS,
1825                    add_prefix,
1826                    &[],
1827                )),
1828                v6::DhcpOption::IaPrefix(v6::IaPrefixSerializer::new(0, 0, remove_prefix, &[])),
1829            ];
1830
1831            let () = send_msg_with_options(
1832                &server_socket,
1833                client_addr,
1834                transaction_id,
1835                v6::MessageType::Reply,
1836                &[
1837                    v6::DhcpOption::ServerId(&SERVER_ID),
1838                    v6::DhcpOption::ClientId(&client_id),
1839                    v6::DhcpOption::IaPd(v6::IaPdSerializer::new(
1840                        v6::IAID::new(0),
1841                        T1,
1842                        T2,
1843                        &ia_prefix,
1844                    )),
1845                ],
1846            )
1847            .await
1848            .expect("failed to send reply message");
1849
1850            let before_handling_reply = zx::MonotonicInstant::get();
1851            select! {
1852                () = client_fut => panic!("should never return"),
1853                res = client_proxy.watch_prefixes().fuse() => check_watch_prefixes_result(
1854                    res,
1855                    before_handling_reply,
1856                    NEW_PREFERRED_LIFETIME_SECS,
1857                    NEW_VALID_LIFETIME_SECS,
1858                    [
1859                        subnet_to_address_with_prefix(update_prefix),
1860                        subnet_to_address_with_prefix(add_prefix),
1861                    ],
1862                ),
1863            }
1864        }
1865    }
1866
1867    #[fuchsia::test]
1868    async fn test_client_schedule_and_cancel_timers() {
1869        let (_client_end, client_stream) = create_request_stream::<ClientMarker>();
1870
1871        let (client_socket, _client_addr) = create_test_socket();
1872        let (_server_socket, server_addr) = create_test_socket();
1873        let mut client = Client::<fasync::net::UdpSocket>::start(
1874            None,
1875            [1, 2, 3], /* transaction ID */
1876            STATELESS_CLIENT_CONFIG,
1877            1, /* interface ID */
1878            || Ok(client_socket),
1879            server_addr,
1880            client_stream,
1881        )
1882        .await
1883        .expect("failed to create test client");
1884
1885        // Stateless DHCP client starts by scheduling a retransmission timer.
1886        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
1887
1888        let () = client.cancel_timer(dhcpv6_core::client::ClientTimerType::Retransmission);
1889        client.assert_scheduled([]);
1890
1891        let now = MonotonicInstant::now();
1892        let () = client.schedule_timer(
1893            dhcpv6_core::client::ClientTimerType::Refresh,
1894            now + Duration::from_nanos(1),
1895        );
1896        let () = client.schedule_timer(
1897            dhcpv6_core::client::ClientTimerType::Retransmission,
1898            now + Duration::from_nanos(2),
1899        );
1900        client.assert_scheduled([
1901            dhcpv6_core::client::ClientTimerType::Retransmission,
1902            dhcpv6_core::client::ClientTimerType::Refresh,
1903        ]);
1904
1905        // We are allowed to reschedule a timer to fire at a new time.
1906        let now = MonotonicInstant::now();
1907        client.schedule_timer(
1908            dhcpv6_core::client::ClientTimerType::Refresh,
1909            now + Duration::from_nanos(1),
1910        );
1911        client.schedule_timer(
1912            dhcpv6_core::client::ClientTimerType::Retransmission,
1913            now + Duration::from_nanos(2),
1914        );
1915
1916        let () = client.cancel_timer(dhcpv6_core::client::ClientTimerType::Refresh);
1917        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
1918
1919        // Ok to cancel a timer that is not scheduled.
1920        client.cancel_timer(dhcpv6_core::client::ClientTimerType::Refresh);
1921
1922        let () = client.cancel_timer(dhcpv6_core::client::ClientTimerType::Retransmission);
1923        client.assert_scheduled([]);
1924
1925        // Ok to cancel a timer that is not scheduled.
1926        client.cancel_timer(dhcpv6_core::client::ClientTimerType::Retransmission);
1927    }
1928
1929    #[fuchsia::test]
1930    async fn test_handle_next_event_on_stateless_client() {
1931        let (client_proxy, client_stream) = create_proxy_and_stream::<ClientMarker>();
1932
1933        let (client_socket, client_addr) = create_test_socket();
1934        let (server_socket, server_addr) = create_test_socket();
1935        let mut client = Client::<fasync::net::UdpSocket>::start(
1936            None,
1937            [1, 2, 3], /* transaction ID */
1938            STATELESS_CLIENT_CONFIG,
1939            1, /* interface ID */
1940            || Ok(client_socket),
1941            server_addr,
1942            client_stream,
1943        )
1944        .await
1945        .expect("failed to create test client");
1946
1947        // Starting the client in stateless should send an information request out.
1948        let ReceivedMessage { client_id, transaction_id: _ } = assert_received_message(
1949            &server_socket,
1950            client_addr,
1951            v6::MessageType::InformationRequest,
1952        )
1953        .await;
1954        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
1955
1956        let mut buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
1957        // Trigger a retransmission.
1958        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
1959        let ReceivedMessage { client_id: got_client_id, transaction_id: _ } =
1960            assert_received_message(
1961                &server_socket,
1962                client_addr,
1963                v6::MessageType::InformationRequest,
1964            )
1965            .await;
1966        assert_eq!(got_client_id, client_id);
1967        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
1968
1969        // Message targeting another transaction ID should be ignored.
1970        let () = send_msg_with_options(
1971            &server_socket,
1972            client_addr,
1973            [5, 6, 7],
1974            v6::MessageType::Reply,
1975            &[],
1976        )
1977        .await
1978        .expect("failed to send test message");
1979        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
1980        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
1981
1982        // Invalid messages should be discarded. Empty buffer is invalid.
1983        let size =
1984            server_socket.send_to(&[], client_addr).await.expect("failed to send test message");
1985        assert_eq!(size, 0);
1986        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
1987        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
1988
1989        // Message targeting this client should cause the client to transition state.
1990        let () = send_msg_with_options(
1991            &server_socket,
1992            client_addr,
1993            [1, 2, 3],
1994            v6::MessageType::Reply,
1995            &[v6::DhcpOption::ServerId(&[4, 5, 6])],
1996        )
1997        .await
1998        .expect("failed to send test message");
1999        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
2000        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Refresh]);
2001
2002        // Reschedule a shorter timer for Refresh so we don't spend time waiting in test.
2003        client.schedule_timer(
2004            dhcpv6_core::client::ClientTimerType::Refresh,
2005            MonotonicInstant::now() + Duration::from_nanos(1),
2006        );
2007
2008        // Trigger a refresh.
2009        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
2010        let ReceivedMessage { client_id, transaction_id: _ } = assert_received_message(
2011            &server_socket,
2012            client_addr,
2013            v6::MessageType::InformationRequest,
2014        )
2015        .await;
2016        assert_eq!(got_client_id, client_id,);
2017        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
2018
2019        let test_fut = async {
2020            assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
2021            client
2022                .dns_responder
2023                .take()
2024                .expect("test client did not get a channel responder")
2025                .send(&[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                .expect("failed to send response on test channel");
2036        };
2037        let (watcher_res, ()) = join!(client_proxy.watch_servers(), test_fut);
2038        let servers = watcher_res.expect("failed to watch servers");
2039        assert_eq!(
2040            servers,
2041            vec![fnet_name::DnsServer_ {
2042                address: Some(fidl_socket_addr!("[fe01::2:3]:42")),
2043                source: Some(fnet_name::DnsServerSource::Dhcpv6(
2044                    fnet_name::Dhcpv6DnsServerSource {
2045                        source_interface: Some(42),
2046                        ..Default::default()
2047                    },
2048                )),
2049                ..Default::default()
2050            }]
2051        );
2052
2053        // Drop the channel should cause `handle_next_event(&mut buf)` to return `None`.
2054        drop(client_proxy);
2055        assert_matches!(client.handle_next_event(&mut buf).await, Ok(None));
2056    }
2057
2058    #[fuchsia::test]
2059    async fn test_handle_next_event_on_stateful_client() {
2060        let (client_proxy, client_stream) = create_proxy_and_stream::<ClientMarker>();
2061
2062        let (client_socket, client_addr) = create_test_socket();
2063        let (server_socket, server_addr) = create_test_socket();
2064        let mut client = Client::<fasync::net::UdpSocket>::start(
2065            Some(CLIENT_ID.into()),
2066            [1, 2, 3], /* transaction ID */
2067            ClientConfig {
2068                information_config: Default::default(),
2069                non_temporary_address_config: AddressConfig {
2070                    address_count: 1,
2071                    preferred_addresses: None,
2072                },
2073                prefix_delegation_config: None,
2074            },
2075            1, /* interface ID */
2076            || Ok(client_socket),
2077            server_addr,
2078            client_stream,
2079        )
2080        .await
2081        .expect("failed to create test client");
2082
2083        // Starting the client in stateful should send out a solicit.
2084        let _: ReceivedMessage =
2085            assert_received_message(&server_socket, client_addr, v6::MessageType::Solicit).await;
2086        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
2087
2088        let mut buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
2089        // Drop the channel should cause `handle_next_event(&mut buf)` to return `None`.
2090        drop(client_proxy);
2091        assert_matches!(client.handle_next_event(&mut buf).await, Ok(None));
2092    }
2093
2094    #[fuchsia::test]
2095    #[should_panic = "received unexpected refresh timeout in state InformationRequesting"]
2096    async fn test_handle_next_event_respects_timer_order() {
2097        let (_client_end, client_stream) = create_request_stream::<ClientMarker>();
2098
2099        let (client_socket, client_addr) = create_test_socket();
2100        let (server_socket, server_addr) = create_test_socket();
2101        let mut client = Client::<fasync::net::UdpSocket>::start(
2102            None,
2103            [1, 2, 3], /* transaction ID */
2104            STATELESS_CLIENT_CONFIG,
2105            1, /* interface ID */
2106            || Ok(client_socket),
2107            server_addr,
2108            client_stream,
2109        )
2110        .await
2111        .expect("failed to create test client");
2112
2113        let mut buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
2114        // A retransmission timer is scheduled when starting the client in stateless mode. Cancel
2115        // it and create a new one with a longer timeout so the test is not flaky.
2116        let () = client.schedule_timer(
2117            dhcpv6_core::client::ClientTimerType::Retransmission,
2118            MonotonicInstant::now() + Duration::from_secs(1_000_000),
2119        );
2120        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
2121
2122        // Trigger a message receive, the message is later discarded because transaction ID doesn't
2123        // match.
2124        let () = send_msg_with_options(
2125            &server_socket,
2126            client_addr,
2127            [5, 6, 7],
2128            v6::MessageType::Reply,
2129            &[],
2130        )
2131        .await
2132        .expect("failed to send test message");
2133        // There are now two pending events, the message receive is handled first because the timer
2134        // is far into the future.
2135        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
2136        // The retransmission timer is still here.
2137        client.assert_scheduled([dhcpv6_core::client::ClientTimerType::Retransmission]);
2138
2139        // Inserts a refresh timer that precedes the retransmission.
2140        let () = client.schedule_timer(
2141            dhcpv6_core::client::ClientTimerType::Refresh,
2142            MonotonicInstant::now() + Duration::from_nanos(1),
2143        );
2144        // This timer is scheduled.
2145        client.assert_scheduled([
2146            dhcpv6_core::client::ClientTimerType::Retransmission,
2147            dhcpv6_core::client::ClientTimerType::Refresh,
2148        ]);
2149
2150        // Now handle_next_event(&mut buf) should trigger a refresh because it
2151        // precedes retransmission. Refresh is not expected while in
2152        // InformationRequesting state and should lead to a panic.
2153        let unreachable = client.handle_next_event(&mut buf).await;
2154        panic!("{unreachable:?}");
2155    }
2156
2157    #[fuchsia::test]
2158    async fn test_handle_next_event_fails_on_recv_err() {
2159        struct StubSocket {}
2160        impl<'a> AsyncSocket<'a> for StubSocket {
2161            type RecvFromFut = futures::future::Ready<Result<(usize, SocketAddr), std::io::Error>>;
2162            type SendToFut = futures::future::Ready<Result<usize, std::io::Error>>;
2163
2164            fn recv_from(&'a self, _buf: &'a mut [u8]) -> Self::RecvFromFut {
2165                futures::future::ready(Err(std::io::Error::other("test recv error")))
2166            }
2167            fn send_to(&'a self, buf: &'a [u8], _addr: SocketAddr) -> Self::SendToFut {
2168                futures::future::ready(Ok(buf.len()))
2169            }
2170        }
2171
2172        let (_client_end, client_stream) = create_request_stream::<ClientMarker>();
2173
2174        let mut client = Client::<StubSocket>::start(
2175            None,
2176            [1, 2, 3], /* transaction ID */
2177            STATELESS_CLIENT_CONFIG,
2178            1, /* interface ID */
2179            || Ok(StubSocket {}),
2180            std_socket_addr!("[::1]:0"),
2181            client_stream,
2182        )
2183        .await
2184        .expect("failed to create test client");
2185
2186        assert_matches!(
2187            client.handle_next_event(&mut [0u8]).await,
2188            Err(ClientError::SocketRecv(err)) if err.kind() == std::io::ErrorKind::Other
2189        );
2190    }
2191}