netemul/
lib.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
// 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.

#![warn(missing_docs, unreachable_patterns)]

//! Netemul utilities.

/// Methods for creating and interacting with virtualized guests in netemul tests.
pub mod guest;

use std::borrow::Cow;
use std::num::NonZeroU64;
use std::ops::DerefMut as _;
use std::path::Path;
use std::pin::pin;

use fidl::endpoints::ProtocolMarker;
use fidl_fuchsia_net_dhcp_ext::{self as fnet_dhcp_ext, ClientProviderExt};
use fidl_fuchsia_net_ext::{self as fnet_ext};
use fidl_fuchsia_net_interfaces_ext::admin::Control;
use fidl_fuchsia_net_interfaces_ext::{self as fnet_interfaces_ext};
use fnet_ext::{FromExt as _, IntoExt as _};
use fnet_interfaces_admin::GrantForInterfaceAuthorization;
use {
    fidl_fuchsia_hardware_network as fnetwork, fidl_fuchsia_io as fio, fidl_fuchsia_net as fnet,
    fidl_fuchsia_net_dhcp as fnet_dhcp, fidl_fuchsia_net_interfaces as fnet_interfaces,
    fidl_fuchsia_net_interfaces_admin as fnet_interfaces_admin,
    fidl_fuchsia_net_neighbor as fnet_neighbor, fidl_fuchsia_net_root as fnet_root,
    fidl_fuchsia_net_routes as fnet_routes, fidl_fuchsia_net_routes_admin as fnet_routes_admin,
    fidl_fuchsia_net_routes_ext as fnet_routes_ext, fidl_fuchsia_net_stack as fnet_stack,
    fidl_fuchsia_netemul as fnetemul, fidl_fuchsia_netemul_network as fnetemul_network,
    fidl_fuchsia_posix_socket as fposix_socket, fidl_fuchsia_posix_socket_ext as fposix_socket_ext,
    fidl_fuchsia_posix_socket_packet as fposix_socket_packet,
    fidl_fuchsia_posix_socket_raw as fposix_socket_raw,
};

use anyhow::{anyhow, Context as _};
use futures::future::{FutureExt as _, LocalBoxFuture, TryFutureExt as _};
use futures::{SinkExt as _, TryStreamExt as _};
use net_types::ip::{GenericOverIp, Ip, Ipv4, Ipv6, Subnet};
use net_types::SpecifiedAddr;

type Result<T = ()> = std::result::Result<T, anyhow::Error>;

/// The default MTU used in netemul endpoint configurations.
pub const DEFAULT_MTU: u16 = 1500;

/// The devfs path at which endpoints show up.
pub const NETDEVICE_DEVFS_PATH: &'static str = "class/network";

/// Returns the full path for a device node `node_name` relative to devfs root.
pub fn devfs_device_path(node_name: &str) -> std::path::PathBuf {
    std::path::Path::new(NETDEVICE_DEVFS_PATH).join(node_name)
}

/// Creates a common netemul endpoint configuration for tests.
pub fn new_endpoint_config(
    mtu: u16,
    mac: Option<fnet::MacAddress>,
) -> fnetemul_network::EndpointConfig {
    fnetemul_network::EndpointConfig {
        mtu,
        mac: mac.map(Box::new),
        port_class: fnetwork::PortClass::Virtual,
    }
}

/// A test sandbox backed by a [`fnetemul::SandboxProxy`].
///
/// `TestSandbox` provides various utility methods to set up network realms for
/// use in testing. The lifetime of the `TestSandbox` is tied to the netemul
/// sandbox itself, dropping it will cause all the created realms, networks, and
/// endpoints to be destroyed.
#[must_use]
pub struct TestSandbox {
    sandbox: fnetemul::SandboxProxy,
}

impl TestSandbox {
    /// Creates a new empty sandbox.
    pub fn new() -> Result<TestSandbox> {
        fuchsia_component::client::connect_to_protocol::<fnetemul::SandboxMarker>()
            .context("failed to connect to sandbox protocol")
            .map(|sandbox| TestSandbox { sandbox })
    }

    /// Creates a realm with `name` and `children`.
    pub fn create_realm<'a, I>(
        &'a self,
        name: impl Into<Cow<'a, str>>,
        children: I,
    ) -> Result<TestRealm<'a>>
    where
        I: IntoIterator,
        I::Item: Into<fnetemul::ChildDef>,
    {
        let (realm, server) = fidl::endpoints::create_proxy::<fnetemul::ManagedRealmMarker>();
        let name = name.into();
        let () = self.sandbox.create_realm(
            server,
            fnetemul::RealmOptions {
                name: Some(name.clone().into_owned()),
                children: Some(children.into_iter().map(Into::into).collect()),
                ..Default::default()
            },
        )?;
        Ok(TestRealm { realm, name, _sandbox: self })
    }

    /// Creates a realm with no components.
    pub fn create_empty_realm<'a>(
        &'a self,
        name: impl Into<Cow<'a, str>>,
    ) -> Result<TestRealm<'a>> {
        self.create_realm(name, std::iter::empty::<fnetemul::ChildDef>())
    }

    /// Connects to the sandbox's `NetworkContext`.
    fn get_network_context(&self) -> Result<fnetemul_network::NetworkContextProxy> {
        let (ctx, server) =
            fidl::endpoints::create_proxy::<fnetemul_network::NetworkContextMarker>();
        let () = self.sandbox.get_network_context(server)?;
        Ok(ctx)
    }

    /// Connects to the sandbox's `NetworkManager`.
    pub fn get_network_manager(&self) -> Result<fnetemul_network::NetworkManagerProxy> {
        let ctx = self.get_network_context()?;
        let (network_manager, server) =
            fidl::endpoints::create_proxy::<fnetemul_network::NetworkManagerMarker>();
        let () = ctx.get_network_manager(server)?;
        Ok(network_manager)
    }

    /// Connects to the sandbox's `EndpointManager`.
    pub fn get_endpoint_manager(&self) -> Result<fnetemul_network::EndpointManagerProxy> {
        let ctx = self.get_network_context()?;
        let (ep_manager, server) =
            fidl::endpoints::create_proxy::<fnetemul_network::EndpointManagerMarker>();
        let () = ctx.get_endpoint_manager(server)?;
        Ok(ep_manager)
    }

    /// Creates a new empty network with default configurations and `name`.
    pub async fn create_network<'a>(
        &'a self,
        name: impl Into<Cow<'a, str>>,
    ) -> Result<TestNetwork<'a>> {
        let name = name.into();
        let netm = self.get_network_manager()?;
        let (status, network) = netm
            .create_network(
                &name,
                &fnetemul_network::NetworkConfig {
                    latency: None,
                    packet_loss: None,
                    reorder: None,
                    ..Default::default()
                },
            )
            .await
            .context("create_network FIDL error")?;
        let () = zx::Status::ok(status).context("create_network failed")?;
        let network = network
            .ok_or_else(|| anyhow::anyhow!("create_network didn't return a valid network"))?
            .into_proxy();
        Ok(TestNetwork { network, name, sandbox: self })
    }

    /// Creates new networks and endpoints as specified in `networks`.
    pub async fn setup_networks<'a>(
        &'a self,
        networks: Vec<fnetemul_network::NetworkSetup>,
    ) -> Result<TestNetworkSetup<'a>> {
        let ctx = self.get_network_context()?;
        let (status, handle) = ctx.setup(&networks).await.context("setup FIDL error")?;
        let () = zx::Status::ok(status).context("setup failed")?;
        let handle = handle
            .ok_or_else(|| anyhow::anyhow!("setup didn't return a valid handle"))?
            .into_proxy();
        Ok(TestNetworkSetup { _setup: handle, _sandbox: self })
    }

    /// Creates a new unattached endpoint with default configurations and `name`.
    ///
    /// Characters may be dropped from the front of `name` if it exceeds the maximum length.
    pub async fn create_endpoint<'a, S>(&'a self, name: S) -> Result<TestEndpoint<'a>>
    where
        S: Into<Cow<'a, str>>,
    {
        self.create_endpoint_with(name, new_endpoint_config(DEFAULT_MTU, None)).await
    }

    /// Creates a new unattached endpoint with the provided configuration.
    ///
    /// Characters may be dropped from the front of `name` if it exceeds the maximum length.
    pub async fn create_endpoint_with<'a>(
        &'a self,
        name: impl Into<Cow<'a, str>>,
        config: fnetemul_network::EndpointConfig,
    ) -> Result<TestEndpoint<'a>> {
        let name = name.into();
        let epm = self.get_endpoint_manager()?;
        let (status, endpoint) =
            epm.create_endpoint(&name, &config).await.context("create_endpoint FIDL error")?;
        let () = zx::Status::ok(status).context("create_endpoint failed")?;
        let endpoint = endpoint
            .ok_or_else(|| anyhow::anyhow!("create_endpoint didn't return a valid endpoint"))?
            .into_proxy();
        Ok(TestEndpoint { endpoint, name, _sandbox: self })
    }
}

/// A set of virtual networks and endpoints.
///
/// Created through [`TestSandbox::setup_networks`].
#[must_use]
pub struct TestNetworkSetup<'a> {
    _setup: fnetemul_network::SetupHandleProxy,
    _sandbox: &'a TestSandbox,
}

impl TestNetworkSetup<'_> {
    /// Extracts the proxy to the backing setup handle.
    ///
    /// Note that this defeats the lifetime semantics that ensure the sandbox in
    /// which these networks were created lives as long as the networks. The caller
    /// of [`TestNetworkSetup::into_proxy`] is responsible for ensuring that the
    /// sandbox outlives the networks.
    pub fn into_proxy(self) -> fnetemul_network::SetupHandleProxy {
        let Self { _setup, _sandbox: _ } = self;
        _setup
    }
}

/// [`TestInterface`] configuration.
#[derive(Default)]
pub struct InterfaceConfig<'a> {
    /// Optional interface name.
    pub name: Option<Cow<'a, str>>,
    /// Optional default route metric.
    pub metric: Option<u32>,
    /// Number of DAD transmits to use before marking an address as Assigned.
    pub dad_transmits: Option<u16>,
}

/// A realm within a netemul sandbox.
#[must_use]
#[derive(Clone)]
pub struct TestRealm<'a> {
    realm: fnetemul::ManagedRealmProxy,
    name: Cow<'a, str>,
    _sandbox: &'a TestSandbox,
}

