1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
// Copyright 2018 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.

use anyhow::{Context as _, Error};
use fidl_fuchsia_net as fnet;
use fidl_fuchsia_net_debug as fdebug;
use fidl_fuchsia_net_dhcp as fdhcp;
use fidl_fuchsia_net_ext as fnet_ext;
use fidl_fuchsia_net_filter as fnet_filter;
use fidl_fuchsia_net_filter_deprecated as ffilter_deprecated;
use fidl_fuchsia_net_filter_ext as fnet_filter_ext;
use fidl_fuchsia_net_interfaces as finterfaces;
use fidl_fuchsia_net_interfaces_admin as finterfaces_admin;
use fidl_fuchsia_net_interfaces_ext as finterfaces_ext;
use fidl_fuchsia_net_name as fname;
use fidl_fuchsia_net_neighbor as fneighbor;
use fidl_fuchsia_net_neighbor_ext as fneighbor_ext;
use fidl_fuchsia_net_root as froot;
use fidl_fuchsia_net_routes as froutes;
use fidl_fuchsia_net_routes_ext as froutes_ext;
use fidl_fuchsia_net_stack as fstack;
use fidl_fuchsia_net_stack_ext::{self as fstack_ext, FidlReturn as _};
use fidl_fuchsia_net_stackmigrationdeprecated as fnet_migration;
use fuchsia_zircon_status as zx;
use futures::{FutureExt as _, StreamExt as _, TryFutureExt as _, TryStreamExt as _};
use net_types::ip::{Ipv4, Ipv6};
use netfilter::FidlReturn as _;
use prettytable::{cell, format, row, Row, Table};
use ser::AddressAssignmentState;
use serde_json::{json, value::Value};
use std::collections::hash_map::HashMap;
use std::{convert::TryFrom as _, iter::FromIterator as _, str::FromStr as _};
use tracing::{info, warn};

mod opts;
pub use opts::{
    underlying_user_facing_error, user_facing_error, Command, CommandEnum, UserFacingError,
};

mod ser;

macro_rules! filter_fidl {
    ($method:expr, $context:expr) => {
        $method.await.transform_result().context($context)
    };
}

fn add_row(t: &mut Table, row: Row) {
    let _: &mut Row = t.add_row(row);
}

/// An interface for acquiring a proxy to a FIDL service.
#[async_trait::async_trait]
pub trait ServiceConnector<S: fidl::endpoints::ProtocolMarker> {
    /// Acquires a proxy to the parameterized FIDL interface.
    async fn connect(&self) -> Result<S::Proxy, Error>;
}

/// An interface for acquiring all system dependencies required by net-cli.
///
/// FIDL dependencies are specified as supertraits. These supertraits are a complete enumeration of
/// all FIDL dependencies required by net-cli.
pub trait NetCliDepsConnector:
    ServiceConnector<fdebug::InterfacesMarker>
    + ServiceConnector<froot::InterfacesMarker>
    + ServiceConnector<fdhcp::Server_Marker>
    + ServiceConnector<ffilter_deprecated::FilterMarker>
    + ServiceConnector<finterfaces::StateMarker>
    + ServiceConnector<fneighbor::ControllerMarker>
    + ServiceConnector<fneighbor::ViewMarker>
    + ServiceConnector<fstack::LogMarker>
    + ServiceConnector<fstack::StackMarker>
    + ServiceConnector<froutes::StateV4Marker>
    + ServiceConnector<froutes::StateV6Marker>
    + ServiceConnector<fname::LookupMarker>
    + ServiceConnector<fnet_migration::ControlMarker>
    + ServiceConnector<fnet_migration::StateMarker>
    + ServiceConnector<fnet_filter::StateMarker>
{
}

impl<O> NetCliDepsConnector for O where
    O: ServiceConnector<fdebug::InterfacesMarker>
        + ServiceConnector<froot::InterfacesMarker>
        + ServiceConnector<fdhcp::Server_Marker>
        + ServiceConnector<ffilter_deprecated::FilterMarker>
        + ServiceConnector<finterfaces::StateMarker>
        + ServiceConnector<fneighbor::ControllerMarker>
        + ServiceConnector<fneighbor::ViewMarker>
        + ServiceConnector<fstack::LogMarker>
        + ServiceConnector<fstack::StackMarker>
        + ServiceConnector<froutes::StateV4Marker>
        + ServiceConnector<froutes::StateV6Marker>
        + ServiceConnector<fname::LookupMarker>
        + ServiceConnector<fnet_migration::ControlMarker>
        + ServiceConnector<fnet_migration::StateMarker>
        + ServiceConnector<fnet_filter::StateMarker>
{
}

pub async fn do_root<C: NetCliDepsConnector>(
    mut out: ffx_writer::Writer,
    Command { cmd }: Command,
    connector: &C,
) -> Result<(), Error> {
    match cmd {
        CommandEnum::If(opts::If { if_cmd: cmd }) => {
            do_if(&mut out, cmd, connector).await.context("failed during if command")
        }
        CommandEnum::Route(opts::Route { route_cmd: cmd }) => {
            do_route(&mut out, cmd, connector).await.context("failed during route command")
        }
        CommandEnum::FilterDeprecated(opts::FilterDeprecated { filter_cmd: cmd }) => {
            do_filter_deprecated(out, cmd, connector)
                .await
                .context("failed during filter-deprecated command")
        }
        CommandEnum::Filter(opts::filter::Filter { filter_cmd: cmd }) => {
            do_filter(out, cmd, connector).await.context("failed during filter command")
        }
        CommandEnum::Log(opts::Log { log_cmd: cmd }) => {
            do_log(cmd, connector).await.context("failed during log command")
        }
        CommandEnum::Dhcp(opts::Dhcp { dhcp_cmd: cmd }) => {
            do_dhcp(cmd, connector).await.context("failed during dhcp command")
        }
        CommandEnum::Dhcpd(opts::dhcpd::Dhcpd { dhcpd_cmd: cmd }) => {
            do_dhcpd(cmd, connector).await.context("failed during dhcpd command")
        }
        CommandEnum::Neigh(opts::Neigh { neigh_cmd: cmd }) => {
            do_neigh(out, cmd, connector).await.context("failed during neigh command")
        }
        CommandEnum::Dns(opts::dns::Dns { dns_cmd: cmd }) => {
            do_dns(out, cmd, connector).await.context("failed during dns command")
        }
        CommandEnum::NetstackMigration(opts::NetstackMigration { cmd }) => {
            do_netstack_migration(out, cmd, connector)
                .await
                .context("failed during migration command")
        }
    }
}

fn shortlist_interfaces(
    name_pattern: &str,
    interfaces: &mut HashMap<u64, finterfaces_ext::PropertiesAndState<()>>,
) {
    interfaces.retain(|_: &u64, properties_and_state| {
        properties_and_state.properties.name.contains(name_pattern)
    })
}

fn write_tabulated_interfaces_info<
    W: std::io::Write,
    I: IntoIterator<Item = ser::InterfaceView>,
>(
    mut out: W,
    interfaces: I,
) -> Result<(), Error> {
    let mut t = Table::new();
    t.set_format(format::FormatBuilder::new().padding(2, 2).build());
    for (
        i,
        ser::InterfaceView {
            nicid,
            name,
            device_class,
            online,
            addresses,
            mac,
            has_default_ipv4_route,
            has_default_ipv6_route,
        },
    ) in interfaces.into_iter().enumerate()
    {
        if i > 0 {
            let () = add_row(&mut t, row![]);
        }

        let () = add_row(&mut t, row!["nicid", nicid]);
        let () = add_row(&mut t, row!["name", name]);
        let () = add_row(
            &mut t,
            row![
                "device class",
                match device_class {
                    ser::DeviceClass::Loopback => "loopback",
                    ser::DeviceClass::Virtual => "virtual",
                    ser::DeviceClass::Ethernet => "ethernet",
                    ser::DeviceClass::Wlan => "wlan",
                    ser::DeviceClass::Ppp => "ppp",
                    ser::DeviceClass::Bridge => "bridge",
                    ser::DeviceClass::WlanAp => "wlan-ap",
                }
            ],
        );
        let () = add_row(&mut t, row!["online", online]);

        let default_routes: std::borrow::Cow<'_, _> =
            if has_default_ipv4_route || has_default_ipv6_route {
                itertools::Itertools::intersperse(
                    has_default_ipv4_route
                        .then_some("IPv4")
                        .into_iter()
                        .chain(has_default_ipv6_route.then_some("IPv6")),
                    ",",
                )
                .collect::<String>()
                .into()
            } else {
                "-".into()
            };
        add_row(&mut t, row!["default routes", default_routes]);

        for ser::Address {
            subnet: ser::Subnet { addr, prefix_len },
            valid_until,
            assignment_state,
        } in addresses.all_addresses()
        {
            let valid_until = valid_until.map(|v| {
                let v = std::time::Duration::from_nanos(v.try_into().unwrap_or_else(|_| 0))
                    .as_secs_f32();
                std::borrow::Cow::Owned(format!("valid until [{v}s]"))
            });
            let assignment_state: Option<std::borrow::Cow<'_, _>> = match assignment_state {
                AddressAssignmentState::Assigned => None,
                AddressAssignmentState::Tentative => Some("TENTATIVE".into()),
                AddressAssignmentState::Unavailable => Some("UNAVAILABLE".into()),
            };
            let extra_bits = itertools::Itertools::intersperse(
                assignment_state.into_iter().chain(valid_until),
                " ".into(),
            )
            .collect::<String>();

            let () = add_row(&mut t, row!["addr", format!("{addr}/{prefix_len}"), extra_bits]);
        }
        match mac {
            None => add_row(&mut t, row!["mac", "-"]),
            Some(mac) => add_row(&mut t, row!["mac", mac]),
        }
    }
    writeln!(out, "{}", t)?;
    Ok(())
}

pub(crate) async fn connect_with_context<S, C>(connector: &C) -> Result<S::Proxy, Error>
where
    C: ServiceConnector<S>,
    S: fidl::endpoints::ProtocolMarker,
{
    connector.connect().await.with_context(|| format!("failed to connect to {}", S::DEBUG_NAME))
}

async fn get_control<C>(connector: &C, id: u64) -> Result<finterfaces_ext::admin::Control, Error>
where
    C: ServiceConnector<froot::InterfacesMarker>,
{
    let root_interfaces = connect_with_context::<froot::InterfacesMarker, _>(connector).await?;
    let (control, server_end) = finterfaces_ext::admin::Control::create_endpoints()
        .context("create admin control endpoints")?;
    let () = root_interfaces.get_admin(id, server_end).context("send get admin request")?;
    Ok(control)
}

fn configuration_with_ip_forwarding_set(
    ip_version: fnet::IpVersion,
    forwarding: bool,
) -> finterfaces_admin::Configuration {
    match ip_version {
        fnet::IpVersion::V4 => finterfaces_admin::Configuration {
            ipv4: Some(finterfaces_admin::Ipv4Configuration {
                forwarding: Some(forwarding),
                ..Default::default()
            }),
            ..Default::default()
        },
        fnet::IpVersion::V6 => finterfaces_admin::Configuration {
            ipv6: Some(finterfaces_admin::Ipv6Configuration {
                forwarding: Some(forwarding),
                ..Default::default()
            }),
            ..Default::default()
        },
    }
}

fn extract_ip_forwarding(
    finterfaces_admin::Configuration {
        ipv4: ipv4_config, ipv6: ipv6_config, ..
    }: finterfaces_admin::Configuration,
    ip_version: fnet::IpVersion,
) -> Result<bool, Error> {
    match ip_version {
        fnet::IpVersion::V4 => {
            let finterfaces_admin::Ipv4Configuration { forwarding, .. } =
                ipv4_config.context("get IPv4 configuration")?;
            forwarding.context("get IPv4 forwarding configuration")
        }
        fnet::IpVersion::V6 => {
            let finterfaces_admin::Ipv6Configuration { forwarding, .. } =
                ipv6_config.context("get IPv6 configuration")?;
            forwarding.context("get IPv6 forwarding configuration")
        }
    }
}

fn extract_igmp_version(
    finterfaces_admin::Configuration { ipv4: ipv4_config, .. }: finterfaces_admin::Configuration,
) -> Result<Option<finterfaces_admin::IgmpVersion>, Error> {
    let finterfaces_admin::Ipv4Configuration { igmp, .. } =
        ipv4_config.context("get IPv4 configuration")?;
    let finterfaces_admin::IgmpConfiguration { version: igmp_version, .. } =
        igmp.context("get IGMP configuration")?;
    Ok(igmp_version)
}

fn extract_mld_version(
    finterfaces_admin::Configuration { ipv6: ipv6_config, .. }: finterfaces_admin::Configuration,
) -> Result<Option<finterfaces_admin::MldVersion>, Error> {
    let finterfaces_admin::Ipv6Configuration { mld, .. } =
        ipv6_config.context("get IPv6 configuration")?;
    let finterfaces_admin::MldConfiguration { version: mld_version, .. } =
        mld.context("get MLD configuration")?;
    Ok(mld_version)
}

