dhcpv6_client/
client.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! Implements a DHCPv6 client.
use std::collections::hash_map::DefaultHasher;
use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
use std::net::{IpAddr, SocketAddr};
use std::ops::Add;
use std::str::FromStr as _;
use std::time::Duration;

use fidl::endpoints::{ControlHandle as _, ServerEnd};
use fidl_fuchsia_net_dhcpv6::{
    ClientMarker, ClientRequest, ClientRequestStream, ClientWatchAddressResponder,
    ClientWatchPrefixesResponder, ClientWatchServersResponder, Duid, Empty, Lifetimes,
    LinkLayerAddress, LinkLayerAddressPlusTime, Prefix, PrefixDelegationConfig,
    RELAY_AGENT_AND_SERVER_LINK_LOCAL_MULTICAST_ADDRESS, RELAY_AGENT_AND_SERVER_PORT,
};
use fidl_fuchsia_net_dhcpv6_ext::{
    AddressConfig, ClientConfig, InformationConfig, NewClientParams,
};
use futures::future::{AbortHandle, Abortable, Aborted};
use futures::stream::futures_unordered::FuturesUnordered;
use futures::{select, stream, Future, FutureExt as _, StreamExt as _, TryStreamExt as _};
use {
    fidl_fuchsia_net as fnet, fidl_fuchsia_net_ext as fnet_ext, fidl_fuchsia_net_name as fnet_name,
    fuchsia_async as fasync,
};

use anyhow::{Context as _, Result};
use assert_matches::assert_matches;
use async_utils::futures::{FutureExt as _, ReplaceValue};
use byteorder::{NetworkEndian, WriteBytesExt as _};
use dns_server_watcher::DEFAULT_DNS_PORT;
use net_types::ip::{Ip as _, Ipv6, Ipv6Addr, Subnet, SubnetError};
use net_types::MulticastAddress as _;
use packet::ParsablePacket;
use packet_formats_dhcp::v6;
use rand::rngs::StdRng;
use rand::SeedableRng;
use tracing::{debug, error, warn};

/// A thin wrapper around `zx::MonotonicInstant` that implements `dhcpv6_core::Instant`.
#[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Debug)]
pub(crate) struct MonotonicInstant(zx::MonotonicInstant);

impl MonotonicInstant {
    fn now() -> MonotonicInstant {
        MonotonicInstant(zx::MonotonicInstant::get())
    }
}

impl dhcpv6_core::Instant for MonotonicInstant {
    fn duration_since(&self, MonotonicInstant(earlier): MonotonicInstant) -> Duration {
        let Self(this) = *self;

        let diff: zx::MonotonicDuration = this - earlier;

        Duration::from_nanos(diff.into_nanos().try_into().unwrap_or_else(|e| {
            panic!(
                "failed to calculate duration since {:?} with instant {:?}: {}",
                earlier, this, e,
            )
        }))
    }

    fn checked_add(&self, duration: Duration) -> Option<MonotonicInstant> {
        Some(self.add(duration))
    }
}

impl Add<Duration> for MonotonicInstant {
    type Output = MonotonicInstant;

    fn add(self, duration: Duration) -> MonotonicInstant {
        let MonotonicInstant(this) = self;
        MonotonicInstant(this + duration.into())
    }
}

#[derive(Debug, thiserror::Error)]
pub enum ClientError {
    #[error("fidl error")]
    Fidl(#[source] fidl::Error),
    #[error("got watch request while the previous one is pending")]
    DoubleWatch,
    #[error("unsupported DHCPv6 configuration")]
    UnsupportedConfigs,
    #[error("socket create error")]
    SocketCreate(std::io::Error),
    #[error("socket receive error")]
    SocketRecv(std::io::Error),
    #[error("unimplemented DHCPv6 functionality: {:?}()", _0)]
    Unimplemented(String),
}

/// Theoretical size limit for UDP datagrams.
///
/// NOTE: This does not take [jumbograms](https://tools.ietf.org/html/rfc2675) into account.
const MAX_UDP_DATAGRAM_SIZE: usize = 65_535;

type TimerFut = ReplaceValue<fasync::Timer, dhcpv6_core::client::ClientTimerType>;

/// A DHCPv6 client.
pub(crate) struct Client<S: for<'a> AsyncSocket<'a>> {
    /// The interface the client is running on.
    interface_id: u64,
    /// Stores the hash of the last observed version of DNS servers by a watcher.
    ///
    /// The client uses this hash to determine whether new changes in DNS servers are observed and
    /// updates should be replied to the watcher.
    last_observed_dns_hash: u64,
    /// Stores a responder to send DNS server updates.
    dns_responder: Option<ClientWatchServersResponder>,
    /// Stores a responder to send acquired addresses.
    address_responder: Option<ClientWatchAddressResponder>,
    /// Holds the discovered prefixes and their lifetimes.
    prefixes: HashMap<fnet::Ipv6AddressWithPrefix, Lifetimes>,
    /// Indicates whether or not the prefixes has changed since last yielded.
    prefixes_changed: bool,
    /// Stores a responder to send acquired prefixes.
    prefixes_responder: Option<ClientWatchPrefixesResponder>,
    /// Maintains the state for the client.
    state_machine: dhcpv6_core::client::ClientStateMachine<MonotonicInstant, StdRng>,
    /// The socket used to communicate with DHCPv6 servers.
    socket: S,
    /// The address to send outgoing messages to.
    server_addr: SocketAddr,
    /// A collection of abort handles to all currently scheduled timers.
    timer_abort_handles: HashMap<dhcpv6_core::client::ClientTimerType, AbortHandle>,
    /// A set of all scheduled timers.
    timer_futs: FuturesUnordered<Abortable<TimerFut>>,
    /// A stream of FIDL requests to this client.
    request_stream: ClientRequestStream,
}

/// A trait that allows stubbing [`fuchsia_async::net::UdpSocket`] in tests.
pub(crate) trait AsyncSocket<'a> {
    type RecvFromFut: Future<Output = Result<(usize, SocketAddr), std::io::Error>> + 'a;
    type SendToFut: Future<Output = Result<usize, std::io::Error>> + 'a;

    fn recv_from(&'a self, buf: &'a mut [u8]) -> Self::RecvFromFut;
    fn send_to(&'a self, buf: &'a [u8], addr: SocketAddr) -> Self::SendToFut;
}

impl<'a> AsyncSocket<'a> for fasync::net::UdpSocket {
    type RecvFromFut = fasync::net::UdpRecvFrom<'a>;
    type SendToFut = fasync::net::SendTo<'a>;

    fn recv_from(&'a self, buf: &'a mut [u8]) -> Self::RecvFromFut {
        self.recv_from(buf)
    }
    fn send_to(&'a self, buf: &'a [u8], addr: SocketAddr) -> Self::SendToFut {
        self.send_to(buf, addr)
    }
}

/// Converts `InformationConfig` to a collection of `v6::OptionCode`.
fn to_dhcpv6_option_codes(
    InformationConfig { dns_servers }: InformationConfig,
) -> Vec<v6::OptionCode> {
    dns_servers.then_some(v6::OptionCode::DnsServers).into_iter().collect()
}

fn to_configured_addresses(
    AddressConfig { address_count, preferred_addresses }: AddressConfig,
) -> Result<HashMap<v6::IAID, HashSet<Ipv6Addr>>, ClientError> {
    let preferred_addresses = preferred_addresses.unwrap_or(Vec::new());
    if preferred_addresses.len() > address_count.into() {
        return Err(ClientError::UnsupportedConfigs);
    }

    // TODO(https://fxbug.dev/42157844): make IAID consistent across
    // configurations.
    Ok((0..)
        .map(v6::IAID::new)
        .zip(
            preferred_addresses
                .into_iter()
                .map(|fnet::Ipv6Address { addr, .. }| HashSet::from([Ipv6Addr::from(addr)]))
                .chain(std::iter::repeat_with(HashSet::new)),
        )
        .take(address_count.into())
        .collect())
}

// The client only supports a single IA_PD.
//
// TODO(https://fxbug.dev/42065403): Support multiple IA_PDs.
const IA_PD_IAID: v6::IAID = v6::IAID::new(0);

/// Creates a state machine for the input client config.
fn create_state_machine(
    duid: Option<dhcpv6_core::ClientDuid>,
    transaction_id: [u8; 3],
    ClientConfig {
        information_config,
        non_temporary_address_config,
        prefix_delegation_config,
    }: ClientConfig,
) -> Result<
    (
        dhcpv6_core::client::ClientStateMachine<MonotonicInstant, StdRng>,
        dhcpv6_core::client::Actions<MonotonicInstant>,
    ),
    ClientError,
> {
    let information_option_codes = to_dhcpv6_option_codes(information_config);
    let configured_non_temporary_addresses = to_configured_addresses(non_temporary_address_config)?;
    let configured_delegated_prefixes = prefix_delegation_config
        .map(|prefix_delegation_config| {
            let prefix = match prefix_delegation_config {
                PrefixDelegationConfig::Empty(Empty {}) => Ok(None),
                PrefixDelegationConfig::PrefixLength(prefix_len) => {
                    if prefix_len == 0 {
                        // Should have used `PrefixDelegationConfig::Empty`.
                        return Err(ClientError::UnsupportedConfigs);
                    }

                    Subnet::new(Ipv6::UNSPECIFIED_ADDRESS, prefix_len).map(Some)
                }
                PrefixDelegationConfig::Prefix(fnet::Ipv6AddressWithPrefix {
                    addr: fnet::Ipv6Address { addr, .. },
                    prefix_len,
                }) => {
                    let addr = Ipv6Addr::from_bytes(addr);
                    if addr == Ipv6::UNSPECIFIED_ADDRESS {
                        // Should have used `PrefixDelegationConfig::PrefixLength`.
                        return Err(ClientError::UnsupportedConfigs);
                    }

                    Subnet::new(addr, prefix_len).map(Some)
                }
            };

            match prefix {
                Ok(o) => Ok(HashMap::from([(IA_PD_IAID, HashSet::from_iter(o.into_iter()))])),
                Err(SubnetError::PrefixTooLong | SubnetError::HostBitsSet) => {
                    Err(ClientError::UnsupportedConfigs)
                }
            }
        })
        .transpose()?;

    let now = MonotonicInstant::now();
    match (
        information_option_codes.is_empty(),
        configured_non_temporary_addresses.is_empty(),
        configured_delegated_prefixes,
    ) {
        (true, true, None) => Err(ClientError::UnsupportedConfigs),
        (false, true, None) => {
            if duid.is_some() {
                Err(ClientError::UnsupportedConfigs)
            } else {
                Ok(dhcpv6_core::client::ClientStateMachine::start_stateless(
                    transaction_id,
                    information_option_codes,
                    StdRng::from_entropy(),
                    now,
                ))
            }
        }
        (
            _request_information,
            _configure_non_temporary_addresses,
            configured_delegated_prefixes,
        ) => Ok(dhcpv6_core::client::ClientStateMachine::start_stateful(
            transaction_id,
            if let Some(duid) = duid {
                duid
            } else {
                return Err(ClientError::UnsupportedConfigs);
            },
            configured_non_temporary_addresses,
            configured_delegated_prefixes.unwrap_or_else(Default::default),
            information_option_codes,
            StdRng::from_entropy(),
            now,
        )),
    }
}