impl<'a> std::fmt::Debug for TestRealm<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        let Self { realm: _, name, _sandbox } = self;
        f.debug_struct("TestRealm").field("name", name).finish_non_exhaustive()
    }
}

impl<'a> TestRealm<'a> {
    /// Connects to a protocol within the realm.
    pub fn connect_to_protocol<S>(&self) -> Result<S::Proxy>
    where
        S: fidl::endpoints::DiscoverableProtocolMarker,
    {
        (|| {
            let (proxy, server_end) = fidl::endpoints::create_proxy::<S>();
            let () = self
                .connect_to_protocol_with_server_end(server_end)
                .context("connect to protocol name with server end")?;
            Result::Ok(proxy)
        })()
        .context(S::DEBUG_NAME)
    }

    /// Connects to a protocol from a child within the realm.
    pub fn connect_to_protocol_from_child<S>(&self, child: &str) -> Result<S::Proxy>
    where
        S: fidl::endpoints::DiscoverableProtocolMarker,
    {
        (|| {
            let (proxy, server_end) = fidl::endpoints::create_proxy::<S>();
            let () = self
                .connect_to_protocol_from_child_at_path_with_server_end(
                    S::PROTOCOL_NAME,
                    child,
                    server_end,
                )
                .context("connect to protocol name with server end")?;
            Result::Ok(proxy)
        })()
        .with_context(|| format!("{} from {child}", S::DEBUG_NAME))
    }

    /// Opens the diagnostics directory of a component.
    pub fn open_diagnostics_directory(&self, child_name: &str) -> Result<fio::DirectoryProxy> {
        let (proxy, server_end) = fidl::endpoints::create_proxy::<fio::DirectoryMarker>();
        let () = self
            .realm
            .open_diagnostics_directory(child_name, server_end)
            .context("open diagnostics dir")?;
        Ok(proxy)
    }

    /// Connects to a protocol within the realm.
    pub fn connect_to_protocol_with_server_end<S: fidl::endpoints::DiscoverableProtocolMarker>(
        &self,
        server_end: fidl::endpoints::ServerEnd<S>,
    ) -> Result {
        self.realm
            .connect_to_protocol(S::PROTOCOL_NAME, None, server_end.into_channel())
            .context("connect to protocol")
    }

    /// Connects to a protocol from a child at a path within the realm.
    pub fn connect_to_protocol_from_child_at_path_with_server_end<
        S: fidl::endpoints::DiscoverableProtocolMarker,
    >(
        &self,
        protocol_path: &str,
        child: &str,
        server_end: fidl::endpoints::ServerEnd<S>,
    ) -> Result {
        self.realm
            .connect_to_protocol(protocol_path, Some(child), server_end.into_channel())
            .context("connect to protocol")
    }

    /// Gets the moniker of the root of the managed realm.
    pub async fn get_moniker(&self) -> Result<String> {
        self.realm.get_moniker().await.context("failed to call get moniker")
    }

    /// Starts the specified child component of the managed realm.
    pub async fn start_child_component(&self, child_name: &str) -> Result {
        self.realm
            .start_child_component(child_name)
            .await?
            .map_err(zx::Status::from_raw)
            .with_context(|| format!("failed to start child component '{}'", child_name))
    }

    /// Stops the specified child component of the managed realm.
    pub async fn stop_child_component(&self, child_name: &str) -> Result {
        self.realm
            .stop_child_component(child_name)
            .await?
            .map_err(zx::Status::from_raw)
            .with_context(|| format!("failed to stop child component '{}'", child_name))
    }

    /// Use default endpoint/interface configuration and the specified address
    /// configuration to create a test interface.
    ///
    /// Characters may be dropped from the front of `ep_name` if it exceeds the
    /// maximum length.
    pub async fn join_network<S>(
        &self,
        network: &TestNetwork<'a>,
        ep_name: S,
    ) -> Result<TestInterface<'a>>
    where
        S: Into<Cow<'a, str>>,
    {
        self.join_network_with_if_config(network, ep_name, Default::default()).await
    }

    /// Use default endpoint configuration and the specified interface/address
    /// configuration to create a test interface.
    ///
    /// Characters may be dropped from the front of `ep_name` if it exceeds the
    /// maximum length.
    pub async fn join_network_with_if_config<S>(
        &self,
        network: &TestNetwork<'a>,
        ep_name: S,
        if_config: InterfaceConfig<'a>,
    ) -> Result<TestInterface<'a>>
    where
        S: Into<Cow<'a, str>>,
    {
        let endpoint =
            network.create_endpoint(ep_name).await.context("failed to create endpoint")?;
        self.install_endpoint(endpoint, if_config).await
    }

    /// Joins `network` with by creating an endpoint with `ep_config` and
    /// installing it into the realm with `if_config`.
    ///
    /// Returns a [`TestInterface`] corresponding to the added interface. The
    /// interface is guaranteed to have its link up and be enabled when this
    /// async function resolves.
    ///
    /// Note that this realm needs a Netstack for this operation to succeed.
    ///
    /// Characters may be dropped from the front of `ep_name` if it exceeds the maximum length.
    pub async fn join_network_with(
        &self,
        network: &TestNetwork<'a>,
        ep_name: impl Into<Cow<'a, str>>,
        ep_config: fnetemul_network::EndpointConfig,
        if_config: InterfaceConfig<'a>,
    ) -> Result<TestInterface<'a>> {
        let installer = self
            .connect_to_protocol::<fnet_interfaces_admin::InstallerMarker>()
            .context("failed to connect to fuchsia.net.interfaces.admin.Installer")?;
        let interface_state = self
            .connect_to_protocol::<fnet_interfaces::StateMarker>()
            .context("failed to connect to fuchsia.net.interfaces.State")?;
        let (endpoint, id, control, device_control) = self
            .join_network_with_installer(
                network,
                installer,
                interface_state,
                ep_name,
                ep_config,
                if_config,
            )
            .await?;