async fn do_if<C: NetCliDepsConnector>(
    out: &mut ffx_writer::Writer,
    cmd: opts::IfEnum,
    connector: &C,
) -> Result<(), Error> {
    match cmd {
        opts::IfEnum::List(opts::IfList { name_pattern }) => {
            let root_interfaces =
                connect_with_context::<froot::InterfacesMarker, _>(connector).await?;
            let interface_state =
                connect_with_context::<finterfaces::StateMarker, _>(connector).await?;
            let stream = finterfaces_ext::event_stream_from_state(
                &interface_state,
                finterfaces_ext::IncludedAddresses::OnlyAssigned,
            )?;
            let mut response = finterfaces_ext::existing(
                stream,
                HashMap::<u64, finterfaces_ext::PropertiesAndState<()>>::new(),
            )
            .await?;
            if let Some(name_pattern) = name_pattern {
                let () = shortlist_interfaces(&name_pattern, &mut response);
            }
            let response = response.into_values().map(
                |finterfaces_ext::PropertiesAndState { properties, state: () }| async {
                    let mac = root_interfaces
                        .get_mac(properties.id.get())
                        .await
                        .context("call get_mac")?;
                    Ok::<_, Error>((properties, mac))
                },
            );
            let response = futures::future::try_join_all(response).await?;
            let mut response: Vec<_> = response
                .into_iter()
                .filter_map(|(properties, mac)| match mac {
                    Err(froot::InterfacesGetMacError::NotFound) => None,
                    Ok(mac) => {
                        let mac = mac.map(|box_| *box_);
                        Some((properties, mac).into())
                    }
                })
                .collect();
            let () = response.sort_by_key(|ser::InterfaceView { nicid, .. }| *nicid);
            if out.is_machine() {
                out.machine(&response)?;
            } else {
                write_tabulated_interfaces_info(out, response.into_iter())
                    .context("error tabulating interface info")?;
            }
        }
        opts::IfEnum::Get(opts::IfGet { interface }) => {
            let id = interface.find_nicid(connector).await?;
            let root_interfaces =
                connect_with_context::<froot::InterfacesMarker, _>(connector).await?;
            let interface_state =
                connect_with_context::<finterfaces::StateMarker, _>(connector).await?;
            let stream = finterfaces_ext::event_stream_from_state(
                &interface_state,
                finterfaces_ext::IncludedAddresses::OnlyAssigned,
            )?;
            let response = finterfaces_ext::existing(
                stream,
                finterfaces_ext::InterfaceState::<()>::Unknown(id),
            )
            .await?;
            match response {
                finterfaces_ext::InterfaceState::Unknown(id) => {
                    return Err(user_facing_error(format!("interface with id={} not found", id)));
                }
                finterfaces_ext::InterfaceState::Known(finterfaces_ext::PropertiesAndState {
                    properties,
                    state: _,
                }) => {
                    let finterfaces_ext::Properties { id, .. } = &properties;
                    let mac = root_interfaces.get_mac(id.get()).await.context("call get_mac")?;
                    match mac {
                        Err(froot::InterfacesGetMacError::NotFound) => {
                            return Err(user_facing_error(format!(
                                "interface with id={} not found",
                                id
                            )));
                        }
                        Ok(mac) => {
                            let mac = mac.map(|box_| *box_);
                            let view = (properties, mac).into();
                            write_tabulated_interfaces_info(out, std::iter::once(view))
                                .context("error tabulating interface info")?;
                        }
                    };
                }
            }
        }
        opts::IfEnum::Igmp(opts::IfIgmp { cmd }) => match cmd {
            opts::IfIgmpEnum::Get(opts::IfIgmpGet { interface }) => {
                let id = interface.find_nicid(connector).await.context("find nicid")?;
                let control = get_control(connector, id).await.context("get control")?;
                let configuration = control
                    .get_configuration()
                    .await
                    .map_err(anyhow::Error::new)
                    .and_then(|res| {
                        res.map_err(|e: finterfaces_admin::ControlGetConfigurationError| {
                            anyhow::anyhow!("{:?}", e)
                        })
                    })
                    .context("get configuration")?;

                out.line(format!("IGMP configuration on interface {}:", id))?;
                out.line(format!(
                    "    Version: {:?}",
                    extract_igmp_version(configuration).context("get IGMP version")?
                ))?;
            }
            opts::IfIgmpEnum::Set(opts::IfIgmpSet { interface, version }) => {
                let id = interface.find_nicid(connector).await.context("find nicid")?;
                let control = get_control(connector, id).await.context("get control")?;
                let prev_config = control
                    .set_configuration(&finterfaces_admin::Configuration {
                        ipv4: Some(finterfaces_admin::Ipv4Configuration {
                            igmp: Some(finterfaces_admin::IgmpConfiguration {
                                version,
                                ..Default::default()
                            }),
                            ..Default::default()
                        }),
                        ..Default::default()
                    })
                    .await
                    .map_err(anyhow::Error::new)
                    .and_then(|res| {
                        res.map_err(|e: finterfaces_admin::ControlSetConfigurationError| {
                            anyhow::anyhow!("{:?}", e)
                        })
                    })
                    .context("set configuration")?;

                info!(
                    "IGMP version set to {:?} on interface {}; previously set to {:?}",
                    version,
                    id,
                    extract_igmp_version(prev_config).context("get IGMP version")?,
                );
            }
        },
        opts::IfEnum::Mld(opts::IfMld { cmd }) => match cmd {
            opts::IfMldEnum::Get(opts::IfMldGet { interface }) => {
                let id = interface.find_nicid(connector).await.context("find nicid")?;
                let control = get_control(connector, id).await.context("get control")?;
                let configuration = control
                    .get_configuration()
                    .await
                    .map_err(anyhow::Error::new)
                    .and_then(|res| {
                        res.map_err(|e: finterfaces_admin::ControlGetConfigurationError| {
                            anyhow::anyhow!("{:?}", e)
                        })
                    })
                    .context("get configuration")?;

                out.line(format!("MLD configuration on interface {}:", id))?;
                out.line(format!(
                    "    Version: {:?}",
                    extract_mld_version(configuration).context("get MLD version")?
                ))?;
            }
            opts::IfMldEnum::Set(opts::IfMldSet { interface, version }) => {
                let id = interface.find_nicid(connector).await.context("find nicid")?;
                let control = get_control(connector, id).await.context("get control")?;
                let prev_config = control
                    .set_configuration(&finterfaces_admin::Configuration {
                        ipv6: Some(finterfaces_admin::Ipv6Configuration {
                            mld: Some(finterfaces_admin::MldConfiguration {
                                version,
                                ..Default::default()
                            }),
                            ..Default::default()
                        }),
                        ..Default::default()
                    })
                    .await
                    .map_err(anyhow::Error::new)
                    .and_then(|res| {
                        res.map_err(|e: finterfaces_admin::ControlSetConfigurationError| {
                            anyhow::anyhow!("{:?}", e)
                        })
                    })
                    .context("set configuration")?;

                info!(
                    "MLD version set to {:?} on interface {}; previously set to {:?}",
                    version,
                    id,
                    extract_mld_version(prev_config).context("get MLD version")?,
                );
            }
        },
        opts::IfEnum::IpForward(opts::IfIpForward { cmd }) => match cmd {
            opts::IfIpForwardEnum::Get(opts::IfIpForwardGet { interface, ip_version }) => {
                let id = interface.find_nicid(connector).await.context("find nicid")?;
                let control = get_control(connector, id).await.context("get control")?;
                let configuration = control
                    .get_configuration()
                    .await
                    .map_err(anyhow::Error::new)
                    .and_then(|res| {
                        res.map_err(|e: finterfaces_admin::ControlGetConfigurationError| {
                            anyhow::anyhow!("{:?}", e)
                        })
                    })
                    .context("get configuration")?;

                out.line(format!(
                    "IP forwarding for {:?} is {} on interface {}",
                    ip_version,
                    extract_ip_forwarding(configuration, ip_version)
                        .context("extract IP forwarding configuration")?,
                    id
                ))?;
            }
            opts::IfIpForwardEnum::Set(opts::IfIpForwardSet { interface, ip_version, enable }) => {
                let id = interface.find_nicid(connector).await.context("find nicid")?;
                let control = get_control(connector, id).await.context("get control")?;
                let prev_config = control
                    .set_configuration(&configuration_with_ip_forwarding_set(ip_version, enable))
                    .await
                    .map_err(anyhow::Error::new)
                    .and_then(|res| {
                        res.map_err(|e: finterfaces_admin::ControlSetConfigurationError| {
                            anyhow::anyhow!("{:?}", e)
                        })
                    })
                    .context("set configuration")?;
                info!(
                    "IP forwarding for {:?} set to {} on interface {}; previously set to {}",
                    ip_version,
                    enable,
                    id,
                    extract_ip_forwarding(prev_config, ip_version)
                        .context("extract IP forwarding configuration")?
                );
            }
        },
        opts::IfEnum::Enable(opts::IfEnable { interface }) => {
            let id = interface.find_nicid(connector).await?;
            let control = get_control(connector, id).await?;
            let did_enable = control
                .enable()
                .await
                .map_err(anyhow::Error::new)
                .and_then(|res| {
                    res.map_err(|e: finterfaces_admin::ControlEnableError| {
                        anyhow::anyhow!("{:?}", e)
                    })
                })
                .context("error enabling interface")?;
            if did_enable {
                info!("Interface {} enabled", id);
            } else {
                info!("Interface {} already enabled", id);
            }
        }
        opts::IfEnum::Disable(opts::IfDisable { interface }) => {
            let id = interface.find_nicid(connector).await?;
            let control = get_control(connector, id).await?;
            let did_disable = control
                .disable()
                .await
                .map_err(anyhow::Error::new)
                .and_then(|res| {
                    res.map_err(|e: finterfaces_admin::ControlDisableError| {
                        anyhow::anyhow!("{:?}", e)
                    })
                })
                .context("error disabling interface")?;
            if did_disable {
                info!("Interface {} disabled", id);
            } else {
                info!("Interface {} already disabled", id);
            }
        }
        opts::IfEnum::Addr(opts::IfAddr { addr_cmd }) => match addr_cmd {
            opts::IfAddrEnum::Add(opts::IfAddrAdd { interface, addr, prefix, no_subnet_route }) => {
                let id = interface.find_nicid(connector).await?;
                let control = get_control(connector, id).await?;
                let addr = fnet_ext::IpAddress::from_str(&addr)?.into();
                let subnet = fnet_ext::Subnet { addr, prefix_len: prefix };
                let (address_state_provider, server_end) = fidl::endpoints::create_proxy::<
                    finterfaces_admin::AddressStateProviderMarker,
                >()
                .context("create proxy")?;
                let () = control
                    .add_address(
                        &subnet.into(),
                        &finterfaces_admin::AddressParameters {
                            add_subnet_route: Some(!no_subnet_route),
                            ..Default::default()
                        },
                        server_end,
                    )
                    .context("call add address")?;

                let () = address_state_provider.detach().context("detach address lifetime")?;
                let state_stream =
                    finterfaces_ext::admin::assignment_state_stream(address_state_provider);

                state_stream
                    .try_filter_map(|state| {
                        futures::future::ok(match state {
                            finterfaces::AddressAssignmentState::Tentative => None,
                            finterfaces::AddressAssignmentState::Assigned => Some(()),
                            finterfaces::AddressAssignmentState::Unavailable => Some(()),
                        })
                    })
                    .try_next()
                    .await
                    .context("error after adding address")?
                    .ok_or_else(|| {
                        anyhow::anyhow!(
                            "Address assignment state stream unexpectedly ended \
                                 before reaching Assigned or Unavailable state. \
                                 This is probably a bug."
                        )
                    })?;

                info!("Address {}/{} added to interface {}", addr, prefix, id);
            }
            opts::IfAddrEnum::Del(opts::IfAddrDel { interface, addr, prefix }) => {
                let id = interface.find_nicid(connector).await?;
                let control = get_control(connector, id).await?;
                let addr = fnet_ext::IpAddress::from_str(&addr)?;
                let did_remove = {
                    let addr = addr.into();
                    let subnet = fnet::Subnet {
                        addr,
                        prefix_len: prefix.unwrap_or_else(|| {
                            8 * u8::try_from(match addr {
                                fnet::IpAddress::Ipv4(fnet::Ipv4Address { addr }) => addr.len(),
                                fnet::IpAddress::Ipv6(fnet::Ipv6Address { addr }) => addr.len(),
                            })
                            .expect("prefix length doesn't fit u8")
                        }),
                    };
                    control
                        .remove_address(&subnet)
                        .await
                        .map_err(anyhow::Error::new)
                        .and_then(|res| {
                            res.map_err(|e: finterfaces_admin::ControlRemoveAddressError| {
                                anyhow::anyhow!("{:?}", e)
                            })
                        })
                        .context("call remove address")?
                };
                if !did_remove {
                    return Err(user_facing_error(format!(
                        "Address {} not found on interface {}",
                        addr, id
                    )));
                }
                info!("Address {} deleted from interface {}", addr, id);
            }
            opts::IfAddrEnum::Wait(opts::IfAddrWait { interface, ipv6 }) => {
                let id = interface.find_nicid(connector).await?;
                let interfaces_state =
                    connect_with_context::<finterfaces::StateMarker, _>(connector).await?;
                let mut state = finterfaces_ext::InterfaceState::<()>::Unknown(id);

                let assigned_addr = finterfaces_ext::wait_interface_with_id(
                    finterfaces_ext::event_stream_from_state(
                        &interfaces_state,
                        finterfaces_ext::IncludedAddresses::OnlyAssigned,
                    )?,
                    &mut state,
                    |finterfaces_ext::PropertiesAndState { properties, state: _ }| {
                        let finterfaces_ext::Properties { addresses, .. } = properties;
                        let addr = if ipv6 {
                            addresses.iter().find_map(
                                |finterfaces_ext::Address {
                                     addr: fnet::Subnet { addr, .. },
                                     ..
                                 }| {
                                    match addr {
                                        fnet::IpAddress::Ipv4(_) => None,
                                        fnet::IpAddress::Ipv6(_) => Some(addr),
                                    }
                                },
                            )
                        } else {
                            addresses.first().map(
                                |finterfaces_ext::Address {
                                     addr: fnet::Subnet { addr, .. },
                                     ..
                                 }| addr,
                            )
                        };
                        addr.map(|addr| {
                            let fnet_ext::IpAddress(addr) = (*addr).into();
                            addr
                        })
                    },
                )
                .await
                .context("wait for assigned address")?;

                out.line(format!("{assigned_addr}"))?;
                info!("Address {} assigned on interface {}", assigned_addr, id);
            }
        },
        opts::IfEnum::Bridge(opts::IfBridge { interfaces }) => {
            let stack = connect_with_context::<fstack::StackMarker, _>(connector).await?;
            let build_name_to_id_map = || async {
                let interface_state =
                    connect_with_context::<finterfaces::StateMarker, _>(connector).await?;
                let stream = finterfaces_ext::event_stream_from_state(
                    &interface_state,
                    finterfaces_ext::IncludedAddresses::OnlyAssigned,
                )?;
                let response = finterfaces_ext::existing(stream, HashMap::new()).await?;
                Ok::<HashMap<String, u64>, Error>(
                    response
                        .into_iter()
                        .map(
                            |(
                                id,
                                finterfaces_ext::PropertiesAndState {
                                    properties:
                                        finterfaces_ext::Properties {
                                            name,
                                            id: _,
                                            device_class: _,
                                            online: _,
                                            addresses: _,
                                            has_default_ipv4_route: _,
                                            has_default_ipv6_route: _,
                                        },
                                    state: (),
                                },
                            )| (name, id),
                        )
                        .collect(),
                )
            };

            let num_interfaces = interfaces.len();

            let (_name_to_id, ids): (Option<HashMap<String, u64>>, Vec<u64>) =
                futures::stream::iter(interfaces)
                    .map(Ok::<_, Error>)
                    .try_fold(
                        (None, Vec::with_capacity(num_interfaces)),
                        |(name_to_id, mut ids), interface| async move {
                            let (name_to_id, id) = match interface {
                                opts::InterfaceIdentifier::Id(id) => (name_to_id, id),
                                opts::InterfaceIdentifier::Name(name) => {
                                    let name_to_id = match name_to_id {
                                        Some(name_to_id) => name_to_id,
                                        None => build_name_to_id_map().await?,
                                    };
                                    let id = name_to_id.get(&name).copied().ok_or_else(|| {
                                        user_facing_error(format!("no interface named {}", name))
                                    })?;
                                    (Some(name_to_id), id)
                                }
                            };
                            ids.push(id);
                            Ok((name_to_id, ids))
                        },
                    )
                    .await?;

            let (bridge, server_end) = fidl::endpoints::create_proxy().context("create proxy")?;
            stack.bridge_interfaces(&ids, server_end).context("bridge interfaces")?;
            let bridge_id = bridge.get_id().await.context("get bridge id")?;
            // Detach the channel so it won't cause bridge destruction on exit.
            bridge.detach().context("detach bridge")?;
            info!("network bridge created with id {}", bridge_id);
        }
    }
    Ok(())
}

async fn do_route<C: NetCliDepsConnector>(
    out: &mut ffx_writer::Writer,
    cmd: opts::RouteEnum,
    connector: &C,
) -> Result<(), Error> {
    match cmd {
        opts::RouteEnum::List(opts::RouteList {}) => do_route_list(out, connector).await?,
        opts::RouteEnum::Add(route) => {
            let stack = connect_with_context::<fstack::StackMarker, _>(connector).await?;
            let nicid = route.interface.find_u32_nicid(connector).await?;
            let entry = route.into_route_table_entry(nicid);
            let () = fstack_ext::exec_fidl!(
                stack.add_forwarding_entry(&entry),
                "error adding next-hop forwarding entry"
            )?;
        }
        opts::RouteEnum::Del(route) => {
            let stack = connect_with_context::<fstack::StackMarker, _>(connector).await?;
            let nicid = route.interface.find_u32_nicid(connector).await?;
            let entry = route.into_route_table_entry(nicid);
            let () = fstack_ext::exec_fidl!(
                stack.del_forwarding_entry(&entry),
                "error removing forwarding entry"
            )?;
        }
    }
    Ok(())
}

async fn do_route_list<C: NetCliDepsConnector>(
    out: &mut ffx_writer::Writer,
    connector: &C,
) -> Result<(), Error> {
    let ipv4_route_event_stream = {
        let state_v4 = connect_with_context::<froutes::StateV4Marker, _>(connector)
            .await
            .context("failed to connect to fuchsia.net.routes/StateV4")?;
        froutes_ext::event_stream_from_state::<Ipv4>(&state_v4)
            .context("failed to initialize a `WatcherV4` client")?
            .fuse()
    };
    let ipv6_route_event_stream = {
        let state_v6 = connect_with_context::<froutes::StateV6Marker, _>(connector)
            .await
            .context("failed to connect to fuchsia.net.routes/StateV6")?;
        froutes_ext::event_stream_from_state::<Ipv6>(&state_v6)
            .context("failed to initialize a `WatcherV6` client")?
            .fuse()
    };
    futures::pin_mut!(ipv4_route_event_stream, ipv6_route_event_stream);
    let (v4_routes, v6_routes) = futures::future::join(
        froutes_ext::collect_routes_until_idle::<_, Vec<_>>(ipv4_route_event_stream),
        froutes_ext::collect_routes_until_idle::<_, Vec<_>>(ipv6_route_event_stream),
    )
    .await;
    let mut v4_routes = v4_routes.context("failed to collect all existing IPv4 routes")?;
    let mut v6_routes = v6_routes.context("failed to collect all existing IPv6 routes")?;
    if out.is_machine() {
        fn to_ser<I: net_types::ip::Ip>(
            route: froutes_ext::InstalledRoute<I>,
        ) -> Option<ser::ForwardingEntry> {
            route.try_into().map_err(|e| warn!("failed to convert route: {:?}", e)).ok()
        }
        let routes = v4_routes
            .into_iter()
            .filter_map(to_ser)
            .chain(v6_routes.into_iter().filter_map(to_ser))
            .collect::<Vec<_>>();
        out.machine(&routes).context("serialize")?;
    } else {
        let mut t = Table::new();
        t.set_format(format::FormatBuilder::new().padding(2, 2).build());

        t.set_titles(row!["Destination", "Gateway", "NICID", "Metric"]);
        fn write_route<I: net_types::ip::Ip>(t: &mut Table, route: froutes_ext::InstalledRoute<I>) {
            let froutes_ext::InstalledRoute {
                route: froutes_ext::Route { destination, action, properties: _ },
                effective_properties: froutes_ext::EffectiveRouteProperties { metric },
            } = route;
            let (device_id, next_hop) = match action {
                froutes_ext::RouteAction::Forward(froutes_ext::RouteTarget {
                    outbound_interface,
                    next_hop,
                }) => (outbound_interface, next_hop),
                froutes_ext::RouteAction::Unknown => {
                    warn!("observed route with unknown RouteAction.");
                    return;
                }
            };
            let next_hop = next_hop.map(|next_hop| next_hop.to_string());
            let next_hop = next_hop.as_ref().map_or("-", |s| s.as_str());
            let () = add_row(t, row![destination, next_hop, device_id, metric]);
        }

        v4_routes.sort();
        for route in v4_routes {
            write_route(&mut t, route);
        }
        v6_routes.sort();
        for route in v6_routes {
            write_route(&mut t, route);
        }

        let _lines_printed: usize = t.print(out)?;
        out.line("")?;
    }
    Ok(())
}