/// Calculates a hash for the input.
fn hash<H: Hash>(h: &H) -> u64 {
    let mut dh = DefaultHasher::new();
    let () = h.hash(&mut dh);
    dh.finish()
}

fn subnet_to_address_with_prefix(prefix: Subnet<Ipv6Addr>) -> fnet::Ipv6AddressWithPrefix {
    fnet::Ipv6AddressWithPrefix {
        addr: fnet::Ipv6Address { addr: prefix.network().ipv6_bytes() },
        prefix_len: prefix.prefix(),
    }
}

impl<S: for<'a> AsyncSocket<'a>> Client<S> {
    /// Starts the client in `config`.
    ///
    /// Input `transaction_id` is used to label outgoing messages and match incoming ones.
    pub(crate) async fn start(
        duid: Option<dhcpv6_core::ClientDuid>,
        transaction_id: [u8; 3],
        config: ClientConfig,
        interface_id: u64,
        socket_fn: impl FnOnce() -> std::io::Result<S>,
        server_addr: SocketAddr,
        request_stream: ClientRequestStream,
    ) -> Result<Self, ClientError> {
        let (state_machine, actions) = create_state_machine(duid, transaction_id, config)?;
        let mut client = Self {
            state_machine,
            interface_id,
            socket: socket_fn().map_err(ClientError::SocketCreate)?,
            server_addr,
            request_stream,
            timer_abort_handles: HashMap::new(),
            timer_futs: FuturesUnordered::new(),
            // Server watcher's API requires blocking iff the first call would return an empty list,
            // so initialize this field with a hash of an empty list.
            last_observed_dns_hash: hash(&Vec::<Ipv6Addr>::new()),
            dns_responder: None,
            address_responder: None,
            prefixes: Default::default(),
            prefixes_changed: false,
            prefixes_responder: None,
        };
        let () = client.run_actions(actions).await?;
        Ok(client)
    }

    /// Runs a list of actions sequentially.
    async fn run_actions(
        &mut self,
        actions: dhcpv6_core::client::Actions<MonotonicInstant>,
    ) -> Result<(), ClientError> {
        stream::iter(actions)
            .map(Ok)
            .try_fold(self, |client, action| async move {
                match action {
                    dhcpv6_core::client::Action::SendMessage(buf) => {
                        let () = match client.socket.send_to(&buf, client.server_addr).await {
                            Ok(size) => assert_eq!(size, buf.len()),
                            Err(e) => warn!(
                                "failed to send message to {}: {}; will retransmit later",
                                client.server_addr, e
                            ),
                        };
                    }
                    dhcpv6_core::client::Action::ScheduleTimer(timer_type, timeout) => {
                        client.schedule_timer(timer_type, timeout)
                    }
                    dhcpv6_core::client::Action::CancelTimer(timer_type) => {
                        client.cancel_timer(timer_type)
                    }
                    dhcpv6_core::client::Action::UpdateDnsServers(servers) => {
                        let () = client.maybe_send_dns_server_updates(servers)?;
                    }
                    dhcpv6_core::client::Action::IaNaUpdates(_) => {
                        // TODO(https://fxbug.dev/42178828): add actions to
                        // (re)schedule preferred and valid lifetime timers.
                        // TODO(https://fxbug.dev/42178817): Add
                        // action to remove the previous address.
                        // TODO(https://fxbug.dev/42177252): Add action to add
                        // the new address and cancel timers for old address.
                    }
                    dhcpv6_core::client::Action::IaPdUpdates(mut updates) => {
                        let updates = {
                            let ret =
                                updates.remove(&IA_PD_IAID).expect("Update missing for IAID");
                            debug_assert_eq!(updates, HashMap::new());
                            ret
                        };

                        let Self { prefixes, prefixes_changed, .. } = client;

                        let now = zx::MonotonicInstant::get();
                        let nonzero_timevalue_to_zx_time = |tv| match tv {
                            v6::NonZeroTimeValue::Finite(tv) => {
                                now + zx::MonotonicDuration::from_seconds(tv.get().into())
                            }
                            v6::NonZeroTimeValue::Infinity => zx::MonotonicInstant::INFINITE,
                        };

                        let calculate_lifetimes = |dhcpv6_core::client::Lifetimes {
                            preferred_lifetime,
                            valid_lifetime,
                        }| {
                            Lifetimes {
                                preferred_until: match preferred_lifetime {
                                    v6::TimeValue::Zero => zx::MonotonicInstant::ZERO,
                                    v6::TimeValue::NonZero(preferred_lifetime) => {
                                        nonzero_timevalue_to_zx_time(preferred_lifetime)
                                    },
                                }.into_nanos(),
                                valid_until: nonzero_timevalue_to_zx_time(valid_lifetime)
                                    .into_nanos(),
                            }
                        };

                        for (prefix, update) in updates.into_iter() {
                            let fidl_prefix = subnet_to_address_with_prefix(prefix);

                            match update {
                                dhcpv6_core::client::IaValueUpdateKind::Added(lifetimes) => {
                                    assert_matches!(
                                        prefixes.insert(
                                            fidl_prefix,
                                            calculate_lifetimes(lifetimes)
                                        ),
                                        None,
                                        "must not know about prefix {} to add it with lifetimes {:?}",
                                        prefix, lifetimes,
                                    );
                                }
                                dhcpv6_core::client::IaValueUpdateKind::UpdatedLifetimes(updated_lifetimes) => {
                                    assert_matches!(
                                        prefixes.get_mut(&fidl_prefix),
                                        Some(lifetimes) => {
                                            *lifetimes = calculate_lifetimes(updated_lifetimes);
                                        },
                                        "must know about prefix {} to update lifetimes with {:?}",
                                        prefix, updated_lifetimes,
                                    );
                                }
                                dhcpv6_core::client::IaValueUpdateKind::Removed => {
                                    assert_matches!(
                                        prefixes.remove(&fidl_prefix),
                                        Some(_),
                                        "must know about prefix {} to remove it",
                                        prefix
                                    );
                                }
                            }
                        }

                        // Mark the client has having updated prefixes so that
                        // callers of `WatchPrefixes` receive the update.
                        *prefixes_changed = true;
                        client.maybe_send_prefixes()?;
                    }
                };
                Ok(client)
            })
            .await
            .map(|_: &mut Client<S>| ())
    }

    /// Sends the latest DNS servers if a watcher is watching, and the latest set of servers are
    /// different from what the watcher has observed last time.
    fn maybe_send_dns_server_updates(&mut self, servers: Vec<Ipv6Addr>) -> Result<(), ClientError> {
        let servers_hash = hash(&servers);
        if servers_hash == self.last_observed_dns_hash {
            Ok(())
        } else {
            Ok(match self.dns_responder.take() {
                Some(responder) => {
                    self.send_dns_server_updates(responder, servers, servers_hash)?
                }
                None => (),
            })
        }
    }

    fn maybe_send_prefixes(&mut self) -> Result<(), ClientError> {
        let Self { prefixes, prefixes_changed, prefixes_responder, .. } = self;

        if !*prefixes_changed {
            return Ok(());
        }

        let responder = if let Some(responder) = prefixes_responder.take() {
            responder
        } else {
            return Ok(());
        };

        let prefixes = prefixes
            .iter()
            .map(|(prefix, lifetimes)| Prefix { prefix: *prefix, lifetimes: *lifetimes })
            .collect::<Vec<_>>();

        responder.send(&prefixes).map_err(ClientError::Fidl)?;
        *prefixes_changed = false;
        Ok(())
    }

    /// Sends a list of DNS servers to a watcher through the input responder and updates the last
    /// observed hash.
    fn send_dns_server_updates(
        &mut self,
        responder: ClientWatchServersResponder,
        servers: Vec<Ipv6Addr>,
        hash: u64,
    ) -> Result<(), ClientError> {
        let response: Vec<_> = servers
            .iter()
            .map(|addr| {
                let address = fnet::Ipv6Address { addr: addr.ipv6_bytes() };
                let zone_index =
                    if is_unicast_link_local_strict(&address) { self.interface_id } else { 0 };

                fnet_name::DnsServer_ {
                    address: Some(fnet::SocketAddress::Ipv6(fnet::Ipv6SocketAddress {
                        address,
                        zone_index,
                        port: DEFAULT_DNS_PORT,
                    })),
                    source: Some(fnet_name::DnsServerSource::Dhcpv6(
                        fnet_name::Dhcpv6DnsServerSource {
                            source_interface: Some(self.interface_id),
                            ..Default::default()
                        },
                    )),
                    ..Default::default()
                }
            })
            .collect();
        let () = responder
            .send(&response)
            // The channel will be closed on error, so return an error to stop the client.
            .map_err(ClientError::Fidl)?;
        self.last_observed_dns_hash = hash;
        Ok(())
    }