        Ok(TestInterface {
            endpoint,
            id,
            realm: self.clone(),
            control,
            device_control: Some(device_control),
            dhcp_client_task: futures::lock::Mutex::default(),
        })
    }

    /// Joins `network` by creating an endpoint with `ep_config` and installing it with
    /// `installer` and `if_config`.
    ///
    /// This inherits the lifetime of `self`, so there's an assumption that `installer` is served
    /// by something in this [`TestRealm`], but there's nothing enforcing this.
    ///
    /// Returns the created endpoint, the interface ID, and the associated interface
    /// [`Control`] and [`fnet_interfaces_admin::DeviceControlProxy`].
    ///
    /// Characters may be dropped from the front of `ep_name` if it exceeds the maximum length.
    pub async fn join_network_with_installer(
        &self,
        network: &TestNetwork<'a>,
        installer: fnet_interfaces_admin::InstallerProxy,
        interface_state: fnet_interfaces::StateProxy,
        ep_name: impl Into<Cow<'a, str>>,
        ep_config: fnetemul_network::EndpointConfig,
        if_config: InterfaceConfig<'a>,
    ) -> Result<(TestEndpoint<'a>, u64, Control, fnet_interfaces_admin::DeviceControlProxy)> {
        let endpoint = network
            .create_endpoint_with(ep_name, ep_config)
            .await
            .context("failed to create endpoint")?;
        let (id, control, device_control) = self
            .install_endpoint_with_installer(installer, interface_state, &endpoint, if_config)
            .await?;
        Ok((endpoint, id, control, device_control))
    }

    /// Installs and configures the endpoint as an interface. Uses `interface_state` to observe that
    /// the interface is up after it is installed.
    ///
    /// This inherits the lifetime of `self`, so there's an assumption that `installer` is served
    /// by something in this [`TestRealm`], but there's nothing enforcing this.
    ///
    /// Note that if `name` is not `None`, the string must fit within interface name limits.
    pub async fn install_endpoint_with_installer(
        &self,
        installer: fnet_interfaces_admin::InstallerProxy,
        interface_state: fnet_interfaces::StateProxy,
        endpoint: &TestEndpoint<'a>,
        if_config: InterfaceConfig<'a>,
    ) -> Result<(u64, Control, fnet_interfaces_admin::DeviceControlProxy)> {
        let (id, control, device_control) =
            endpoint.install(installer, if_config).await.context("failed to add endpoint")?;

        let () = endpoint.set_link_up(true).await.context("failed to start endpoint")?;
        let _did_enable: bool = control
            .enable()
            .await
            .map_err(anyhow::Error::new)
            .and_then(|res| {
                res.map_err(|e: fnet_interfaces_admin::ControlEnableError| {
                    anyhow::anyhow!("{:?}", e)
                })
            })
            .context("failed to enable interface")?;

        // Wait for Netstack to observe interface up so callers can safely
        // assume the state of the world on return.
        let () = fnet_interfaces_ext::wait_interface_with_id(
            fnet_interfaces_ext::event_stream_from_state::<fnet_interfaces_ext::DefaultInterest>(
                &interface_state,
                fnet_interfaces_ext::IncludedAddresses::OnlyAssigned,
            )?,
            &mut fnet_interfaces_ext::InterfaceState::<(), _>::Unknown(id),
            |properties_and_state| properties_and_state.properties.online.then_some(()),
        )
        .await
        .context("failed to observe interface up")?;

        Ok((id, control, device_control))
    }

    /// Installs and configures the endpoint in this realm.
    ///
    /// Note that if `name` is not `None`, the string must fit within interface name limits.
    pub async fn install_endpoint(
        &self,
        endpoint: TestEndpoint<'a>,
        if_config: InterfaceConfig<'a>,
    ) -> Result<TestInterface<'a>> {
        let installer = self
            .connect_to_protocol::<fnet_interfaces_admin::InstallerMarker>()
            .context("failed to connect to fuchsia.net.interfaces.admin.Installer")?;
        let interface_state = self
            .connect_to_protocol::<fnet_interfaces::StateMarker>()
            .context("failed to connect to fuchsia.net.interfaces.State")?;
        let (id, control, device_control) = self
            .install_endpoint_with_installer(installer, interface_state, &endpoint, if_config)
            .await?;
        Ok(TestInterface {
            endpoint,
            id,
            realm: self.clone(),
            control,
            device_control: Some(device_control),
            dhcp_client_task: futures::lock::Mutex::default(),
        })
    }

    /// Adds a raw device connector to the realm's devfs.
    pub async fn add_raw_device(
        &self,
        path: &Path,
        device: fidl::endpoints::ClientEnd<fnetemul_network::DeviceProxy_Marker>,
    ) -> Result {
        let path = path.to_str().with_context(|| format!("convert {} to str", path.display()))?;
        self.realm
            .add_device(path, device)
            .await
            .context("add device")?
            .map_err(zx::Status::from_raw)
            .context("add device error")
    }

    /// Adds a device to the realm's virtual device filesystem.
    pub async fn add_virtual_device(&self, e: &TestEndpoint<'_>, path: &Path) -> Result {
        let (device, device_server_end) =
            fidl::endpoints::create_endpoints::<fnetemul_network::DeviceProxy_Marker>();
        e.get_proxy_(device_server_end).context("get proxy")?;

        self.add_raw_device(path, device).await
    }

    /// Removes a device from the realm's virtual device filesystem.
    pub async fn remove_virtual_device(&self, path: &Path) -> Result {
        let path = path.to_str().with_context(|| format!("convert {} to str", path.display()))?;
        self.realm
            .remove_device(path)
            .await
            .context("remove device")?
            .map_err(zx::Status::from_raw)
            .context("remove device error")
    }

    /// Creates a Datagram [`socket2::Socket`] backed by the implementation of
    /// `fuchsia.posix.socket/Provider` in this realm.
    pub async fn datagram_socket(
        &self,
        domain: fposix_socket::Domain,
        proto: fposix_socket::DatagramSocketProtocol,
    ) -> Result<socket2::Socket> {
        let socket_provider = self
            .connect_to_protocol::<fposix_socket::ProviderMarker>()
            .context("failed to connect to socket provider")?;

        fposix_socket_ext::datagram_socket(&socket_provider, domain, proto)
            .await
            .context("failed to call socket")?
            .context("failed to create socket")
    }

    /// Creates a raw [`socket2::Socket`] backed by the implementation of
    /// `fuchsia.posix.socket.raw/Provider` in this realm.
    pub async fn raw_socket(
        &self,
        domain: fposix_socket::Domain,
        association: fposix_socket_raw::ProtocolAssociation,
    ) -> Result<socket2::Socket> {
        let socket_provider = self
            .connect_to_protocol::<fposix_socket_raw::ProviderMarker>()
            .context("failed to connect to socket provider")?;
        let sock = socket_provider
            .socket(domain, &association)
            .await
            .context("failed to call socket")?
            .map_err(|e| std::io::Error::from_raw_os_error(e.into_primitive()))
            .context("failed to create socket")?;

        Ok(fdio::create_fd(sock.into()).context("failed to create fd")?.into())
    }

    /// Creates a [`socket2::Socket`] backed by the implementation of
    /// [`fuchsia.posix.socket.packet/Provider`] in this realm.
    ///
    /// [`fuchsia.posix.socket.packet/Provider`]: fposix_socket_packet::ProviderMarker
    pub async fn packet_socket(&self, kind: fposix_socket_packet::Kind) -> Result<socket2::Socket> {
        let socket_provider = self
            .connect_to_protocol::<fposix_socket_packet::ProviderMarker>()
            .context("failed to connect to socket provider")?;

        fposix_socket_ext::packet_socket(&socket_provider, kind)
            .await
            .context("failed to call socket")?
            .context("failed to create socket")
    }

    /// Creates a Stream [`socket2::Socket`] backed by the implementation of
    /// `fuchsia.posix.socket/Provider` in this realm.
    pub async fn stream_socket(
        &self,
        domain: fposix_socket::Domain,
        proto: fposix_socket::StreamSocketProtocol,
    ) -> Result<socket2::Socket> {
        let socket_provider = self
            .connect_to_protocol::<fposix_socket::ProviderMarker>()
            .context("failed to connect to socket provider")?;
        let sock = socket_provider
            .stream_socket(domain, proto)
            .await
            .context("failed to call socket")?
            .map_err(|e| std::io::Error::from_raw_os_error(e.into_primitive()))
            .context("failed to create socket")?;

        Ok(fdio::create_fd(sock.into()).context("failed to create fd")?.into())
    }

    /// Shuts down the realm.
    ///
    /// It is often useful to call this method to ensure that the realm
    /// completes orderly shutdown before allowing other resources to be dropped
    /// and get cleaned up, such as [`TestEndpoint`]s, which components in the
    /// realm might be interacting with.
    pub async fn shutdown(&self) -> Result {
        let () = self.realm.shutdown().context("call shutdown")?;
        let events = self
            .realm
            .take_event_stream()
            .try_collect::<Vec<_>>()
            .await
            .context("error on realm event stream")?;
        // Ensure there are no more events sent on the event stream after `OnShutdown`.
        assert_matches::assert_matches!(events[..], [fnetemul::ManagedRealmEvent::OnShutdown {}]);
        Ok(())
    }

    /// Constructs an ICMP socket.
    pub async fn icmp_socket<Ip: ping::FuchsiaIpExt>(
        &self,
    ) -> Result<fuchsia_async::net::DatagramSocket> {
        let sock = self
            .datagram_socket(Ip::DOMAIN_FIDL, fposix_socket::DatagramSocketProtocol::IcmpEcho)
            .await
            .context("failed to create ICMP datagram socket")?;
        fuchsia_async::net::DatagramSocket::new_from_socket(sock)
            .context("failed to create async ICMP datagram socket")
    }

    /// Sends a single ICMP echo request to `addr`, and waits for the echo reply.
    pub async fn ping_once<Ip: ping::FuchsiaIpExt>(&self, addr: Ip::SockAddr, seq: u16) -> Result {
        let icmp_sock = self.icmp_socket::<Ip>().await?;

        const MESSAGE: &'static str = "hello, world";
        let (mut sink, mut stream) = ping::new_unicast_sink_and_stream::<
            Ip,
            _,
            { MESSAGE.len() + ping::ICMP_HEADER_LEN },
        >(&icmp_sock, &addr, MESSAGE.as_bytes());

        let send_fut = sink.send(seq).map_err(anyhow::Error::new);
        let recv_fut = stream.try_next().map(|r| match r {
            Ok(Some(got)) if got == seq => Ok(()),
            Ok(Some(got)) => Err(anyhow!("unexpected echo reply; got: {}, want: {}", got, seq)),
            Ok(None) => Err(anyhow!("echo reply stream ended unexpectedly")),
            Err(e) => Err(anyhow::Error::from(e)),
        });

        let ((), ()) = futures::future::try_join(send_fut, recv_fut)
            .await
            .with_context(|| format!("failed to ping from {} to {}", self.name, addr,))?;
        Ok(())
    }

    /// Add a static neighbor entry.
    ///
    /// Useful to prevent NUD resolving too slow and causing spurious test failures.
    pub async fn add_neighbor_entry(
        &self,
        interface: u64,
        addr: fnet::IpAddress,
        mac: fnet::MacAddress,
    ) -> Result {
        let controller = self
            .connect_to_protocol::<fnet_neighbor::ControllerMarker>()
            .context("connect to protocol")?;
        controller
            .add_entry(interface, &addr, &mac)
            .await
            .context("add_entry")?
            .map_err(zx::Status::from_raw)
            .context("add_entry failed")
    }

    /// Get a stream of interface events from a new watcher with default
    /// interest.
    pub fn get_interface_event_stream(
        &self,
    ) -> Result<
        impl futures::Stream<
            Item = std::result::Result<
                fnet_interfaces_ext::EventWithInterest<fnet_interfaces_ext::DefaultInterest>,
                fidl::Error,
            >,
        >,
    > {
        self.get_interface_event_stream_with_interest::<fnet_interfaces_ext::DefaultInterest>()
    }

    /// Get a stream of interface events from a new watcher with specified
    /// interest.
    pub fn get_interface_event_stream_with_interest<I: fnet_interfaces_ext::FieldInterests>(
        &self,
    ) -> Result<
        impl futures::Stream<
            Item = std::result::Result<fnet_interfaces_ext::EventWithInterest<I>, fidl::Error>,
        >,
    > {
        let interface_state = self
            .connect_to_protocol::<fnet_interfaces::StateMarker>()
            .context("connect to protocol")?;
        fnet_interfaces_ext::event_stream_from_state::<I>(
            &interface_state,
            fnet_interfaces_ext::IncludedAddresses::OnlyAssigned,
        )
        .context("get interface event stream")
    }

    /// Gets the table ID for the main route table.
    pub async fn main_table_id<
        I: fnet_routes_ext::FidlRouteIpExt + fnet_routes_ext::admin::FidlRouteAdminIpExt,
    >(
        &self,
    ) -> u32 {
        let main_route_table = self
            .connect_to_protocol::<I::RouteTableMarker>()
            .expect("failed to connect to main route table");
        fnet_routes_ext::admin::get_table_id::<I>(&main_route_table)
            .await
            .expect("failed to get_table_id")
            .get()
    }
}

/// A virtual Network.
///
/// `TestNetwork` is a single virtual broadcast domain backed by Netemul.
/// Created through [`TestSandbox::create_network`].
#[must_use]
pub struct TestNetwork<'a> {
    network: fnetemul_network::NetworkProxy,
    name: Cow<'a, str>,
    sandbox: &'a TestSandbox,
}

impl<'a> std::fmt::Debug for TestNetwork<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        let Self { name, network: _, sandbox: _ } = self;
        f.debug_struct("TestNetwork").field("name", name).finish_non_exhaustive()
    }
}

impl<'a> TestNetwork<'a> {
    /// Extracts the proxy to the backing network.
    ///
    /// Note that this defeats the lifetime semantics that ensure the sandbox in
    /// which this network was created lives as long as the network. The caller of
    /// [`TestNetwork::into_proxy`] is responsible for ensuring that the sandbox
    /// outlives the network.
    pub fn into_proxy(self) -> fnetemul_network::NetworkProxy {
        let Self { network, name: _, sandbox: _ } = self;
        network
    }

    /// Gets a FIDL client for the backing network.
    async fn get_client_end_clone(
        &self,
    ) -> Result<fidl::endpoints::ClientEnd<fnetemul_network::NetworkMarker>> {
        let network_manager =
            self.sandbox.get_network_manager().context("get_network_manager failed")?;
        let client = network_manager
            .get_network(&self.name)
            .await
            .context("get_network failed")?
            .with_context(|| format!("no network found with name {}", self.name))?;
        Ok(client)
    }