async fn do_filter_deprecated<C: NetCliDepsConnector, W: std::io::Write>(
    mut out: W,
    cmd: opts::FilterDeprecatedEnum,
    connector: &C,
) -> Result<(), Error> {
    let filter = connect_with_context::<ffilter_deprecated::FilterMarker, _>(connector).await?;
    match cmd {
        opts::FilterDeprecatedEnum::GetRules(opts::FilterGetRules {}) => {
            let (rules, generation): (Vec<ffilter_deprecated::Rule>, u32) =
                filter.get_rules().await?;
            writeln!(out, "{:?} (generation {})", rules, generation)?;
        }
        opts::FilterDeprecatedEnum::SetRules(opts::FilterSetRules { rules }) => {
            let (_cur_rules, generation) = filter.get_rules().await?;
            let rules = netfilter::parser_deprecated::parse_str_to_rules(&rules)?;
            let () = filter_fidl!(
                filter.update_rules(&rules, generation),
                "error setting filter rules"
            )?;
            info!("successfully set filter rules");
        }
        opts::FilterDeprecatedEnum::GetNatRules(opts::FilterGetNatRules {}) => {
            let (rules, generation): (Vec<ffilter_deprecated::Nat>, u32) =
                filter.get_nat_rules().await?;
            writeln!(out, "{:?} (generation {})", rules, generation)?;
        }
        opts::FilterDeprecatedEnum::SetNatRules(opts::FilterSetNatRules { rules }) => {
            let (_cur_rules, generation) = filter.get_nat_rules().await?;
            let rules = netfilter::parser_deprecated::parse_str_to_nat_rules(&rules)?;
            let () = filter_fidl!(
                filter.update_nat_rules(&rules, generation),
                "error setting NAT rules"
            )?;
            info!("successfully set NAT rules");
        }
        opts::FilterDeprecatedEnum::GetRdrRules(opts::FilterGetRdrRules {}) => {
            let (rules, generation): (Vec<ffilter_deprecated::Rdr>, u32) =
                filter.get_rdr_rules().await?;
            writeln!(out, "{:?} (generation {})", rules, generation)?;
        }
        opts::FilterDeprecatedEnum::SetRdrRules(opts::FilterSetRdrRules { rules }) => {
            let (_cur_rules, generation) = filter.get_rdr_rules().await?;
            let rules = netfilter::parser_deprecated::parse_str_to_rdr_rules(&rules)?;
            let () = filter_fidl!(
                filter.update_rdr_rules(&rules, generation),
                "error setting RDR rules"
            )?;
            info!("successfully set RDR rules");
        }
    }
    Ok(())
}

async fn do_filter<C: NetCliDepsConnector, W: std::io::Write>(
    mut out: W,
    cmd: opts::filter::FilterEnum,
    connector: &C,
) -> Result<(), Error> {
    match cmd {
        opts::filter::FilterEnum::List(opts::filter::List {}) => {
            let state = connect_with_context::<fnet_filter::StateMarker, _>(connector).await?;
            let stream = fnet_filter_ext::event_stream_from_state(state)?;
            futures::pin_mut!(stream);
            let resources: HashMap<_, _> =
                fnet_filter_ext::get_existing_resources(&mut stream).await?;
            writeln!(out, "resources = {resources:#?}")?;
        }
    }
    Ok(())
}

async fn do_log<C: NetCliDepsConnector>(cmd: opts::LogEnum, connector: &C) -> Result<(), Error> {
    let log = connect_with_context::<fstack::LogMarker, _>(connector).await?;
    match cmd {
        opts::LogEnum::SetPackets(opts::LogSetPackets { enabled }) => {
            let () = log.set_log_packets(enabled).await.context("error setting log packets")?;
            info!("log packets set to {:?}", enabled);
        }
    }
    Ok(())
}

async fn do_dhcp<C: NetCliDepsConnector>(cmd: opts::DhcpEnum, connector: &C) -> Result<(), Error> {
    let stack = connect_with_context::<fstack::StackMarker, _>(connector).await?;
    match cmd {
        opts::DhcpEnum::Start(opts::DhcpStart { interface }) => {
            let id = interface.find_nicid(connector).await?;
            let () = fstack_ext::exec_fidl!(
                stack.set_dhcp_client_enabled(id, true),
                "error stopping DHCP client"
            )?;
            info!("dhcp client started on interface {}", id);
        }
        opts::DhcpEnum::Stop(opts::DhcpStop { interface }) => {
            let id = interface.find_nicid(connector).await?;
            let () = fstack_ext::exec_fidl!(
                stack.set_dhcp_client_enabled(id, false),
                "error stopping DHCP client"
            )?;
            info!("dhcp client stopped on interface {}", id);
        }
    }
    Ok(())
}

async fn do_dhcpd<C: NetCliDepsConnector>(
    cmd: opts::dhcpd::DhcpdEnum,
    connector: &C,
) -> Result<(), Error> {
    let dhcpd_server = connect_with_context::<fdhcp::Server_Marker, _>(connector).await?;
    match cmd {
        opts::dhcpd::DhcpdEnum::Start(opts::dhcpd::Start {}) => {
            Ok(do_dhcpd_start(dhcpd_server).await?)
        }
        opts::dhcpd::DhcpdEnum::Stop(opts::dhcpd::Stop {}) => {
            Ok(do_dhcpd_stop(dhcpd_server).await?)
        }
        opts::dhcpd::DhcpdEnum::Get(get_arg) => Ok(do_dhcpd_get(get_arg, dhcpd_server).await?),
        opts::dhcpd::DhcpdEnum::Set(set_arg) => Ok(do_dhcpd_set(set_arg, dhcpd_server).await?),
        opts::dhcpd::DhcpdEnum::List(list_arg) => Ok(do_dhcpd_list(list_arg, dhcpd_server).await?),
        opts::dhcpd::DhcpdEnum::Reset(reset_arg) => {
            Ok(do_dhcpd_reset(reset_arg, dhcpd_server).await?)
        }
        opts::dhcpd::DhcpdEnum::ClearLeases(opts::dhcpd::ClearLeases {}) => {
            Ok(do_dhcpd_clear_leases(dhcpd_server).await?)
        }
    }
}

async fn do_neigh<C: NetCliDepsConnector>(
    out: ffx_writer::Writer,
    cmd: opts::NeighEnum,
    connector: &C,
) -> Result<(), Error> {
    match cmd {
        opts::NeighEnum::Add(opts::NeighAdd { interface, ip, mac }) => {
            let interface = interface.find_nicid(connector).await?;
            let controller =
                connect_with_context::<fneighbor::ControllerMarker, _>(connector).await?;
            let () = do_neigh_add(interface, ip.into(), mac.into(), controller)
                .await
                .context("failed during neigh add command")?;
            info!("Added entry ({}, {}) for interface {}", ip, mac, interface);
        }
        opts::NeighEnum::Clear(opts::NeighClear { interface, ip_version }) => {
            let interface = interface.find_nicid(connector).await?;
            let controller =
                connect_with_context::<fneighbor::ControllerMarker, _>(connector).await?;
            let () = do_neigh_clear(interface, ip_version, controller)
                .await
                .context("failed during neigh clear command")?;
            info!("Cleared entries for interface {}", interface);
        }
        opts::NeighEnum::Del(opts::NeighDel { interface, ip }) => {
            let interface = interface.find_nicid(connector).await?;
            let controller =
                connect_with_context::<fneighbor::ControllerMarker, _>(connector).await?;
            let () = do_neigh_del(interface, ip.into(), controller)
                .await
                .context("failed during neigh del command")?;
            info!("Deleted entry {} for interface {}", ip, interface);
        }
        opts::NeighEnum::List(opts::NeighList {}) => {
            let view = connect_with_context::<fneighbor::ViewMarker, _>(connector).await?;
            let () = print_neigh_entries(out, false /* watch_for_changes */, view)
                .await
                .context("error listing neighbor entries")?;
        }
        opts::NeighEnum::Watch(opts::NeighWatch {}) => {
            let view = connect_with_context::<fneighbor::ViewMarker, _>(connector).await?;
            let () = print_neigh_entries(out, true /* watch_for_changes */, view)
                .await
                .context("error watching for changes to the neighbor table")?;
        }
        opts::NeighEnum::Config(opts::NeighConfig { neigh_config_cmd }) => match neigh_config_cmd {
            opts::NeighConfigEnum::Get(opts::NeighGetConfig { interface, ip_version }) => {
                let interface = interface.find_nicid(connector).await?;
                let view = connect_with_context::<fneighbor::ViewMarker, _>(connector).await?;
                let () = print_neigh_config(interface, ip_version, view)
                    .await
                    .context("failed during neigh config get command")?;
            }
            opts::NeighConfigEnum::Update(opts::NeighUpdateConfig {
                interface,
                ip_version,
                base_reachable_time,
            }) => {
                let updates =
                    fneighbor::UnreachabilityConfig { base_reachable_time, ..Default::default() };
                let interface = interface.find_nicid(connector).await?;
                let controller =
                    connect_with_context::<fneighbor::ControllerMarker, _>(connector).await?;
                let () = update_neigh_config(interface, ip_version, updates, controller)
                    .await
                    .context("failed during neigh config update command")?;
                info!("Updated config for interface {}", interface);
            }
        },
    }
    Ok(())
}

async fn do_neigh_add(
    interface: u64,
    neighbor: fnet::IpAddress,
    mac: fnet::MacAddress,
    controller: fneighbor::ControllerProxy,
) -> Result<(), Error> {
    controller
        .add_entry(interface, &neighbor.into(), &mac.into())
        .await
        .context("FIDL error adding neighbor entry")?
        .map_err(zx::Status::from_raw)
        .context("error adding neighbor entry")
}

async fn do_neigh_clear(
    interface: u64,
    ip_version: fnet::IpVersion,
    controller: fneighbor::ControllerProxy,
) -> Result<(), Error> {
    controller
        .clear_entries(interface, ip_version)
        .await
        .context("FIDL error clearing neighbor table")?
        .map_err(zx::Status::from_raw)
        .context("error clearing neighbor table")
}

async fn do_neigh_del(
    interface: u64,
    neighbor: fnet::IpAddress,
    controller: fneighbor::ControllerProxy,
) -> Result<(), Error> {
    controller
        .remove_entry(interface, &neighbor.into())
        .await
        .context("FIDL error removing neighbor entry")?
        .map_err(zx::Status::from_raw)
        .context("error removing neighbor entry")
}

fn unpack_neigh_iter_item(
    item: fneighbor::EntryIteratorItem,
) -> Result<(&'static str, Option<fneighbor_ext::Entry>), Error> {
    let displayed_state_change_status = ser::DISPLAYED_NEIGH_ENTRY_VARIANTS.select(&item);

    Ok((
        displayed_state_change_status,
        match item {
            fneighbor::EntryIteratorItem::Existing(entry)
            | fneighbor::EntryIteratorItem::Added(entry)
            | fneighbor::EntryIteratorItem::Changed(entry)
            | fneighbor::EntryIteratorItem::Removed(entry) => {
                Some(fneighbor_ext::Entry::try_from(entry)?)
            }
            fneighbor::EntryIteratorItem::Idle(fneighbor::IdleEvent) => None,
        },
    ))
}

fn jsonify_neigh_iter_item(
    item: fneighbor::EntryIteratorItem,
    include_entry_state: bool,
) -> Result<Value, Error> {
    let (state_change_status, entry) = unpack_neigh_iter_item(item)?;
    let entry_json = entry
        .map(ser::NeighborTableEntry::from)
        .map(serde_json::to_value)
        .map(|res| res.map_err(Error::new))
        .unwrap_or(Err(anyhow::anyhow!("failed to jsonify NeighborTableEntry")))?;
    if include_entry_state {
        Ok(json!({
            "state_change_status": state_change_status,
            "entry": entry_json,
        }))
    } else {
        Ok(entry_json)
    }
}

async fn print_neigh_entries(
    mut out: ffx_writer::Writer,
    watch_for_changes: bool,
    view: fneighbor::ViewProxy,
) -> Result<(), Error> {
    let (it_client, it_server) =
        fidl::endpoints::create_endpoints::<fneighbor::EntryIteratorMarker>();
    let it = it_client.into_proxy().context("error creating proxy to entry iterator")?;

    let () = view
        .open_entry_iterator(it_server, &fneighbor::EntryIteratorOptions::default())
        .context("error opening a connection to the entry iterator")?;

    let out_ref = &mut out;
    if watch_for_changes {
        neigh_entry_stream(it, watch_for_changes)
            .map_ok(|item| {
                write_neigh_entry(out_ref, item, /* include_entry_state= */ watch_for_changes)
                    .context("error writing entry")
            })
            .try_fold((), |(), r| futures::future::ready(r))
            .await?;
    } else {
        let results: Vec<Result<fneighbor::EntryIteratorItem, _>> =
            neigh_entry_stream(it, watch_for_changes).collect().await;
        if out.is_machine() {
            let jsonified_items: Value =
                itertools::process_results(results.into_iter(), |items| {
                    itertools::process_results(
                        items.map(|item| {
                            jsonify_neigh_iter_item(
                                item,
                                /* include_entry_state= */ watch_for_changes,
                            )
                        }),
                        |json_values| Value::from_iter(json_values),
                    )
                })??;
            out.machine(&jsonified_items)?;
        } else {
            itertools::process_results(results.into_iter(), |mut items| {
                items.try_for_each(|item| {
                    write_tabular_neigh_entry(
                        &mut out,
                        item,
                        /* include_entry_state= */ watch_for_changes,
                    )
                })
            })??;
        }
    }

    Ok(())
}

async fn print_neigh_config(
    interface: u64,
    version: fnet::IpVersion,
    view: fneighbor::ViewProxy,
) -> Result<(), Error> {
    let config = view
        .get_unreachability_config(interface, version)
        .await
        .context("get_unreachability_config FIDL error")?
        .map_err(zx::Status::from_raw)
        .context("get_unreachability_config failed")?;

    println!("{:#?}", config);
    Ok(())
}

async fn update_neigh_config(
    interface: u64,
    version: fnet::IpVersion,
    updates: fneighbor::UnreachabilityConfig,
    controller: fneighbor::ControllerProxy,
) -> Result<(), Error> {
    controller
        .update_unreachability_config(interface, version, &updates)
        .await
        .context("update_unreachability_config FIDL error")?
        .map_err(zx::Status::from_raw)
        .context("update_unreachability_config failed")
}

fn neigh_entry_stream(
    iterator: fneighbor::EntryIteratorProxy,
    watch_for_changes: bool,
) -> impl futures::Stream<Item = Result<fneighbor::EntryIteratorItem, Error>> {
    futures::stream::try_unfold(iterator, |iterator| {
        iterator
            .get_next()
            .map_ok(|items| Some((items, iterator)))
            .map(|r| r.context("error getting items from iterator"))
    })
    .map_ok(|items| futures::stream::iter(items.into_iter().map(Ok)))
    .try_flatten()
    .take_while(move |item| {
        futures::future::ready(item.as_ref().is_ok_and(|item| {
            if let fneighbor::EntryIteratorItem::Idle(fneighbor::IdleEvent {}) = item {
                watch_for_changes
            } else {
                true
            }
        }))
    })
}

fn write_tabular_neigh_entry<W: std::io::Write>(
    mut f: W,
    item: fneighbor::EntryIteratorItem,
    include_entry_state: bool,
) -> Result<(), Error> {
    let (state_change_status, entry) = unpack_neigh_iter_item(item)?;
    match entry {
        Some(entry) => {
            if include_entry_state {
                writeln!(
                    &mut f,
                    "{:width$} | {}",
                    state_change_status,
                    entry,
                    width = ser::DISPLAYED_NEIGH_ENTRY_VARIANTS
                        .into_iter()
                        .map(|s| s.len())
                        .max()
                        .unwrap_or(0),
                )?
            } else {
                writeln!(&mut f, "{}", entry)?
            }
        }
        None => writeln!(&mut f, "{}", state_change_status)?,
    }
    Ok(())
}

fn write_neigh_entry(
    f: &mut ffx_writer::Writer,
    item: fneighbor::EntryIteratorItem,
    include_entry_state: bool,
) -> Result<(), Error> {
    if f.is_machine() {
        let entry = jsonify_neigh_iter_item(item, include_entry_state)?;
        f.machine(&entry)?;
    } else {
        write_tabular_neigh_entry(f, item, include_entry_state)?
    }
    Ok(())
}

async fn do_dhcpd_start(server: fdhcp::Server_Proxy) -> Result<(), Error> {
    server.start_serving().await?.map_err(zx::Status::from_raw).context("failed to start server")
}

async fn do_dhcpd_stop(server: fdhcp::Server_Proxy) -> Result<(), Error> {
    server.stop_serving().await.context("failed to stop server")
}

async fn do_dhcpd_get(get_arg: opts::dhcpd::Get, server: fdhcp::Server_Proxy) -> Result<(), Error> {
    match get_arg.arg {
        opts::dhcpd::GetArg::Option(opts::dhcpd::OptionArg { name }) => {
            let res = server
                .get_option(name.clone().into())
                .await?
                .map_err(zx::Status::from_raw)
                .with_context(|| format!("get_option({:?}) failed", name))?;
            println!("{:#?}", res);
        }
        opts::dhcpd::GetArg::Parameter(opts::dhcpd::ParameterArg { name }) => {
            let res = server
                .get_parameter(name.clone().into())
                .await?
                .map_err(zx::Status::from_raw)
                .with_context(|| format!("get_parameter({:?}) failed", name))?;
            println!("{:#?}", res);
        }
    };
    Ok(())
}

