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