    /// Schedules a timer for `timer_type` to fire at `instant`.
    ///
    /// If a timer for `timer_type` is already scheduled, the timer is
    /// updated to fire at the new time.
    fn schedule_timer(
        &mut self,
        timer_type: dhcpv6_core::client::ClientTimerType,
        MonotonicInstant(instant): MonotonicInstant,
    ) {
        let (handle, reg) = AbortHandle::new_pair();
        match self.timer_abort_handles.insert(timer_type, handle) {
            // Abort the previous handle.
            Some(handle) => handle.abort(),
            None => {}
        }

        self.timer_futs.push(Abortable::new(
            fasync::Timer::new(fasync::MonotonicInstant::from_zx(instant))
                .replace_value(timer_type),
            reg,
        ))
    }

    /// Cancels a previously scheduled timer for `timer_type`.
    ///
    /// If a timer was not previously scheduled for `timer_type`, this
    /// call is effectively a no-op.
    fn cancel_timer(&mut self, timer_type: dhcpv6_core::client::ClientTimerType) {
        match self.timer_abort_handles.remove(&timer_type) {
            Some(handle) => handle.abort(),
            None => {}
        }
    }

    /// Handles a timeout.
    async fn handle_timeout(
        &mut self,
        timer_type: dhcpv6_core::client::ClientTimerType,
    ) -> Result<(), ClientError> {
        // This timer just fired.
        self.cancel_timer(timer_type);

        let actions = self.state_machine.handle_timeout(timer_type, MonotonicInstant::now());
        self.run_actions(actions).await
    }

    /// Handles a received message.
    async fn handle_message_recv(&mut self, mut msg: &[u8]) -> Result<(), ClientError> {
        let msg = match v6::Message::parse(&mut msg, ()) {
            Ok(msg) => msg,
            Err(e) => {
                // Discard invalid messages.
                //
                // https://tools.ietf.org/html/rfc8415#section-16.
                warn!("failed to parse received message: {}", e);
                return Ok(());
            }
        };
        let actions = self.state_machine.handle_message_receive(msg, MonotonicInstant::now());
        self.run_actions(actions).await
    }

    /// Handles a FIDL request sent to this client.
    fn handle_client_request(&mut self, request: ClientRequest) -> Result<(), ClientError> {
        debug!("handling client request: {:?}", request);
        match request {
            ClientRequest::WatchServers { responder } => match self.dns_responder {
                Some(_) => {
                    // Drop the previous responder to close the channel.
                    self.dns_responder = None;
                    // Return an error to stop the client because the channel is closed.
                    Err(ClientError::DoubleWatch)
                }
                None => {
                    let dns_servers = self.state_machine.get_dns_servers();
                    let servers_hash = hash(&dns_servers);
                    if servers_hash != self.last_observed_dns_hash {
                        // Something has changed from the last time, update the watcher.
                        let () =
                            self.send_dns_server_updates(responder, dns_servers, servers_hash)?;
                    } else {
                        // Nothing has changed, update the watcher later.
                        self.dns_responder = Some(responder);
                    }
                    Ok(())
                }
            },
            ClientRequest::WatchAddress { responder } => match self.address_responder.take() {
                // The responder will be dropped and cause the channel to be closed.
                Some(ClientWatchAddressResponder { .. }) => Err(ClientError::DoubleWatch),
                None => {
                    // TODO(https://fxbug.dev/42152192): Implement the address watcher.
                    warn!("WatchAddress call will block forever as it is unimplemented");
                    self.address_responder = Some(responder);
                    Ok(())
                }
            },
            ClientRequest::WatchPrefixes { responder } => match self.prefixes_responder.take() {
                // The responder will be dropped and cause the channel to be closed.
                Some(ClientWatchPrefixesResponder { .. }) => Err(ClientError::DoubleWatch),
                None => {
                    self.prefixes_responder = Some(responder);
                    self.maybe_send_prefixes()
                }
            },
            // TODO(https://fxbug.dev/42152193): Implement Shutdown.
            ClientRequest::Shutdown { responder: _ } => {
                Err(ClientError::Unimplemented("Shutdown".to_string()))
            }
        }
    }

    /// Handles the next event and returns the result.
    ///
    /// Takes a pre-allocated buffer to avoid repeated allocation.
    ///
    /// The returned `Option` is `None` if `request_stream` on the client is closed.
    async fn handle_next_event(&mut self, buf: &mut [u8]) -> Result<Option<()>, ClientError> {
        select! {
            timer_res = self.timer_futs.select_next_some() => {
                match timer_res {
                    Ok(timer_type) => {
                        let () = self.handle_timeout(timer_type).await?;
                        Ok(Some(()))
                    },
                    // The timer was aborted, do nothing.
                    Err(Aborted) => {
                        debug!("timer aborted");
                        Ok(Some(()))
                    }
                }
            },
            recv_from_res = self.socket.recv_from(buf).fuse() => {
                let (size, _addr) = recv_from_res.map_err(ClientError::SocketRecv)?;
                let () = self.handle_message_recv(&buf[..size]).await?;
                Ok(Some(()))
            },
            request = self.request_stream.try_next() => {
                match request {
                    Ok(request) => {
                        request.map(|request| self.handle_client_request(request)).transpose()
                    }
                    Err(e) => {
                        Err(ClientError::Fidl(e))
                    }
                }
            }
        }
    }
}

/// Creates a socket listening on the input address.
fn create_socket(addr: SocketAddr) -> std::io::Result<fasync::net::UdpSocket> {
    let socket = socket2::Socket::new(
        socket2::Domain::IPV6,
        socket2::Type::DGRAM,
        Some(socket2::Protocol::UDP),
    )?;
    // It is possible to run multiple clients on the same address.
    let () = socket.set_reuse_port(true)?;
    let () = socket.bind(&addr.into())?;
    fasync::net::UdpSocket::from_socket(socket.into())
}

/// Returns `true` if the input address is a link-local address (`fe80::/64`).
///
/// TODO(https://github.com/rust-lang/rust/issues/27709): use is_unicast_link_local_strict() in
/// stable rust when it's available.
fn is_unicast_link_local_strict(addr: &fnet::Ipv6Address) -> bool {
    addr.addr[..8] == [0xfe, 0x80, 0, 0, 0, 0, 0, 0]
}

fn duid_from_fidl(duid: Duid) -> Result<dhcpv6_core::ClientDuid, ()> {
    /// According to [RFC 8415, section 11.2], DUID of type DUID-LLT has a type value of 1
    ///
    /// [RFC 8415, section 11.2]: https://datatracker.ietf.org/doc/html/rfc8415#section-11.2
    const DUID_TYPE_LLT: [u8; 2] = [0, 1];
    /// According to [RFC 8415, section 11.4], DUID of type DUID-LL has a type value of 3
    ///
    /// [RFC 8415, section 11.4]: https://datatracker.ietf.org/doc/html/rfc8415#section-11.4
    const DUID_TYPE_LL: [u8; 2] = [0, 3];
    /// According to [RFC 8415, section 11.5], DUID of type DUID-UUID has a type value of 4.
    ///
    /// [RFC 8415, section 11.5]: https://datatracker.ietf.org/doc/html/rfc8415#section-11.5
    const DUID_TYPE_UUID: [u8; 2] = [0, 4];
    /// According to [RFC 8415, section 11.2], the hardware type of Ethernet as assigned by
    /// [IANA] is 1.
    ///
    /// [RFC 8415, section 11.2]: https://datatracker.ietf.org/doc/html/rfc8415#section-11.2
    /// [IANA]: https://www.iana.org/assignments/arp-parameters/arp-parameters.xhtml
    const HARDWARE_TYPE_ETHERNET: [u8; 2] = [0, 1];
    match duid {
        // DUID-LLT with a MAC address is 14 bytes (2 bytes for the type + 2
        // bytes for the hardware type + 4 bytes for the timestamp + 6 bytes
        // for the MAC address), which is guaranteed to fit in the 18-byte limit
        // of `ClientDuid`.
        Duid::LinkLayerAddressPlusTime(LinkLayerAddressPlusTime {
            time,
            link_layer_address: LinkLayerAddress::Ethernet(mac),
        }) => {
            let mut duid = dhcpv6_core::ClientDuid::new();
            duid.try_extend_from_slice(&DUID_TYPE_LLT).unwrap();
            duid.try_extend_from_slice(&HARDWARE_TYPE_ETHERNET).unwrap();
            duid.write_u32::<NetworkEndian>(time).unwrap();
            duid.try_extend_from_slice(&mac.octets).unwrap();
            Ok(duid)
        }
        // DUID-LL with a MAC address is 10 bytes (2 bytes for the type + 2
        // bytes for the hardware type + 6 bytes for the MAC address), which
        // is guaranteed to fit in the 18-byte limit of `ClientDuid`.
        Duid::LinkLayerAddress(LinkLayerAddress::Ethernet(mac)) => Ok(DUID_TYPE_LL
            .into_iter()
            .chain(HARDWARE_TYPE_ETHERNET.into_iter())
            .chain(mac.octets.into_iter())
            .collect()),
        // DUID-UUID is 18 bytes (2 bytes for the type + 16 bytes for the UUID),
        // which is guaranteed to fit in the 18-byte limit of `ClientDuid`.
        Duid::Uuid(uuid) => Ok(DUID_TYPE_UUID.into_iter().chain(uuid.into_iter()).collect()),
        _ => Err(()),
    }
}