async fn do_dhcpd_set(set_arg: opts::dhcpd::Set, server: fdhcp::Server_Proxy) -> Result<(), Error> {
    match set_arg.arg {
        opts::dhcpd::SetArg::Option(opts::dhcpd::OptionArg { name }) => {
            let () = server
                .set_option(&name.clone().into())
                .await?
                .map_err(zx::Status::from_raw)
                .with_context(|| format!("set_option({:?}) failed", name))?;
        }
        opts::dhcpd::SetArg::Parameter(opts::dhcpd::ParameterArg { name }) => {
            let () = server
                .set_parameter(&name.clone().into())
                .await?
                .map_err(zx::Status::from_raw)
                .with_context(|| format!("set_parameter({:?}) failed", name))?;
        }
    };
    Ok(())
}

async fn do_dhcpd_list(
    list_arg: opts::dhcpd::List,
    server: fdhcp::Server_Proxy,
) -> Result<(), Error> {
    match list_arg.arg {
        opts::dhcpd::ListArg::Option(opts::dhcpd::OptionToken {}) => {
            let res = server
                .list_options()
                .await?
                .map_err(zx::Status::from_raw)
                .context("list_options() failed")?;

            println!("{:#?}", res);
        }
        opts::dhcpd::ListArg::Parameter(opts::dhcpd::ParameterToken {}) => {
            let res = server
                .list_parameters()
                .await?
                .map_err(zx::Status::from_raw)
                .context("list_parameters() failed")?;
            println!("{:#?}", res);
        }
    };
    Ok(())
}

async fn do_dhcpd_reset(
    reset_arg: opts::dhcpd::Reset,
    server: fdhcp::Server_Proxy,
) -> Result<(), Error> {
    match reset_arg.arg {
        opts::dhcpd::ResetArg::Option(opts::dhcpd::OptionToken {}) => {
            let () = server
                .reset_options()
                .await?
                .map_err(zx::Status::from_raw)
                .context("reset_options() failed")?;
        }
        opts::dhcpd::ResetArg::Parameter(opts::dhcpd::ParameterToken {}) => {
            let () = server
                .reset_parameters()
                .await?
                .map_err(zx::Status::from_raw)
                .context("reset_parameters() failed")?;
        }
    };
    Ok(())
}

async fn do_dhcpd_clear_leases(server: fdhcp::Server_Proxy) -> Result<(), Error> {
    server.clear_leases().await?.map_err(zx::Status::from_raw).context("clear_leases() failed")
}

async fn do_dns<W: std::io::Write, C: NetCliDepsConnector>(
    mut out: W,
    cmd: opts::dns::DnsEnum,
    connector: &C,
) -> Result<(), Error> {
    let lookup = connect_with_context::<fname::LookupMarker, _>(connector).await?;
    let opts::dns::DnsEnum::Lookup(opts::dns::Lookup { hostname, ipv4, ipv6, sort }) = cmd;
    let result = lookup
        .lookup_ip(
            &hostname,
            &fname::LookupIpOptions {
                ipv4_lookup: Some(ipv4),
                ipv6_lookup: Some(ipv6),
                sort_addresses: Some(sort),
                ..Default::default()
            },
        )
        .await?
        .map_err(|e| anyhow::anyhow!("DNS lookup failed: {:?}", e))?;
    let fname::LookupResult { addresses, .. } = result;
    let addrs = addresses.context("`addresses` not set in response from DNS resolver")?;
    for addr in addrs {
        writeln!(out, "{}", fnet_ext::IpAddress::from(addr))?;
    }
    Ok(())
}