    /// Sets the configuration for this network to `config`.
    pub async fn set_config(&self, config: fnetemul_network::NetworkConfig) -> Result<()> {
        let status = self.network.set_config(&config).await.context("call set_config")?;
        zx::Status::ok(status).context("set config")
    }

    /// Attaches `ep` to this network.
    pub async fn attach_endpoint(&self, ep: &TestEndpoint<'a>) -> Result<()> {
        let status =
            self.network.attach_endpoint(&ep.name).await.context("attach_endpoint FIDL error")?;
        let () = zx::Status::ok(status).context("attach_endpoint failed")?;
        Ok(())
    }

    /// Creates a new endpoint with `name` attached to this network.
    ///
    /// Characters may be dropped from the front of `name` if it exceeds the maximum length.
    pub async fn create_endpoint<S>(&self, name: S) -> Result<TestEndpoint<'a>>
    where
        S: Into<Cow<'a, str>>,
    {
        let ep = self
            .sandbox
            .create_endpoint(name)
            .await
            .with_context(|| format!("failed to create endpoint for network {}", self.name))?;
        let () = self.attach_endpoint(&ep).await.with_context(|| {
            format!("failed to attach endpoint {} to network {}", ep.name, self.name)
        })?;
        Ok(ep)
    }

    /// Creates a new endpoint with `name` and `config` attached to this network.
    ///
    /// Characters may be dropped from the front of `name` if it exceeds the maximum length.
    pub async fn create_endpoint_with(
        &self,
        name: impl Into<Cow<'a, str>>,
        config: fnetemul_network::EndpointConfig,
    ) -> Result<TestEndpoint<'a>> {
        let ep = self
            .sandbox
            .create_endpoint_with(name, config)
            .await
            .with_context(|| format!("failed to create endpoint for network {}", self.name))?;
        let () = self.attach_endpoint(&ep).await.with_context(|| {
            format!("failed to attach endpoint {} to network {}", ep.name, self.name)
        })?;
        Ok(ep)
    }

    /// Returns a fake endpoint.
    pub fn create_fake_endpoint(&self) -> Result<TestFakeEndpoint<'a>> {
        let (endpoint, server) =
            fidl::endpoints::create_proxy::<fnetemul_network::FakeEndpointMarker>();
        let () = self.network.create_fake_endpoint(server)?;
        return Ok(TestFakeEndpoint { endpoint, _sandbox: self.sandbox });
    }

    /// Starts capturing packet in this network.
    ///
    /// The packet capture will be stored under a predefined directory:
    /// `/custom_artifacts`. More details can be found here:
    /// https://fuchsia.dev/fuchsia-src/development/testing/components/test_runner_framework?hl=en#custom-artifacts
    pub async fn start_capture(&self, name: &str) -> Result<PacketCapture> {
        let manager = self.sandbox.get_network_manager()?;
        let client = manager.get_network(&self.name).await?.expect("network must exist");
        zx::ok(self.network.start_capture(name).await?)?;
        let sync_proxy = fnetemul_network::NetworkSynchronousProxy::new(client.into_channel());
        Ok(PacketCapture { sync_proxy })
    }

    /// Stops packet capture in this network.
    pub async fn stop_capture(&self) -> Result<()> {
        Ok(self.network.stop_capture().await?)
    }
}

/// The object that has the same life as the packet capture, once the object is
/// dropped, the underlying packet capture will be stopped.
pub struct PacketCapture {
    sync_proxy: fnetemul_network::NetworkSynchronousProxy,
}

impl Drop for PacketCapture {
    fn drop(&mut self) {
        self.sync_proxy
            .stop_capture(zx::MonotonicInstant::INFINITE)
            .expect("failed to stop packet capture")
    }
}

/// A virtual network endpoint backed by Netemul.
#[must_use]
pub struct TestEndpoint<'a> {
    endpoint: fnetemul_network::EndpointProxy,
    name: Cow<'a, str>,
    _sandbox: &'a TestSandbox,
}

impl<'a> std::fmt::Debug for TestEndpoint<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        let Self { endpoint: _, name, _sandbox } = self;
        f.debug_struct("TestEndpoint").field("name", name).finish_non_exhaustive()
    }
}

impl<'a> std::ops::Deref for TestEndpoint<'a> {
    type Target = fnetemul_network::EndpointProxy;

    fn deref(&self) -> &Self::Target {
        &self.endpoint
    }
}

/// A virtual fake network endpoint backed by Netemul.
#[must_use]
pub struct TestFakeEndpoint<'a> {
    endpoint: fnetemul_network::FakeEndpointProxy,
    _sandbox: &'a TestSandbox,
}

impl<'a> std::ops::Deref for TestFakeEndpoint<'a> {
    type Target = fnetemul_network::FakeEndpointProxy;

    fn deref(&self) -> &Self::Target {
        &self.endpoint
    }
}

impl<'a> TestFakeEndpoint<'a> {
    /// Return a stream of frames.
    ///
    /// Frames will be yielded as they are read from the fake endpoint.
    pub fn frame_stream(
        &self,
    ) -> impl futures::Stream<Item = std::result::Result<(Vec<u8>, u64), fidl::Error>> + '_ {
        futures::stream::try_unfold(&self.endpoint, |ep| ep.read().map_ok(move |r| Some((r, ep))))
    }
}

/// Helper function to retrieve device and port information from a port
/// instance.
async fn to_netdevice_inner(
    port: fidl::endpoints::ClientEnd<fnetwork::PortMarker>,
) -> Result<(fidl::endpoints::ClientEnd<fnetwork::DeviceMarker>, fnetwork::PortId)> {
    let port = port.into_proxy();
    let (device, server_end) = fidl::endpoints::create_endpoints::<fnetwork::DeviceMarker>();
    let () = port.get_device(server_end)?;
    let port_id = port
        .get_info()
        .await
        .context("get port info")?
        .id
        .ok_or_else(|| anyhow::anyhow!("missing port id"))?;
    Ok((device, port_id))
}

impl<'a> TestEndpoint<'a> {
    /// Extracts the proxy to the backing endpoint.
    ///
    /// Note that this defeats the lifetime semantics that ensure the sandbox in
    /// which this endpoint was created lives as long as the endpoint. The caller of
    /// [`TestEndpoint::into_proxy`] is responsible for ensuring that the sandbox
    /// outlives the endpoint.
    pub fn into_proxy(self) -> fnetemul_network::EndpointProxy {
        let Self { endpoint, name: _, _sandbox: _ } = self;
        endpoint
    }

    /// Gets access to this device's virtual Network device.
    ///
    /// Note that an error is returned if the Endpoint is not a
    /// [`fnetemul_network::DeviceConnection::NetworkDevice`].
    pub async fn get_netdevice(
        &self,
    ) -> Result<(fidl::endpoints::ClientEnd<fnetwork::DeviceMarker>, fnetwork::PortId)> {
        let (port, server_end) = fidl::endpoints::create_endpoints();
        self.get_port(server_end)
            .with_context(|| format!("failed to get device connection for {}", self.name))?;
        to_netdevice_inner(port).await
    }

    /// Installs the [`TestEndpoint`] via the provided [`fnet_interfaces_admin::InstallerProxy`].
    ///
    /// Returns the interface ID, and the associated interface
    /// [`Control`] and [`fnet_interfaces_admin::DeviceControlProxy`] on
    /// success.
    pub async fn install(
        &self,
        installer: fnet_interfaces_admin::InstallerProxy,
        InterfaceConfig { name, metric, dad_transmits }: InterfaceConfig<'_>,
    ) -> Result<(u64, Control, fnet_interfaces_admin::DeviceControlProxy)> {
        let name = name.map(|n| {
            truncate_dropping_front(n.into(), fnet_interfaces::INTERFACE_NAME_LENGTH.into())
                .to_string()
        });
        let (device, port_id) = self.get_netdevice().await?;
        let device_control = {
            let (control, server_end) =
                fidl::endpoints::create_proxy::<fnet_interfaces_admin::DeviceControlMarker>();
            let () = installer.install_device(device, server_end).context("install device")?;
            control
        };
        let (control, server_end) = Control::create_endpoints().context("create endpoints")?;
        let () = device_control
            .create_interface(
                &port_id,
                server_end,
                &fnet_interfaces_admin::Options { name, metric, ..Default::default() },
            )
            .context("create interface")?;
        if let Some(dad_transmits) = dad_transmits {
            let _: Option<u16> =
                set_dad_transmits(&control, dad_transmits).await.context("set dad transmits")?;
        }

        let id = control.get_id().await.context("get id")?;
        Ok((id, control, device_control))
    }

    /// Adds the [`TestEndpoint`] to the provided `realm` with an optional
    /// interface name.
    ///
    /// Returns the interface ID and control protocols on success.
    pub async fn add_to_stack(
        &self,
        realm: &TestRealm<'a>,
        config: InterfaceConfig<'a>,
    ) -> Result<(u64, Control, fnet_interfaces_admin::DeviceControlProxy)> {
        let installer = realm
            .connect_to_protocol::<fnet_interfaces_admin::InstallerMarker>()
            .context("connect to protocol")?;

        self.install(installer, config).await
    }

    /// Like `into_interface_realm_with_name` but with default parameters.
    pub async fn into_interface_in_realm(self, realm: &TestRealm<'a>) -> Result<TestInterface<'a>> {
        self.into_interface_in_realm_with_name(realm, Default::default()).await
    }

    /// Consumes this `TestEndpoint` and tries to add it to the Netstack in
    /// `realm`, returning a [`TestInterface`] on success.
    pub async fn into_interface_in_realm_with_name(
        self,
        realm: &TestRealm<'a>,
        config: InterfaceConfig<'a>,
    ) -> Result<TestInterface<'a>> {
        let installer = realm
            .connect_to_protocol::<fnet_interfaces_admin::InstallerMarker>()
            .context("connect to protocol")?;

        let (id, control, device_control) =
            self.install(installer, config).await.context("failed to install")?;

        Ok(TestInterface {
            endpoint: self,
            id,
            realm: realm.clone(),
            control,
            device_control: Some(device_control),
            dhcp_client_task: futures::lock::Mutex::default(),
        })
    }
}