/// Starts a client based on `params`.
///
/// `request` will be serviced by the client.
pub(crate) async fn serve_client(
    NewClientParams { interface_id, address, duid, config }: NewClientParams,
    request: ServerEnd<ClientMarker>,
) -> Result<()> {
    if Ipv6Addr::from(address.address.addr).is_multicast()
        || (is_unicast_link_local_strict(&address.address) && address.zone_index != interface_id)
    {
        return request
            .close_with_epitaph(zx::Status::INVALID_ARGS)
            .context("closing request channel with epitaph");
    }

    let fnet_ext::SocketAddress(addr) = fnet::SocketAddress::Ipv6(address).into();
    let servers_addr = IpAddr::from_str(RELAY_AGENT_AND_SERVER_LINK_LOCAL_MULTICAST_ADDRESS)
        .with_context(|| {
            format!(
                "{} should be a valid IPv6 address",
                RELAY_AGENT_AND_SERVER_LINK_LOCAL_MULTICAST_ADDRESS,
            )
        })?;
    let duid = match duid.map(|fidl| duid_from_fidl(fidl)).transpose() {
        Ok(duid) => duid,
        Err(()) => {
            return request
                .close_with_epitaph(zx::Status::INVALID_ARGS)
                .context("closing request channel with epitaph")
        }
    };
    let (request_stream, control_handle) = request.into_stream_and_control_handle();
    let mut client = match Client::<fasync::net::UdpSocket>::start(
        duid,
        dhcpv6_core::client::transaction_id(),
        config,
        interface_id,
        || create_socket(addr),
        SocketAddr::new(servers_addr, RELAY_AGENT_AND_SERVER_PORT),
        request_stream,
    )
    .await
    {
        Ok(client) => client,
        Err(ClientError::UnsupportedConfigs) => {
            control_handle.shutdown_with_epitaph(zx::Status::INVALID_ARGS);
            return Ok(());
        }
        Err(e) => {
            return Err(e.into());
        }
    };
    let mut buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
    loop {
        match client.handle_next_event(&mut buf).await? {
            Some(()) => (),
            None => break Ok(()),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::pin::{pin, Pin};
    use std::task::Poll;

    use fidl::endpoints::{
        create_proxy, create_proxy_and_stream, create_request_stream, ClientEnd,
    };
    use fidl_fuchsia_net_dhcpv6::{self as fnet_dhcpv6, ClientProxy, DEFAULT_CLIENT_PORT};
    use fuchsia_async as fasync;
    use futures::{join, poll, TryFutureExt as _};

    use assert_matches::assert_matches;
    use net_declare::{
        fidl_ip_v6, fidl_ip_v6_with_prefix, fidl_mac, fidl_socket_addr, fidl_socket_addr_v6,
        net_ip_v6, net_subnet_v6, std_socket_addr,
    };
    use net_types::ip::IpAddress as _;
    use packet::serialize::InnerPacketBuilder;
    use test_case::test_case;

    use super::*;

    /// Creates a test socket bound to an ephemeral port on localhost.
    fn create_test_socket() -> (fasync::net::UdpSocket, SocketAddr) {
        let addr: SocketAddr = std_socket_addr!("[::1]:0");
        let socket = std::net::UdpSocket::bind(addr).expect("failed to create test socket");
        let addr = socket.local_addr().expect("failed to get address of test socket");
        (fasync::net::UdpSocket::from_socket(socket).expect("failed to create test socket"), addr)
    }

    struct ReceivedMessage {
        transaction_id: [u8; 3],
        // Client IDs are optional in Information Request messages.
        //
        // Per RFC 8415 section 18.2.6,
        //
        //   The client SHOULD include a Client Identifier option (see
        //   Section 21.2) to identify itself to the server (however, see
        //   Section 4.3.1 of [RFC7844] for reasons why a client may not want to
        //   include this option).
        //
        // Per RFC 7844 section 4.3.1,
        //
        //   According to [RFC3315], a DHCPv6 client includes its client
        //   identifier in most of the messages it sends. There is one exception,
        //   however: the client is allowed to omit its client identifier when
        //   sending Information-request messages.
        client_id: Option<Vec<u8>>,
    }

    /// Asserts `socket` receives a message of `msg_type` from
    /// `want_from_addr`.
    async fn assert_received_message(
        socket: &fasync::net::UdpSocket,
        want_from_addr: SocketAddr,
        msg_type: v6::MessageType,
    ) -> ReceivedMessage {
        let mut buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
        let (size, from_addr) =
            socket.recv_from(&mut buf).await.expect("failed to receive on test server socket");
        assert_eq!(from_addr, want_from_addr);
        let buf = &mut &buf[..size]; // Implements BufferView.
        let msg = v6::Message::parse(buf, ()).expect("failed to parse message");
        assert_eq!(msg.msg_type(), msg_type);

        let mut client_id = None;
        for opt in msg.options() {
            match opt {
                v6::ParsedDhcpOption::ClientId(id) => {
                    assert_eq!(core::mem::replace(&mut client_id, Some(id.to_vec())), None)
                }
                _ => {}
            }
        }

        ReceivedMessage { transaction_id: *msg.transaction_id(), client_id: client_id }
    }

    const TEST_MAC: fnet::MacAddress = fidl_mac!("00:01:02:03:04:05");

    #[test_case(
        Duid::LinkLayerAddress(LinkLayerAddress::Ethernet(TEST_MAC)),
        &[0, 3, 0, 1, 0, 1, 2, 3, 4, 5];
        "ll"
    )]
    #[test_case(
        Duid::LinkLayerAddressPlusTime(LinkLayerAddressPlusTime {
            time: 0,
            link_layer_address: LinkLayerAddress::Ethernet(TEST_MAC),
        }),
        &[0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5];
        "llt"
    )]
    #[test_case(
        Duid::Uuid([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]),
        &[0, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
        "uuid"
    )]
    #[fuchsia::test]
    fn test_duid_from_fidl(duid: Duid, want: &[u8]) {
        assert_eq!(duid_from_fidl(duid), Ok(dhcpv6_core::ClientDuid::try_from(want).unwrap()));
    }

    #[fuchsia::test]
    fn test_create_client_with_unsupported_config() {
        let prefix_delegation_configs = [
            None,
            // Prefix length config without a non-zero length.
            Some(PrefixDelegationConfig::PrefixLength(0)),
            // Prefix length too long.
            Some(PrefixDelegationConfig::PrefixLength(Ipv6Addr::BYTES * 8 + 1)),
            // Network-bits unset.
            Some(PrefixDelegationConfig::Prefix(fidl_ip_v6_with_prefix!("::/64"))),
            // Host-bits set.
            Some(PrefixDelegationConfig::Prefix(fidl_ip_v6_with_prefix!("a::1/64"))),
        ];

        for prefix_delegation_config in prefix_delegation_configs.iter() {
            assert_matches!(
                create_state_machine(
                    prefix_delegation_config.is_some().then(|| CLIENT_ID.into()),
                    [1, 2, 3],
                    ClientConfig {
                        information_config: Default::default(),
                        non_temporary_address_config: Default::default(),
                        prefix_delegation_config: prefix_delegation_config.clone(),
                    }
                ),
                Err(ClientError::UnsupportedConfigs),
                "prefix_delegation_config={:?}",
                prefix_delegation_config
            );
        }
    }

    const STATELESS_CLIENT_CONFIG: ClientConfig = ClientConfig {
        information_config: InformationConfig { dns_servers: true },
        non_temporary_address_config: AddressConfig { address_count: 0, preferred_addresses: None },
        prefix_delegation_config: None,
    };

    #[fuchsia::test]
    async fn test_client_stops_on_channel_close() {
        let (client_proxy, server_end) = create_proxy::<ClientMarker>();

        let ((), client_res) = join!(
            async { drop(client_proxy) },
            serve_client(
                NewClientParams {
                    interface_id: 1,
                    address: fidl_socket_addr_v6!("[::1]:546"),
                    config: STATELESS_CLIENT_CONFIG,
                    duid: None,
                },
                server_end,
            ),
        );
        client_res.expect("client future should return with Ok");
    }

    fn client_proxy_watch_servers(
        client_proxy: &fnet_dhcpv6::ClientProxy,
    ) -> impl Future<Output = Result<(), fidl::Error>> {
        client_proxy.watch_servers().map_ok(|_: Vec<fidl_fuchsia_net_name::DnsServer_>| ())
    }

    fn client_proxy_watch_address(
        client_proxy: &fnet_dhcpv6::ClientProxy,
    ) -> impl Future<Output = Result<(), fidl::Error>> {
        client_proxy.watch_address().map_ok(
            |_: (
                fnet::Subnet,
                fidl_fuchsia_net_interfaces_admin::AddressParameters,
                fidl::endpoints::ServerEnd<
                    fidl_fuchsia_net_interfaces_admin::AddressStateProviderMarker,
                >,
            )| (),
        )
    }

    fn client_proxy_watch_prefixes(
        client_proxy: &fnet_dhcpv6::ClientProxy,
    ) -> impl Future<Output = Result<(), fidl::Error>> {
        client_proxy.watch_prefixes().map_ok(|_: Vec<fnet_dhcpv6::Prefix>| ())
    }

    #[test_case(client_proxy_watch_servers; "watch_servers")]
    #[test_case(client_proxy_watch_address; "watch_address")]
    #[test_case(client_proxy_watch_prefixes; "watch_prefixes")]
    #[fuchsia::test]
    async fn test_client_should_return_error_on_double_watch<Fut, F>(watch: F)
    where
        Fut: Future<Output = Result<(), fidl::Error>>,
        F: Fn(&fnet_dhcpv6::ClientProxy) -> Fut,
    {
        let (client_proxy, server_end) = create_proxy::<ClientMarker>();

        let (caller1_res, caller2_res, client_res) = join!(
            watch(&client_proxy),
            watch(&client_proxy),
            serve_client(
                NewClientParams {
                    interface_id: 1,
                    address: fidl_socket_addr_v6!("[::1]:546"),
                    config: STATELESS_CLIENT_CONFIG,
                    duid: None,
                },
                server_end,
            )
        );

        assert_matches!(
            caller1_res,
            Err(fidl::Error::ClientChannelClosed { status: zx::Status::PEER_CLOSED, .. })
        );
        assert_matches!(
            caller2_res,
            Err(fidl::Error::ClientChannelClosed { status: zx::Status::PEER_CLOSED, .. })
        );
        assert!(client_res
            .expect_err("client should fail with double watch error")
            .to_string()
            .contains("got watch request while the previous one is pending"));
    }

    const VALID_INFORMATION_CONFIGS: [InformationConfig; 2] =
        [InformationConfig { dns_servers: false }, InformationConfig { dns_servers: true }];

    const VALID_DELEGATED_PREFIX_CONFIGS: [Option<PrefixDelegationConfig>; 4] = [
        Some(PrefixDelegationConfig::Empty(Empty {})),
        Some(PrefixDelegationConfig::PrefixLength(1)),
        Some(PrefixDelegationConfig::PrefixLength(127)),
        Some(PrefixDelegationConfig::Prefix(fidl_ip_v6_with_prefix!("a::/64"))),
    ];

    // Can't be a const variable because we allocate a vector.
    fn get_valid_non_temporary_address_configs() -> [AddressConfig; 5] {
        [
            Default::default(),
            AddressConfig { address_count: 1, preferred_addresses: None },
            AddressConfig { address_count: 1, preferred_addresses: Some(Vec::new()) },
            AddressConfig {
                address_count: 1,
                preferred_addresses: Some(vec![fidl_ip_v6!("a::1")]),
            },
            AddressConfig {
                address_count: 2,
                preferred_addresses: Some(vec![fidl_ip_v6!("a::2")]),
            },
        ]
    }

    #[fuchsia::test]
    fn test_client_starts_with_valid_args() {
        for information_config in VALID_INFORMATION_CONFIGS {
            for non_temporary_address_config in get_valid_non_temporary_address_configs() {
                for prefix_delegation_config in VALID_DELEGATED_PREFIX_CONFIGS {
                    let mut exec = fasync::TestExecutor::new();

                    let (client_proxy, server_end) = create_proxy::<ClientMarker>();

                    let test_fut = async {
                        join!(
                            client_proxy.watch_servers(),
                            serve_client(
                                NewClientParams {
                                    interface_id: 1,
                                    address: fidl_socket_addr_v6!("[::1]:546"),
                                    config: ClientConfig {
                                        information_config: information_config.clone(),
                                        non_temporary_address_config: non_temporary_address_config
                                            .clone(),
                                        prefix_delegation_config: prefix_delegation_config.clone(),
                                    },
                                    duid: (non_temporary_address_config.address_count != 0
                                        || prefix_delegation_config.is_some())
                                    .then(|| fnet_dhcpv6::Duid::LinkLayerAddress(
                                        fnet_dhcpv6::LinkLayerAddress::Ethernet(fidl_mac!(
                                            "00:11:22:33:44:55"
                                        ))
                                    )),
                                },
                                server_end
                            )
                        )
                    };
                    let mut test_fut = pin!(test_fut);
                    assert_matches!(
                        exec.run_until_stalled(&mut test_fut),
                        Poll::Pending,
                        "information_config={:?}, non_temporary_address_config={:?}, prefix_delegation_config={:?}",
                        information_config, non_temporary_address_config, prefix_delegation_config
                    );
                }
            }
        }
    }

    const CLIENT_ID: [u8; 18] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17];

    #[fuchsia::test]
    async fn test_client_starts_in_correct_mode() {
        for information_config @ InformationConfig { dns_servers } in VALID_INFORMATION_CONFIGS {
            for non_temporary_address_config @ AddressConfig {
                address_count,
                preferred_addresses: _,
            } in get_valid_non_temporary_address_configs()
            {
                for prefix_delegation_config in VALID_DELEGATED_PREFIX_CONFIGS {
                    let (stateful, want_msg_type) =
                        if address_count == 0 && prefix_delegation_config.is_none() {
                            if !dns_servers {
                                continue;
                            } else {
                                (false, v6::MessageType::InformationRequest)
                            }
                        } else {
                            (true, v6::MessageType::Solicit)
                        };

                    let (_, client_stream): (ClientEnd<ClientMarker>, _) =
                        create_request_stream::<ClientMarker>();

                    let (client_socket, client_addr) = create_test_socket();
                    let (server_socket, server_addr) = create_test_socket();
                    println!(
                        "{:?} {:?} {:?}",
                        information_config, non_temporary_address_config, prefix_delegation_config
                    );
                    let _: Client<fasync::net::UdpSocket> = Client::start(
                        stateful.then(|| CLIENT_ID.into()),
                        [1, 2, 3], /* transaction ID */
                        ClientConfig {
                            information_config: information_config.clone(),
                            non_temporary_address_config: non_temporary_address_config.clone(),
                            prefix_delegation_config: prefix_delegation_config.clone(),
                        },
                        1, /* interface ID */
                        || Ok(client_socket),
                        server_addr,
                        client_stream,
                    )
                    .await
                        .unwrap_or_else(|e| panic!(
                            "failed to create test client: {}; information_config={:?}, non_temporary_address_config={:?}, prefix_delegation_config={:?}",
                            e, information_config, non_temporary_address_config, prefix_delegation_config
                        ));

                    let _: ReceivedMessage =
                        assert_received_message(&server_socket, client_addr, want_msg_type).await;
                }
            }
        }
    }

    // TODO(https://fxbug.dev/335656784): Replace this with a netemul test that isn't
    // sensitive to implementation details.
    #[fuchsia::test]
    async fn test_client_fails_to_start_with_invalid_args() {
        for params in vec![
            // Interface ID and zone index mismatch on link-local address.
            NewClientParams {
                interface_id: 2,
                address: fnet::Ipv6SocketAddress {
                    address: fidl_ip_v6!("fe80::1"),
                    port: DEFAULT_CLIENT_PORT,
                    zone_index: 1,
                },
                config: STATELESS_CLIENT_CONFIG,
                duid: None,
            },
            // Multicast address is invalid.
            NewClientParams {
                interface_id: 1,
                address: fnet::Ipv6SocketAddress {
                    address: fidl_ip_v6!("ff01::1"),
                    port: DEFAULT_CLIENT_PORT,
                    zone_index: 1,
                },
                config: STATELESS_CLIENT_CONFIG,
                duid: None,
            },
            // Stateless with DUID.
            NewClientParams {
                interface_id: 1,
                address: fidl_socket_addr_v6!("[2001:db8::1]:12345"),
                config: STATELESS_CLIENT_CONFIG,
                duid: Some(fnet_dhcpv6::Duid::LinkLayerAddress(
                    fnet_dhcpv6::LinkLayerAddress::Ethernet(fidl_mac!("00:11:22:33:44:55")),
                )),
            },
            // Stateful missing DUID.
            NewClientParams {
                interface_id: 1,
                address: fidl_socket_addr_v6!("[2001:db8::1]:12345"),
                config: ClientConfig {
                    information_config: InformationConfig { dns_servers: true },
                    non_temporary_address_config: AddressConfig {
                        address_count: 1,
                        preferred_addresses: None,
                    },
                    prefix_delegation_config: None,
                },
                duid: None,
            },
        ] {
            let (client_proxy, server_end) = create_proxy::<ClientMarker>();
            let () =
                serve_client(params, server_end).await.expect("start server failed unexpectedly");
            // Calling any function on the client proxy should fail due to channel closed with
            // `INVALID_ARGS`.
            assert_matches!(
                client_proxy.watch_servers().await,
                Err(fidl::Error::ClientChannelClosed { status: zx::Status::INVALID_ARGS, .. })
            );
        }
    }

    #[test]
    fn test_is_unicast_link_local_strict() {
        assert_eq!(is_unicast_link_local_strict(&fidl_ip_v6!("fe80::")), true);
        assert_eq!(is_unicast_link_local_strict(&fidl_ip_v6!("fe80::1")), true);
        assert_eq!(is_unicast_link_local_strict(&fidl_ip_v6!("fe80::ffff:1:2:3")), true);
        assert_eq!(is_unicast_link_local_strict(&fidl_ip_v6!("fe80::1:0:0:0:0")), false);
        assert_eq!(is_unicast_link_local_strict(&fidl_ip_v6!("fe81::")), false);
    }

    fn create_test_dns_server(
        address: fnet::Ipv6Address,
        source_interface: u64,
        zone_index: u64,
    ) -> fnet_name::DnsServer_ {
        fnet_name::DnsServer_ {
            address: Some(fnet::SocketAddress::Ipv6(fnet::Ipv6SocketAddress {
                address,
                zone_index,
                port: DEFAULT_DNS_PORT,
            })),
            source: Some(fnet_name::DnsServerSource::Dhcpv6(fnet_name::Dhcpv6DnsServerSource {
                source_interface: Some(source_interface),
                ..Default::default()
            })),
            ..Default::default()
        }
    }

    async fn send_msg_with_options(
        socket: &fasync::net::UdpSocket,
        to_addr: SocketAddr,
        transaction_id: [u8; 3],
        msg_type: v6::MessageType,
        options: &[v6::DhcpOption<'_>],
    ) -> Result<()> {
        let builder = v6::MessageBuilder::new(msg_type, transaction_id, options);
        let mut buf = vec![0u8; builder.bytes_len()];
        let () = builder.serialize(&mut buf);
        let size = socket.send_to(&buf, to_addr).await?;
        assert_eq!(size, buf.len());
        Ok(())
    }

    #[fuchsia::test]
    fn test_client_should_respond_to_dns_watch_requests() {
        let mut exec = fasync::TestExecutor::new();
        let transaction_id = [1, 2, 3];

        let (client_proxy, client_stream) = create_proxy_and_stream::<ClientMarker>();

        let (client_socket, client_addr) = create_test_socket();
        let (server_socket, server_addr) = create_test_socket();
        let mut client = exec
            .run_singlethreaded(Client::<fasync::net::UdpSocket>::start(
                None,
                transaction_id,
                STATELESS_CLIENT_CONFIG,
                1, /* interface ID */
                || Ok(client_socket),
                server_addr,
                client_stream,
            ))
            .expect("failed to create test client");

        type WatchServersResponseFut = <fnet_dhcpv6::ClientProxy as fnet_dhcpv6::ClientProxyInterface>::WatchServersResponseFut;
        type WatchServersResponse = <WatchServersResponseFut as Future>::Output;

        struct Test<'a> {
            client: &'a mut Client<fasync::net::UdpSocket>,
            buf: Vec<u8>,
            watcher_fut: WatchServersResponseFut,
        }

        impl<'a> Test<'a> {
            fn new(
                client: &'a mut Client<fasync::net::UdpSocket>,
                client_proxy: &ClientProxy,
            ) -> Self {
                Self {
                    client,
                    buf: vec![0u8; MAX_UDP_DATAGRAM_SIZE],
                    watcher_fut: client_proxy.watch_servers(),
                }
            }

            async fn handle_next_event(&mut self) {
                self.client
                    .handle_next_event(&mut self.buf)
                    .await
                    .expect("test client failed to handle next event")
                    .expect("request stream closed");
            }

            async fn refresh_client(&mut self) {
                // Make the client ready for another reply immediately on signal, so it can
                // start receiving updates without waiting for the full refresh timeout which is
                // unrealistic in tests.
                if self
                    .client
                    .timer_abort_handles
                    .contains_key(&dhcpv6_core::client::ClientTimerType::Refresh)
                {
                    self.client
                        .handle_timeout(dhcpv6_core::client::ClientTimerType::Refresh)
                        .await
                        .expect("test client failed to handle timeout");
                } else {
                    panic!("no refresh timer is scheduled and refresh is requested in test");
                }
                // Allow the client to handle the timeout-aborted event.
                self.handle_next_event().await;
            }

            // Drive both the DHCPv6 client's event handling logic and the DNS server
            // watcher until the DNS server watcher receives an update from the client (or
            // the client unexpectedly exits).
            fn run(&mut self) -> Pin<Box<dyn Future<Output = WatchServersResponse> + '_>> {
                let Self { client, buf, watcher_fut } = self;
                Box::pin(async move {
                    let client_fut = async {
                        loop {
                            client
                                .handle_next_event(buf)
                                .await
                                .expect("test client failed to handle next event")
                                .expect("request stream closed");
                        }
                    }
                    .fuse();
                    let mut client_fut = pin!(client_fut);
                    let mut watcher_fut = watcher_fut.fuse();
                    select! {
                        () = client_fut => panic!("test client returned unexpectedly"),
                        r = watcher_fut => r,
                    }
                })
            }
        }

        {
            // No DNS configurations received yet.
            let mut test = Test::new(&mut client, &client_proxy);

            // Handle the WatchServers request.
            exec.run_singlethreaded(test.handle_next_event());
            assert!(
                test.client.dns_responder.is_some(),
                "WatchServers responder should be present"
            );

            // Send an empty list to the client, should not update watcher.
            let () = exec
                .run_singlethreaded(send_msg_with_options(
                    &server_socket,
                    client_addr,
                    transaction_id,
                    v6::MessageType::Reply,
                    &[v6::DhcpOption::ServerId(&[1, 2, 3]), v6::DhcpOption::DnsServers(&[])],
                ))
                .expect("failed to send test reply");
            // Wait for the client to handle the next event (processing the reply we just
            // sent). Note that it is not enough to simply drive the client future until it
            // is stalled as we do elsewhere in the test, because we have no guarantee that
            // the netstack has delivered the UDP packet to the client by the time the
            // `send_to` call returned.
            exec.run_singlethreaded(test.handle_next_event());
            assert_matches!(exec.run_until_stalled(&mut test.run()), Poll::Pending);

            // Send a list of DNS servers, the watcher should be updated accordingly.
            exec.run_singlethreaded(test.refresh_client());
            let dns_servers = [net_ip_v6!("fe80::1:2")];
            let () = exec
                .run_singlethreaded(send_msg_with_options(
                    &server_socket,
                    client_addr,
                    transaction_id,
                    v6::MessageType::Reply,
                    &[
                        v6::DhcpOption::ServerId(&[1, 2, 3]),
                        v6::DhcpOption::DnsServers(&dns_servers),
                    ],
                ))
                .expect("failed to send test reply");
            let want_servers = vec![create_test_dns_server(
                fidl_ip_v6!("fe80::1:2"),
                1, /* source interface */
                1, /* zone index */
            )];
            let servers = exec.run_singlethreaded(test.run()).expect("get servers");
            assert_eq!(servers, want_servers);
        } // drop `test_fut` so `client_fut` is no longer mutably borrowed.

        {
            // No new changes, should not update watcher.
            let mut test = Test::new(&mut client, &client_proxy);

            // Handle the WatchServers request.
            exec.run_singlethreaded(test.handle_next_event());
            assert!(
                test.client.dns_responder.is_some(),
                "WatchServers responder should be present"
            );

            // Send the same list of DNS servers, should not update watcher.
            exec.run_singlethreaded(test.refresh_client());
            let dns_servers = [net_ip_v6!("fe80::1:2")];
            let () = exec
                .run_singlethreaded(send_msg_with_options(
                    &server_socket,
                    client_addr,
                    transaction_id,
                    v6::MessageType::Reply,
                    &[
                        v6::DhcpOption::ServerId(&[1, 2, 3]),
                        v6::DhcpOption::DnsServers(&dns_servers),
                    ],
                ))
                .expect("failed to send test reply");
            // Wait for the client to handle the next event (processing the reply we just
            // sent). Note that it is not enough to simply drive the client future until it
            // is stalled as we do elsewhere in the test, because we have no guarantee that
            // the netstack has delivered the UDP packet to the client by the time the
            // `send_to` call returned.
            exec.run_singlethreaded(test.handle_next_event());
            assert_matches!(exec.run_until_stalled(&mut test.run()), Poll::Pending);

            // Send a different list of DNS servers, should update watcher.
            exec.run_singlethreaded(test.refresh_client());
            let dns_servers = [net_ip_v6!("fe80::1:2"), net_ip_v6!("1234::5:6")];
            let () = exec
                .run_singlethreaded(send_msg_with_options(
                    &server_socket,
                    client_addr,
                    transaction_id,
                    v6::MessageType::Reply,
                    &[
                        v6::DhcpOption::ServerId(&[1, 2, 3]),
                        v6::DhcpOption::DnsServers(&dns_servers),
                    ],
                ))
                .expect("failed to send test reply");
            let want_servers = vec![
                create_test_dns_server(
                    fidl_ip_v6!("fe80::1:2"),
                    1, /* source interface */
                    1, /* zone index */
                ),
                // Only set zone index for link local addresses.
                create_test_dns_server(
                    fidl_ip_v6!("1234::5:6"),
                    1, /* source interface */
                    0, /* zone index */
                ),
            ];
            let servers = exec.run_singlethreaded(test.run()).expect("get servers");
            assert_eq!(servers, want_servers);
        } // drop `test_fut` so `client_fut` is no longer mutably borrowed.

        {
            // Send an empty list of DNS servers, should update watcher,
            // because this is different from what the watcher has seen
            // last time.
            let mut test = Test::new(&mut client, &client_proxy);

            exec.run_singlethreaded(test.refresh_client());
            let () = exec
                .run_singlethreaded(send_msg_with_options(
                    &server_socket,
                    client_addr,
                    transaction_id,
                    v6::MessageType::Reply,
                    &[v6::DhcpOption::ServerId(&[1, 2, 3]), v6::DhcpOption::DnsServers(&[])],
                ))
                .expect("failed to send test reply");
            let want_servers = Vec::<fnet_name::DnsServer_>::new();
            assert_eq!(exec.run_singlethreaded(test.run()).expect("get servers"), want_servers);
        } // drop `test_fut` so `client_fut` is no longer mutably borrowed.
    }

    #[fuchsia::test]
    async fn test_client_should_respond_with_dns_servers_on_first_watch_if_non_empty() {
        let transaction_id = [1, 2, 3];

        let (client_proxy, client_stream) = create_proxy_and_stream::<ClientMarker>();

        let (client_socket, client_addr) = create_test_socket();
        let (server_socket, server_addr) = create_test_socket();
        let client = Client::<fasync::net::UdpSocket>::start(
            None,
            transaction_id,
            STATELESS_CLIENT_CONFIG,
            1, /* interface ID */
            || Ok(client_socket),
            server_addr,
            client_stream,
        )
        .await
        .expect("failed to create test client");

        let dns_servers = [net_ip_v6!("fe80::1:2"), net_ip_v6!("1234::5:6")];
        let () = send_msg_with_options(
            &server_socket,
            client_addr,
            transaction_id,
            v6::MessageType::Reply,
            &[v6::DhcpOption::ServerId(&[4, 5, 6]), v6::DhcpOption::DnsServers(&dns_servers)],
        )
        .await
        .expect("failed to send test message");

        let buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
        let handle_client_events_fut =
            futures::stream::try_unfold((client, buf), |(mut client, mut buf)| async {
                client
                    .handle_next_event(&mut buf)
                    .await
                    .map(|res| res.map(|()| ((), (client, buf))))
            })
            .try_fold((), |(), ()| futures::future::ready(Ok(())))
            .fuse();
        let mut handle_client_events_fut = pin!(handle_client_events_fut);

        let want_servers = vec![
            create_test_dns_server(
                fidl_ip_v6!("fe80::1:2"),
                1, /* source interface */
                1, /* zone index */
            ),
            create_test_dns_server(
                fidl_ip_v6!("1234::5:6"),
                1, /* source interface */
                0, /* zone index */
            ),
        ];
        let found_servers = select!(
            status = handle_client_events_fut => panic!("client unexpectedly exited: {status:?}"),
            found_servers = client_proxy.watch_servers() => found_servers.expect(
                "watch servers should succeed"),
        );
        assert_eq!(found_servers, want_servers);
    }

    #[fuchsia::test]
    async fn watch_prefixes() {
        const SERVER_ID: [u8; 3] = [3, 4, 5];
        const PREFERRED_LIFETIME_SECS: u32 = 1000;
        const VALID_LIFETIME_SECS: u32 = 2000;
        // Use the smallest possible value to enter the Renewing state
        // as fast as possible to keep the test's run-time as low as possible.
        const T1: u32 = 1;
        const T2: u32 = 2000;

        let (client_proxy, client_stream) = create_proxy_and_stream::<ClientMarker>();

        let (client_socket, client_addr) = create_test_socket();
        let (server_socket, server_addr) = create_test_socket();
        let mut client = Client::<fasync::net::UdpSocket>::start(
            Some(CLIENT_ID.into()),
            [1, 2, 3],
            ClientConfig {
                information_config: Default::default(),
                non_temporary_address_config: Default::default(),
                prefix_delegation_config: Some(PrefixDelegationConfig::Empty(Empty {})),
            },
            1, /* interface ID */
            || Ok(client_socket),
            server_addr,
            client_stream,
        )
        .await
        .expect("failed to create test client");

        let client_fut = async {
            let mut buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
            loop {
                select! {
                    res = client.handle_next_event(&mut buf).fuse() => {
                        match res.expect("test client failed to handle next event") {
                            Some(()) => (),
                            None => break (),
                        };
                    }
                }
            }
        }
        .fuse();
        let mut client_fut = pin!(client_fut);

        let update_prefix = net_subnet_v6!("a::/64");
        let remove_prefix = net_subnet_v6!("b::/64");
        let add_prefix = net_subnet_v6!("c::/64");

        // Go through the motions to assign a prefix.
        let client_id = {
            let ReceivedMessage { client_id, transaction_id } =
                assert_received_message(&server_socket, client_addr, v6::MessageType::Solicit)
                    .await;
            // Client IDs are mandatory in stateful DHCPv6.
            let client_id = client_id.unwrap();

            let ia_prefix = [
                v6::DhcpOption::IaPrefix(v6::IaPrefixSerializer::new(
                    PREFERRED_LIFETIME_SECS,
                    VALID_LIFETIME_SECS,
                    update_prefix,
                    &[],
                )),
                v6::DhcpOption::IaPrefix(v6::IaPrefixSerializer::new(
                    PREFERRED_LIFETIME_SECS,
                    VALID_LIFETIME_SECS,
                    remove_prefix,
                    &[],
                )),
            ];
            let () = send_msg_with_options(
                &server_socket,
                client_addr,
                transaction_id,
                v6::MessageType::Advertise,
                &[
                    v6::DhcpOption::ServerId(&SERVER_ID),
                    v6::DhcpOption::ClientId(&client_id),
                    v6::DhcpOption::Preference(u8::MAX),
                    v6::DhcpOption::IaPd(v6::IaPdSerializer::new(IA_PD_IAID, T1, T2, &ia_prefix)),
                ],
            )
            .await
            .expect("failed to send adv message");

            // Wait for the client to send a Request and send Reply so a prefix
            // is assigned.
            let transaction_id = select! {
                () = client_fut => panic!("should never return"),
                res = assert_received_message(
                    &server_socket,
                    client_addr,
                    v6::MessageType::Request,
                ).fuse() => {
                    let ReceivedMessage { client_id: req_client_id, transaction_id } = res;
                    assert_eq!(Some(&client_id), req_client_id.as_ref());
                    transaction_id
                },
            };

            let () = send_msg_with_options(
                &server_socket,
                client_addr,
                transaction_id,
                v6::MessageType::Reply,
                &[
                    v6::DhcpOption::ServerId(&SERVER_ID),
                    v6::DhcpOption::ClientId(&client_id),
                    v6::DhcpOption::IaPd(v6::IaPdSerializer::new(IA_PD_IAID, T1, T2, &ia_prefix)),
                ],
            )
            .await
            .expect("failed to send reply message");

            client_id
        };

        let check_watch_prefixes_result =
            |res: Result<Vec<Prefix>, _>,
             before_handling_reply,
             preferred_lifetime_secs: u32,
             valid_lifetime_secs: u32,
             expected_prefixes| {
                assert_matches!(
                    res.unwrap()[..],
                    [
                        Prefix {
                            prefix: got_prefix1,
                            lifetimes: Lifetimes {
                                preferred_until: preferred_until1,
                                valid_until: valid_until1,
                            },
                        },
                        Prefix {
                            prefix: got_prefix2,
                            lifetimes: Lifetimes {
                                preferred_until: preferred_until2,
                                valid_until: valid_until2,
                            },
                        },
                    ] => {
                        let now = zx::MonotonicInstant::get();
                        let preferred_until = zx::MonotonicInstant::from_nanos(preferred_until1);
                        let valid_until = zx::MonotonicInstant::from_nanos(valid_until1);

                        let preferred_for = zx::MonotonicDuration::from_seconds(
                            preferred_lifetime_secs.into(),
                        );
                        let valid_for = zx::MonotonicDuration::from_seconds(valid_lifetime_secs.into());

                        assert_eq!(
                            HashSet::from([got_prefix1, got_prefix2]),
                            HashSet::from(expected_prefixes),
                        );
                        assert!(preferred_until >= before_handling_reply + preferred_for);
                        assert!(preferred_until <= now + preferred_for);
                        assert!(valid_until >= before_handling_reply + valid_for);
                        assert!(valid_until <= now + valid_for);

                        assert_eq!(preferred_until1, preferred_until2);
                        assert_eq!(valid_until1, valid_until2);
                    }
                )
            };

        // Wait for a prefix to become assigned from the perspective of the DHCPv6
        // FIDL client.
        {
            // watch_prefixes should not return before a lease is negotiated. Note
            // that the client has not yet handled the Reply message.
            let mut watch_prefixes = client_proxy.watch_prefixes().fuse();
            assert_matches!(poll!(&mut watch_prefixes), Poll::Pending);
            let before_handling_reply = zx::MonotonicInstant::get();
            select! {
                () = client_fut => panic!("should never return"),
                res = watch_prefixes => check_watch_prefixes_result(
                    res,
                    before_handling_reply,
                    PREFERRED_LIFETIME_SECS,
                    VALID_LIFETIME_SECS,
                    [
                        subnet_to_address_with_prefix(update_prefix),
                        subnet_to_address_with_prefix(remove_prefix),
                    ],
                ),
            }
        }

        // Wait for the client to attempt to renew the lease and go through the
        // motions to update the lease.
        {
            let transaction_id = select! {
                () = client_fut => panic!("should never return"),
                res = assert_received_message(
                    &server_socket,
                    client_addr,
                    v6::MessageType::Renew,
                ).fuse() => {
                    let ReceivedMessage { client_id: ren_client_id, transaction_id } = res;
                    assert_eq!(ren_client_id.as_ref(), Some(&client_id));
                    transaction_id
                },
            };

            const NEW_PREFERRED_LIFETIME_SECS: u32 = 2 * PREFERRED_LIFETIME_SECS;
            const NEW_VALID_LIFETIME_SECS: u32 = 2 * VALID_LIFETIME_SECS;
            let ia_prefix = [
                v6::DhcpOption::IaPrefix(v6::IaPrefixSerializer::new(
                    NEW_PREFERRED_LIFETIME_SECS,
                    NEW_VALID_LIFETIME_SECS,
                    update_prefix,
                    &[],
                )),
                v6::DhcpOption::IaPrefix(v6::IaPrefixSerializer::new(
                    NEW_PREFERRED_LIFETIME_SECS,
                    NEW_VALID_LIFETIME_SECS,
                    add_prefix,
                    &[],
                )),
                v6::DhcpOption::IaPrefix(v6::IaPrefixSerializer::new(0, 0, remove_prefix, &[])),
            ];

            let () = send_msg_with_options(
                &server_socket,
                client_addr,
                transaction_id,
                v6::MessageType::Reply,
                &[
                    v6::DhcpOption::ServerId(&SERVER_ID),
                    v6::DhcpOption::ClientId(&client_id),
                    v6::DhcpOption::IaPd(v6::IaPdSerializer::new(
                        v6::IAID::new(0),
                        T1,
                        T2,
                        &ia_prefix,
                    )),
                ],
            )
            .await
            .expect("failed to send reply message");

            let before_handling_reply = zx::MonotonicInstant::get();
            select! {
                () = client_fut => panic!("should never return"),
                res = client_proxy.watch_prefixes().fuse() => check_watch_prefixes_result(
                    res,
                    before_handling_reply,
                    NEW_PREFERRED_LIFETIME_SECS,
                    NEW_VALID_LIFETIME_SECS,
                    [
                        subnet_to_address_with_prefix(update_prefix),
                        subnet_to_address_with_prefix(add_prefix),
                    ],
                ),
            }
        }
    }

    #[fuchsia::test]
    async fn test_client_schedule_and_cancel_timers() {
        let (_client_end, client_stream) = create_request_stream::<ClientMarker>();

        let (client_socket, _client_addr) = create_test_socket();
        let (_server_socket, server_addr) = create_test_socket();
        let mut client = Client::<fasync::net::UdpSocket>::start(
            None,
            [1, 2, 3], /* transaction ID */
            STATELESS_CLIENT_CONFIG,
            1, /* interface ID */
            || Ok(client_socket),
            server_addr,
            client_stream,
        )
        .await
        .expect("failed to create test client");

        // Stateless DHCP client starts by scheduling a retransmission timer.
        assert_eq!(
            client.timer_abort_handles.keys().collect::<Vec<_>>(),
            vec![&dhcpv6_core::client::ClientTimerType::Retransmission]
        );

        let () = client.cancel_timer(dhcpv6_core::client::ClientTimerType::Retransmission);
        assert_eq!(
            client.timer_abort_handles.keys().collect::<Vec<_>>(),
            Vec::<&dhcpv6_core::client::ClientTimerType>::new()
        );

        let now = MonotonicInstant::now();
        let () = client.schedule_timer(
            dhcpv6_core::client::ClientTimerType::Refresh,
            now + Duration::from_nanos(1),
        );
        let () = client.schedule_timer(
            dhcpv6_core::client::ClientTimerType::Retransmission,
            now + Duration::from_nanos(2),
        );
        assert_eq!(
            client.timer_abort_handles.keys().collect::<HashSet<_>>(),
            vec![
                &dhcpv6_core::client::ClientTimerType::Retransmission,
                &dhcpv6_core::client::ClientTimerType::Refresh
            ]
            .into_iter()
            .collect()
        );

        // We are allowed to reschedule a timer to fire at a new time.
        let now = MonotonicInstant::now();
        client.schedule_timer(
            dhcpv6_core::client::ClientTimerType::Refresh,
            now + Duration::from_nanos(1),
        );
        client.schedule_timer(
            dhcpv6_core::client::ClientTimerType::Retransmission,
            now + Duration::from_nanos(2),
        );

        let () = client.cancel_timer(dhcpv6_core::client::ClientTimerType::Refresh);
        assert_eq!(
            client.timer_abort_handles.keys().collect::<Vec<_>>(),
            vec![&dhcpv6_core::client::ClientTimerType::Retransmission]
        );

        // Ok to cancel a timer that is not scheduled.
        client.cancel_timer(dhcpv6_core::client::ClientTimerType::Refresh);

        let () = client.cancel_timer(dhcpv6_core::client::ClientTimerType::Retransmission);
        assert_eq!(
            client
                .timer_abort_handles
                .keys()
                .collect::<Vec<&dhcpv6_core::client::ClientTimerType>>(),
            Vec::<&dhcpv6_core::client::ClientTimerType>::new()
        );

        // Ok to cancel a timer that is not scheduled.
        client.cancel_timer(dhcpv6_core::client::ClientTimerType::Retransmission);
    }

    #[fuchsia::test]
    async fn test_handle_next_event_on_stateless_client() {
        let (client_proxy, client_stream) = create_proxy_and_stream::<ClientMarker>();

        let (client_socket, client_addr) = create_test_socket();
        let (server_socket, server_addr) = create_test_socket();
        let mut client = Client::<fasync::net::UdpSocket>::start(
            None,
            [1, 2, 3], /* transaction ID */
            STATELESS_CLIENT_CONFIG,
            1, /* interface ID */
            || Ok(client_socket),
            server_addr,
            client_stream,
        )
        .await
        .expect("failed to create test client");

        // Starting the client in stateless should send an information request out.
        let ReceivedMessage { client_id, transaction_id: _ } = assert_received_message(
            &server_socket,
            client_addr,
            v6::MessageType::InformationRequest,
        )
        .await;
        assert_eq!(
            client.timer_abort_handles.keys().collect::<Vec<_>>(),
            vec![&dhcpv6_core::client::ClientTimerType::Retransmission]
        );

        let mut buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
        // Trigger a retransmission.
        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
        let ReceivedMessage { client_id: got_client_id, transaction_id: _ } =
            assert_received_message(
                &server_socket,
                client_addr,
                v6::MessageType::InformationRequest,
            )
            .await;
        assert_eq!(got_client_id, client_id);
        assert_eq!(
            client.timer_abort_handles.keys().collect::<Vec<_>>(),
            vec![&dhcpv6_core::client::ClientTimerType::Retransmission]
        );

        // Message targeting another transaction ID should be ignored.
        let () = send_msg_with_options(
            &server_socket,
            client_addr,
            [5, 6, 7],
            v6::MessageType::Reply,
            &[],
        )
        .await
        .expect("failed to send test message");
        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
        assert_eq!(
            client.timer_abort_handles.keys().collect::<Vec<_>>(),
            vec![&dhcpv6_core::client::ClientTimerType::Retransmission]
        );

        // Invalid messages should be discarded. Empty buffer is invalid.
        let size =
            server_socket.send_to(&[], client_addr).await.expect("failed to send test message");
        assert_eq!(size, 0);
        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
        assert_eq!(
            client.timer_abort_handles.keys().collect::<Vec<_>>(),
            vec![&dhcpv6_core::client::ClientTimerType::Retransmission]
        );

        // Message targeting this client should cause the client to transition state.
        let () = send_msg_with_options(
            &server_socket,
            client_addr,
            [1, 2, 3],
            v6::MessageType::Reply,
            &[v6::DhcpOption::ServerId(&[4, 5, 6])],
        )
        .await
        .expect("failed to send test message");
        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
        assert_eq!(
            client.timer_abort_handles.keys().collect::<Vec<_>>(),
            vec![&dhcpv6_core::client::ClientTimerType::Refresh]
        );
        // Discard aborted retransmission timer.
        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));

        // Reschedule a shorter timer for Refresh so we don't spend time waiting in test.
        client.cancel_timer(dhcpv6_core::client::ClientTimerType::Refresh);
        // Discard cancelled refresh timer.
        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
        client.schedule_timer(
            dhcpv6_core::client::ClientTimerType::Refresh,
            MonotonicInstant::now() + Duration::from_nanos(1),
        );

        // Trigger a refresh.
        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
        let ReceivedMessage { client_id, transaction_id: _ } = assert_received_message(
            &server_socket,
            client_addr,
            v6::MessageType::InformationRequest,
        )
        .await;
        assert_eq!(got_client_id, client_id,);
        assert_eq!(
            client.timer_abort_handles.keys().collect::<Vec<_>>(),
            vec![&dhcpv6_core::client::ClientTimerType::Retransmission]
        );

        let test_fut = async {
            assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
            client
                .dns_responder
                .take()
                .expect("test client did not get a channel responder")
                .send(&[fnet_name::DnsServer_ {
                    address: Some(fidl_socket_addr!("[fe01::2:3]:42")),
                    source: Some(fnet_name::DnsServerSource::Dhcpv6(
                        fnet_name::Dhcpv6DnsServerSource {
                            source_interface: Some(42),
                            ..Default::default()
                        },
                    )),
                    ..Default::default()
                }])
                .expect("failed to send response on test channel");
        };
        let (watcher_res, ()) = join!(client_proxy.watch_servers(), test_fut);
        let servers = watcher_res.expect("failed to watch servers");
        assert_eq!(
            servers,
            vec![fnet_name::DnsServer_ {
                address: Some(fidl_socket_addr!("[fe01::2:3]:42")),
                source: Some(fnet_name::DnsServerSource::Dhcpv6(
                    fnet_name::Dhcpv6DnsServerSource {
                        source_interface: Some(42),
                        ..Default::default()
                    },
                )),
                ..Default::default()
            }]
        );

        // Drop the channel should cause `handle_next_event(&mut buf)` to return `None`.
        drop(client_proxy);
        assert_matches!(client.handle_next_event(&mut buf).await, Ok(None));
    }

    #[fuchsia::test]
    async fn test_handle_next_event_on_stateful_client() {
        let (client_proxy, client_stream) = create_proxy_and_stream::<ClientMarker>();

        let (client_socket, client_addr) = create_test_socket();
        let (server_socket, server_addr) = create_test_socket();
        let mut client = Client::<fasync::net::UdpSocket>::start(
            Some(CLIENT_ID.into()),
            [1, 2, 3], /* transaction ID */
            ClientConfig {
                information_config: Default::default(),
                non_temporary_address_config: AddressConfig {
                    address_count: 1,
                    preferred_addresses: None,
                },
                prefix_delegation_config: None,
            },
            1, /* interface ID */
            || Ok(client_socket),
            server_addr,
            client_stream,
        )
        .await
        .expect("failed to create test client");

        // Starting the client in stateful should send out a solicit.
        let _: ReceivedMessage =
            assert_received_message(&server_socket, client_addr, v6::MessageType::Solicit).await;
        assert_eq!(
            client.timer_abort_handles.keys().collect::<Vec<_>>(),
            vec![&dhcpv6_core::client::ClientTimerType::Retransmission]
        );

        let mut buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
        // Drop the channel should cause `handle_next_event(&mut buf)` to return `None`.
        drop(client_proxy);
        assert_matches!(client.handle_next_event(&mut buf).await, Ok(None));
    }

    #[fuchsia::test]
    #[should_panic]
    async fn test_handle_next_event_respects_timer_order() {
        let (_client_end, client_stream) = create_request_stream::<ClientMarker>();

        let (client_socket, client_addr) = create_test_socket();
        let (server_socket, server_addr) = create_test_socket();
        let mut client = Client::<fasync::net::UdpSocket>::start(
            None,
            [1, 2, 3], /* transaction ID */
            STATELESS_CLIENT_CONFIG,
            1, /* interface ID */
            || Ok(client_socket),
            server_addr,
            client_stream,
        )
        .await
        .expect("failed to create test client");

        let mut buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
        // A retransmission timer is scheduled when starting the client in stateless mode. Cancel
        // it and create a new one with a longer timeout so the test is not flaky.
        let () = client.cancel_timer(dhcpv6_core::client::ClientTimerType::Retransmission);
        // Discard cancelled retransmission timer.
        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
        let () = client.schedule_timer(
            dhcpv6_core::client::ClientTimerType::Retransmission,
            MonotonicInstant::now() + Duration::from_secs(1_000_000),
        );
        assert_eq!(
            client.timer_abort_handles.keys().collect::<Vec<_>>(),
            vec![&dhcpv6_core::client::ClientTimerType::Retransmission]
        );

        // Trigger a message receive, the message is later discarded because transaction ID doesn't
        // match.
        let () = send_msg_with_options(
            &server_socket,
            client_addr,
            [5, 6, 7],
            v6::MessageType::Reply,
            &[],
        )
        .await
        .expect("failed to send test message");
        // There are now two pending events, the message receive is handled first because the timer
        // is far into the future.
        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
        // The retransmission timer is still here.
        assert_eq!(
            client.timer_abort_handles.keys().collect::<Vec<_>>(),
            vec![&dhcpv6_core::client::ClientTimerType::Retransmission]
        );

        // Inserts a refresh timer that precedes the retransmission.
        let () = client.schedule_timer(
            dhcpv6_core::client::ClientTimerType::Refresh,
            MonotonicInstant::now() + Duration::from_nanos(1),
        );
        // This timer is scheduled.
        assert_eq!(
            client.timer_abort_handles.keys().collect::<HashSet<_>>(),
            vec![
                &dhcpv6_core::client::ClientTimerType::Retransmission,
                &dhcpv6_core::client::ClientTimerType::Refresh
            ]
            .into_iter()
            .collect()
        );

        // Now handle_next_event(&mut buf) should trigger a refresh because it
        // precedes retransmission. Refresh is not expected while in
        // InformationRequesting state and should lead to a panic.
        assert_matches!(client.handle_next_event(&mut buf).await, Ok(Some(())));
    }

    #[fuchsia::test]
    async fn test_handle_next_event_fails_on_recv_err() {
        struct StubSocket {}
        impl<'a> AsyncSocket<'a> for StubSocket {
            type RecvFromFut = futures::future::Ready<Result<(usize, SocketAddr), std::io::Error>>;
            type SendToFut = futures::future::Ready<Result<usize, std::io::Error>>;

            fn recv_from(&'a self, _buf: &'a mut [u8]) -> Self::RecvFromFut {
                futures::future::ready(Err(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    "test recv error",
                )))
            }
            fn send_to(&'a self, buf: &'a [u8], _addr: SocketAddr) -> Self::SendToFut {
                futures::future::ready(Ok(buf.len()))
            }
        }

        let (_client_end, client_stream) = create_request_stream::<ClientMarker>();

        let mut client = Client::<StubSocket>::start(
            None,
            [1, 2, 3], /* transaction ID */
            STATELESS_CLIENT_CONFIG,
            1, /* interface ID */
            || Ok(StubSocket {}),
            std_socket_addr!("[::1]:0"),
            client_stream,
        )
        .await
        .expect("failed to create test client");

        assert_matches!(
            client.handle_next_event(&mut [0u8]).await,
            Err(ClientError::SocketRecv(err)) if err.kind() == std::io::ErrorKind::Other
        );
    }
}