async fn do_netstack_migration<W: std::io::Write, C: NetCliDepsConnector>(
    mut out: W,
    cmd: opts::NetstackMigrationEnum,
    connector: &C,
) -> Result<(), Error> {
    match cmd {
        opts::NetstackMigrationEnum::Set(opts::NetstackMigrationSet { version }) => {
            let control =
                connect_with_context::<fnet_migration::ControlMarker, _>(connector).await?;
            control
                .set_user_netstack_version(Some(&fnet_migration::VersionSetting { version }))
                .await
                .context("failed to set stack version")
        }
        opts::NetstackMigrationEnum::Clear(opts::NetstackMigrationClear {}) => {
            let control =
                connect_with_context::<fnet_migration::ControlMarker, _>(connector).await?;
            control.set_user_netstack_version(None).await.context("failed to set stack version")
        }
        opts::NetstackMigrationEnum::Get(opts::NetstackMigrationGet {}) => {
            let state = connect_with_context::<fnet_migration::StateMarker, _>(connector).await?;
            let fnet_migration::InEffectVersion { current_boot, user, automated, .. } =
                state.get_netstack_version().await.context("failed to get stack version")?;
            writeln!(out, "current_boot = {current_boot:?}")?;
            writeln!(out, "user = {user:?}")?;
            writeln!(out, "automated = {automated:?}")?;
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use assert_matches::assert_matches;
    use fidl::endpoints::ProtocolMarker;
    use fidl_fuchsia_hardware_network as fhardware_network;
    use fidl_fuchsia_net_routes as froutes;
    use fidl_fuchsia_net_routes_ext as froutes_ext;
    use fuchsia_async::{self as fasync, TimeoutExt as _};
    use net_declare::{fidl_ip, fidl_ip_v4, fidl_mac, fidl_subnet};
    use std::{convert::TryInto as _, fmt::Debug};
    use test_case::test_case;

    const IF_ADDR_V4: fnet::Subnet = fidl_subnet!("192.168.0.1/32");
    const IF_ADDR_V6: fnet::Subnet = fidl_subnet!("fd00::1/64");

    const MAC_1: fnet::MacAddress = fidl_mac!("01:02:03:04:05:06");
    const MAC_2: fnet::MacAddress = fidl_mac!("02:03:04:05:06:07");

    #[derive(Default)]
    struct TestConnector {
        debug_interfaces: Option<fdebug::InterfacesProxy>,
        dhcpd: Option<fdhcp::Server_Proxy>,
        interfaces_state: Option<finterfaces::StateProxy>,
        stack: Option<fstack::StackProxy>,
        root_interfaces: Option<froot::InterfacesProxy>,
        routes_v4: Option<froutes::StateV4Proxy>,
        routes_v6: Option<froutes::StateV6Proxy>,
        name_lookup: Option<fname::LookupProxy>,
        filter: Option<fnet_filter::StateProxy>,
    }

    #[async_trait::async_trait]
    impl ServiceConnector<fdebug::InterfacesMarker> for TestConnector {
        async fn connect(
            &self,
        ) -> Result<<fdebug::InterfacesMarker as ProtocolMarker>::Proxy, Error> {
            self.debug_interfaces
                .as_ref()
                .cloned()
                .ok_or(anyhow::anyhow!("connector has no dhcp server instance"))
        }
    }

    #[async_trait::async_trait]
    impl ServiceConnector<froot::InterfacesMarker> for TestConnector {
        async fn connect(
            &self,
        ) -> Result<<froot::InterfacesMarker as ProtocolMarker>::Proxy, Error> {
            self.root_interfaces
                .as_ref()
                .cloned()
                .ok_or(anyhow::anyhow!("connector has no root interfaces instance"))
        }
    }

    #[async_trait::async_trait]
    impl ServiceConnector<fdhcp::Server_Marker> for TestConnector {
        async fn connect(&self) -> Result<<fdhcp::Server_Marker as ProtocolMarker>::Proxy, Error> {
            self.dhcpd
                .as_ref()
                .cloned()
                .ok_or(anyhow::anyhow!("connector has no dhcp server instance"))
        }
    }

    #[async_trait::async_trait]
    impl ServiceConnector<ffilter_deprecated::FilterMarker> for TestConnector {
        async fn connect(
            &self,
        ) -> Result<<ffilter_deprecated::FilterMarker as ProtocolMarker>::Proxy, Error> {
            Err(anyhow::anyhow!("connect filter_deprecated unimplemented for test connector"))
        }
    }

    #[async_trait::async_trait]
    impl ServiceConnector<finterfaces::StateMarker> for TestConnector {
        async fn connect(
            &self,
        ) -> Result<<finterfaces::StateMarker as ProtocolMarker>::Proxy, Error> {
            self.interfaces_state
                .as_ref()
                .cloned()
                .ok_or(anyhow::anyhow!("connector has no interfaces state instance"))
        }
    }

    #[async_trait::async_trait]
    impl ServiceConnector<fneighbor::ControllerMarker> for TestConnector {
        async fn connect(
            &self,
        ) -> Result<<fneighbor::ControllerMarker as ProtocolMarker>::Proxy, Error> {
            Err(anyhow::anyhow!("connect neighbor controller unimplemented for test connector"))
        }
    }

    #[async_trait::async_trait]
    impl ServiceConnector<fneighbor::ViewMarker> for TestConnector {
        async fn connect(&self) -> Result<<fneighbor::ViewMarker as ProtocolMarker>::Proxy, Error> {
            Err(anyhow::anyhow!("connect neighbor view unimplemented for test connector"))
        }
    }

    #[async_trait::async_trait]
    impl ServiceConnector<fstack::LogMarker> for TestConnector {
        async fn connect(&self) -> Result<<fstack::LogMarker as ProtocolMarker>::Proxy, Error> {
            Err(anyhow::anyhow!("connect log unimplemented for test connector"))
        }
    }

    #[async_trait::async_trait]
    impl ServiceConnector<fstack::StackMarker> for TestConnector {
        async fn connect(&self) -> Result<<fstack::StackMarker as ProtocolMarker>::Proxy, Error> {
            self.stack.as_ref().cloned().ok_or(anyhow::anyhow!("connector has no stack instance"))
        }
    }

    #[async_trait::async_trait]
    impl ServiceConnector<froutes::StateV4Marker> for TestConnector {
        async fn connect(
            &self,
        ) -> Result<<froutes::StateV4Marker as ProtocolMarker>::Proxy, Error> {
            self.routes_v4
                .as_ref()
                .cloned()
                .ok_or(anyhow::anyhow!("connector has no routes_v4 instance"))
        }
    }

    #[async_trait::async_trait]
    impl ServiceConnector<froutes::StateV6Marker> for TestConnector {
        async fn connect(
            &self,
        ) -> Result<<froutes::StateV6Marker as ProtocolMarker>::Proxy, Error> {
            self.routes_v6
                .as_ref()
                .cloned()
                .ok_or(anyhow::anyhow!("connector has no routes_v6 instance"))
        }
    }

    #[async_trait::async_trait]
    impl ServiceConnector<fname::LookupMarker> for TestConnector {
        async fn connect(&self) -> Result<<fname::LookupMarker as ProtocolMarker>::Proxy, Error> {
            self.name_lookup
                .as_ref()
                .cloned()
                .ok_or(anyhow::anyhow!("connector has no name lookup instance"))
        }
    }

    #[async_trait::async_trait]
    impl ServiceConnector<fnet_migration::ControlMarker> for TestConnector {
        async fn connect(
            &self,
        ) -> Result<<fnet_migration::ControlMarker as ProtocolMarker>::Proxy, Error> {
            unimplemented!("stack migration not supported");
        }
    }

    #[async_trait::async_trait]
    impl ServiceConnector<fnet_migration::StateMarker> for TestConnector {
        async fn connect(
            &self,
        ) -> Result<<fnet_migration::StateMarker as ProtocolMarker>::Proxy, Error> {
            unimplemented!("stack migration not supported");
        }
    }

    #[async_trait::async_trait]
    impl ServiceConnector<fnet_filter::StateMarker> for TestConnector {
        async fn connect(
            &self,
        ) -> Result<<fnet_filter::StateMarker as ProtocolMarker>::Proxy, Error> {
            self.filter.as_ref().cloned().ok_or(anyhow::anyhow!("connector has no filter instance"))
        }
    }

    fn trim_whitespace_for_comparison(s: &str) -> String {
        s.trim().lines().map(|s| s.trim()).collect::<Vec<&str>>().join("\n")
    }

    fn get_fake_interface(
        id: u64,
        name: &'static str,
        device_class: finterfaces::DeviceClass,
        octets: Option<[u8; 6]>,
    ) -> (finterfaces_ext::Properties, Option<fnet::MacAddress>) {
        (
            finterfaces_ext::Properties {
                id: id.try_into().unwrap(),
                name: name.to_string(),
                device_class,
                online: true,
                addresses: Vec::new(),
                has_default_ipv4_route: false,
                has_default_ipv6_route: false,
            },
            octets.map(|octets| fnet::MacAddress { octets }),
        )
    }

    fn shortlist_interfaces_by_nicid(name_pattern: &str) -> Vec<u64> {
        let mut interfaces = [
            get_fake_interface(
                1,
                "lo",
                finterfaces::DeviceClass::Loopback(finterfaces::Empty),
                None,
            ),
            get_fake_interface(
                10,
                "eth001",
                finterfaces::DeviceClass::Device(fhardware_network::DeviceClass::Ethernet),
                Some([1, 2, 3, 4, 5, 6]),
            ),
            get_fake_interface(
                20,
                "eth002",
                finterfaces::DeviceClass::Device(fhardware_network::DeviceClass::Ethernet),
                Some([1, 2, 3, 4, 5, 7]),
            ),
            get_fake_interface(
                30,
                "eth003",
                finterfaces::DeviceClass::Device(fhardware_network::DeviceClass::Ethernet),
                Some([1, 2, 3, 4, 5, 8]),
            ),
            get_fake_interface(
                100,
                "wlan001",
                finterfaces::DeviceClass::Device(fhardware_network::DeviceClass::Wlan),
                Some([2, 2, 3, 4, 5, 6]),
            ),
            get_fake_interface(
                200,
                "wlan002",
                finterfaces::DeviceClass::Device(fhardware_network::DeviceClass::Wlan),
                Some([2, 2, 3, 4, 5, 7]),
            ),
            get_fake_interface(
                300,
                "wlan003",
                finterfaces::DeviceClass::Device(fhardware_network::DeviceClass::Wlan),
                Some([2, 2, 3, 4, 5, 8]),
            ),
        ]
        .into_iter()
        .map(|(properties, _): (_, Option<fnet::MacAddress>)| {
            let finterfaces_ext::Properties { id, .. } = &properties;
            (id.get(), finterfaces_ext::PropertiesAndState { properties, state: () })
        })
        .collect();
        let () = shortlist_interfaces(name_pattern, &mut interfaces);
        let mut interfaces: Vec<_> = interfaces.into_keys().collect();
        let () = interfaces.sort();
        interfaces
    }

    #[test]
    fn test_shortlist_interfaces() {
        assert_eq!(vec![1, 10, 20, 30, 100, 200, 300], shortlist_interfaces_by_nicid(""));
        assert_eq!(vec![0_u64; 0], shortlist_interfaces_by_nicid("no such thing"));

        assert_eq!(vec![1], shortlist_interfaces_by_nicid("lo"));
        assert_eq!(vec![10, 20, 30], shortlist_interfaces_by_nicid("eth"));
        assert_eq!(vec![10, 20, 30], shortlist_interfaces_by_nicid("th"));
        assert_eq!(vec![100, 200, 300], shortlist_interfaces_by_nicid("wlan"));
        assert_eq!(vec![10, 100], shortlist_interfaces_by_nicid("001"));
    }

    #[test_case(fnet::IpVersion::V4, true ; "IPv4 enable routing")]
    #[test_case(fnet::IpVersion::V4, false ; "IPv4 disable routing")]
    #[test_case(fnet::IpVersion::V6, true ; "IPv6 enable routing")]
    #[test_case(fnet::IpVersion::V6, false ; "IPv6 disable routing")]
    #[fasync::run_singlethreaded(test)]
    async fn if_ip_forward(ip_version: fnet::IpVersion, enable: bool) {
        let interface1 = TestInterface { nicid: 1, name: "interface1" };
        let (root_interfaces, mut requests) =
            fidl::endpoints::create_proxy_and_stream::<froot::InterfacesMarker>().unwrap();
        let connector =
            TestConnector { root_interfaces: Some(root_interfaces), ..Default::default() };

        let requests_fut = set_configuration_request(
            &mut requests,
            interface1.nicid,
            |c| extract_ip_forwarding(c, ip_version).expect("extract IP forwarding configuration"),
            enable,
        );
        let mut out = ffx_writer::Writer::new_test(None);
        let do_if_fut = do_if(
            &mut out,
            opts::IfEnum::IpForward(opts::IfIpForward {
                cmd: opts::IfIpForwardEnum::Set(opts::IfIpForwardSet {
                    interface: interface1.identifier(false /* use_ifname */),
                    ip_version,
                    enable,
                }),
            }),
            &connector,
        );
        let ((), ()) = futures::future::try_join(do_if_fut, requests_fut.map(Ok))
            .await
            .expect("setting interface ip forwarding should succeed");

        let requests_fut = get_configuration_request(
            &mut requests,
            interface1.nicid,
            configuration_with_ip_forwarding_set(ip_version, enable),
        );
        let mut output_buf = ffx_writer::Writer::new_test(None);
        let do_if_fut = do_if(
            &mut output_buf,
            opts::IfEnum::IpForward(opts::IfIpForward {
                cmd: opts::IfIpForwardEnum::Get(opts::IfIpForwardGet {
                    interface: interface1.identifier(false /* use_ifname */),
                    ip_version,
                }),
            }),
            &connector,
        );
        let ((), ()) = futures::future::try_join(do_if_fut, requests_fut.map(Ok))
            .await
            .expect("getting interface ip forwarding should succeed");
        let got_output = output_buf.test_output().unwrap();
        pretty_assertions::assert_eq!(
            trim_whitespace_for_comparison(&got_output),
            trim_whitespace_for_comparison(&format!(
                "IP forwarding for {:?} is {} on interface {}",
                ip_version, enable, interface1.nicid
            )),
        )
    }

    async fn set_configuration_request<
        O: Debug + PartialEq,
        F: FnOnce(finterfaces_admin::Configuration) -> O,
    >(
        requests: &mut froot::InterfacesRequestStream,
        expected_nicid: u64,
        extract_config: F,
        expected_config: O,
    ) {
        let (id, control, _control_handle) = requests
            .next()
            .await
            .expect("root request stream not ended")
            .expect("root request stream not error")
            .into_get_admin()
            .expect("get admin request");
        assert_eq!(id, expected_nicid);

        let mut control: finterfaces_admin::ControlRequestStream =
            control.into_stream().expect("control request stream");
        let (configuration, responder) = control
            .next()
            .await
            .expect("control request stream not ended")
            .expect("control request stream not error")
            .into_set_configuration()
            .expect("set configuration request");
        assert_eq!(extract_config(configuration), expected_config);
        // net-cli does not check the returned configuration so we do not
        // return a populated one.
        let () = responder.send(Ok(&Default::default())).expect("responder.send should succeed");
    }

    async fn get_configuration_request(
        requests: &mut froot::InterfacesRequestStream,
        expected_nicid: u64,
        config: finterfaces_admin::Configuration,
    ) {
        let (id, control, _control_handle) = requests
            .next()
            .await
            .expect("root request stream not ended")
            .expect("root request stream not error")
            .into_get_admin()
            .expect("get admin request");
        assert_eq!(id, expected_nicid);

        let mut control: finterfaces_admin::ControlRequestStream =
            control.into_stream().expect("control request stream");
        let responder = control
            .next()
            .await
            .expect("control request stream not ended")
            .expect("control request stream not error")
            .into_get_configuration()
            .expect("get configuration request");
        let () = responder.send(Ok(&config)).expect("responder.send should succeed");
    }

    #[test_case(finterfaces_admin::IgmpVersion::V1)]
    #[test_case(finterfaces_admin::IgmpVersion::V2)]
    #[test_case(finterfaces_admin::IgmpVersion::V3)]
    #[fasync::run_singlethreaded(test)]
    async fn if_igmp(igmp_version: finterfaces_admin::IgmpVersion) {
        let interface1 = TestInterface { nicid: 1, name: "interface1" };
        let (root_interfaces, mut requests) =
            fidl::endpoints::create_proxy_and_stream::<froot::InterfacesMarker>().unwrap();
        let connector =
            TestConnector { root_interfaces: Some(root_interfaces), ..Default::default() };

        let requests_fut = set_configuration_request(
            &mut requests,
            interface1.nicid,
            |c| extract_igmp_version(c).unwrap(),
            Some(igmp_version),
        );
        let mut out = ffx_writer::Writer::new_test(None);
        let do_if_fut = do_if(
            &mut out,
            opts::IfEnum::Igmp(opts::IfIgmp {
                cmd: opts::IfIgmpEnum::Set(opts::IfIgmpSet {
                    interface: interface1.identifier(false /* use_ifname */),
                    version: Some(igmp_version),
                }),
            }),
            &connector,
        );
        let ((), ()) = futures::future::try_join(do_if_fut, requests_fut.map(Ok))
            .await
            .expect("setting interface IGMP configuration should succeed");

        let requests_fut = get_configuration_request(
            &mut requests,
            interface1.nicid,
            finterfaces_admin::Configuration {
                ipv4: Some(finterfaces_admin::Ipv4Configuration {
                    igmp: Some(finterfaces_admin::IgmpConfiguration {
                        version: Some(igmp_version),
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
                ..Default::default()
            },
        );
        let mut output_buf = ffx_writer::Writer::new_test(None);
        let do_if_fut = do_if(
            &mut output_buf,
            opts::IfEnum::Igmp(opts::IfIgmp {
                cmd: opts::IfIgmpEnum::Get(opts::IfIgmpGet {
                    interface: interface1.identifier(false /* use_ifname */),
                }),
            }),
            &connector,
        );
        let ((), ()) = futures::future::try_join(do_if_fut, requests_fut.map(Ok))
            .await
            .expect("getting interface IGMP configuration should succeed");
        let got_output = output_buf.test_output().unwrap();
        pretty_assertions::assert_eq!(
            trim_whitespace_for_comparison(&got_output),
            trim_whitespace_for_comparison(&format!(
                "IGMP configuration on interface {}:\n    Version: {:?}",
                interface1.nicid,
                Some(igmp_version),
            )),
        )
    }

    #[test_case(finterfaces_admin::MldVersion::V1)]
    #[test_case(finterfaces_admin::MldVersion::V2)]
    #[fasync::run_singlethreaded(test)]
    async fn if_mld(mld_version: finterfaces_admin::MldVersion) {
        let interface1 = TestInterface { nicid: 1, name: "interface1" };
        let (root_interfaces, mut requests) =
            fidl::endpoints::create_proxy_and_stream::<froot::InterfacesMarker>().unwrap();
        let connector =
            TestConnector { root_interfaces: Some(root_interfaces), ..Default::default() };

        let requests_fut = set_configuration_request(
            &mut requests,
            interface1.nicid,
            |c| extract_mld_version(c).unwrap(),
            Some(mld_version),
        );
        let mut out = ffx_writer::Writer::new_test(None);
        let do_if_fut = do_if(
            &mut out,
            opts::IfEnum::Mld(opts::IfMld {
                cmd: opts::IfMldEnum::Set(opts::IfMldSet {
                    interface: interface1.identifier(false /* use_ifname */),
                    version: Some(mld_version),
                }),
            }),
            &connector,
        );
        let ((), ()) = futures::future::try_join(do_if_fut, requests_fut.map(Ok))
            .await
            .expect("setting interface MLD configuration should succeed");

        let requests_fut = get_configuration_request(
            &mut requests,
            interface1.nicid,
            finterfaces_admin::Configuration {
                ipv6: Some(finterfaces_admin::Ipv6Configuration {
                    mld: Some(finterfaces_admin::MldConfiguration {
                        version: Some(mld_version),
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
                ..Default::default()
            },
        );
        let mut output_buf = ffx_writer::Writer::new_test(None);
        let do_if_fut = do_if(
            &mut output_buf,
            opts::IfEnum::Mld(opts::IfMld {
                cmd: opts::IfMldEnum::Get(opts::IfMldGet {
                    interface: interface1.identifier(false /* use_ifname */),
                }),
            }),
            &connector,
        );
        let ((), ()) = futures::future::try_join(do_if_fut, requests_fut.map(Ok))
            .await
            .expect("getting interface MLD configuration should succeed");
        let got_output = output_buf.test_output().unwrap();
        pretty_assertions::assert_eq!(
            trim_whitespace_for_comparison(&got_output),
            trim_whitespace_for_comparison(&format!(
                "MLD configuration on interface {}:\n    Version: {:?}",
                interface1.nicid,
                Some(mld_version),
            )),
        )
    }

    async fn always_answer_with_interfaces(
        interfaces_state_requests: finterfaces::StateRequestStream,
        interfaces: Vec<finterfaces::Properties>,
    ) {
        interfaces_state_requests
            .try_for_each(|request| {
                let interfaces = interfaces.clone();
                async move {
                    let (finterfaces::WatcherOptions { .. }, server_end, _): (
                        _,
                        _,
                        finterfaces::StateControlHandle,
                    ) = request.into_get_watcher().expect("request type should be GetWatcher");

                    let mut watcher_request_stream: finterfaces::WatcherRequestStream =
                        server_end.into_stream().expect("watcher FIDL error");

                    for event in interfaces
                        .into_iter()
                        .map(finterfaces::Event::Existing)
                        .chain(std::iter::once(finterfaces::Event::Idle(finterfaces::Empty)))
                    {
                        let () = watcher_request_stream
                            .try_next()
                            .await
                            .expect("watcher watch FIDL error")
                            .expect("watcher request stream should not have ended")
                            .into_watch()
                            .expect("request should be of type Watch")
                            .send(&event)
                            .expect("responder.send should succeed");
                    }

                    assert_matches!(
                        watcher_request_stream.try_next().await.expect("watcher watch FIDL error"),
                        None,
                        "remaining watcher request stream should be empty"
                    );
                    Ok(())
                }
            })
            .await
            .expect("interfaces state FIDL error")
    }

    #[derive(Clone)]
    struct TestInterface {
        nicid: u64,
        name: &'static str,
    }

    impl TestInterface {
        fn identifier(&self, use_ifname: bool) -> opts::InterfaceIdentifier {
            let Self { nicid, name } = self;
            if use_ifname {
                opts::InterfaceIdentifier::Name(name.to_string())
            } else {
                opts::InterfaceIdentifier::Id(*nicid)
            }
        }
    }

    #[test_case(true, false ; "when interface is up, and adding subnet route")]
    #[test_case(true, true ; "when interface is up, and not adding subnet route")]
    #[test_case(false, false ; "when interface is down, and adding subnet route")]
    #[test_case(false, true ; "when interface is down, and not adding subnet route")]
    #[fasync::run_singlethreaded(test)]
    async fn if_addr_add(interface_is_up: bool, no_subnet_route: bool) {
        const TEST_PREFIX_LENGTH: u8 = 64;

        let interface1 = TestInterface { nicid: 1, name: "interface1" };
        let (root_interfaces, mut requests) =
            fidl::endpoints::create_proxy_and_stream::<froot::InterfacesMarker>().unwrap();

        let connector =
            TestConnector { root_interfaces: Some(root_interfaces), ..Default::default() };
        let mut out = ffx_writer::Writer::new_test(None);
        let do_if_fut = do_if(
            &mut out,
            opts::IfEnum::Addr(opts::IfAddr {
                addr_cmd: opts::IfAddrEnum::Add(opts::IfAddrAdd {
                    interface: interface1.identifier(false /* use_ifname */),
                    addr: fnet_ext::IpAddress::from(IF_ADDR_V6.addr).to_string(),
                    prefix: TEST_PREFIX_LENGTH,
                    no_subnet_route,
                }),
            }),
            &connector,
        )
        .map(|res| res.expect("success"));

        let admin_fut = async {
            let (id, control, _control_handle) = requests
                .next()
                .await
                .expect("root request stream not ended")
                .expect("root request stream not error")
                .into_get_admin()
                .expect("get admin request");
            assert_eq!(id, interface1.nicid);

            let mut control: finterfaces_admin::ControlRequestStream =
                control.into_stream().expect("control request stream");
            let (
                addr,
                addr_params,
                address_state_provider_server_end,
                _admin_control_control_handle,
            ) = control
                .next()
                .await
                .expect("control request stream not ended")
                .expect("control request stream not error")
                .into_add_address()
                .expect("add address request");
            assert_eq!(addr, IF_ADDR_V6);
            assert_eq!(
                addr_params,
                finterfaces_admin::AddressParameters {
                    add_subnet_route: Some(!no_subnet_route),
                    ..Default::default()
                }
            );

            let mut address_state_provider_request_stream = address_state_provider_server_end
                .into_stream()
                .expect("address state provider FIDL error");
            async fn next_request(
                stream: &mut finterfaces_admin::AddressStateProviderRequestStream,
            ) -> finterfaces_admin::AddressStateProviderRequest {
                stream
                    .next()
                    .await
                    .expect("address state provider request stream not ended")
                    .expect("address state provider request stream not error")
            }

            let _address_state_provider_control_handle =
                next_request(&mut address_state_provider_request_stream)
                    .await
                    .into_detach()
                    .expect("detach request");

            for _ in 0..3 {
                let () = next_request(&mut address_state_provider_request_stream)
                    .await
                    .into_watch_address_assignment_state()
                    .expect("watch address assignment state request")
                    .send(finterfaces::AddressAssignmentState::Tentative)
                    .expect("send address assignment state succeeds");
            }

            let () = next_request(&mut address_state_provider_request_stream)
                .await
                .into_watch_address_assignment_state()
                .expect("watch address assignment state request")
                .send(if interface_is_up {
                    finterfaces::AddressAssignmentState::Assigned
                } else {
                    finterfaces::AddressAssignmentState::Unavailable
                })
                .expect("send address assignment state succeeds");
        };

        let ((), ()) = futures::join!(admin_fut, do_if_fut);
    }

    #[test_case(false ; "providing nicids")]
    #[test_case(true ; "providing interface names")]
    #[fasync::run_singlethreaded(test)]
    async fn if_del_addr(use_ifname: bool) {
        let interface1 = TestInterface { nicid: 1, name: "interface1" };
        let interface2 = TestInterface { nicid: 2, name: "interface2" };

        let (root_interfaces, mut requests) =
            fidl::endpoints::create_proxy_and_stream::<froot::InterfacesMarker>().unwrap();
        let (interfaces_state, interfaces_requests) =
            fidl::endpoints::create_proxy_and_stream::<finterfaces::StateMarker>().unwrap();

        let (interface1_properties, _mac) = get_fake_interface(
            interface1.nicid,
            interface1.name,
            finterfaces::DeviceClass::Device(fhardware_network::DeviceClass::Ethernet),
            None,
        );

        let interfaces_fut =
            always_answer_with_interfaces(interfaces_requests, vec![interface1_properties.into()])
                .fuse();
        futures::pin_mut!(interfaces_fut);

        let connector = TestConnector {
            root_interfaces: Some(root_interfaces),
            interfaces_state: Some(interfaces_state),
            ..Default::default()
        };

        let mut out = ffx_writer::Writer::new_test(None);
        // Make the first request.
        let succeeds = do_if(
            &mut out,
            opts::IfEnum::Addr(opts::IfAddr {
                addr_cmd: opts::IfAddrEnum::Del(opts::IfAddrDel {
                    interface: interface1.identifier(use_ifname),
                    addr: fnet_ext::IpAddress::from(IF_ADDR_V4.addr).to_string(),
                    prefix: None, // The prefix should be set to the default of 32 for IPv4.
                }),
            }),
            &connector,
        )
        .map(|res| res.expect("success"));
        let handler_fut = async {
            let (id, control, _control_handle) = requests
                .next()
                .await
                .expect("root request stream not ended")
                .expect("root request stream not error")
                .into_get_admin()
                .expect("get admin request");
            assert_eq!(id, interface1.nicid);
            let mut control = control.into_stream().expect("control request stream");
            let (addr, responder) = control
                .next()
                .await
                .expect("control request stream not ended")
                .expect("control request stream not error")
                .into_remove_address()
                .expect("del address request");
            assert_eq!(addr, IF_ADDR_V4);
            let () = responder.send(Ok(true)).expect("responder send");
        };

        futures::select! {
            () = interfaces_fut => panic!("interfaces_fut should never complete"),
            ((), ()) = futures::future::join(handler_fut, succeeds).fuse() => {},
        }

        let mut out = ffx_writer::Writer::new_test(None);
        // Make the second request.
        let fails = do_if(
            &mut out,
            opts::IfEnum::Addr(opts::IfAddr {
                addr_cmd: opts::IfAddrEnum::Del(opts::IfAddrDel {
                    interface: interface2.identifier(use_ifname),
                    addr: fnet_ext::IpAddress::from(IF_ADDR_V6.addr).to_string(),
                    prefix: Some(IF_ADDR_V6.prefix_len),
                }),
            }),
            &connector,
        )
        .map(|res| res.expect_err("failure"));

        if use_ifname {
            // The caller will have failed to find an interface matching the name,
            // so we don't expect any requests to make it to us.
            futures::select! {
                () = interfaces_fut => panic!("interfaces_fut should never complete"),
                e = fails.fuse() => {
                    assert_eq!(e.to_string(), format!("No interface with name {}", interface2.name));
                },
            }
        } else {
            let handler_fut = async {
                let (id, control, _control_handle) = requests
                    .next()
                    .await
                    .expect("root request stream not ended")
                    .expect("root request stream not error")
                    .into_get_admin()
                    .expect("get admin request");
                assert_eq!(id, interface2.nicid);
                let mut control = control.into_stream().expect("control request stream");
                let (addr, responder) = control
                    .next()
                    .await
                    .expect("control request stream not ended")
                    .expect("control request stream not error")
                    .into_remove_address()
                    .expect("del address request");
                assert_eq!(addr, IF_ADDR_V6);
                let () = responder.send(Ok(false)).expect("responder send");
            };
            futures::select! {
                () = interfaces_fut => panic!("interfaces_fut should never complete"),
                ((), e) = futures::future::join(handler_fut, fails).fuse() => {
                    let fnet_ext::IpAddress(addr) = IF_ADDR_V6.addr.into();
                    assert_eq!(e.to_string(), format!("Address {} not found on interface {}", addr, interface2.nicid));
                },
            }
        }
    }

    const INTERFACE_NAME: &str = "if1";

    fn interface_properties(
        addrs: Vec<(fnet::Subnet, finterfaces::AddressAssignmentState)>,
    ) -> finterfaces::Properties {
        finterfaces_ext::Properties {
            id: INTERFACE_ID.try_into().unwrap(),
            name: INTERFACE_NAME.to_string(),
            device_class: finterfaces::DeviceClass::Device(
                fhardware_network::DeviceClass::Ethernet,
            ),
            online: true,
            addresses: addrs
                .into_iter()
                .map(|(addr, assignment_state)| finterfaces_ext::Address {
                    addr,
                    assignment_state,
                    valid_until: fuchsia_zircon_types::ZX_TIME_INFINITE,
                })
                .collect(),
            has_default_ipv4_route: false,
            has_default_ipv6_route: false,
        }
        .into()
    }

    #[test_case(
        false,
        vec![
            finterfaces::Event::Existing(interface_properties(vec![])),
            finterfaces::Event::Idle(finterfaces::Empty),
            finterfaces::Event::Changed(interface_properties(vec![
                (fidl_subnet!("192.168.0.1/32"), finterfaces::AddressAssignmentState::Assigned)
            ])),
        ],
        "192.168.0.1";
        "wait for an address to be assigned"
    )]
    #[test_case(
        false,
        vec![
            finterfaces::Event::Existing(interface_properties(vec![
                (fidl_subnet!("192.168.0.1/32"), finterfaces::AddressAssignmentState::Assigned),
                (fidl_subnet!("fd00::1/64"), finterfaces::AddressAssignmentState::Assigned),
            ])),
        ],
        "192.168.0.1";
        "prefer first when any address requested"
    )]
    #[test_case(
        true,
        vec![
            finterfaces::Event::Existing(interface_properties(vec![
                (fidl_subnet!("192.168.0.1/32"), finterfaces::AddressAssignmentState::Assigned)
            ])),
            finterfaces::Event::Idle(finterfaces::Empty),
            finterfaces::Event::Changed(interface_properties(vec![
                (fidl_subnet!("fd00::1/64"), finterfaces::AddressAssignmentState::Assigned)
            ])),
        ],
        "fd00::1";
        "wait for IPv6 when IPv6 address requested"
    )]
    #[fasync::run_singlethreaded(test)]
    async fn if_addr_wait(ipv6: bool, events: Vec<finterfaces::Event>, expected_output: &str) {
        let interface = TestInterface { nicid: INTERFACE_ID, name: INTERFACE_NAME };

        let (interfaces_state, mut request_stream) =
            fidl::endpoints::create_proxy_and_stream::<finterfaces::StateMarker>().unwrap();

        let interfaces_handler = async move {
            let (finterfaces::WatcherOptions { include_non_assigned_addresses, .. }, server_end, _) =
                request_stream
                    .next()
                    .await
                    .expect("should call state")
                    .expect("should succeed")
                    .into_get_watcher()
                    .expect("request should be GetWatcher");
            assert_eq!(include_non_assigned_addresses, Some(false));
            let mut request_stream: finterfaces::WatcherRequestStream =
                server_end.into_stream().expect("server end into request stream");
            for event in events {
                request_stream
                    .next()
                    .await
                    .expect("should call watcher")
                    .expect("should succeed")
                    .into_watch()
                    .expect("request should be Watch")
                    .send(&event)
                    .expect("send response");
            }
        };

        let connector =
            TestConnector { interfaces_state: Some(interfaces_state), ..Default::default() };
        let mut out = ffx_writer::Writer::new_test(None);
        let run_command = do_if(
            &mut out,
            opts::IfEnum::Addr(opts::IfAddr {
                addr_cmd: opts::IfAddrEnum::Wait(opts::IfAddrWait {
                    interface: interface.identifier(false),
                    ipv6,
                }),
            }),
            &connector,
        )
        .map(|r| r.expect("command should succeed"));

        let ((), ()) = futures::future::join(interfaces_handler, run_command).await;

        let output = out.test_output().unwrap();
        pretty_assertions::assert_eq!(
            trim_whitespace_for_comparison(&output),
            trim_whitespace_for_comparison(expected_output),
        );
    }

    fn wanted_net_if_list_json() -> String {
        json!([
            {
                "addresses": {
                    "ipv4": [],
                    "ipv6": [],
                },
                "device_class": "Loopback",
                "mac": "00:00:00:00:00:00",
                "name": "lo",
                "nicid": 1,
                "online": true,
                "has_default_ipv4_route": false,
                "has_default_ipv6_route": false,
            },
            {
                "addresses": {
                    "ipv4": [],
                    "ipv6": [],
                },
                "device_class": "Ethernet",
                "mac": "01:02:03:04:05:06",
                "name": "eth001",
                "nicid": 10,
                "online": true,
                "has_default_ipv4_route": false,
                "has_default_ipv6_route": false,
            },
            {
                "addresses": {
                    "ipv4": [],
                    "ipv6": [],
                },
                "device_class": "Virtual",
                "mac": null,
                "name": "virt001",
                "nicid": 20,
                "online": true,
                "has_default_ipv4_route": false,
                "has_default_ipv6_route": false,
            },
            {
                "addresses": {
                    "ipv4": [
                        {
                            "addr": "192.168.0.1",
                            "assignment_state": "Tentative",
                            "prefix_len": 24,
                            "valid_until": 2500000000_u64,
                        }
                    ],
                    "ipv6": [],
                },
                "device_class": "Ethernet",
                "mac": null,
                "name": "eth002",
                "nicid": 30,
                "online": true,
                "has_default_ipv4_route": false,
                "has_default_ipv6_route": true,
            },
            {
                "addresses": {
                    "ipv4": [],
                    "ipv6": [{
                        "addr": "2001:db8::1",
                        "assignment_state": "Unavailable",
                        "prefix_len": 64,
                        "valid_until": null,
                    }],
                },
                "device_class": "Ethernet",
                "mac": null,
                "name": "eth003",
                "nicid": 40,
                "online": true,
                "has_default_ipv4_route": true,
                "has_default_ipv6_route": true,
            },
        ])
        .to_string()
    }

    fn wanted_net_if_list_tabular() -> String {
        String::from(
            r#"
nicid             1
name              lo
device class      loopback
online            true
default routes    -
mac               00:00:00:00:00:00

nicid             10
name              eth001
device class      ethernet
online            true
default routes    -
mac               01:02:03:04:05:06

nicid             20
name              virt001
device class      virtual
online            true
default routes    -
mac               -

nicid             30
name              eth002
device class      ethernet
online            true
default routes    IPv6
addr              192.168.0.1/24       TENTATIVE valid until [2.5s]
mac               -

nicid             40
name              eth003
device class      ethernet
online            true
default routes    IPv4,IPv6
addr              2001:db8::1/64       UNAVAILABLE
mac               -
"#,
        )
    }

    #[test_case(true, wanted_net_if_list_json() ; "in json format")]
    #[test_case(false, wanted_net_if_list_tabular() ; "in tabular format")]
    #[fasync::run_singlethreaded(test)]
    async fn if_list(json: bool, wanted_output: String) {
        let (root_interfaces, root_interfaces_stream) =
            fidl::endpoints::create_proxy_and_stream::<froot::InterfacesMarker>().unwrap();
        let (interfaces_state, interfaces_state_stream) =
            fidl::endpoints::create_proxy_and_stream::<finterfaces::StateMarker>().unwrap();

        let mut output = if json {
            ffx_writer::Writer::new_test(Some(ffx_writer::Format::Json))
        } else {
            ffx_writer::Writer::new_test(None)
        };
        let output_ref = &mut output;

        let do_if_fut = async {
            let connector = TestConnector {
                root_interfaces: Some(root_interfaces),
                interfaces_state: Some(interfaces_state),
                ..Default::default()
            };
            do_if(output_ref, opts::IfEnum::List(opts::IfList { name_pattern: None }), &connector)
                .map(|res| res.expect("if list"))
                .await
        };
        let watcher_stream = interfaces_state_stream
            .and_then(|req| match req {
                finterfaces::StateRequest::GetWatcher {
                    options: _,
                    watcher,
                    control_handle: _,
                } => futures::future::ready(watcher.into_stream()),
            })
            .try_flatten()
            .map(|res| res.expect("watcher stream error"));
        let (interfaces, mac_addresses): (Vec<_>, HashMap<_, _>) = [
            get_fake_interface(
                1,
                "lo",
                finterfaces::DeviceClass::Loopback(finterfaces::Empty),
                Some([0, 0, 0, 0, 0, 0]),
            ),
            get_fake_interface(
                10,
                "eth001",
                finterfaces::DeviceClass::Device(fhardware_network::DeviceClass::Ethernet),
                Some([1, 2, 3, 4, 5, 6]),
            ),
            get_fake_interface(
                20,
                "virt001",
                finterfaces::DeviceClass::Device(fhardware_network::DeviceClass::Virtual),
                None,
            ),
            (
                finterfaces_ext::Properties {
                    id: 30.try_into().unwrap(),
                    name: "eth002".to_string(),
                    device_class: finterfaces::DeviceClass::Device(
                        fhardware_network::DeviceClass::Ethernet,
                    ),
                    online: true,
                    addresses: vec![finterfaces_ext::Address {
                        addr: fidl_subnet!("192.168.0.1/24"),
                        valid_until: std::time::Duration::from_millis(2500)
                            .as_nanos()
                            .try_into()
                            .unwrap(),
                        assignment_state: finterfaces::AddressAssignmentState::Tentative,
                    }],
                    has_default_ipv4_route: false,
                    has_default_ipv6_route: true,
                },
                None,
            ),
            (
                finterfaces_ext::Properties {
                    id: 40.try_into().unwrap(),
                    name: "eth003".to_string(),
                    device_class: finterfaces::DeviceClass::Device(
                        fhardware_network::DeviceClass::Ethernet,
                    ),
                    online: true,
                    addresses: vec![finterfaces_ext::Address {
                        addr: fidl_subnet!("2001:db8::1/64"),
                        valid_until: i64::MAX,
                        assignment_state: finterfaces::AddressAssignmentState::Unavailable,
                    }],
                    has_default_ipv4_route: true,
                    has_default_ipv6_route: true,
                },
                None,
            ),
        ]
        .into_iter()
        .map(|(properties, mac)| {
            let finterfaces_ext::Properties { id, .. } = &properties;
            let id = *id;
            (properties, (id, mac))
        })
        .unzip();
        let interfaces =
            futures::stream::iter(interfaces.into_iter().map(Some).chain(std::iter::once(None)));
        let watcher_fut = watcher_stream.zip(interfaces).for_each(|(req, properties)| match req {
            finterfaces::WatcherRequest::Watch { responder } => {
                let event = properties.map_or(
                    finterfaces::Event::Idle(finterfaces::Empty),
                    |finterfaces_ext::Properties {
                         id,
                         name,
                         device_class,
                         online,
                         addresses,
                         has_default_ipv4_route,
                         has_default_ipv6_route,
                     }| {
                        finterfaces::Event::Existing(finterfaces::Properties {
                            id: Some(id.get()),
                            name: Some(name),
                            device_class: Some(device_class),
                            online: Some(online),
                            addresses: Some(
                                addresses
                                    .into_iter()
                                    .map(
                                        |finterfaces_ext::Address {
                                             addr,
                                             valid_until,
                                             assignment_state,
                                         }| {
                                            finterfaces::Address {
                                                addr: Some(addr),
                                                valid_until: Some(valid_until),
                                                assignment_state: Some(assignment_state),
                                                ..Default::default()
                                            }
                                        },
                                    )
                                    .collect(),
                            ),
                            has_default_ipv4_route: Some(has_default_ipv4_route),
                            has_default_ipv6_route: Some(has_default_ipv6_route),
                            ..Default::default()
                        })
                    },
                );
                let () = responder.send(&event).expect("send watcher event");
                futures::future::ready(())
            }
        });
        let root_fut = root_interfaces_stream
            .map(|res| res.expect("root interfaces stream error"))
            .for_each_concurrent(None, |req| {
                let (id, responder) = req.into_get_mac().expect("get_mac request");
                let () = responder
                    .send(
                        mac_addresses
                            .get(&id.try_into().unwrap())
                            .map(Option::as_ref)
                            .ok_or(froot::InterfacesGetMacError::NotFound),
                    )
                    .expect("send get_mac response");
                futures::future::ready(())
            });
        let ((), (), ()) = futures::future::join3(do_if_fut, watcher_fut, root_fut).await;

        let got_output = output.test_output().unwrap();

        if json {
            let got: Value = serde_json::from_str(&got_output).unwrap();
            let want: Value = serde_json::from_str(&wanted_output).unwrap();
            pretty_assertions::assert_eq!(got, want);
        } else {
            pretty_assertions::assert_eq!(
                trim_whitespace_for_comparison(&got_output),
                trim_whitespace_for_comparison(&wanted_output),
            );
        }
    }

    async fn test_do_dhcp(cmd: opts::DhcpEnum) {
        let (stack, mut requests) =
            fidl::endpoints::create_proxy_and_stream::<fstack::StackMarker>().unwrap();
        let connector = TestConnector { stack: Some(stack), ..Default::default() };
        let op = do_dhcp(cmd.clone(), &connector);
        let op_succeeds = async move {
            let (expected_id, expected_enable) = match cmd {
                opts::DhcpEnum::Start(opts::DhcpStart { interface }) => (interface, true),
                opts::DhcpEnum::Stop(opts::DhcpStop { interface }) => (interface, false),
            };
            let request = requests
                .try_next()
                .await
                .expect("start FIDL error")
                .expect("request stream should not have ended");
            let (received_id, enable, responder) = request
                .into_set_dhcp_client_enabled()
                .expect("request should be of type StopDhcpClient");
            assert_eq!(opts::InterfaceIdentifier::Id(u64::from(received_id)), expected_id);
            assert_eq!(enable, expected_enable);
            responder.send(Ok(())).map_err(anyhow::Error::new)
        };
        let ((), ()) =
            futures::future::try_join(op, op_succeeds).await.expect("dhcp command should succeed");
    }

    #[fasync::run_singlethreaded(test)]
    async fn dhcp_start() {
        let () = test_do_dhcp(opts::DhcpEnum::Start(opts::DhcpStart { interface: 1.into() })).await;
    }

    #[fasync::run_singlethreaded(test)]
    async fn dhcp_stop() {
        let () = test_do_dhcp(opts::DhcpEnum::Stop(opts::DhcpStop { interface: 1.into() })).await;
    }

    async fn test_modify_route(cmd: opts::RouteEnum) {
        let expected_interface = match &cmd {
            opts::RouteEnum::List(_) => panic!("test_modify_route should not take a List command"),
            opts::RouteEnum::Add(opts::RouteAdd { interface, .. }) => interface,
            opts::RouteEnum::Del(opts::RouteDel { interface, .. }) => interface,
        }
        .clone();
        let expected_id = match expected_interface {
            opts::InterfaceIdentifier::Id(ref id) => *id,
            opts::InterfaceIdentifier::Name(_) => {
                panic!("expected test to work only with ids")
            }
        };

        let (stack, mut requests) =
            fidl::endpoints::create_proxy_and_stream::<fstack::StackMarker>().unwrap();
        let connector = TestConnector { stack: Some(stack), ..Default::default() };
        let mut out = ffx_writer::Writer::new_test(None);
        let op = do_route(&mut out, cmd.clone(), &connector);
        let op_succeeds = async move {
            let () = match cmd {
                opts::RouteEnum::List(opts::RouteList {}) => {
                    panic!("test_modify_route should not take a List command")
                }
                opts::RouteEnum::Add(route) => {
                    let expected_entry = route.into_route_table_entry(
                        expected_id.try_into().expect("nicid does not fit in u32"),
                    );
                    let (entry, responder) = requests
                        .try_next()
                        .await
                        .expect("add route FIDL error")
                        .expect("request stream should not have ended")
                        .into_add_forwarding_entry()
                        .expect("request should be of type AddRoute");
                    assert_eq!(entry, expected_entry);
                    responder.send(Ok(()))
                }
                opts::RouteEnum::Del(route) => {
                    let expected_entry = route.into_route_table_entry(
                        expected_id.try_into().expect("nicid does not fit in u32"),
                    );
                    let (entry, responder) = requests
                        .try_next()
                        .await
                        .expect("del route FIDL error")
                        .expect("request stream should not have ended")
                        .into_del_forwarding_entry()
                        .expect("request should be of type DelRoute");
                    assert_eq!(entry, expected_entry);
                    responder.send(Ok(()))
                }
            }?;
            Ok(())
        };
        let ((), ()) =
            futures::future::try_join(op, op_succeeds).await.expect("dhcp command should succeed");
    }

    #[fasync::run_singlethreaded(test)]
    async fn route_add() {
        // Test arguments have been arbitrarily selected.
        let () = test_modify_route(opts::RouteEnum::Add(opts::RouteAdd {
            destination: std::net::IpAddr::V4(std::net::Ipv4Addr::new(192, 168, 1, 0)),
            prefix_len: 24,
            gateway: None,
            interface: 2.into(),
            metric: 100,
        }))
        .await;
    }

    #[fasync::run_singlethreaded(test)]
    async fn route_del() {
        // Test arguments have been arbitrarily selected.
        let () = test_modify_route(opts::RouteEnum::Del(opts::RouteDel {
            destination: std::net::IpAddr::V4(std::net::Ipv4Addr::new(192, 168, 1, 0)),
            prefix_len: 24,
            gateway: None,
            interface: 2.into(),
            metric: 100,
        }))
        .await;
    }

    fn wanted_route_list_json() -> String {
        json!([
            {
                "destination":{"addr":"1.1.1.0","prefix_len":24},
                "gateway":"1.1.1.2",
                "metric":4,
                "nicid":3
            },
            {
                "destination":{"addr":"10.10.10.0","prefix_len":24},
                "gateway":"10.10.10.20",
                "metric":40,
                "nicid":30
            },
            {
                "destination":{"addr":"fe80::","prefix_len":64},
                "gateway":serde_json::Value::Null,
                "metric":400,
                "nicid":300
            }

        ])
        .to_string()
    }

    fn wanted_route_list_tabular() -> String {
        "Destination      Gateway        NICID    Metric
         1.1.1.0/24       1.1.1.2        3        4
         10.10.10.0/24    10.10.10.20    30       40
         fe80::/64        -              300      400
         "
        .to_string()
    }

    #[test_case(true, wanted_route_list_json() ; "in json format")]
    #[test_case(false, wanted_route_list_tabular() ; "in tabular format")]
    #[fasync::run_singlethreaded(test)]
    async fn route_list(json: bool, wanted_output: String) {
        let (routes_v4_controller, mut routes_v4_state_stream) =
            fidl::endpoints::create_proxy_and_stream::<froutes::StateV4Marker>().unwrap();
        let (routes_v6_controller, mut routes_v6_state_stream) =
            fidl::endpoints::create_proxy_and_stream::<froutes::StateV6Marker>().unwrap();
        let connector = TestConnector {
            routes_v4: Some(routes_v4_controller),
            routes_v6: Some(routes_v6_controller),
            ..Default::default()
        };

        let mut output = if json {
            ffx_writer::Writer::new_test(Some(ffx_writer::Format::Json))
        } else {
            ffx_writer::Writer::new_test(None)
        };

        let do_route_fut =
            do_route(&mut output, opts::RouteEnum::List(opts::RouteList {}), &connector);

        let v4_route_events = vec![
            froutes::EventV4::Existing(froutes::InstalledRouteV4 {
                route: Some(froutes::RouteV4 {
                    destination: net_declare::fidl_ip_v4_with_prefix!("1.1.1.0/24"),
                    action: froutes::RouteActionV4::Forward(froutes::RouteTargetV4 {
                        outbound_interface: 3,
                        next_hop: Some(Box::new(net_declare::fidl_ip_v4!("1.1.1.2"))),
                    }),
                    properties: froutes::RoutePropertiesV4 {
                        specified_properties: Some(froutes::SpecifiedRouteProperties {
                            metric: Some(froutes::SpecifiedMetric::ExplicitMetric(4)),
                            ..Default::default()
                        }),
                        ..Default::default()
                    },
                }),
                effective_properties: Some(froutes::EffectiveRouteProperties {
                    metric: Some(4),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            froutes::EventV4::Existing(froutes::InstalledRouteV4 {
                route: Some(froutes::RouteV4 {
                    destination: net_declare::fidl_ip_v4_with_prefix!("10.10.10.0/24"),
                    action: froutes::RouteActionV4::Forward(froutes::RouteTargetV4 {
                        outbound_interface: 30,
                        next_hop: Some(Box::new(net_declare::fidl_ip_v4!("10.10.10.20"))),
                    }),
                    properties: froutes::RoutePropertiesV4 {
                        specified_properties: Some(froutes::SpecifiedRouteProperties {
                            metric: Some(froutes::SpecifiedMetric::ExplicitMetric(40)),
                            ..Default::default()
                        }),
                        ..Default::default()
                    },
                }),
                effective_properties: Some(froutes::EffectiveRouteProperties {
                    metric: Some(40),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            froutes::EventV4::Idle(froutes::Empty),
        ];
        let v6_route_events = vec![
            froutes::EventV6::Existing(froutes::InstalledRouteV6 {
                route: Some(froutes::RouteV6 {
                    destination: net_declare::fidl_ip_v6_with_prefix!("fe80::/64"),
                    action: froutes::RouteActionV6::Forward(froutes::RouteTargetV6 {
                        outbound_interface: 300,
                        next_hop: None,
                    }),
                    properties: froutes::RoutePropertiesV6 {
                        specified_properties: Some(froutes::SpecifiedRouteProperties {
                            metric: Some(froutes::SpecifiedMetric::ExplicitMetric(400)),
                            ..Default::default()
                        }),
                        ..Default::default()
                    },
                }),
                effective_properties: Some(froutes::EffectiveRouteProperties {
                    metric: Some(400),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            froutes::EventV6::Idle(froutes::Empty),
        ];

        let route_v4_fut = routes_v4_state_stream.select_next_some().then(|request| {
            froutes_ext::testutil::serve_state_request::<Ipv4>(
                request,
                futures::stream::once(futures::future::ready(v4_route_events)),
            )
        });
        let route_v6_fut = routes_v6_state_stream.select_next_some().then(|request| {
            froutes_ext::testutil::serve_state_request::<Ipv6>(
                request,
                futures::stream::once(futures::future::ready(v6_route_events)),
            )
        });

        let ((), (), ()) =
            futures::try_join!(do_route_fut, route_v4_fut.map(Ok), route_v6_fut.map(Ok))
                .expect("listing forwarding table entries should succeed");

        let got_output = output.test_output().unwrap();

        if json {
            let got: Value = serde_json::from_str(&got_output).unwrap();
            let want: Value = serde_json::from_str(&wanted_output).unwrap();
            pretty_assertions::assert_eq!(got, want);
        } else {
            pretty_assertions::assert_eq!(
                trim_whitespace_for_comparison(&got_output),
                trim_whitespace_for_comparison(&wanted_output),
            );
        }
    }

    #[test_case(false ; "providing nicids")]
    #[test_case(true ; "providing interface names")]
    #[fasync::run_singlethreaded(test)]
    async fn bridge(use_ifname: bool) {
        let (stack, mut stack_requests) =
            fidl::endpoints::create_proxy_and_stream::<fstack::StackMarker>().unwrap();
        let (interfaces_state, interfaces_state_requests) =
            fidl::endpoints::create_proxy_and_stream::<finterfaces::StateMarker>().unwrap();
        let connector = TestConnector {
            interfaces_state: Some(interfaces_state),
            stack: Some(stack),
            ..Default::default()
        };

        let bridge_ifs = vec![
            TestInterface { nicid: 1, name: "interface1" },
            TestInterface { nicid: 2, name: "interface2" },
            TestInterface { nicid: 3, name: "interface3" },
        ];

        let interface_fidls = bridge_ifs
            .iter()
            .map(|interface| {
                let (interface, _mac) = get_fake_interface(
                    interface.nicid,
                    interface.name,
                    finterfaces::DeviceClass::Device(fhardware_network::DeviceClass::Ethernet),
                    None,
                );
                interface.into()
            })
            .collect::<Vec<_>>();

        let interfaces_fut =
            always_answer_with_interfaces(interfaces_state_requests, interface_fidls);

        let bridge_id = 4;
        let mut out = ffx_writer::Writer::new_test(None);
        let bridge = do_if(
            &mut out,
            opts::IfEnum::Bridge(opts::IfBridge {
                interfaces: bridge_ifs
                    .iter()
                    .map(|interface| interface.identifier(use_ifname))
                    .collect(),
            }),
            &connector,
        );

        let bridge_succeeds = async move {
            let (requested_ifs, bridge_server_end, _control_handle) = stack_requests
                .try_next()
                .await
                .expect("stack requests FIDL error")
                .expect("request stream should not have ended")
                .into_bridge_interfaces()
                .expect("request should be of type BridgeInterfaces");
            assert_eq!(
                requested_ifs,
                bridge_ifs.iter().map(|interface| interface.nicid).collect::<Vec<_>>()
            );
            let mut bridge_requests = bridge_server_end.into_stream().expect("bridge stream");
            let responder = bridge_requests
                .try_next()
                .await
                .expect("bridge requests FIDL error")
                .expect("request stream should not have ended")
                .into_get_id()
                .expect("request should be get_id");
            responder.send(bridge_id).expect("responding with bridge ID should succeed");
            let _control_handle = bridge_requests
                .try_next()
                .await
                .expect("bridge requests FIDL error")
                .expect("request stream should not have ended")
                .into_detach()
                .expect("request should be detach");
            Ok(())
        };
        futures::select! {
            () = interfaces_fut.fuse() => panic!("interfaces_fut should never complete"),
            result = futures::future::try_join(bridge, bridge_succeeds).fuse() => {
                let ((), ()) = result.expect("if bridge should succeed");
            }
        }
    }

    async fn test_get_neigh_entries(
        watch_for_changes: bool,
        batches: Vec<Vec<fneighbor::EntryIteratorItem>>,
        want: String,
    ) {
        let (it, mut requests) =
            fidl::endpoints::create_proxy_and_stream::<fneighbor::EntryIteratorMarker>().unwrap();

        let server = async {
            for items in batches {
                let responder = requests
                    .try_next()
                    .await
                    .expect("neigh FIDL error")
                    .expect("request stream should not have ended")
                    .into_get_next()
                    .expect("request should be of type GetNext");
                let () = responder.send(&items).expect("responder.send should succeed");
            }
        }
        .on_timeout(std::time::Duration::from_secs(60), || panic!("server responder timed out"));

        let client = async {
            let mut stream = neigh_entry_stream(it, watch_for_changes);

            let item_to_string = |item| {
                let mut buf = ffx_writer::Writer::new_test(None);
                let () = write_neigh_entry(&mut buf, item, watch_for_changes)
                    .expect("write_neigh_entry should succeed");
                buf.test_output().expect("string should be UTF-8")
            };

            // Check each string sent by get_neigh_entries
            for want_line in want.lines() {
                let got = stream
                    .next()
                    .await
                    .map(|item| item_to_string(item.expect("neigh_entry_stream should succeed")));
                assert_eq!(got, Some(format!("{}\n", want_line)));
            }

            // When listing entries, the sender should close after sending all existing entries.
            if !watch_for_changes {
                match stream.next().await {
                    Some(Ok(item)) => {
                        panic!("unexpected item from stream: {}", item_to_string(item))
                    }
                    Some(Err(err)) => panic!("unexpected error from stream: {}", err),
                    None => {}
                }
            }
        };

        let ((), ()) = futures::future::join(client, server).await;
    }

    async fn test_neigh_none(watch_for_changes: bool, want: String) {
        test_get_neigh_entries(
            watch_for_changes,
            vec![vec![fneighbor::EntryIteratorItem::Idle(fneighbor::IdleEvent {})]],
            want,
        )
        .await
    }

    #[fasync::run_singlethreaded(test)]
    async fn neigh_list_none() {
        test_neigh_none(false /* watch_for_changes */, "".to_string()).await
    }

    #[fasync::run_singlethreaded(test)]
    async fn neigh_watch_none() {
        test_neigh_none(true /* watch_for_changes */, "IDLE".to_string()).await
    }

    fn timestamp_60s_ago() -> i64 {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::SystemTime::UNIX_EPOCH)
            .expect("failed to get duration since epoch");
        let past = now - std::time::Duration::from_secs(60);
        i64::try_from(past.as_nanos()).expect("failed to convert duration to i64")
    }

    async fn test_neigh_one(watch_for_changes: bool, want: fn(fneighbor_ext::Entry) -> String) {
        fn new_entry(updated_at: i64) -> fneighbor::Entry {
            fneighbor::Entry {
                interface: Some(1),
                neighbor: Some(IF_ADDR_V4.addr),
                state: Some(fneighbor::EntryState::Reachable),
                mac: Some(MAC_1),
                updated_at: Some(updated_at),
                ..Default::default()
            }
        }

        let updated_at = timestamp_60s_ago();

        test_get_neigh_entries(
            watch_for_changes,
            vec![vec![
                fneighbor::EntryIteratorItem::Existing(new_entry(updated_at)),
                fneighbor::EntryIteratorItem::Idle(fneighbor::IdleEvent {}),
            ]],
            want(fneighbor_ext::Entry::try_from(new_entry(updated_at)).unwrap()),
        )
        .await
    }

    #[fasync::run_singlethreaded(test)]
    async fn neigh_list_one() {
        test_neigh_one(false /* watch_for_changes */, |entry| format!("{}\n", entry)).await
    }

    #[fasync::run_singlethreaded(test)]
    async fn neigh_watch_one() {
        test_neigh_one(true /* watch_for_changes */, |entry| {
            format!(
                "EXISTING | {}\n\
                 IDLE\n",
                entry
            )
        })
        .await
    }

    async fn test_neigh_many(
        watch_for_changes: bool,
        want: fn(fneighbor_ext::Entry, fneighbor_ext::Entry) -> String,
    ) {
        fn new_entry(
            ip: fnet::IpAddress,
            mac: fnet::MacAddress,
            updated_at: i64,
        ) -> fneighbor::Entry {
            fneighbor::Entry {
                interface: Some(1),
                neighbor: Some(ip),
                state: Some(fneighbor::EntryState::Reachable),
                mac: Some(mac),
                updated_at: Some(updated_at),
                ..Default::default()
            }
        }

        let updated_at = timestamp_60s_ago();
        let offset = i64::try_from(std::time::Duration::from_secs(60).as_nanos())
            .expect("failed to convert duration to i64");

        test_get_neigh_entries(
            watch_for_changes,
            vec![vec![
                fneighbor::EntryIteratorItem::Existing(new_entry(
                    IF_ADDR_V4.addr,
                    MAC_1,
                    updated_at,
                )),
                fneighbor::EntryIteratorItem::Existing(new_entry(
                    IF_ADDR_V6.addr,
                    MAC_2,
                    updated_at - offset,
                )),
                fneighbor::EntryIteratorItem::Idle(fneighbor::IdleEvent {}),
            ]],
            want(
                fneighbor_ext::Entry::try_from(new_entry(IF_ADDR_V4.addr, MAC_1, updated_at))
                    .unwrap(),
                fneighbor_ext::Entry::try_from(new_entry(
                    IF_ADDR_V6.addr,
                    MAC_2,
                    updated_at - offset,
                ))
                .unwrap(),
            ),
        )
        .await
    }

    #[fasync::run_singlethreaded(test)]
    async fn neigh_list_many() {
        test_neigh_many(false /* watch_for_changes */, |a, b| format!("{}\n{}\n", a, b)).await
    }

    #[fasync::run_singlethreaded(test)]
    async fn neigh_watch_many() {
        test_neigh_many(true /* watch_for_changes */, |a, b| {
            format!(
                "EXISTING | {}\n\
                 EXISTING | {}\n\
                 IDLE\n",
                a, b
            )
        })
        .await
    }

    fn wanted_neigh_list_json() -> String {
        json!({
            "interface": 1,
            "mac": "01:02:03:04:05:06",
            "neighbor": "192.168.0.1",
            "state": "REACHABLE",
        })
        .to_string()
    }

    fn wanted_neigh_watch_json() -> String {
        json!({
            "entry": {
                "interface": 1,
                "mac": "01:02:03:04:05:06",
                "neighbor": "192.168.0.1",
                "state": "REACHABLE",
            },
            "state_change_status": "EXISTING",
        })
        .to_string()
    }

    #[test_case(true, false, &wanted_neigh_list_json() ; "in json format, not including entry state")]
    #[test_case(false, false, "Interface 1 | IP 192.168.0.1 | MAC 01:02:03:04:05:06 | REACHABLE" ; "in tabular format, not including entry state")]
    #[test_case(true, true, &wanted_neigh_watch_json() ; "in json format, including entry state")]
    #[test_case(false, true, "EXISTING | Interface 1 | IP 192.168.0.1 | MAC 01:02:03:04:05:06 | REACHABLE" ; "in tabular format, including entry state")]
    fn neigh_write_entry(json: bool, include_entry_state: bool, wanted_output: &str) {
        let entry = fneighbor::EntryIteratorItem::Existing(fneighbor::Entry {
            interface: Some(1),
            neighbor: Some(IF_ADDR_V4.addr),
            state: Some(fneighbor::EntryState::Reachable),
            mac: Some(MAC_1),
            updated_at: Some(timestamp_60s_ago()),
            ..Default::default()
        });

        let mut output = if json {
            ffx_writer::Writer::new_test(Some(ffx_writer::Format::Json))
        } else {
            ffx_writer::Writer::new_test(None)
        };
        write_neigh_entry(&mut output, entry, include_entry_state)
            .expect("write_neigh_entry should succeed");
        let got_output = output.test_output().unwrap();
        pretty_assertions::assert_eq!(
            trim_whitespace_for_comparison(&got_output),
            trim_whitespace_for_comparison(wanted_output),
        );
    }

    const INTERFACE_ID: u64 = 1;
    const IP_VERSION: fnet::IpVersion = fnet::IpVersion::V4;

    #[fasync::run_singlethreaded(test)]
    async fn neigh_add() {
        let (controller, mut requests) =
            fidl::endpoints::create_proxy_and_stream::<fneighbor::ControllerMarker>().unwrap();
        let neigh = do_neigh_add(INTERFACE_ID, IF_ADDR_V4.addr, MAC_1, controller);
        let neigh_succeeds = async {
            let (got_interface_id, got_ip_address, got_mac, responder) = requests
                .try_next()
                .await
                .expect("neigh FIDL error")
                .expect("request stream should not have ended")
                .into_add_entry()
                .expect("request should be of type AddEntry");
            assert_eq!(got_interface_id, INTERFACE_ID);
            assert_eq!(got_ip_address, IF_ADDR_V4.addr);
            assert_eq!(got_mac, MAC_1);
            let () = responder.send(Ok(())).expect("responder.send should succeed");
            Ok(())
        };
        let ((), ()) = futures::future::try_join(neigh, neigh_succeeds)
            .await
            .expect("neigh add should succeed");
    }

    #[fasync::run_singlethreaded(test)]
    async fn neigh_clear() {
        let (controller, mut requests) =
            fidl::endpoints::create_proxy_and_stream::<fneighbor::ControllerMarker>().unwrap();
        let neigh = do_neigh_clear(INTERFACE_ID, IP_VERSION, controller);
        let neigh_succeeds = async {
            let (got_interface_id, got_ip_version, responder) = requests
                .try_next()
                .await
                .expect("neigh FIDL error")
                .expect("request stream should not have ended")
                .into_clear_entries()
                .expect("request should be of type ClearEntries");
            assert_eq!(got_interface_id, INTERFACE_ID);
            assert_eq!(got_ip_version, IP_VERSION);
            let () = responder.send(Ok(())).expect("responder.send should succeed");
            Ok(())
        };
        let ((), ()) = futures::future::try_join(neigh, neigh_succeeds)
            .await
            .expect("neigh clear should succeed");
    }

    #[fasync::run_singlethreaded(test)]
    async fn neigh_del() {
        let (controller, mut requests) =
            fidl::endpoints::create_proxy_and_stream::<fneighbor::ControllerMarker>().unwrap();
        let neigh = do_neigh_del(INTERFACE_ID, IF_ADDR_V4.addr, controller);
        let neigh_succeeds = async {
            let (got_interface_id, got_ip_address, responder) = requests
                .try_next()
                .await
                .expect("neigh FIDL error")
                .expect("request stream should not have ended")
                .into_remove_entry()
                .expect("request should be of type RemoveEntry");
            assert_eq!(got_interface_id, INTERFACE_ID);
            assert_eq!(got_ip_address, IF_ADDR_V4.addr);
            let () = responder.send(Ok(())).expect("responder.send should succeed");
            Ok(())
        };
        let ((), ()) = futures::future::try_join(neigh, neigh_succeeds)
            .await
            .expect("neigh remove should succeed");
    }

    #[fasync::run_singlethreaded(test)]
    async fn neigh_config_get() {
        let (view, mut requests) =
            fidl::endpoints::create_proxy_and_stream::<fneighbor::ViewMarker>()
                .expect("creating a request stream and proxy for testing should succeed");
        let neigh = print_neigh_config(INTERFACE_ID, IP_VERSION, view);
        let neigh_succeeds = async {
            let (got_interface_id, got_ip_version, responder) = requests
                .try_next()
                .await
                .expect("neigh FIDL error")
                .expect("request stream should not have ended")
                .into_get_unreachability_config()
                .expect("request should be of type GetUnreachabilityConfig");
            assert_eq!(got_interface_id, INTERFACE_ID);
            assert_eq!(got_ip_version, IP_VERSION);
            let () =
                responder.send(Ok(&Default::default())).expect("responder.send should succeed");
            Ok(())
        };
        let ((), ()) = futures::future::try_join(neigh, neigh_succeeds)
            .await
            .expect("neigh config get should succeed");
    }

    #[fasync::run_singlethreaded(test)]
    async fn neigh_config_update() {
        let config = fneighbor::UnreachabilityConfig::default();

        let (controller, mut requests) =
            fidl::endpoints::create_proxy_and_stream::<fneighbor::ControllerMarker>()
                .expect("creating a request stream and proxy for testing should succeed");
        let neigh = update_neigh_config(
            INTERFACE_ID,
            IP_VERSION,
            fneighbor::UnreachabilityConfig::default(),
            controller,
        );
        let neigh_succeeds = async {
            let (got_interface_id, got_ip_version, got_config, responder) = requests
                .try_next()
                .await
                .expect("neigh FIDL error")
                .expect("request stream should not have ended")
                .into_update_unreachability_config()
                .expect("request should be of type UpdateUnreachabilityConfig");
            assert_eq!(got_interface_id, INTERFACE_ID);
            assert_eq!(got_ip_version, IP_VERSION);
            assert_eq!(got_config, config);
            let () = responder.send(Ok(())).expect("responder.send should succeed");
            Ok(())
        };
        let ((), ()) = futures::future::try_join(neigh, neigh_succeeds)
            .await
            .expect("neigh config update should succeed");
    }

    #[test_case(opts::dhcpd::DhcpdEnum::Get(opts::dhcpd::Get {
            arg: opts::dhcpd::GetArg::Option(
                opts::dhcpd::OptionArg {
                    name: opts::dhcpd::Option_::SubnetMask(
                        opts::dhcpd::SubnetMask { mask: None }) }),
        }); "get option")]
    #[test_case(opts::dhcpd::DhcpdEnum::Get(opts::dhcpd::Get {
            arg: opts::dhcpd::GetArg::Parameter(opts::dhcpd::ParameterArg {
                name: opts::dhcpd::Parameter::LeaseLength(
                    opts::dhcpd::LeaseLength { default: None, max: None }),
            }),
        }); "get parameter")]
    #[test_case(opts::dhcpd::DhcpdEnum::Set(opts::dhcpd::Set {
            arg: opts::dhcpd::SetArg::Option(opts::dhcpd::OptionArg {
                name: opts::dhcpd::Option_::SubnetMask(opts::dhcpd::SubnetMask {
                    mask: Some(net_declare::std_ip_v4!("255.255.255.0")),
                }),
            }),
        }); "set option")]
    #[test_case(opts::dhcpd::DhcpdEnum::Set(opts::dhcpd::Set {
            arg: opts::dhcpd::SetArg::Parameter(opts::dhcpd::ParameterArg {
                name: opts::dhcpd::Parameter::LeaseLength(
                    opts::dhcpd::LeaseLength { max: Some(42), default: Some(42) }),
            }),
        }); "set parameter")]
    #[test_case(opts::dhcpd::DhcpdEnum::List(opts::dhcpd::List { arg:
        opts::dhcpd::ListArg::Option(opts::dhcpd::OptionToken {}) }); "list option")]
    #[test_case(opts::dhcpd::DhcpdEnum::List(
        opts::dhcpd::List { arg: opts::dhcpd::ListArg::Parameter(opts::dhcpd::ParameterToken {}) });
        "list parameter")]
    #[test_case(opts::dhcpd::DhcpdEnum::Reset(opts::dhcpd::Reset {
        arg: opts::dhcpd::ResetArg::Option(opts::dhcpd::OptionToken {}) }); "reset option")]
    #[test_case(opts::dhcpd::DhcpdEnum::Reset(
        opts::dhcpd::Reset {
            arg: opts::dhcpd::ResetArg::Parameter(opts::dhcpd::ParameterToken {}) });
        "reset parameter")]
    #[test_case(opts::dhcpd::DhcpdEnum::ClearLeases(opts::dhcpd::ClearLeases {}); "clear leases")]
    #[test_case(opts::dhcpd::DhcpdEnum::Start(opts::dhcpd::Start {}); "start")]
    #[test_case(opts::dhcpd::DhcpdEnum::Stop(opts::dhcpd::Stop {}); "stop")]
    #[fasync::run_singlethreaded(test)]
    async fn test_do_dhcpd(cmd: opts::dhcpd::DhcpdEnum) {
        let (dhcpd, mut requests) =
            fidl::endpoints::create_proxy_and_stream::<fdhcp::Server_Marker>()
                .expect("failed to create proxy and request stream for dhcp server");

        let connector = TestConnector { dhcpd: Some(dhcpd), ..Default::default() };
        let op = do_dhcpd(cmd.clone(), &connector);
        let op_succeeds = async move {
            let req = requests
                .try_next()
                .await
                .expect("receiving request")
                .expect("request stream should not have ended");
            match cmd {
                opts::dhcpd::DhcpdEnum::Get(opts::dhcpd::Get { arg }) => match arg {
                    opts::dhcpd::GetArg::Option(opts::dhcpd::OptionArg { name }) => {
                        let (code, responder) =
                            req.into_get_option().expect("request should be of type get option");
                        assert_eq!(
                            <opts::dhcpd::Option_ as Into<fdhcp::OptionCode>>::into(name),
                            code
                        );
                        // We don't care what the value is here, we just need something to give as
                        // an argument to responder.send().
                        let dummy_result = fdhcp::Option_::SubnetMask(fidl_ip_v4!("255.255.255.0"));
                        let () = responder
                            .send(Ok(&dummy_result))
                            .expect("responder.send should succeed");
                        Ok(())
                    }
                    opts::dhcpd::GetArg::Parameter(opts::dhcpd::ParameterArg { name }) => {
                        let (param, responder) = req
                            .into_get_parameter()
                            .expect("request should be of type get parameter");
                        assert_eq!(
                            <opts::dhcpd::Parameter as Into<fdhcp::ParameterName>>::into(name),
                            param
                        );
                        // We don't care what the value is here, we just need something to give as
                        // an argument to responder.send().
                        let dummy_result = fdhcp::Parameter::Lease(fdhcp::LeaseLength::default());
                        let () = responder
                            .send(Ok(&dummy_result))
                            .expect("responder.send should succeed");
                        Ok(())
                    }
                },
                opts::dhcpd::DhcpdEnum::Set(opts::dhcpd::Set { arg }) => match arg {
                    opts::dhcpd::SetArg::Option(opts::dhcpd::OptionArg { name }) => {
                        let (opt, responder) =
                            req.into_set_option().expect("request should be of type set option");
                        assert_eq!(<opts::dhcpd::Option_ as Into<fdhcp::Option_>>::into(name), opt);
                        let () = responder.send(Ok(())).expect("responder.send should succeed");
                        Ok(())
                    }
                    opts::dhcpd::SetArg::Parameter(opts::dhcpd::ParameterArg { name }) => {
                        let (opt, responder) = req
                            .into_set_parameter()
                            .expect("request should be of type set parameter");
                        assert_eq!(
                            <opts::dhcpd::Parameter as Into<fdhcp::Parameter>>::into(name),
                            opt
                        );
                        let () = responder.send(Ok(())).expect("responder.send should succeed");
                        Ok(())
                    }
                },
                opts::dhcpd::DhcpdEnum::List(opts::dhcpd::List { arg }) => match arg {
                    opts::dhcpd::ListArg::Option(opts::dhcpd::OptionToken {}) => {
                        let responder = req
                            .into_list_options()
                            .expect("request should be of type list options");
                        let () = responder.send(Ok(&[])).expect("responder.send should succeed");
                        Ok(())
                    }
                    opts::dhcpd::ListArg::Parameter(opts::dhcpd::ParameterToken {}) => {
                        let responder = req
                            .into_list_parameters()
                            .expect("request should be of type list options");
                        let () = responder.send(Ok(&[])).expect("responder.send should succeed");
                        Ok(())
                    }
                },
                opts::dhcpd::DhcpdEnum::Reset(opts::dhcpd::Reset { arg }) => match arg {
                    opts::dhcpd::ResetArg::Option(opts::dhcpd::OptionToken {}) => {
                        let responder = req
                            .into_reset_options()
                            .expect("request should be of type reset options");
                        let () = responder.send(Ok(())).expect("responder.send should succeed");
                        Ok(())
                    }
                    opts::dhcpd::ResetArg::Parameter(opts::dhcpd::ParameterToken {}) => {
                        let responder = req
                            .into_reset_parameters()
                            .expect("request should be of type reset parameters");
                        let () = responder.send(Ok(())).expect("responder.send should succeed");
                        Ok(())
                    }
                },
                opts::dhcpd::DhcpdEnum::ClearLeases(opts::dhcpd::ClearLeases {}) => {
                    let responder =
                        req.into_clear_leases().expect("request should be of type clear leases");
                    let () = responder.send(Ok(())).expect("responder.send should succeed");
                    Ok(())
                }
                opts::dhcpd::DhcpdEnum::Start(opts::dhcpd::Start {}) => {
                    let responder =
                        req.into_start_serving().expect("request should be of type start serving");
                    let () = responder.send(Ok(())).expect("responder.send should succeed");
                    Ok(())
                }
                opts::dhcpd::DhcpdEnum::Stop(opts::dhcpd::Stop {}) => {
                    let responder =
                        req.into_stop_serving().expect("request should be of type stop serving");
                    let () = responder.send().expect("responder.send should succeed");
                    Ok(())
                }
            }
        };
        let ((), ()) = futures::future::try_join(op, op_succeeds)
            .await
            .expect("dhcp server command should succeed");
    }

    #[fasync::run_singlethreaded(test)]
    async fn dns_lookup() {
        let (lookup, mut requests) =
            fidl::endpoints::create_proxy_and_stream::<fname::LookupMarker>().unwrap();
        let connector = TestConnector { name_lookup: Some(lookup), ..Default::default() };

        let cmd = opts::dns::DnsEnum::Lookup(opts::dns::Lookup {
            hostname: "example.com".to_string(),
            ipv4: true,
            ipv6: true,
            sort: true,
        });
        let mut output = Vec::new();
        let dns_command = do_dns(&mut output, cmd.clone(), &connector)
            .map(|result| result.expect("dns command should succeed"));

        let handle_request = async move {
            let (hostname, options, responder) = requests
                .try_next()
                .await
                .expect("FIDL error")
                .expect("request stream should not have ended")
                .into_lookup_ip()
                .expect("request should be of type LookupIp");
            let opts::dns::DnsEnum::Lookup(opts::dns::Lookup {
                hostname: want_hostname,
                ipv4,
                ipv6,
                sort,
            }) = cmd;
            let want_options = fname::LookupIpOptions {
                ipv4_lookup: Some(ipv4),
                ipv6_lookup: Some(ipv6),
                sort_addresses: Some(sort),
                ..Default::default()
            };
            assert_eq!(
                hostname, want_hostname,
                "received IP lookup request for unexpected hostname"
            );
            assert_eq!(options, want_options, "received unexpected IP lookup options");

            responder
                .send(Ok(&fname::LookupResult {
                    addresses: Some(vec![fidl_ip!("203.0.113.1"), fidl_ip!("2001:db8::1")]),
                    ..Default::default()
                }))
                .expect("send response");
        };
        let ((), ()) = futures::future::join(dns_command, handle_request).await;

        const WANT_OUTPUT: &str = "
203.0.113.1
2001:db8::1
";
        let got_output = std::str::from_utf8(&output).unwrap();
        pretty_assertions::assert_eq!(
            trim_whitespace_for_comparison(got_output),
            trim_whitespace_for_comparison(WANT_OUTPUT),
        );
    }

    #[fasync::run_singlethreaded(test)]
    async fn test_do_filter() {
        let mut output = Vec::new();
        let (filter, mut requests) =
            fidl::endpoints::create_proxy_and_stream::<fnet_filter::StateMarker>()
                .expect("failed to create proxy and request stream for filter server");

        let connector = TestConnector { filter: Some(filter), ..Default::default() };
        let op = do_filter(
            &mut output,
            opts::filter::FilterEnum::List(opts::filter::List {}),
            &connector,
        );
        let op_succeeds = async move {
            let req = requests
                .try_next()
                .await
                .expect("receiving request")
                .expect("request stream should not have ended");
            let (_options, server_end, _state_control_handle) =
                req.into_get_watcher().expect("request should be of type GetWatcher");

            let mut watcher_request_stream = server_end.into_stream().expect("watcher FIDL error");

            let events = [
                fnet_filter::Event::Existing(fnet_filter::ExistingResource {
                    controller: "test controller".to_string(),
                    resource: fnet_filter::Resource::Namespace(fnet_filter::Namespace {
                        id: Option::Some("test namespace".to_string()),
                        domain: Option::Some(fnet_filter::Domain::Ipv4),
                        ..Default::default()
                    }),
                }),
                fnet_filter::Event::Idle(fnet_filter::Empty),
            ];
            let () = watcher_request_stream
                .try_next()
                .await
                .expect("watcher watch FIDL error")
                .expect("watcher request stream should not have ended")
                .into_watch()
                .expect("request should be of type Watch")
                .send(&events)
                .expect("responder.send should succeed");

            assert_matches!(
                watcher_request_stream.try_next().await.expect("watcher watch FIDL error"),
                None,
                "remaining watcher request stream should be empty because client should close \
                watcher channel after observing existing resources"
            );

            Ok(())
        };
        let ((), ()) = futures::future::try_join(op, op_succeeds)
            .await
            .expect("filter server command should succeed");

        const WANT_OUTPUT: &str = r#"resources = {
    ControllerId(
        "test controller",
    ): {
        Namespace(
            NamespaceId(
                "test namespace",
            ),
        ): Namespace(
            Namespace {
                id: NamespaceId(
                    "test namespace",
                ),
                domain: Ipv4,
            },
        ),
    },
}"#;
        let got_output = std::str::from_utf8(&output).unwrap();
        pretty_assertions::assert_eq!(
            trim_whitespace_for_comparison(got_output),
            trim_whitespace_for_comparison(WANT_OUTPUT),
        );
    }
}