/// The DHCP client version.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum DhcpClientVersion {
    /// The in-Netstack2 DHCP client.
    InStack,
    /// The out-of-stack DHCP client.
    OutOfStack,
}

/// Abstraction for how DHCP client functionality is provided.
pub trait DhcpClient {
    /// The DHCP client version to be used.
    const DHCP_CLIENT_VERSION: DhcpClientVersion;
}

/// The in-Netstack2 DHCP client.
pub enum InStack {}

impl DhcpClient for InStack {
    const DHCP_CLIENT_VERSION: DhcpClientVersion = DhcpClientVersion::InStack;
}

/// The out-of-stack DHCP client.
pub enum OutOfStack {}

impl DhcpClient for OutOfStack {
    const DHCP_CLIENT_VERSION: DhcpClientVersion = DhcpClientVersion::OutOfStack;
}

/// A [`TestEndpoint`] that is installed in a realm's Netstack.
///
/// Note that a [`TestInterface`] adds to the reference count of the underlying
/// realm of its [`TestRealm`]. That is, a [`TestInterface`] that outlives the
/// [`TestRealm`] it created is sufficient to keep the underlying realm alive.
#[must_use]
pub struct TestInterface<'a> {
    endpoint: TestEndpoint<'a>,
    realm: TestRealm<'a>,
    id: u64,
    control: Control,
    device_control: Option<fnet_interfaces_admin::DeviceControlProxy>,
    dhcp_client_task: futures::lock::Mutex<Option<fnet_dhcp_ext::testutil::DhcpClientTask>>,
}

impl<'a> std::fmt::Debug for TestInterface<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        let Self { endpoint, id, realm: _, control: _, device_control: _, dhcp_client_task: _ } =
            self;
        f.debug_struct("TestInterface")
            .field("endpoint", endpoint)
            .field("id", id)
            .finish_non_exhaustive()
    }
}

impl<'a> std::ops::Deref for TestInterface<'a> {
    type Target = fnetemul_network::EndpointProxy;

    fn deref(&self) -> &Self::Target {
        &self.endpoint
    }
}

impl<'a> TestInterface<'a> {
    /// Gets the interface identifier.
    pub fn id(&self) -> u64 {
        self.id
    }

    /// Returns the endpoint associated with the interface.
    pub fn endpoint(&self) -> &TestEndpoint<'a> {
        &self.endpoint
    }

    /// Returns the interface's control handle.
    pub fn control(&self) -> &Control {
        &self.control
    }

    /// Returns the authorization token for this interface.
    pub async fn get_authorization(&self) -> Result<GrantForInterfaceAuthorization> {
        Ok(self.control.get_authorization_for_interface().await?)
    }

    /// Connects to fuchsia.net.stack in this interface's realm.
    pub fn connect_stack(&self) -> Result<fnet_stack::StackProxy> {
        self.realm.connect_to_protocol::<fnet_stack::StackMarker>()
    }

    /// Installs a route in the realm's netstack's global route table with `self` as the outgoing
    /// interface with the given `destination` and `metric`, optionally via the `next_hop`.
    ///
    /// Returns whether the route was newly added to the stack.
    async fn add_route<
        I: Ip + fnet_routes_ext::FidlRouteIpExt + fnet_routes_ext::admin::FidlRouteAdminIpExt,
    >(
        &self,
        destination: Subnet<I::Addr>,
        next_hop: Option<SpecifiedAddr<I::Addr>>,
        metric: fnet_routes::SpecifiedMetric,
    ) -> Result<bool> {
        let route_set = self.create_authenticated_global_route_set::<I>().await?;
        fnet_routes_ext::admin::add_route::<I>(
            &route_set,
            &fnet_routes_ext::Route::<I>::new_forward(destination, self.id(), next_hop, metric)
                .try_into()
                .expect("convert to FIDL should succeed"),
        )
        .await
        .context("FIDL error adding route")?
        .map_err(|e| anyhow::anyhow!("error adding route: {e:?}"))
    }

    /// Installs a route in the realm's netstack's global route table with `self` as the outgoing
    /// interface with the given `destination` and `metric`, optionally via the `next_hop`.
    ///
    /// Returns whether the route was newly added to the stack. Returns `Err` if `destination` and
    /// `next_hop` don't share the same IP version.
    pub async fn add_route_either(
        &self,
        destination: fnet::Subnet,
        next_hop: Option<fnet::IpAddress>,
        metric: fnet_routes::SpecifiedMetric,
    ) -> Result<bool> {
        let fnet::Subnet { addr: destination_addr, prefix_len } = destination;
        match destination_addr {
            fnet::IpAddress::Ipv4(destination_addr) => {
                let next_hop = match next_hop {
                    Some(fnet::IpAddress::Ipv4(next_hop)) => Some(
                        SpecifiedAddr::new(net_types::ip::Ipv4Addr::from_ext(next_hop))
                            .ok_or(anyhow::anyhow!("next hop must not be unspecified address"))?,
                    ),
                    Some(fnet::IpAddress::Ipv6(_)) => {
                        return Err(anyhow::anyhow!(
                            "next hop must be same IP version as destination"
                        ))
                    }
                    None => None,
                };
                self.add_route::<Ipv4>(
                    Subnet::new(destination_addr.into_ext(), prefix_len)
                        .map_err(|e| anyhow::anyhow!("invalid subnet: {e:?}"))?,
                    next_hop,
                    metric,
                )
                .await
            }
            fnet::IpAddress::Ipv6(destination_addr) => {
                let next_hop = match next_hop {
                    Some(fnet::IpAddress::Ipv6(next_hop)) => Some(
                        SpecifiedAddr::new(net_types::ip::Ipv6Addr::from_ext(next_hop))
                            .ok_or(anyhow::anyhow!("next hop must not be unspecified address"))?,
                    ),
                    Some(fnet::IpAddress::Ipv4(_)) => {
                        return Err(anyhow::anyhow!(
                            "next hop must be same IP version as destination"
                        ))
                    }
                    None => None,
                };
                self.add_route::<Ipv6>(
                    Subnet::new(destination_addr.into_ext(), prefix_len)
                        .map_err(|e| anyhow::anyhow!("invalid subnet: {e:?}"))?,
                    next_hop,
                    metric,
                )
                .await
            }
        }
    }

    /// Removes a route from the realm's netstack's global route table with `self` as the outgoing
    /// interface with the given `destination` and `metric`, optionally via the `next_hop`.
    ///
    /// Returns whether the route actually existed in the stack before it was removed.
    async fn remove_route<
        I: Ip + fnet_routes_ext::FidlRouteIpExt + fnet_routes_ext::admin::FidlRouteAdminIpExt,
    >(
        &self,
        destination: Subnet<I::Addr>,
        next_hop: Option<SpecifiedAddr<I::Addr>>,
        metric: fnet_routes::SpecifiedMetric,
    ) -> Result<bool> {
        let route_set = self.create_authenticated_global_route_set::<I>().await?;
        fnet_routes_ext::admin::remove_route::<I>(
            &route_set,
            &fnet_routes_ext::Route::<I>::new_forward(destination, self.id(), next_hop, metric)
                .try_into()
                .expect("convert to FIDL should succeed"),
        )
        .await
        .context("FIDL error removing route")?
        .map_err(|e| anyhow::anyhow!("error removing route: {e:?}"))
    }

    /// Removes a route from the realm's netstack's global route table with `self` as the outgoing
    /// interface with the given `destination` and `metric`, optionally via the `next_hop`.
    ///
    /// Returns whether the route actually existed in the stack before it was removed. Returns `Err`
    /// if `destination` and `next_hop` don't share the same IP version.
    async fn remove_route_either(
        &self,
        destination: fnet::Subnet,
        next_hop: Option<fnet::IpAddress>,
        metric: fnet_routes::SpecifiedMetric,
    ) -> Result<bool> {
        let fnet::Subnet { addr: destination_addr, prefix_len } = destination;
        match destination_addr {
            fnet::IpAddress::Ipv4(destination_addr) => {
                let next_hop = match next_hop {
                    Some(fnet::IpAddress::Ipv4(next_hop)) => Some(
                        SpecifiedAddr::new(net_types::ip::Ipv4Addr::from_ext(next_hop))
                            .ok_or(anyhow::anyhow!("next hop must not be unspecified address"))?,
                    ),
                    Some(fnet::IpAddress::Ipv6(_)) => {
                        return Err(anyhow::anyhow!(
                            "next hop must be same IP version as destination"
                        ))
                    }
                    None => None,
                };
                self.remove_route::<Ipv4>(
                    Subnet::new(destination_addr.into_ext(), prefix_len)
                        .map_err(|e| anyhow::anyhow!("invalid subnet: {e:?}"))?,
                    next_hop,
                    metric,
                )
                .await
            }
            fnet::IpAddress::Ipv6(destination_addr) => {
                let next_hop = match next_hop {
                    Some(fnet::IpAddress::Ipv6(next_hop)) => Some(
                        SpecifiedAddr::new(net_types::ip::Ipv6Addr::from_ext(next_hop))
                            .ok_or(anyhow::anyhow!("next hop must not be unspecified address"))?,
                    ),
                    Some(fnet::IpAddress::Ipv4(_)) => {
                        return Err(anyhow::anyhow!(
                            "next hop must be same IP version as destination"
                        ))
                    }
                    None => None,
                };
                self.remove_route::<Ipv6>(
                    Subnet::new(destination_addr.into_ext(), prefix_len)
                        .map_err(|e| anyhow::anyhow!("invalid subnet: {e:?}"))?,
                    next_hop,
                    metric,
                )
                .await
            }
        }
    }

    /// Add a direct route from the interface to the given subnet.
    pub async fn add_subnet_route(&self, subnet: fnet::Subnet) -> Result<()> {
        let subnet = fnet_ext::apply_subnet_mask(subnet);
        let newly_added = self
            .add_route_either(
                subnet,
                None,
                fnet_routes::SpecifiedMetric::InheritedFromInterface(fnet_routes::Empty),
            )
            .await?;

        if !newly_added {
            Err(anyhow::anyhow!(
                "route to {subnet:?} on {} should not have already existed",
                self.id()
            ))
        } else {
            Ok(())
        }
    }

    /// Delete a direct route from the interface to the given subnet.
    pub async fn del_subnet_route(&self, subnet: fnet::Subnet) -> Result<()> {
        let subnet = fnet_ext::apply_subnet_mask(subnet);
        let newly_removed = self
            .remove_route_either(
                subnet,
                None,
                fnet_routes::SpecifiedMetric::InheritedFromInterface(fnet_routes::Empty),
            )
            .await?;

        if !newly_removed {
            Err(anyhow::anyhow!(
                "route to {subnet:?} on {} should have previously existed before being removed",
                self.id()
            ))
        } else {
            Ok(())
        }
    }

    /// Add a default route through the given `next_hop` with the given `metric`.
    pub async fn add_default_route_with_metric(
        &self,
        next_hop: fnet::IpAddress,
        metric: fnet_routes::SpecifiedMetric,
    ) -> Result<()> {
        let corresponding_default_subnet = match next_hop {
            fnet::IpAddress::Ipv4(_) => net_declare::fidl_subnet!("0.0.0.0/0"),
            fnet::IpAddress::Ipv6(_) => net_declare::fidl_subnet!("::/0"),
        };

        let newly_added =
            self.add_route_either(corresponding_default_subnet, Some(next_hop), metric).await?;

        if !newly_added {
            Err(anyhow::anyhow!(
                "default route through {} via {next_hop:?} already exists",
                self.id()
            ))
        } else {
            Ok(())
        }
    }

    /// Add a default route through the given `next_hop` with the given `metric`.
    pub async fn add_default_route_with_explicit_metric(
        &self,
        next_hop: fnet::IpAddress,
        metric: u32,
    ) -> Result<()> {
        self.add_default_route_with_metric(
            next_hop,
            fnet_routes::SpecifiedMetric::ExplicitMetric(metric),
        )
        .await
    }

    /// Add a default route through the given `next_hop`.
    pub async fn add_default_route(&self, next_hop: fnet::IpAddress) -> Result<()> {
        self.add_default_route_with_metric(
            next_hop,
            fnet_routes::SpecifiedMetric::InheritedFromInterface(fnet_routes::Empty),
        )
        .await
    }

    /// Remove a default route through the given address.
    pub async fn remove_default_route(&self, next_hop: fnet::IpAddress) -> Result<()> {
        let corresponding_default_subnet = match next_hop {
            fnet::IpAddress::Ipv4(_) => net_declare::fidl_subnet!("0.0.0.0/0"),
            fnet::IpAddress::Ipv6(_) => net_declare::fidl_subnet!("::/0"),
        };

        let newly_removed = self
            .remove_route_either(
                corresponding_default_subnet,
                Some(next_hop),
                fnet_routes::SpecifiedMetric::InheritedFromInterface(fnet_routes::Empty),
            )
            .await?;

        if !newly_removed {
            Err(anyhow::anyhow!(
                "default route through {} via {next_hop:?} does not exist",
                self.id()
            ))
        } else {
            Ok(())
        }
    }

    /// Add a route to the given `destination` subnet via the given `next_hop`.
    pub async fn add_gateway_route(
        &self,
        destination: fnet::Subnet,
        next_hop: fnet::IpAddress,
    ) -> Result<()> {
        let newly_added = self
            .add_route_either(
                destination,
                Some(next_hop),
                fnet_routes::SpecifiedMetric::InheritedFromInterface(fnet_routes::Empty),
            )
            .await?;

        if !newly_added {
            Err(anyhow::anyhow!(
                "should have newly added route to {destination:?} via {next_hop:?} through {}",
                self.id()
            ))
        } else {
            Ok(())
        }
    }

    /// Create a root route set authenticated to manage routes through this interface.
    pub async fn create_authenticated_global_route_set<
        I: fnet_routes_ext::FidlRouteIpExt + fnet_routes_ext::admin::FidlRouteAdminIpExt,
    >(
        &self,
    ) -> Result<<I::RouteSetMarker as ProtocolMarker>::Proxy> {
        #[derive(GenericOverIp)]
        #[generic_over_ip(I, Ip)]
        struct Out<'a, I: fnet_routes_ext::admin::FidlRouteAdminIpExt>(
            LocalBoxFuture<'a, <I::RouteSetMarker as ProtocolMarker>::Proxy>,
        );

        let Out(proxy_fut) = I::map_ip_out(
            self,
            |this| {
                Out(this
                    .get_global_route_set_v4()
                    .map(|result| result.expect("get global route set"))
                    .boxed_local())
            },
            |this| {
                Out(this
                    .get_global_route_set_v6()
                    .map(|result| result.expect("get global route set"))
                    .boxed_local())
            },
        );

        let route_set = proxy_fut.await;
        let fnet_interfaces_admin::GrantForInterfaceAuthorization { interface_id, token } =
            self.get_authorization().await.expect("get interface grant");
        fnet_routes_ext::admin::authenticate_for_interface::<I>(
            &route_set,
            fnet_interfaces_admin::ProofOfInterfaceAuthorization { interface_id, token },
        )
        .await
        .expect("authentication should not have FIDL error")
        .expect("authentication should succeed");
        Ok(route_set)
    }

    async fn get_global_route_set_v4(&self) -> Result<fnet_routes_admin::RouteSetV4Proxy> {
        let root_routes = self
            .realm
            .connect_to_protocol::<fnet_root::RoutesV4Marker>()
            .expect("get fuchsia.net.root.RoutesV4");
        let (route_set, server_end) =
            fidl::endpoints::create_proxy::<fnet_routes_admin::RouteSetV4Marker>();
        root_routes.global_route_set(server_end).expect("calling global_route_set should succeed");
        Ok(route_set)
    }

    async fn get_global_route_set_v6(&self) -> Result<fnet_routes_admin::RouteSetV6Proxy> {
        let root_routes = self
            .realm
            .connect_to_protocol::<fnet_root::RoutesV6Marker>()
            .expect("get fuchsia.net.root.RoutesV6");
        let (route_set, server_end) =
            fidl::endpoints::create_proxy::<fnet_routes_admin::RouteSetV6Marker>();
        root_routes.global_route_set(server_end).expect("calling global_route_set should succeed");
        Ok(route_set)
    }

    /// Gets the interface's properties with assigned addresses.
    async fn get_properties(
        &self,
        included_addresses: fnet_interfaces_ext::IncludedAddresses,
    ) -> Result<fnet_interfaces_ext::Properties<fnet_interfaces_ext::AllInterest>> {
        let interface_state = self.realm.connect_to_protocol::<fnet_interfaces::StateMarker>()?;
        let properties = fnet_interfaces_ext::existing(
            fnet_interfaces_ext::event_stream_from_state(&interface_state, included_addresses)?,
            fnet_interfaces_ext::InterfaceState::<(), _>::Unknown(self.id),
        )
        .await
        .context("failed to get existing interfaces")?;
        match properties {
            fnet_interfaces_ext::InterfaceState::Unknown(id) => Err(anyhow::anyhow!(
                "could not find interface {} for endpoint {}",
                id,
                self.endpoint.name
            )),
            fnet_interfaces_ext::InterfaceState::Known(
                fnet_interfaces_ext::PropertiesAndState { properties, state: () },
            ) => Ok(properties),
        }
    }

    /// Gets the interface's addresses.
    pub async fn get_addrs(
        &self,
        included_addresses: fnet_interfaces_ext::IncludedAddresses,
    ) -> Result<Vec<fnet_interfaces_ext::Address<fnet_interfaces_ext::AllInterest>>> {
        let fnet_interfaces_ext::Properties { addresses, .. } =
            self.get_properties(included_addresses).await?;
        Ok(addresses)
    }

    /// Gets the interface's device name.
    pub async fn get_interface_name(&self) -> Result<String> {
        let fnet_interfaces_ext::Properties { name, .. } =
            self.get_properties(fnet_interfaces_ext::IncludedAddresses::OnlyAssigned).await?;
        Ok(name)
    }

    /// Gets the interface's port class.
    pub async fn get_port_class(&self) -> Result<fnet_interfaces_ext::PortClass> {
        let fnet_interfaces_ext::Properties { port_class, .. } =
            self.get_properties(fnet_interfaces_ext::IncludedAddresses::OnlyAssigned).await?;
        Ok(port_class)
    }

    /// Gets the interface's MAC address.
    pub async fn mac(&self) -> fnet::MacAddress {
        let (port, server_end) =
            fidl::endpoints::create_proxy::<fidl_fuchsia_hardware_network::PortMarker>();
        self.get_port(server_end).expect("get_port");
        let (mac_addressing, server_end) =
            fidl::endpoints::create_proxy::<fidl_fuchsia_hardware_network::MacAddressingMarker>();
        port.get_mac(server_end).expect("get_mac");
        mac_addressing.get_unicast_address().await.expect("get_unicast_address")
    }

    async fn set_dhcp_client_enabled(&self, enable: bool) -> Result<()> {
        self.connect_stack()
            .context("connect stack")?
            .set_dhcp_client_enabled(self.id, enable)
            .await
            .context("failed to call SetDhcpClientEnabled")?
            .map_err(|e| anyhow!("{:?}", e))
    }

    /// Starts DHCP on this interface.
    pub async fn start_dhcp<D: DhcpClient>(&self) -> Result<()> {
        match D::DHCP_CLIENT_VERSION {
            DhcpClientVersion::InStack => self.start_dhcp_in_stack().await,
            DhcpClientVersion::OutOfStack => self.start_dhcp_client_out_of_stack().await,
        }
    }

    async fn start_dhcp_in_stack(&self) -> Result<()> {
        self.set_dhcp_client_enabled(true).await.context("failed to start dhcp client")
    }

    async fn start_dhcp_client_out_of_stack(&self) -> Result<()> {
        let Self { endpoint: _, realm, id, control, device_control: _, dhcp_client_task } = self;
        let id = NonZeroU64::new(*id).expect("interface ID should be nonzero");
        let mut dhcp_client_task = dhcp_client_task.lock().await;
        let dhcp_client_task = dhcp_client_task.deref_mut();

        let provider = realm
            .connect_to_protocol::<fnet_dhcp::ClientProviderMarker>()
            .expect("get fuchsia.net.dhcp.ClientProvider");

        provider.check_presence().await.expect("check presence should succeed");

        let client = provider.new_client_ext(id, fnet_dhcp_ext::default_new_client_params());
        let control = control.clone();
        let route_set_provider = realm
            .connect_to_protocol::<fnet_routes_admin::RouteTableV4Marker>()
            .expect("get fuchsia.net.routes.RouteTableV4");
        let (route_set, server_end) =
            fidl::endpoints::create_proxy::<fnet_routes_admin::RouteSetV4Marker>();
        route_set_provider.new_route_set(server_end).expect("calling new_route_set should succeed");
        let task = fnet_dhcp_ext::testutil::DhcpClientTask::new(client, id, route_set, control);
        *dhcp_client_task = Some(task);
        Ok(())
    }

    /// Stops DHCP on this interface.
    pub async fn stop_dhcp<D: DhcpClient>(&self) -> Result<()> {
        match D::DHCP_CLIENT_VERSION {
            DhcpClientVersion::InStack => self.stop_dhcp_in_stack().await,
            DhcpClientVersion::OutOfStack => {
                self.stop_dhcp_out_of_stack().await;
                Ok(())
            }
        }
    }

    async fn stop_dhcp_in_stack(&self) -> Result<()> {
        self.set_dhcp_client_enabled(false).await.context("failed to stop dhcp client")
    }

    async fn stop_dhcp_out_of_stack(&self) {
        let Self { endpoint: _, realm: _, id: _, control: _, device_control: _, dhcp_client_task } =
            self;
        let mut dhcp_client_task = dhcp_client_task.lock().await;
        if let Some(task) = dhcp_client_task.deref_mut().take() {
            task.shutdown().await.expect("client shutdown should succeed");
        }
    }

    /// Adds an address, waiting until the address assignment state is
    /// `ASSIGNED`.
    pub async fn add_address(&self, subnet: fnet::Subnet) -> Result<()> {
        let (address_state_provider, server) =
            fidl::endpoints::create_proxy::<fnet_interfaces_admin::AddressStateProviderMarker>();
        let () = address_state_provider.detach().context("detach address lifetime")?;
        let () = self
            .control
            .add_address(&subnet, &fnet_interfaces_admin::AddressParameters::default(), server)
            .context("FIDL error")?;

        let mut state_stream =
            fnet_interfaces_ext::admin::assignment_state_stream(address_state_provider);
        fnet_interfaces_ext::admin::wait_assignment_state(
            &mut state_stream,
            fnet_interfaces::AddressAssignmentState::Assigned,
        )
        .await?;
        Ok(())
    }

    /// Adds an address and a subnet route, waiting until the address assignment
    /// state is `ASSIGNED`.
    pub async fn add_address_and_subnet_route(&self, subnet: fnet::Subnet) -> Result<()> {
        let (address_state_provider, server) =
            fidl::endpoints::create_proxy::<fnet_interfaces_admin::AddressStateProviderMarker>();
        address_state_provider.detach().context("detach address lifetime")?;
        self.control
            .add_address(
                &subnet,
                &fnet_interfaces_admin::AddressParameters {
                    add_subnet_route: Some(true),
                    ..Default::default()
                },
                server,
            )
            .context("FIDL error")?;

        let state_stream =
            fnet_interfaces_ext::admin::assignment_state_stream(address_state_provider);
        let mut state_stream = pin!(state_stream);

        fnet_interfaces_ext::admin::wait_assignment_state(
            &mut state_stream,
            fnet_interfaces::AddressAssignmentState::Assigned,
        )
        .await
        .context("assignment state")?;
        Ok(())
    }

    /// Removes an address and its corresponding subnet route.
    pub async fn del_address_and_subnet_route(
        &self,
        addr_with_prefix: fnet::Subnet,
    ) -> Result<bool> {
        let did_remove =
            self.control.remove_address(&addr_with_prefix).await.context("FIDL error").and_then(
                |res| {
                    res.map_err(|e: fnet_interfaces_admin::ControlRemoveAddressError| {
                        anyhow::anyhow!("{:?}", e)
                    })
                },
            )?;

        if did_remove {
            let destination = fnet_ext::apply_subnet_mask(addr_with_prefix);
            let newly_removed_route = self
                .remove_route_either(
                    destination,
                    None,
                    fnet_routes::SpecifiedMetric::InheritedFromInterface(fnet_routes::Empty),
                )
                .await?;

            // We don't assert on the route having been newly-removed because it could also
            // be removed due to the AddressStateProvider going away.
            let _: bool = newly_removed_route;
        }
        Ok(did_remove)
    }

    /// Removes all IPv6 LinkLocal addresses on the interface.
    ///
    /// Useful to purge the interface of autogenerated SLAAC addresses.
    pub async fn remove_ipv6_linklocal_addresses(
        &self,
    ) -> Result<Vec<fnet_interfaces_ext::Address<fnet_interfaces_ext::AllInterest>>> {
        let mut result = Vec::new();
        for address in self.get_addrs(fnet_interfaces_ext::IncludedAddresses::All).await? {
            let fnet_interfaces_ext::Address { addr: fnet::Subnet { addr, prefix_len }, .. } =
                &address;
            match addr {
                fidl_fuchsia_net::IpAddress::Ipv4(fidl_fuchsia_net::Ipv4Address { addr: _ }) => {
                    continue
                }
                fidl_fuchsia_net::IpAddress::Ipv6(fidl_fuchsia_net::Ipv6Address { addr }) => {
                    let v6_addr = net_types::ip::Ipv6Addr::from_bytes(*addr);
                    if !v6_addr.is_unicast_link_local() {
                        continue;
                    }
                }
            }
            let _newly_removed: bool = self
                .del_address_and_subnet_route(fnet::Subnet { addr: *addr, prefix_len: *prefix_len })
                .await?;
            result.push(address);
        }
        Ok(result)
    }

    /// Set configuration on this interface.
    ///
    /// Returns an error if the operation is unsupported or a no-op.
    ///
    /// Note that this function should not be made public and should only be
    /// used to implement helpers for setting specific pieces of configuration,
    /// as it cannot be guaranteed that this function is kept up-to-date with
    /// the underlying FIDL types and thus may not always be able to uphold the
    /// error return contract.
    async fn set_configuration(&self, config: fnet_interfaces_admin::Configuration) -> Result<()> {
        let fnet_interfaces_admin::Configuration {
            ipv4: previous_ipv4, ipv6: previous_ipv6, ..
        } = self
            .control()
            .set_configuration(&config.clone())
            .await
            .context("FIDL error")?
            .map_err(|e| anyhow!("set configuration error: {:?}", e))?;

        fn verify_config_changed<T: Eq>(previous: Option<T>, current: Option<T>) -> Result<()> {
            if let Some(current) = current {
                let previous = previous.ok_or_else(|| anyhow!("configuration not supported"))?;
                if previous == current {
                    return Err(anyhow!("configuration change is a no-op"));
                }
            }
            Ok(())
        }

        let fnet_interfaces_admin::Configuration { ipv4, ipv6, .. } = config;
        if let Some(fnet_interfaces_admin::Ipv4Configuration {
            unicast_forwarding,
            multicast_forwarding,
            ..
        }) = ipv4
        {
            let fnet_interfaces_admin::Ipv4Configuration {
                unicast_forwarding: previous_unicast_forwarding,
                multicast_forwarding: previous_multicast_forwarding,
                ..
            } = previous_ipv4.ok_or_else(|| anyhow!("IPv4 configuration not supported"))?;
            verify_config_changed(previous_unicast_forwarding, unicast_forwarding)
                .context("IPv4 unicast forwarding")?;
            verify_config_changed(previous_multicast_forwarding, multicast_forwarding)
                .context("IPv4 multicast forwarding")?;
        }
        if let Some(fnet_interfaces_admin::Ipv6Configuration {
            unicast_forwarding,
            multicast_forwarding,
            ..
        }) = ipv6
        {
            let fnet_interfaces_admin::Ipv6Configuration {
                unicast_forwarding: previous_unicast_forwarding,
                multicast_forwarding: previous_multicast_forwarding,
                ..
            } = previous_ipv6.ok_or_else(|| anyhow!("IPv6 configuration not supported"))?;
            verify_config_changed(previous_unicast_forwarding, unicast_forwarding)
                .context("IPv6 unicast forwarding")?;
            verify_config_changed(previous_multicast_forwarding, multicast_forwarding)
                .context("IPv6 multicast forwarding")?;
        }
        Ok(())
    }

    /// Enable/disable IPv6 forwarding on this interface.
    pub async fn set_ipv6_forwarding_enabled(&self, enabled: bool) -> Result<()> {
        self.set_configuration(fnet_interfaces_admin::Configuration {
            ipv6: Some(fnet_interfaces_admin::Ipv6Configuration {
                unicast_forwarding: Some(enabled),
                ..Default::default()
            }),
            ..Default::default()
        })
        .await
    }

    /// Enable/disable IPv4 forwarding on this interface.
    pub async fn set_ipv4_forwarding_enabled(&self, enabled: bool) -> Result<()> {
        self.set_configuration(fnet_interfaces_admin::Configuration {
            ipv4: Some(fnet_interfaces_admin::Ipv4Configuration {
                unicast_forwarding: Some(enabled),
                ..Default::default()
            }),
            ..Default::default()
        })
        .await
    }

    /// Consumes this [`TestInterface`] and removes the associated interface
    /// in the Netstack, returning the device lifetime-carrying channels.
    pub async fn remove(
        self,
    ) -> Result<(fnetemul_network::EndpointProxy, Option<fnet_interfaces_admin::DeviceControlProxy>)>
    {
        let Self {
            endpoint: TestEndpoint { endpoint, name: _, _sandbox: _ },
            id: _,
            realm: _,
            control,
            device_control,
            dhcp_client_task: _,
        } = self;
        // For Network Devices, the `control` handle  is tied to the lifetime of
        // the interface; dropping it triggers interface removal in the
        // Netstack. For Ethernet devices this is a No-Op.
        std::mem::drop(control);
        Ok((endpoint, device_control))
    }

    /// Consumes this [`TestInterface`] and removes the underlying device. The
    /// Netstack will implicitly remove the interface and clients can expect to
    /// observe a `PEER_CLOSED` event on the returned control channel.
    pub fn remove_device(self) -> (Control, Option<fnet_interfaces_admin::DeviceControlProxy>) {
        let Self {
            endpoint: TestEndpoint { endpoint, name: _, _sandbox: _ },
            id: _,
            realm: _,
            control,
            device_control,
            dhcp_client_task: _,
        } = self;
        std::mem::drop(endpoint);
        (control, device_control)
    }

    /// Waits for this interface to signal that it's been removed.
    pub async fn wait_removal(self) -> Result<fnet_interfaces_admin::InterfaceRemovedReason> {
        let Self {
            // Keep this alive, we don't want to trigger removal.
            endpoint: _endpoint,
            id: _,
            realm: _,
            control,
            dhcp_client_task: _,
            // Keep this alive, we don't want to trigger removal.
            device_control: _device_control,
        } = self;
        match control.wait_termination().await {
            fnet_interfaces_ext::admin::TerminalError::Fidl(e) => {
                Err(e).context("waiting interface control termination")
            }
            fnet_interfaces_ext::admin::TerminalError::Terminal(reason) => Ok(reason),
        }
    }

    /// Sets the number of DAD transmits on this interface.
    ///
    /// Returns the previous configuration value, if reported by the API.
    pub async fn set_dad_transmits(&self, dad_transmits: u16) -> Result<Option<u16>> {
        set_dad_transmits(self.control(), dad_transmits).await
    }

    /// Sets whether temporary SLAAC address generation is enabled
    /// or disabled on this interface.
    pub async fn set_temporary_address_generation_enabled(&self, enabled: bool) -> Result<()> {
        self.set_configuration(fnet_interfaces_admin::Configuration {
            ipv6: Some(fnet_interfaces_admin::Ipv6Configuration {
                ndp: Some(fnet_interfaces_admin::NdpConfiguration {
                    slaac: Some(fnet_interfaces_admin::SlaacConfiguration {
                        temporary_address: Some(enabled),
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        })
        .await
    }
}

async fn set_dad_transmits(control: &Control, dad_transmits: u16) -> Result<Option<u16>> {
    control
        .set_configuration(&fnet_interfaces_admin::Configuration {
            ipv6: Some(fnet_interfaces_admin::Ipv6Configuration {
                ndp: Some(fnet_interfaces_admin::NdpConfiguration {
                    dad: Some(fnet_interfaces_admin::DadConfiguration {
                        transmits: Some(dad_transmits),
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        })
        .await?
        .map(|config| config.ipv6?.ndp?.dad?.transmits)
        .map_err(|e| anyhow::anyhow!("set configuration error {e:?}"))
}

/// Get the [`socket2::Domain`] for `addr`.
fn get_socket2_domain(addr: &std::net::SocketAddr) -> fposix_socket::Domain {
    let domain = match addr {
        std::net::SocketAddr::V4(_) => fposix_socket::Domain::Ipv4,
        std::net::SocketAddr::V6(_) => fposix_socket::Domain::Ipv6,
    };

    domain
}

/// Trait describing UDP sockets that can be bound in a testing realm.
pub trait RealmUdpSocket: Sized {
    /// Creates a UDP socket in `realm` bound to `addr`.
    fn bind_in_realm<'a>(
        realm: &'a TestRealm<'a>,
        addr: std::net::SocketAddr,
    ) -> futures::future::LocalBoxFuture<'a, Result<Self>>;
}

impl RealmUdpSocket for std::net::UdpSocket {
    fn bind_in_realm<'a>(
        realm: &'a TestRealm<'a>,
        addr: std::net::SocketAddr,
    ) -> futures::future::LocalBoxFuture<'a, Result<Self>> {
        async move {
            let sock = realm
                .datagram_socket(
                    get_socket2_domain(&addr),
                    fposix_socket::DatagramSocketProtocol::Udp,
                )
                .await
                .context("failed to create socket")?;

            let () = sock.bind(&addr.into()).context("bind failed")?;

            Result::Ok(sock.into())
        }
        .boxed_local()
    }
}

impl RealmUdpSocket for fuchsia_async::net::UdpSocket {
    fn bind_in_realm<'a>(
        realm: &'a TestRealm<'a>,
        addr: std::net::SocketAddr,
    ) -> futures::future::LocalBoxFuture<'a, Result<Self>> {
        std::net::UdpSocket::bind_in_realm(realm, addr)
            .and_then(|udp| {
                futures::future::ready(
                    fuchsia_async::net::UdpSocket::from_socket(udp)
                        .context("failed to create fuchsia_async socket"),
                )
            })
            .boxed_local()
    }
}

/// Trait describing TCP listeners bound in a testing realm.
pub trait RealmTcpListener: Sized {
    /// Creates a TCP listener in `realm` bound to `addr`.
    fn listen_in_realm<'a>(
        realm: &'a TestRealm<'a>,
        addr: std::net::SocketAddr,
    ) -> futures::future::LocalBoxFuture<'a, Result<Self>> {
        Self::listen_in_realm_with(realm, addr, |_: &socket2::Socket| Ok(()))
    }

    /// Creates a TCP listener by creating a Socket2 socket in `realm`. Closure `setup` is called
    /// with the reference of the socket before the socket is bound to `addr`.
    fn listen_in_realm_with<'a>(
        realm: &'a TestRealm<'a>,
        addr: std::net::SocketAddr,
        setup: impl FnOnce(&socket2::Socket) -> Result<()> + 'a,
    ) -> futures::future::LocalBoxFuture<'a, Result<Self>>;
}

impl RealmTcpListener for std::net::TcpListener {
    fn listen_in_realm_with<'a>(
        realm: &'a TestRealm<'a>,
        addr: std::net::SocketAddr,
        setup: impl FnOnce(&socket2::Socket) -> Result<()> + 'a,
    ) -> futures::future::LocalBoxFuture<'a, Result<Self>> {
        async move {
            let sock = realm
                .stream_socket(get_socket2_domain(&addr), fposix_socket::StreamSocketProtocol::Tcp)
                .await
                .context("failed to create server socket")?;
            let () = setup(&sock)?;
            let () = sock.bind(&addr.into()).context("failed to bind server socket")?;
            // Use 128 for the listen() backlog, same as the original implementation of TcpListener
            // in Rust std (see https://doc.rust-lang.org/src/std/sys_common/net.rs.html#386).
            let () = sock.listen(128).context("failed to listen on server socket")?;

            Result::Ok(sock.into())
        }
        .boxed_local()
    }
}

impl RealmTcpListener for fuchsia_async::net::TcpListener {
    fn listen_in_realm_with<'a>(
        realm: &'a TestRealm<'a>,
        addr: std::net::SocketAddr,
        setup: impl FnOnce(&socket2::Socket) -> Result<()> + 'a,
    ) -> futures::future::LocalBoxFuture<'a, Result<Self>> {
        std::net::TcpListener::listen_in_realm_with(realm, addr, setup)
            .and_then(|listener| {
                futures::future::ready(
                    fuchsia_async::net::TcpListener::from_std(listener)
                        .context("failed to create fuchsia_async socket"),
                )
            })
            .boxed_local()
    }
}

/// Trait describing TCP streams in a testing realm.
pub trait RealmTcpStream: Sized {
    /// Creates a TCP stream in `realm` connected to `addr`.
    fn connect_in_realm<'a>(
        realm: &'a TestRealm<'a>,
        addr: std::net::SocketAddr,
    ) -> futures::future::LocalBoxFuture<'a, Result<Self>>;

    /// Creates a TCP stream in `realm` bound to `local` and connected to `dst`.
    fn bind_and_connect_in_realm<'a>(
        realm: &'a TestRealm<'a>,
        local: std::net::SocketAddr,
        dst: std::net::SocketAddr,
    ) -> futures::future::LocalBoxFuture<'a, Result<Self>>;

    /// Creates a TCP stream in `realm` connected to `addr`.
    ///
    /// Closure `with_sock` is called with the reference of the socket before
    /// the socket is connected to `addr`.
    fn connect_in_realm_with_sock<'a, F: FnOnce(&socket2::Socket) -> Result + 'a>(
        realm: &'a TestRealm<'a>,
        dst: std::net::SocketAddr,
        with_sock: F,
    ) -> futures::future::LocalBoxFuture<'a, Result<Self>>;

    // TODO: Implement this trait for std::net::TcpStream.
}

impl RealmTcpStream for fuchsia_async::net::TcpStream {
    fn connect_in_realm<'a>(
        realm: &'a TestRealm<'a>,
        addr: std::net::SocketAddr,
    ) -> futures::future::LocalBoxFuture<'a, Result<Self>> {
        Self::connect_in_realm_with_sock(realm, addr, |_: &socket2::Socket| Ok(()))
    }

    fn bind_and_connect_in_realm<'a>(
        realm: &'a TestRealm<'a>,
        local: std::net::SocketAddr,
        dst: std::net::SocketAddr,
    ) -> futures::future::LocalBoxFuture<'a, Result<Self>> {
        Self::connect_in_realm_with_sock(realm, dst, move |sock| {
            sock.bind(&local.into()).context("failed to bind")
        })
    }

    fn connect_in_realm_with_sock<'a, F: FnOnce(&socket2::Socket) -> Result + 'a>(
        realm: &'a TestRealm<'a>,
        dst: std::net::SocketAddr,
        with_sock: F,
    ) -> futures::future::LocalBoxFuture<'a, Result<fuchsia_async::net::TcpStream>> {
        async move {
            let sock = realm
                .stream_socket(get_socket2_domain(&dst), fposix_socket::StreamSocketProtocol::Tcp)
                .await
                .context("failed to create socket")?;

            with_sock(&sock)?;

            let stream = fuchsia_async::net::TcpStream::connect_from_raw(sock, dst)
                .context("failed to create client tcp stream")?
                .await
                .context("failed to connect to server")?;

            Result::Ok(stream)
        }
        .boxed_local()
    }
}

fn truncate_dropping_front(s: Cow<'_, str>, len: usize) -> Cow<'_, str> {
    match s.len().checked_sub(len) {
        None => s,
        Some(start) => {
            // NB: Drop characters from the front because it's likely that a name that
            // exceeds the length limit is the full name of a test whose suffix is more
            // informative because nesting of test cases appends suffixes.
            match s {
                Cow::Borrowed(s) => Cow::Borrowed(&s[start..]),
                Cow::Owned(mut s) => {
                    let _: std::string::Drain<'_> = s.drain(..start);
                    Cow::Owned(s)
                }
            }
        }
    }
}