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
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
// 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 alloc::collections::HashMap;
use alloc::vec::Vec;
use core::cmp::Ordering;
use core::fmt::Debug;
use core::hash::Hash;
use core::marker::PhantomData;
use core::num::{NonZeroU16, NonZeroU8};
use core::ops::ControlFlow;
#[cfg(test)]
use core::ops::DerefMut;
use core::sync::atomic::{self, AtomicU16};

use const_unwrap::const_unwrap_option;
use derivative::Derivative;
use explicit::ResultExt as _;
use lock_order::lock::{OrderedLockAccess, OrderedLockRef};
use log::{debug, error, trace};
use net_types::ip::{
    GenericOverIp, Ip, IpInvariant, Ipv4, Ipv4Addr, Ipv6, Ipv6Addr, Ipv6SourceAddr, Mtu, Subnet,
};
use net_types::{
    MulticastAddr, MulticastAddress, NonMappedAddr, NonMulticastAddr, SpecifiedAddr,
    SpecifiedAddress as _, UnicastAddr, Witness,
};
use netstack3_base::socket::SocketIpAddrExt as _;
use netstack3_base::sync::{Mutex, PrimaryRc, RwLock, StrongRc, WeakRc};
use netstack3_base::{
    AnyDevice, BroadcastIpExt, CoreTimerContext, Counter, CounterContext, DeviceIdContext,
    DeviceIdentifier as _, DeviceWithName, ErrorAndSerializer, EventContext, FrameDestination,
    HandleableTimer, Inspectable, Inspector, InstantContext, IpDeviceAddr, IpExt, Matcher as _,
    NestedIntoCoreTimerCtx, NotFoundError, RngContext, SendFrameErrorReason,
    StrongDeviceIdentifier, TimerBindingsTypes, TimerContext, TimerHandler, TracingContext,
    WrapBroadcastMarker,
};
use netstack3_filter::{
    self as filter, ConntrackConnection, FilterBindingsContext, FilterBindingsTypes,
    FilterHandler as _, FilterIpContext, FilterIpExt, FilterIpMetadata, FilterTimerId,
    ForwardedPacket, IngressVerdict, IpPacket, TransportPacketSerializer, Tuple,
};
use packet::{Buf, BufferMut, GrowBuffer, ParseBufferMut, ParseMetadata, Serializer};
use packet_formats::error::IpParseError;
use packet_formats::ip::{DscpAndEcn, IpPacket as _, IpPacketBuilder as _};
use packet_formats::ipv4::{Ipv4FragmentType, Ipv4Packet};
use packet_formats::ipv6::Ipv6Packet;
use thiserror::Error;
use zerocopy::SplitByteSlice;

use crate::internal::device::opaque_iid::IidSecret;
use crate::internal::device::slaac::SlaacCounters;
use crate::internal::device::state::{
    IpDeviceStateBindingsTypes, IpDeviceStateIpExt, Ipv6AddressFlags, Ipv6AddressState,
};
use crate::internal::device::{
    self, IpAddressId as _, IpDeviceBindingsContext, IpDeviceIpExt, IpDeviceSendContext,
};
use crate::internal::gmp::GmpQueryHandler;
use crate::internal::icmp::{
    IcmpBindingsTypes, IcmpErrorHandler, IcmpHandlerIpExt, Icmpv4Error, Icmpv4ErrorKind,
    Icmpv4State, Icmpv4StateBuilder, Icmpv6ErrorKind, Icmpv6State, Icmpv6StateBuilder,
};
use crate::internal::ipv6::Ipv6PacketAction;
use crate::internal::multicast_forwarding::counters::MulticastForwardingCounters;
use crate::internal::multicast_forwarding::route::{
    MulticastRouteIpExt, MulticastRouteTarget, MulticastRouteTargets,
};
use crate::internal::multicast_forwarding::state::{
    MulticastForwardingState, MulticastForwardingStateContext,
};
use crate::internal::multicast_forwarding::{
    MulticastForwardingBindingsTypes, MulticastForwardingDeviceContext, MulticastForwardingEvent,
    MulticastForwardingTimerId,
};
use crate::internal::path_mtu::{PmtuBindingsTypes, PmtuCache, PmtuTimerId};
use crate::internal::raw::counters::RawIpSocketCounters;
use crate::internal::raw::{RawIpSocketHandler, RawIpSocketMap, RawIpSocketsBindingsTypes};
use crate::internal::reassembly::{
    FragmentBindingsTypes, FragmentHandler, FragmentProcessingState, FragmentTimerId,
    FragmentablePacket, IpPacketFragmentCache,
};
use crate::internal::routing::rules::{Marks, Rule, RuleAction, RuleInput, RulesTable};
use crate::internal::routing::{
    IpRoutingDeviceContext, NonLocalSrcAddrPolicy, PacketOrigin, RoutingTable,
};
use crate::internal::socket::{IpSocketBindingsContext, IpSocketContext, IpSocketHandler};
use crate::internal::types::{
    self, Destination, InternalForwarding, NextHop, ResolvedRoute, RoutableIpAddr,
};
use crate::internal::{ipv6, multicast_forwarding};

#[cfg(test)]
mod tests;

/// Default IPv4 TTL.
pub const DEFAULT_TTL: NonZeroU8 = const_unwrap_option(NonZeroU8::new(64));

/// Hop limits for packets sent to multicast and unicast destinations.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[allow(missing_docs)]
pub struct HopLimits {
    pub unicast: NonZeroU8,
    pub multicast: NonZeroU8,
}

/// Default hop limits for sockets.
pub const DEFAULT_HOP_LIMITS: HopLimits =
    HopLimits { unicast: DEFAULT_TTL, multicast: const_unwrap_option(NonZeroU8::new(1)) };

/// The IPv6 subnet that contains all addresses; `::/0`.
// Safe because 0 is less than the number of IPv6 address bits.
pub const IPV6_DEFAULT_SUBNET: Subnet<Ipv6Addr> =
    unsafe { Subnet::new_unchecked(Ipv6::UNSPECIFIED_ADDRESS, 0) };

/// An error encountered when receiving a transport-layer packet.
#[derive(Debug)]
#[allow(missing_docs)]
pub enum TransportReceiveError {
    ProtocolUnsupported,
    PortUnreachable,
}

impl TransportReceiveError {
    fn into_icmpv4_error(self, header_len: usize) -> Icmpv4Error {
        let kind = match self {
            TransportReceiveError::ProtocolUnsupported => Icmpv4ErrorKind::ProtocolUnreachable,
            TransportReceiveError::PortUnreachable => Icmpv4ErrorKind::PortUnreachable,
        };
        Icmpv4Error { kind, header_len }
    }

    fn into_icmpv6_error(self, header_len: usize) -> Icmpv6ErrorKind {
        match self {
            TransportReceiveError::ProtocolUnsupported => {
                Icmpv6ErrorKind::ProtocolUnreachable { header_len }
            }
            TransportReceiveError::PortUnreachable => Icmpv6ErrorKind::PortUnreachable,
        }
    }
}

/// Sidecar metadata passed along with the packet.
///
/// Note: This metadata may be regenerated when packet handling requires
/// performing multiple actions (e.g. sending the packet out multiple interfaces
/// as part of multicast forwarding).
#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct IpLayerPacketMetadata<I: packet_formats::ip::IpExt, BT: FilterBindingsTypes> {
    conntrack_connection: Option<ConntrackConnection<I, BT>>,
    #[cfg(debug_assertions)]
    drop_check: IpLayerPacketMetadataDropCheck,
}

/// A type that asserts, on drop, that it was intentionally being dropped.
///
/// NOTE: Unfortunately, debugging this requires backtraces, since track_caller
/// won't do what we want (https://github.com/rust-lang/rust/issues/116942).
/// Since this is only enabled in debug, the assumption is that stacktraces are
/// enabled.
#[cfg(debug_assertions)]
#[derive(Default)]
struct IpLayerPacketMetadataDropCheck {
    okay_to_drop: bool,
}

impl<I: packet_formats::ip::IpExt, BT: FilterBindingsTypes> IpLayerPacketMetadata<I, BT> {
    /// Acknowledge that it's okay to drop this packet metadata.
    ///
    /// When compiled with debug assertions, dropping [`IplayerPacketMetadata`]
    /// will panic if this method has not previously been called.
    pub(crate) fn acknowledge_drop(&mut self) {
        #[cfg(debug_assertions)]
        {
            self.drop_check.okay_to_drop = true;
        }
    }
}

#[cfg(debug_assertions)]
impl Drop for IpLayerPacketMetadataDropCheck {
    fn drop(&mut self) {
        if !self.okay_to_drop {
            panic!(
                "IpLayerPacketMetadata dropped without acknowledgement.  https://fxbug.dev/334127474"
            );
        }
    }
}

impl<I: packet_formats::ip::IpExt, BT: FilterBindingsTypes> FilterIpMetadata<I, BT>
    for IpLayerPacketMetadata<I, BT>
{
    fn take_conntrack_connection(&mut self) -> Option<ConntrackConnection<I, BT>> {
        self.conntrack_connection.take()
    }

    fn replace_conntrack_connection(
        &mut self,
        conn: ConntrackConnection<I, BT>,
    ) -> Option<ConntrackConnection<I, BT>> {
        self.conntrack_connection.replace(conn)
    }
}

/// Send errors observed at or above the IP layer that carry a serializer.
pub type IpSendFrameError<S> = ErrorAndSerializer<IpSendFrameErrorReason, S>;

/// Send error cause for [`IpSendFrameError`].
#[derive(Debug, PartialEq)]
pub enum IpSendFrameErrorReason {
    /// Error comes from the device layer.
    Device(SendFrameErrorReason),
    /// The frame's source or destination address is in the loopback subnet, but
    /// the target device is not the loopback device.
    IllegalLoopbackAddress,
}

impl From<SendFrameErrorReason> for IpSendFrameErrorReason {
    fn from(value: SendFrameErrorReason) -> Self {
        Self::Device(value)
    }
}

/// Informs the transport layer of parameters for transparent local delivery.
#[derive(Debug, GenericOverIp, Clone)]
#[generic_over_ip(I, Ip)]
pub struct TransparentLocalDelivery<I: IpExt> {
    /// The local delivery address.
    pub addr: SpecifiedAddr<I::Addr>,
    /// The local delivery port.
    pub port: NonZeroU16,
}

/// Meta information for an incoming packet.
#[derive(Debug, Derivative, GenericOverIp, Clone)]
#[derivative(Default(bound = ""))]
#[generic_over_ip(I, Ip)]
pub struct ReceiveIpPacketMeta<I: IpExt> {
    /// Indicates that the packet was sent to a broadcast address.
    pub broadcast: Option<I::BroadcastMarker>,

    /// Destination overrides for the transparent proxy.
    pub transparent_override: Option<TransparentLocalDelivery<I>>,

    /// DSCP and ECN values received in Traffic Class or TOS field.
    pub dscp_and_ecn: DscpAndEcn,
}

/// The execution context provided by a transport layer protocol to the IP
/// layer.
///
/// An implementation for `()` is provided which indicates that a particular
/// transport layer protocol is unsupported.
pub trait IpTransportContext<I: IpExt, BC, CC: DeviceIdContext<AnyDevice> + ?Sized> {
    /// Receive an ICMP error message.
    ///
    /// All arguments beginning with `original_` are fields from the IP packet
    /// that triggered the error. The `original_body` is provided here so that
    /// the error can be associated with a transport-layer socket. `device`
    /// identifies the device that received the ICMP error message packet.
    ///
    /// While ICMPv4 error messages are supposed to contain the first 8 bytes of
    /// the body of the offending packet, and ICMPv6 error messages are supposed
    /// to contain as much of the offending packet as possible without violating
    /// the IPv6 minimum MTU, the caller does NOT guarantee that either of these
    /// hold. It is `receive_icmp_error`'s responsibility to handle any length
    /// of `original_body`, and to perform any necessary validation.
    fn receive_icmp_error(
        core_ctx: &mut CC,
        bindings_ctx: &mut BC,
        device: &CC::DeviceId,
        original_src_ip: Option<SpecifiedAddr<I::Addr>>,
        original_dst_ip: SpecifiedAddr<I::Addr>,
        original_body: &[u8],
        err: I::ErrorCode,
    );

    /// Receive a transport layer packet in an IP packet.
    ///
    /// In the event of an unreachable port, `receive_ip_packet` returns the
    /// buffer in its original state (with the transport packet un-parsed) in
    /// the `Err` variant.
    fn receive_ip_packet<B: BufferMut>(
        core_ctx: &mut CC,
        bindings_ctx: &mut BC,
        device: &CC::DeviceId,
        src_ip: I::RecvSrcAddr,
        dst_ip: SpecifiedAddr<I::Addr>,
        buffer: B,
        meta: ReceiveIpPacketMeta<I>,
    ) -> Result<(), (B, TransportReceiveError)>;
}

impl<I: IpExt, BC, CC: DeviceIdContext<AnyDevice> + ?Sized> IpTransportContext<I, BC, CC> for () {
    fn receive_icmp_error(
        _core_ctx: &mut CC,
        _bindings_ctx: &mut BC,
        _device: &CC::DeviceId,
        _original_src_ip: Option<SpecifiedAddr<I::Addr>>,
        _original_dst_ip: SpecifiedAddr<I::Addr>,
        _original_body: &[u8],
        err: I::ErrorCode,
    ) {
        trace!("IpTransportContext::receive_icmp_error: Received ICMP error message ({:?}) for unsupported IP protocol", err);
    }

    fn receive_ip_packet<B: BufferMut>(
        _core_ctx: &mut CC,
        _bindings_ctx: &mut BC,
        _device: &CC::DeviceId,
        _src_ip: I::RecvSrcAddr,
        _dst_ip: SpecifiedAddr<I::Addr>,
        buffer: B,
        _meta: ReceiveIpPacketMeta<I>,
    ) -> Result<(), (B, TransportReceiveError)> {
        Err((buffer, TransportReceiveError::ProtocolUnsupported))
    }
}

/// The base execution context provided by the IP layer to transport layer
/// protocols.
pub trait BaseTransportIpContext<I: IpExt, BC>: DeviceIdContext<AnyDevice> {
    /// The iterator given to
    /// [`BaseTransportIpContext::with_devices_with_assigned_addr`].
    type DevicesWithAddrIter<'s>: Iterator<Item = Self::DeviceId>;

    /// Is this one of our local addresses, and is it in the assigned state?
    ///
    /// Calls `cb` with an iterator over all the local interfaces for which
    /// `addr` is an associated address, and, for IPv6, for which it is in the
    /// "assigned" state.
    fn with_devices_with_assigned_addr<O, F: FnOnce(Self::DevicesWithAddrIter<'_>) -> O>(
        &mut self,
        addr: SpecifiedAddr<I::Addr>,
        cb: F,
    ) -> O;

    /// Get default hop limits.
    ///
    /// If `device` is not `None` and exists, its hop limits will be returned.
    /// Otherwise the system defaults are returned.
    fn get_default_hop_limits(&mut self, device: Option<&Self::DeviceId>) -> HopLimits;

    /// Gets the original destination for the tracked connection indexed by
    /// `tuple`, which includes the source and destination addresses and
    /// transport-layer ports as well as the transport protocol number.
    fn get_original_destination(&mut self, tuple: &Tuple<I>) -> Option<(I::Addr, u16)>;
}

/// A marker trait for the traits required by the transport layer from the IP
/// layer.
pub trait TransportIpContext<I: IpExt, BC>:
    BaseTransportIpContext<I, BC> + IpSocketHandler<I, BC>
{
}

impl<I, CC, BC> TransportIpContext<I, BC> for CC
where
    I: IpExt,
    CC: BaseTransportIpContext<I, BC> + IpSocketHandler<I, BC>,
{
}

/// Abstraction over the ability to join and leave multicast groups.
pub trait MulticastMembershipHandler<I: Ip, BC>: DeviceIdContext<AnyDevice> {
    /// Requests that the specified device join the given multicast group.
    ///
    /// If this method is called multiple times with the same device and
    /// address, the device will remain joined to the multicast group until
    /// [`MulticastTransportIpContext::leave_multicast_group`] has been called
    /// the same number of times.
    fn join_multicast_group(
        &mut self,
        bindings_ctx: &mut BC,
        device: &Self::DeviceId,
        addr: MulticastAddr<I::Addr>,
    );

    /// Requests that the specified device leave the given multicast group.
    ///
    /// Each call to this method must correspond to an earlier call to
    /// [`MulticastTransportIpContext::join_multicast_group`]. The device
    /// remains a member of the multicast group so long as some call to
    /// `join_multicast_group` has been made without a corresponding call to
    /// `leave_multicast_group`.
    fn leave_multicast_group(
        &mut self,
        bindings_ctx: &mut BC,
        device: &Self::DeviceId,
        addr: MulticastAddr<I::Addr>,
    );

    /// Selects a default device with which to join the given multicast group.
    ///
    /// The selection is made by consulting the routing table; If there is no
    /// route available to the given address, an error is returned.
    fn select_device_for_multicast_group(
        &mut self,
        addr: MulticastAddr<I::Addr>,
        marks: &Marks,
    ) -> Result<Self::DeviceId, ResolveRouteError>;
}

// TODO(joshlf): With all 256 protocol numbers (minus reserved ones) given their
// own associated type in both traits, running `cargo check` on a 2018 MacBook
// Pro takes over a minute. Eventually - and before we formally publish this as
// a library - we should identify the bottleneck in the compiler and optimize
// it. For the time being, however, we only support protocol numbers that we
// actually use (TCP and UDP).

/// Enables a blanket implementation of [`TransportIpContext`].
///
/// Implementing this marker trait for a type enables a blanket implementation
/// of `TransportIpContext` given the other requirements are met.
pub trait UseTransportIpContextBlanket {}

/// An iterator supporting the blanket implementation of
/// [`BaseTransportIpContext::with_devices_with_assigned_addr`].
pub struct AssignedAddressDeviceIterator<Iter, I, D>(Iter, PhantomData<(I, D)>);

impl<Iter, I, D> Iterator for AssignedAddressDeviceIterator<Iter, I, D>
where
    Iter: Iterator<Item = (D, I::AddressStatus)>,
    I: IpLayerIpExt,
{
    type Item = D;
    fn next(&mut self) -> Option<D> {
        let Self(iter, PhantomData) = self;
        iter.by_ref().find_map(|(device, state)| is_unicast_assigned::<I>(&state).then_some(device))
    }
}

impl<
        I: IpLayerIpExt,
        BC: FilterBindingsContext,
        CC: IpDeviceContext<I>
            + IpSocketHandler<I, BC>
            + IpStateContext<I>
            + FilterIpContext<I, BC>
            + UseTransportIpContextBlanket,
    > BaseTransportIpContext<I, BC> for CC
{
    type DevicesWithAddrIter<'s> =
        AssignedAddressDeviceIterator<CC::DeviceAndAddressStatusIter<'s>, I, CC::DeviceId>;

    fn with_devices_with_assigned_addr<O, F: FnOnce(Self::DevicesWithAddrIter<'_>) -> O>(
        &mut self,
        addr: SpecifiedAddr<I::Addr>,
        cb: F,
    ) -> O {
        self.with_address_statuses(addr, |it| cb(AssignedAddressDeviceIterator(it, PhantomData)))
    }

    fn get_default_hop_limits(&mut self, device: Option<&Self::DeviceId>) -> HopLimits {
        match device {
            Some(device) => HopLimits {
                unicast: IpDeviceStateContext::<I>::get_hop_limit(self, device),
                ..DEFAULT_HOP_LIMITS
            },
            None => DEFAULT_HOP_LIMITS,
        }
    }

    fn get_original_destination(&mut self, tuple: &Tuple<I>) -> Option<(I::Addr, u16)> {
        self.with_filter_state(|state| {
            let conn = state.conntrack.get_connection(&tuple)?;

            if !conn.destination_nat() {
                return None;
            }

            // The tuple marking the original direction of the connection is
            // never modified by NAT. This means it can be used to recover the
            // destination before NAT was performed.
            let original = conn.original_tuple();
            Some((original.dst_addr, original.dst_port_or_id))
        })
    }
}

/// The status of an IP address on an interface.
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub enum AddressStatus<S> {
    Present(S),
    Unassigned,
}

impl<S> AddressStatus<S> {
    fn into_present(self) -> Option<S> {
        match self {
            Self::Present(s) => Some(s),
            Self::Unassigned => None,
        }
    }
}

impl AddressStatus<Ipv4PresentAddressStatus> {
    /// Creates an IPv4 `AddressStatus` for `addr` on `device`.
    pub fn from_context_addr_v4<
        BC: IpDeviceStateBindingsTypes,
        CC: device::IpDeviceStateContext<Ipv4, BC> + GmpQueryHandler<Ipv4, BC>,
    >(
        core_ctx: &mut CC,
        device: &CC::DeviceId,
        addr: SpecifiedAddr<Ipv4Addr>,
    ) -> AddressStatus<Ipv4PresentAddressStatus> {
        if addr.is_limited_broadcast() {
            return AddressStatus::Present(Ipv4PresentAddressStatus::LimitedBroadcast);
        }

        if MulticastAddr::new(addr.get())
            .is_some_and(|addr| GmpQueryHandler::gmp_is_in_group(core_ctx, device, addr))
        {
            return AddressStatus::Present(Ipv4PresentAddressStatus::Multicast);
        }

        core_ctx.with_address_ids(device, |mut addrs, _core_ctx| {
            addrs
                .find_map(|addr_id| {
                    let dev_addr = addr_id.addr_sub();
                    let (dev_addr, subnet) = dev_addr.addr_subnet();

                    if **dev_addr == addr {
                        Some(AddressStatus::Present(Ipv4PresentAddressStatus::Unicast))
                    } else if addr.get() == subnet.broadcast() {
                        Some(AddressStatus::Present(Ipv4PresentAddressStatus::SubnetBroadcast))
                    } else if device.is_loopback() && subnet.contains(addr.as_ref()) {
                        Some(AddressStatus::Present(Ipv4PresentAddressStatus::LoopbackSubnet))
                    } else {
                        None
                    }
                })
                .unwrap_or(AddressStatus::Unassigned)
        })
    }
}

impl AddressStatus<Ipv6PresentAddressStatus> {
    /// /// Creates an IPv6 `AddressStatus` for `addr` on `device`.
    pub fn from_context_addr_v6<
        BC: IpDeviceBindingsContext<Ipv6, CC::DeviceId>,
        CC: device::Ipv6DeviceContext<BC> + GmpQueryHandler<Ipv6, BC>,
    >(
        core_ctx: &mut CC,
        device: &CC::DeviceId,
        addr: SpecifiedAddr<Ipv6Addr>,
    ) -> AddressStatus<Ipv6PresentAddressStatus> {
        if MulticastAddr::new(addr.get())
            .is_some_and(|addr| GmpQueryHandler::gmp_is_in_group(core_ctx, device, addr))
        {
            return AddressStatus::Present(Ipv6PresentAddressStatus::Multicast);
        }

        let addr_id = match core_ctx.get_address_id(device, addr) {
            Ok(o) => o,
            Err(NotFoundError) => return AddressStatus::Unassigned,
        };

        let assigned = core_ctx.with_ip_address_state(
            device,
            &addr_id,
            |Ipv6AddressState {
                 flags: Ipv6AddressFlags { deprecated: _, assigned },
                 config: _,
             }| { *assigned },
        );

        if assigned {
            AddressStatus::Present(Ipv6PresentAddressStatus::UnicastAssigned)
        } else {
            AddressStatus::Present(Ipv6PresentAddressStatus::UnicastTentative)
        }
    }
}

impl<S: GenericOverIp<I>, I: Ip> GenericOverIp<I> for AddressStatus<S> {
    type Type = AddressStatus<S::Type>;
}

/// The status of an IPv4 address.
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub enum Ipv4PresentAddressStatus {
    LimitedBroadcast,
    SubnetBroadcast,
    Multicast,
    Unicast,
    /// This status indicates that the queried device was Loopback. The address
    /// belongs to a subnet that is assigned to the interface. This status
    /// takes lower precedence than `Unicast` and `SubnetBroadcast``, E.g. if
    /// the loopback device is assigned `127.0.0.1/8`:
    ///   * address `127.0.0.1` -> `Unicast`
    ///   * address `127.0.0.2` -> `LoopbackSubnet`
    ///   * address `127.255.255.255` -> `SubnetBroadcast`
    /// This exists for Linux conformance, which on the Loopback device,
    /// considers an IPv4 address assigned if it belongs to one of the device's
    /// assigned subnets.
    LoopbackSubnet,
}

impl Ipv4PresentAddressStatus {
    fn to_broadcast_marker(&self) -> Option<<Ipv4 as BroadcastIpExt>::BroadcastMarker> {
        match self {
            Self::LimitedBroadcast | Self::SubnetBroadcast => Some(()),
            Self::Multicast | Self::Unicast | Self::LoopbackSubnet => None,
        }
    }
}

/// The status of an IPv6 address.
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub enum Ipv6PresentAddressStatus {
    Multicast,
    UnicastAssigned,
    UnicastTentative,
}

/// An extension trait providing IP layer properties.
pub trait IpLayerIpExt: IpExt + MulticastRouteIpExt + IcmpHandlerIpExt + FilterIpExt {
    /// IP Address status.
    type AddressStatus: Debug;
    /// IP Address state.
    type State<StrongDeviceId: StrongDeviceIdentifier, BT: IpLayerBindingsTypes>: AsRef<
        IpStateInner<Self, StrongDeviceId, BT>,
    >;
    /// State kept for packet identifiers.
    type PacketIdState;
    /// The type of a single packet identifier.
    type PacketId;
    /// Receive counters.
    type RxCounters: Default + Inspectable;
    /// Produces the next packet ID from the state.
    fn next_packet_id_from_state(state: &Self::PacketIdState) -> Self::PacketId;
}

impl IpLayerIpExt for Ipv4 {
    type AddressStatus = Ipv4PresentAddressStatus;
    type State<StrongDeviceId: StrongDeviceIdentifier, BT: IpLayerBindingsTypes> =
        Ipv4State<StrongDeviceId, BT>;
    type PacketIdState = AtomicU16;
    type PacketId = u16;
    type RxCounters = Ipv4RxCounters;
    fn next_packet_id_from_state(next_packet_id: &Self::PacketIdState) -> Self::PacketId {
        // Relaxed ordering as we only need atomicity without synchronization. See
        // https://en.cppreference.com/w/cpp/atomic/memory_order#Relaxed_ordering
        // for more details.
        next_packet_id.fetch_add(1, atomic::Ordering::Relaxed)
    }
}

impl IpLayerIpExt for Ipv6 {
    type AddressStatus = Ipv6PresentAddressStatus;
    type State<StrongDeviceId: StrongDeviceIdentifier, BT: IpLayerBindingsTypes> =
        Ipv6State<StrongDeviceId, BT>;
    type PacketIdState = ();
    type PacketId = ();
    type RxCounters = Ipv6RxCounters;
    fn next_packet_id_from_state((): &Self::PacketIdState) -> Self::PacketId {
        ()
    }
}

/// The state context provided to the IP layer.
pub trait IpStateContext<I: IpLayerIpExt>:
    IpRouteTablesContext<I, DeviceId: DeviceWithName>
{
    /// The context that provides access to the IP routing tables.
    type IpRouteTablesCtx<'a>: IpRouteTablesContext<I, DeviceId = Self::DeviceId>;

    /// Gets an immutable reference to the rules table.
    fn with_rules_table<
        O,
        F: FnOnce(&mut Self::IpRouteTablesCtx<'_>, &RulesTable<I, Self::DeviceId>) -> O,
    >(
        &mut self,
        cb: F,
    ) -> O;

    /// Gets a mutable reference to the rules table.
    fn with_rules_table_mut<
        O,
        F: FnOnce(&mut Self::IpRouteTablesCtx<'_>, &mut RulesTable<I, Self::DeviceId>) -> O,
    >(
        &mut self,
        cb: F,
    ) -> O;
}

/// The state context that gives access to routing tables provided to the IP layer.
pub trait IpRouteTablesContext<I: IpLayerIpExt>: IpDeviceContext<I> {
    /// The inner device id context.
    type IpDeviceIdCtx<'a>: DeviceIdContext<AnyDevice, DeviceId = Self::DeviceId, WeakDeviceId = Self::WeakDeviceId>
        + IpRoutingDeviceContext<I>
        + IpDeviceStateContext<I>
        + IpDeviceContext<I>;

    /// Gets the main table ID.
    fn main_table_id(&self) -> RoutingTableId<I, Self::DeviceId>;

    /// Gets mutable access to all the routing tables that currently exist.
    fn with_ip_routing_tables_mut<
        O,
        F: FnOnce(
            &mut HashMap<
                RoutingTableId<I, Self::DeviceId>,
                PrimaryRc<RwLock<RoutingTable<I, Self::DeviceId>>>,
            >,
        ) -> O,
    >(
        &mut self,
        cb: F,
    ) -> O;

    // TODO(https://fxbug.dev/354724171): Remove this function when we no longer
    // make routing decisions starting from the main table.
    /// Calls the function with an immutable reference to IP routing table.
    fn with_main_ip_routing_table<
        O,
        F: FnOnce(&mut Self::IpDeviceIdCtx<'_>, &RoutingTable<I, Self::DeviceId>) -> O,
    >(
        &mut self,
        cb: F,
    ) -> O {
        let main_table_id = self.main_table_id();
        self.with_ip_routing_table(&main_table_id, cb)
    }

    // TODO(https://fxbug.dev/341194323): Remove this function when we no longer
    // only update the main routing table by default.
    /// Calls the function with a mutable reference to IP routing table.
    fn with_main_ip_routing_table_mut<
        O,
        F: FnOnce(&mut Self::IpDeviceIdCtx<'_>, &mut RoutingTable<I, Self::DeviceId>) -> O,
    >(
        &mut self,
        cb: F,
    ) -> O {
        let main_table_id = self.main_table_id();
        self.with_ip_routing_table_mut(&main_table_id, cb)
    }

    /// Calls the function with an immutable reference to IP routing table.
    fn with_ip_routing_table<
        O,
        F: FnOnce(&mut Self::IpDeviceIdCtx<'_>, &RoutingTable<I, Self::DeviceId>) -> O,
    >(
        &mut self,
        table_id: &RoutingTableId<I, Self::DeviceId>,
        cb: F,
    ) -> O;

    /// Calls the function with a mutable reference to IP routing table.
    fn with_ip_routing_table_mut<
        O,
        F: FnOnce(&mut Self::IpDeviceIdCtx<'_>, &mut RoutingTable<I, Self::DeviceId>) -> O,
    >(
        &mut self,
        table_id: &RoutingTableId<I, Self::DeviceId>,
        cb: F,
    ) -> O;
}

/// Provides access to an IP device's state for the IP layer.
pub trait IpDeviceStateContext<I: IpLayerIpExt>: DeviceIdContext<AnyDevice> {
    /// Calls the callback with the next packet ID.
    fn with_next_packet_id<O, F: FnOnce(&I::PacketIdState) -> O>(&self, cb: F) -> O;

    /// Returns the best local address for communicating with the remote.
    fn get_local_addr_for_remote(
        &mut self,
        device_id: &Self::DeviceId,
        remote: Option<SpecifiedAddr<I::Addr>>,
    ) -> Option<IpDeviceAddr<I::Addr>>;

    /// Returns the hop limit.
    fn get_hop_limit(&mut self, device_id: &Self::DeviceId) -> NonZeroU8;

    /// Gets the status of an address.
    ///
    /// Only the specified device will be checked for the address. Returns
    /// [`AddressStatus::Unassigned`] if the address is not assigned to the
    /// device.
    fn address_status_for_device(
        &mut self,
        addr: SpecifiedAddr<I::Addr>,
        device_id: &Self::DeviceId,
    ) -> AddressStatus<I::AddressStatus>;
}

/// The IP device context provided to the IP layer.
pub trait IpDeviceContext<I: IpLayerIpExt>: IpDeviceStateContext<I> {
    /// Is the device enabled?
    fn is_ip_device_enabled(&mut self, device_id: &Self::DeviceId) -> bool;

    /// The iterator provided to [`IpDeviceContext::with_address_statuses`].
    type DeviceAndAddressStatusIter<'a>: Iterator<Item = (Self::DeviceId, I::AddressStatus)>;

    /// Provides access to the status of an address.
    ///
    /// Calls the provided callback with an iterator over the devices for which
    /// the address is assigned and the status of the assignment for each
    /// device.
    fn with_address_statuses<F: FnOnce(Self::DeviceAndAddressStatusIter<'_>) -> R, R>(
        &mut self,
        addr: SpecifiedAddr<I::Addr>,
        cb: F,
    ) -> R;

    /// Returns true iff the device has unicast forwarding enabled.
    fn is_device_unicast_forwarding_enabled(&mut self, device_id: &Self::DeviceId) -> bool;
}

/// Provides the ability to check neighbor reachability via a specific device.
pub trait IpDeviceConfirmReachableContext<I: IpLayerIpExt, BC>: DeviceIdContext<AnyDevice> {
    /// Confirm transport-layer forward reachability to the specified neighbor
    /// through the specified device.
    fn confirm_reachable(
        &mut self,
        bindings_ctx: &mut BC,
        device: &Self::DeviceId,
        neighbor: SpecifiedAddr<I::Addr>,
    );
}

/// Provides access to an IP device's MTU for the IP layer.
pub trait IpDeviceMtuContext<I: Ip>: DeviceIdContext<AnyDevice> {
    /// Returns the MTU of the device.
    ///
    /// The MTU is the maximum size of an IP packet.
    fn get_mtu(&mut self, device_id: &Self::DeviceId) -> Mtu;
}

/// Events observed at the IP layer.
#[derive(Debug, Eq, Hash, PartialEq, GenericOverIp)]
#[generic_over_ip(I, Ip)]
pub enum IpLayerEvent<DeviceId, I: IpLayerIpExt> {
    /// A route needs to be added.
    AddRoute(types::AddableEntry<I::Addr, DeviceId>),
    /// Routes matching these specifiers need to be removed.
    RemoveRoutes {
        /// Destination subnet
        subnet: Subnet<I::Addr>,
        /// Outgoing interface
        device: DeviceId,
        /// Gateway/next-hop
        gateway: Option<SpecifiedAddr<I::Addr>>,
    },
    /// The multicast forwarding engine emitted an event.
    MulticastForwarding(MulticastForwardingEvent<I, DeviceId>),
}

impl<DeviceId, I: IpLayerIpExt> From<MulticastForwardingEvent<I, DeviceId>>
    for IpLayerEvent<DeviceId, I>
{
    fn from(event: MulticastForwardingEvent<I, DeviceId>) -> IpLayerEvent<DeviceId, I> {
        IpLayerEvent::MulticastForwarding(event)
    }
}

impl<DeviceId, I: IpLayerIpExt> IpLayerEvent<DeviceId, I> {
    /// Changes the device id type with `map`.
    pub fn map_device<N, F: Fn(DeviceId) -> N>(self, map: F) -> IpLayerEvent<N, I> {
        match self {
            IpLayerEvent::AddRoute(types::AddableEntry { subnet, device, gateway, metric }) => {
                IpLayerEvent::AddRoute(types::AddableEntry {
                    subnet,
                    device: map(device),
                    gateway,
                    metric,
                })
            }
            IpLayerEvent::RemoveRoutes { subnet, device, gateway } => {
                IpLayerEvent::RemoveRoutes { subnet, device: map(device), gateway }
            }
            IpLayerEvent::MulticastForwarding(e) => {
                IpLayerEvent::MulticastForwarding(e.map_device(map))
            }
        }
    }
}

/// The bindings execution context for the IP layer.
pub trait IpLayerBindingsContext<I: IpLayerIpExt, DeviceId>:
    InstantContext + EventContext<IpLayerEvent<DeviceId, I>> + TracingContext + FilterBindingsContext
{
}
impl<
        I: IpLayerIpExt,
        DeviceId,
        BC: InstantContext
            + EventContext<IpLayerEvent<DeviceId, I>>
            + TracingContext
            + FilterBindingsContext,
    > IpLayerBindingsContext<I, DeviceId> for BC
{
}

/// A marker trait for bindings types at the IP layer.
pub trait IpLayerBindingsTypes: IcmpBindingsTypes + IpStateBindingsTypes {}
impl<BT: IcmpBindingsTypes + IpStateBindingsTypes> IpLayerBindingsTypes for BT {}

/// The execution context for the IP layer.
pub trait IpLayerContext<
    I: IpLayerIpExt,
    BC: IpLayerBindingsContext<I, <Self as DeviceIdContext<AnyDevice>>::DeviceId>,
>:
    IpStateContext<I>
    + IpDeviceContext<I>
    + IpDeviceMtuContext<I>
    + IpDeviceSendContext<I, BC>
    + IcmpErrorHandler<I, BC>
    + MulticastForwardingStateContext<I, BC>
    + MulticastForwardingDeviceContext<I>
    + CounterContext<MulticastForwardingCounters<I>>
{
}

impl<
        I: IpLayerIpExt,
        BC: IpLayerBindingsContext<I, <CC as DeviceIdContext<AnyDevice>>::DeviceId>,
        CC: IpStateContext<I>
            + IpDeviceContext<I>
            + IpDeviceMtuContext<I>
            + IpDeviceSendContext<I, BC>
            + IcmpErrorHandler<I, BC>
            + MulticastForwardingStateContext<I, BC>
            + MulticastForwardingDeviceContext<I>
            + CounterContext<MulticastForwardingCounters<I>>,
    > IpLayerContext<I, BC> for CC
{
}

fn is_unicast_assigned<I: IpLayerIpExt>(status: &I::AddressStatus) -> bool {
    #[derive(GenericOverIp)]
    #[generic_over_ip(I, Ip)]
    struct WrapAddressStatus<'a, I: IpLayerIpExt>(&'a I::AddressStatus);

    I::map_ip(
        WrapAddressStatus(status),
        |WrapAddressStatus(status)| match status {
            Ipv4PresentAddressStatus::Unicast | Ipv4PresentAddressStatus::LoopbackSubnet => true,
            Ipv4PresentAddressStatus::LimitedBroadcast
            | Ipv4PresentAddressStatus::SubnetBroadcast
            | Ipv4PresentAddressStatus::Multicast => false,
        },
        |WrapAddressStatus(status)| match status {
            Ipv6PresentAddressStatus::UnicastAssigned => true,
            Ipv6PresentAddressStatus::Multicast | Ipv6PresentAddressStatus::UnicastTentative => {
                false
            }
        },
    )
}

fn is_local_assigned_address<I: Ip + IpLayerIpExt, CC: IpDeviceStateContext<I>>(
    core_ctx: &mut CC,
    device: &CC::DeviceId,
    addr: IpDeviceAddr<I::Addr>,
) -> bool {
    match core_ctx.address_status_for_device(addr.into(), device) {
        AddressStatus::Present(status) => is_unicast_assigned::<I>(&status),
        AddressStatus::Unassigned => false,
    }
}

fn get_device_with_assigned_address<I, CC>(
    core_ctx: &mut CC,
    addr: IpDeviceAddr<I::Addr>,
) -> Option<(CC::DeviceId, I::AddressStatus)>
where
    I: IpLayerIpExt,
    CC: IpDeviceStateContext<I> + IpDeviceContext<I>,
{
    core_ctx.with_address_statuses(addr.into(), |mut it| {
        it.find_map(|(device, status)| {
            is_unicast_assigned::<I>(&status).then_some((device, status))
        })
    })
}

// Returns the local IP address to use for sending packets from the
// given device to `addr`, restricting to `local_ip` if it is not
// `None`.
fn get_local_addr<I: Ip + IpLayerIpExt, CC: IpDeviceStateContext<I>>(
    core_ctx: &mut CC,
    local_ip_and_policy: Option<(IpDeviceAddr<I::Addr>, NonLocalSrcAddrPolicy)>,
    device: &CC::DeviceId,
    remote_addr: Option<RoutableIpAddr<I::Addr>>,
) -> Result<IpDeviceAddr<I::Addr>, ResolveRouteError> {
    match local_ip_and_policy {
        Some((local_ip, NonLocalSrcAddrPolicy::Allow)) => Ok(local_ip),
        Some((local_ip, NonLocalSrcAddrPolicy::Deny)) => {
            is_local_assigned_address(core_ctx, device, local_ip)
                .then_some(local_ip)
                .ok_or(ResolveRouteError::NoSrcAddr)
        }
        None => core_ctx
            .get_local_addr_for_remote(device, remote_addr.map(Into::into))
            .ok_or(ResolveRouteError::NoSrcAddr),
    }
}

/// An error occurred while resolving the route to a destination
#[derive(Error, Copy, Clone, Debug, Eq, GenericOverIp, PartialEq)]
#[generic_over_ip()]
pub enum ResolveRouteError {
    /// A source address could not be selected.
    #[error("a source address could not be selected")]
    NoSrcAddr,
    /// The destination in unreachable.
    #[error("no route exists to the destination IP address")]
    Unreachable,
}

/// Like [`get_local_addr`], but willing to forward internally as necessary.
fn get_local_addr_with_internal_forwarding<I, CC>(
    core_ctx: &mut CC,
    local_ip_and_policy: Option<(IpDeviceAddr<I::Addr>, NonLocalSrcAddrPolicy)>,
    device: &CC::DeviceId,
    remote_addr: Option<RoutableIpAddr<I::Addr>>,
) -> Result<(IpDeviceAddr<I::Addr>, InternalForwarding<CC::DeviceId>), ResolveRouteError>
where
    I: IpLayerIpExt,
    CC: IpDeviceContext<I> + IpDeviceStateContext<I>,
{
    match get_local_addr(core_ctx, local_ip_and_policy, device, remote_addr) {
        Ok(src_addr) => Ok((src_addr, InternalForwarding::NotUsed)),
        Err(e) => {
            // If a local_ip was specified, the local_ip is assigned to a
            // device, and that device has forwarding enabled, use internal
            // forwarding.
            //
            // This enables a weak host model when the Netstack is configured as
            // a router. Conceptually the netstack is forwarding the packet from
            // the local IP's device to the output device of the selected route.
            if let Some((local_ip, _policy)) = local_ip_and_policy {
                if let Some((device, _addr_status)) =
                    get_device_with_assigned_address(core_ctx, local_ip)
                {
                    if core_ctx.is_device_unicast_forwarding_enabled(&device) {
                        return Ok((local_ip, InternalForwarding::Used(device)));
                    }
                }
            }
            Err(e)
        }
    }
}

/// The information about the rule walk in addition to a custom state. This type is introduced so
/// that `walk_rules` can be extended later with more information about the walk if needed.
#[derive(Debug, PartialEq, Eq)]
struct RuleWalkInfo<O> {
    /// Whether there is a rule with a source address matcher during the walk.
    observed_source_address_matcher: bool,
    /// The custom info carried. For example this could be the lookup result from the user provided
    /// function.
    inner: O,
}

/// A helper function that traverses through the rules table.
///
/// To walk through the rules, you need to provide it with an initial value for the loop and a
/// callback function that yieds a [`ControlFlow`] result to indicate whether the traversal should
/// stop.
///
/// # Returns
///
/// - `ControlFlow::Break(RuleAction::Lookup(_))` if we hit a lookup rule and an output is
///   yielded from the route table.
/// - `ControlFlow::Break(RuleAction::Unreachable)` if we hit an unreachable rule.
/// - `ControlFlow::Continue(_)` if we finished walking the rules table without yielding any
///   result.
fn walk_rules<
    I: IpLayerIpExt,
    CC: IpRouteTablesContext<I, DeviceId: DeviceWithName>,
    O,
    State,
    F: FnMut(
        State,
        &mut CC::IpDeviceIdCtx<'_>,
        &RoutingTable<I, CC::DeviceId>,
    ) -> ControlFlow<O, State>,
>(
    core_ctx: &mut CC,
    rules: &RulesTable<I, CC::DeviceId>,
    init: State,
    rule_input: &RuleInput<'_, I, CC::DeviceId>,
    mut lookup_table: F,
) -> ControlFlow<RuleAction<RuleWalkInfo<O>>, RuleWalkInfo<State>> {
    rules.iter().try_fold(
        RuleWalkInfo { inner: init, observed_source_address_matcher: false },
        |RuleWalkInfo { inner: state, observed_source_address_matcher },
         Rule { action, matcher }| {
            let observed_source_address_matcher =
                observed_source_address_matcher || matcher.source_address_matcher.is_some();
            if !matcher.matches(rule_input) {
                return ControlFlow::Continue(RuleWalkInfo {
                    inner: state,
                    observed_source_address_matcher,
                });
            }
            match action {
                RuleAction::Unreachable => return ControlFlow::Break(RuleAction::Unreachable),
                RuleAction::Lookup(table_id) => core_ctx.with_ip_routing_table(
                    &table_id,
                    |core_ctx, table| match lookup_table(state, core_ctx, table) {
                        ControlFlow::Break(out) => {
                            ControlFlow::Break(RuleAction::Lookup(RuleWalkInfo {
                                inner: out,
                                observed_source_address_matcher,
                            }))
                        }
                        ControlFlow::Continue(state) => ControlFlow::Continue(RuleWalkInfo {
                            inner: state,
                            observed_source_address_matcher,
                        }),
                    },
                ),
            }
        },
    )
}

/// Returns the outgoing routing instructions for reaching the given destination.
///
/// If a `device` is specified, the resolved route is limited to those that
/// egress over the device.
///
/// If `src_ip` is specified the resolved route is limited to those that egress
/// over a device with the address assigned.
///
/// This function should only be used for calculating a route for an outgoing packet
/// that is generated by us.
pub fn resolve_output_route_to_destination<
    I: Ip + IpDeviceStateIpExt + IpDeviceIpExt + IpLayerIpExt,
    BC: IpDeviceBindingsContext<I, CC::DeviceId> + IpLayerBindingsContext<I, CC::DeviceId>,
    CC: IpStateContext<I>
        + IpDeviceContext<I>
        + IpDeviceStateContext<I>
        + device::IpDeviceConfigurationContext<I, BC>,
>(
    core_ctx: &mut CC,
    device: Option<&CC::DeviceId>,
    src_ip_and_policy: Option<(IpDeviceAddr<I::Addr>, NonLocalSrcAddrPolicy)>,
    dst_ip: Option<RoutableIpAddr<I::Addr>>,
    marks: &Marks,
) -> Result<ResolvedRoute<I, CC::DeviceId>, ResolveRouteError> {
    enum LocalDelivery<A, D> {
        WeakLoopback { dst_ip: A, device: D },
        StrongForDevice(D),
    }

    // Check if locally destined. If the destination is an address assigned
    // on an interface, and an egress interface wasn't specifically
    // selected, route via the loopback device. This lets us operate as a
    // strong host when an outgoing interface is explicitly requested while
    // still enabling local delivery via the loopback interface, which is
    // acting as a weak host. Note that if the loopback interface is
    // requested as an outgoing interface, route selection is still
    // performed as a strong host! This makes the loopback interface behave
    // more like the other interfaces on the system.
    //
    // TODO(https://fxbug.dev/42175703): Encode the delivery of locally-
    // destined packets to loopback in the route table.
    //
    // TODO(https://fxbug.dev/322539434): Linux is more permissive about
    // allowing cross-device local delivery even when SO_BINDTODEVICE or
    // link-local addresses are involved, and this behavior may need to be
    // emulated.
    let local_delivery_instructions: Option<LocalDelivery<IpDeviceAddr<I::Addr>, CC::DeviceId>> = {
        let dst_ip = dst_ip.and_then(IpDeviceAddr::new_from_socket_ip_addr);
        match (device, dst_ip) {
            (Some(device), Some(dst_ip)) => is_local_assigned_address(core_ctx, device, dst_ip)
                .then_some(LocalDelivery::StrongForDevice(device.clone())),
            (None, Some(dst_ip)) => {
                get_device_with_assigned_address(core_ctx, dst_ip).map(
                    |(dst_device, _addr_status)| {
                        // If either the source or destination addresses needs
                        // a zone ID, then use strong host to enforce that the
                        // source and destination addresses are assigned to the
                        // same interface.
                        if src_ip_and_policy
                            .is_some_and(|(ip, _policy)| ip.as_ref().must_have_zone())
                            || dst_ip.as_ref().must_have_zone()
                        {
                            LocalDelivery::StrongForDevice(dst_device)
                        } else {
                            LocalDelivery::WeakLoopback { dst_ip, device: dst_device }
                        }
                    },
                )
            }
            (_, None) => None,
        }
    };

    if let Some(local_delivery) = local_delivery_instructions {
        let loopback = core_ctx.loopback_id().ok_or(ResolveRouteError::Unreachable)?;

        let (src_addr, dest_device) = match local_delivery {
            LocalDelivery::WeakLoopback { dst_ip, device } => {
                let src_ip = match src_ip_and_policy {
                    Some((src_ip, NonLocalSrcAddrPolicy::Deny)) => {
                        let _device = get_device_with_assigned_address(core_ctx, src_ip)
                            .ok_or(ResolveRouteError::NoSrcAddr)?;
                        src_ip
                    }
                    Some((src_ip, NonLocalSrcAddrPolicy::Allow)) => src_ip,
                    None => dst_ip,
                };
                (src_ip, device)
            }
            LocalDelivery::StrongForDevice(device) => {
                (get_local_addr(core_ctx, src_ip_and_policy, &device, dst_ip)?, device)
            }
        };
        return Ok(ResolvedRoute {
            src_addr,
            local_delivery_device: Some(dest_device),
            device: loopback,
            next_hop: NextHop::RemoteAsNeighbor,
            internal_forwarding: InternalForwarding::NotUsed,
        });
    }
    let bound_address = src_ip_and_policy.map(|(sock_addr, _policy)| sock_addr.into_inner().get());
    let rule_input = RuleInput {
        packet_origin: PacketOrigin::Local { bound_address, bound_device: device },
        marks,
    };
    core_ctx.with_rules_table(|core_ctx, rules| {
        let mut walk_rules = |rule_input, src_ip_and_policy| {
            walk_rules(
                core_ctx,
                rules,
                None, /* first error encountered */
                rule_input,
                |first_error, core_ctx, table| {
                    let mut matching_with_addr = table.lookup_filter_map(
                        core_ctx,
                        device,
                        dst_ip.map_or(I::UNSPECIFIED_ADDRESS, |a| a.addr()),
                        |core_ctx, d| {
                            Some(get_local_addr_with_internal_forwarding(
                                core_ctx,
                                src_ip_and_policy,
                                d,
                                dst_ip,
                            ))
                        },
                    );

                    let first_error_in_this_table = match matching_with_addr.next() {
                        Some((
                            Destination { device, next_hop },
                            Ok((local_addr, internal_forwarding)),
                        )) => {
                            return ControlFlow::Break(Ok((
                                Destination { device: device.clone(), next_hop },
                                local_addr,
                                internal_forwarding,
                            )));
                        }
                        Some((_, Err(e))) => e,
                        // Note: rule evaluation will continue on to the next rule, if the
                        // previous rule was `Lookup` but the table didn't have the route
                        // inside of it.
                        None => return ControlFlow::Continue(first_error),
                    };

                    matching_with_addr
                        .filter_map(|(destination, local_addr)| {
                            // Select successful routes. We ignore later errors
                            // since we've already saved the first one.
                            local_addr.ok_checked::<ResolveRouteError>().map(
                                |(local_addr, internal_forwarding)| {
                                    (destination, local_addr, internal_forwarding)
                                },
                            )
                        })
                        .next()
                        .map_or(
                            ControlFlow::Continue(first_error.or(Some(first_error_in_this_table))),
                            |(
                                Destination { device, next_hop },
                                local_addr,
                                internal_forwarding,
                            )| {
                                ControlFlow::Break(Ok((
                                    Destination { device: device.clone(), next_hop },
                                    local_addr,
                                    internal_forwarding,
                                )))
                            },
                        )
                },
            )
        };

        let result = match walk_rules(&rule_input, src_ip_and_policy) {
            // Only try to resolve a route again if all of the following are true:
            // 1. The source address is not provided by the caller.
            // 2. A route is successfully resolved so we selected a source address.
            // 3. There is a rule with a source address matcher during the resolution.
            // The rationale is to make sure the route resolution converges to a sensible route
            // after considering the source address we select.
            ControlFlow::Break(RuleAction::Lookup(RuleWalkInfo {
                inner: Ok((_dst, selected_src_addr, _internal_forwarding)),
                observed_source_address_matcher: true,
            })) if src_ip_and_policy.is_none() => walk_rules(
                &RuleInput {
                    packet_origin: PacketOrigin::Local {
                        bound_address: Some(selected_src_addr.into()),
                        bound_device: device,
                    },
                    marks,
                },
                Some((selected_src_addr, NonLocalSrcAddrPolicy::Deny)),
            ),
            result => result,
        };

        match result {
            ControlFlow::Break(RuleAction::Lookup(RuleWalkInfo {
                inner: result,
                observed_source_address_matcher: _,
            })) => {
                result.map(|(Destination { device, next_hop }, src_addr, internal_forwarding)| {
                    ResolvedRoute {
                        src_addr,
                        device,
                        local_delivery_device: None,
                        next_hop,
                        internal_forwarding,
                    }
                })
            }
            ControlFlow::Break(RuleAction::Unreachable) => Err(ResolveRouteError::Unreachable),
            ControlFlow::Continue(RuleWalkInfo {
                inner: first_error,
                observed_source_address_matcher: _,
            }) => Err(first_error.unwrap_or(ResolveRouteError::Unreachable)),
        }
    })
}

/// Enables a blanket implementation of [`IpSocketContext`].
///
/// Implementing this marker trait for a type enables a blanket implementation
/// of `IpSocketContext` given the other requirements are met.
pub trait UseIpSocketContextBlanket {}

impl<
        I: Ip + IpDeviceStateIpExt + IpDeviceIpExt + IpLayerIpExt,
        BC: IpDeviceBindingsContext<I, CC::DeviceId>
            + IpLayerBindingsContext<I, CC::DeviceId>
            + IpSocketBindingsContext,
        CC: IpLayerEgressContext<I, BC>
            + IpStateContext<I>
            + IpDeviceContext<I>
            + IpDeviceConfirmReachableContext<I, BC>
            + IpDeviceStateContext<I>
            + IpDeviceMtuContext<I>
            + device::IpDeviceConfigurationContext<I, BC>
            + UseIpSocketContextBlanket,
    > IpSocketContext<I, BC> for CC
{
    fn lookup_route(
        &mut self,
        _bindings_ctx: &mut BC,
        device: Option<&CC::DeviceId>,
        local_ip: Option<IpDeviceAddr<I::Addr>>,
        addr: RoutableIpAddr<I::Addr>,
        transparent: bool,
        marks: &Marks,
    ) -> Result<ResolvedRoute<I, CC::DeviceId>, ResolveRouteError> {
        let src_ip_and_policy = local_ip.map(|local_ip| {
            (
                local_ip,
                if transparent {
                    NonLocalSrcAddrPolicy::Allow
                } else {
                    NonLocalSrcAddrPolicy::Deny
                },
            )
        });
        resolve_output_route_to_destination(self, device, src_ip_and_policy, Some(addr), marks)
    }

    fn send_ip_packet<S>(
        &mut self,
        bindings_ctx: &mut BC,
        meta: SendIpPacketMeta<
            I,
            &<CC as DeviceIdContext<AnyDevice>>::DeviceId,
            SpecifiedAddr<I::Addr>,
        >,
        body: S,
        packet_metadata: IpLayerPacketMetadata<I, BC>,
    ) -> Result<(), IpSendFrameError<S>>
    where
        S: TransportPacketSerializer<I>,
        S::Buffer: BufferMut,
    {
        send_ip_packet_from_device(self, bindings_ctx, meta.into(), body, packet_metadata)
    }

    fn get_loopback_device(&mut self) -> Option<Self::DeviceId> {
        device::IpDeviceConfigurationContext::<I, _>::loopback_id(self)
    }

    fn confirm_reachable(
        &mut self,
        bindings_ctx: &mut BC,
        dst: SpecifiedAddr<I::Addr>,
        input: RuleInput<'_, I, Self::DeviceId>,
    ) {
        match lookup_route_table(self, dst.get(), input) {
            Some(Destination { next_hop, device }) => {
                let neighbor = match next_hop {
                    NextHop::RemoteAsNeighbor => dst,
                    NextHop::Gateway(gateway) => gateway,
                    NextHop::Broadcast(marker) => {
                        I::map_ip::<_, ()>(
                            WrapBroadcastMarker(marker),
                            |WrapBroadcastMarker(())| {
                                debug!(
                                    "can't confirm {dst:?}@{device:?} as reachable: \
                                    dst is a broadcast address"
                                );
                            },
                            |WrapBroadcastMarker(never)| match never {},
                        );
                        return;
                    }
                };
                IpDeviceConfirmReachableContext::confirm_reachable(
                    self,
                    bindings_ctx,
                    &device,
                    neighbor,
                );
            }
            None => {
                debug!("can't confirm {dst:?} as reachable: no route");
            }
        }
    }
}

/// The IP context providing dispatch to the available transport protocols.
///
/// This trait acts like a demux on the transport protocol for ingress IP
/// packets.
pub trait IpTransportDispatchContext<I: IpLayerIpExt, BC>: DeviceIdContext<AnyDevice> {
    /// Dispatches a received incoming IP packet to the appropriate protocol.
    fn dispatch_receive_ip_packet<B: BufferMut>(
        &mut self,
        bindings_ctx: &mut BC,
        device: &Self::DeviceId,
        src_ip: I::RecvSrcAddr,
        dst_ip: SpecifiedAddr<I::Addr>,
        proto: I::Proto,
        body: B,
        meta: ReceiveIpPacketMeta<I>,
    ) -> Result<(), TransportReceiveError>;
}

/// A marker trait for all the contexts required for IP ingress.
pub trait IpLayerIngressContext<I: IpLayerIpExt, BC: IpLayerBindingsContext<I, Self::DeviceId>>:
    IpTransportDispatchContext<I, BC, DeviceId: filter::InterfaceProperties<BC::DeviceClass>>
    + IpDeviceStateContext<I>
    + IpDeviceMtuContext<I>
    + IpDeviceSendContext<I, BC>
    + IcmpErrorHandler<I, BC>
    + IpLayerContext<I, BC>
    + FragmentHandler<I, BC>
    + FilterHandlerProvider<I, BC>
    + RawIpSocketHandler<I, BC>
{
}

impl<
        I: IpLayerIpExt,
        BC: IpLayerBindingsContext<I, CC::DeviceId>,
        CC: IpTransportDispatchContext<
                I,
                BC,
                DeviceId: filter::InterfaceProperties<BC::DeviceClass>,
            > + IpDeviceStateContext<I>
            + IpDeviceMtuContext<I>
            + IpDeviceSendContext<I, BC>
            + IcmpErrorHandler<I, BC>
            + IpLayerContext<I, BC>
            + FragmentHandler<I, BC>
            + FilterHandlerProvider<I, BC>
            + RawIpSocketHandler<I, BC>,
    > IpLayerIngressContext<I, BC> for CC
{
}

/// A marker trait for all the contexts required for IP egress.
pub trait IpLayerEgressContext<I, BC>:
    IpDeviceSendContext<I, BC, DeviceId: filter::InterfaceProperties<BC::DeviceClass>>
    + FilterHandlerProvider<I, BC>
    + CounterContext<IpCounters<I>>
where
    I: IpLayerIpExt,
    BC: FilterBindingsContext,
{
}

impl<I, BC, CC> IpLayerEgressContext<I, BC> for CC
where
    I: IpLayerIpExt,
    BC: FilterBindingsContext,
    CC: IpDeviceSendContext<I, BC, DeviceId: filter::InterfaceProperties<BC::DeviceClass>>
        + FilterHandlerProvider<I, BC>
        + CounterContext<IpCounters<I>>,
{
}

/// A marker trait for all the contexts required for IP forwarding.
pub trait IpLayerForwardingContext<I: IpLayerIpExt, BC: IpLayerBindingsContext<I, Self::DeviceId>>:
    IpLayerEgressContext<I, BC> + IcmpErrorHandler<I, BC> + IpDeviceMtuContext<I>
{
}

impl<
        I: IpLayerIpExt,
        BC: IpLayerBindingsContext<I, CC::DeviceId>,
        CC: IpLayerEgressContext<I, BC> + IcmpErrorHandler<I, BC> + IpDeviceMtuContext<I>,
    > IpLayerForwardingContext<I, BC> for CC
{
}

/// A builder for IPv4 state.
#[derive(Copy, Clone, Default)]
pub struct Ipv4StateBuilder {
    icmp: Icmpv4StateBuilder,
}

impl Ipv4StateBuilder {
    /// Get the builder for the ICMPv4 state.
    #[cfg(any(test, feature = "testutils"))]
    pub fn icmpv4_builder(&mut self) -> &mut Icmpv4StateBuilder {
        &mut self.icmp
    }

    /// Builds the [`Ipv4State`].
    pub fn build<
        CC: CoreTimerContext<IpLayerTimerId, BC>,
        StrongDeviceId: StrongDeviceIdentifier,
        BC: TimerContext + RngContext + IpLayerBindingsTypes,
    >(
        self,
        bindings_ctx: &mut BC,
    ) -> Ipv4State<StrongDeviceId, BC> {
        let Ipv4StateBuilder { icmp } = self;

        Ipv4State {
            inner: IpStateInner::new::<CC>(bindings_ctx),
            icmp: icmp.build(),
            next_packet_id: Default::default(),
        }
    }
}

/// A builder for IPv6 state.
#[derive(Copy, Clone, Default)]
pub struct Ipv6StateBuilder {
    icmp: Icmpv6StateBuilder,
}

impl Ipv6StateBuilder {
    /// Builds the [`Ipv6State`].
    pub fn build<
        CC: CoreTimerContext<IpLayerTimerId, BC>,
        StrongDeviceId: StrongDeviceIdentifier,
        BC: TimerContext + RngContext + IpLayerBindingsTypes,
    >(
        self,
        bindings_ctx: &mut BC,
    ) -> Ipv6State<StrongDeviceId, BC> {
        let Ipv6StateBuilder { icmp } = self;

        Ipv6State {
            inner: IpStateInner::new::<CC>(bindings_ctx),
            icmp: icmp.build(),
            slaac_counters: Default::default(),
            slaac_temp_secret_key: IidSecret::new_random(&mut bindings_ctx.rng()),
        }
    }
}

/// The stack's IPv4 state.
pub struct Ipv4State<StrongDeviceId: StrongDeviceIdentifier, BT: IpLayerBindingsTypes> {
    /// The common inner IP layer state.
    pub inner: IpStateInner<Ipv4, StrongDeviceId, BT>,
    /// The ICMP state.
    pub icmp: Icmpv4State<BT>,
    /// The atomic counter providing IPv4 packet identifiers.
    pub next_packet_id: AtomicU16,
}

impl<StrongDeviceId: StrongDeviceIdentifier, BT: IpLayerBindingsTypes>
    AsRef<IpStateInner<Ipv4, StrongDeviceId, BT>> for Ipv4State<StrongDeviceId, BT>
{
    fn as_ref(&self) -> &IpStateInner<Ipv4, StrongDeviceId, BT> {
        &self.inner
    }
}

/// Generates an IP packet ID.
///
/// This is only meaningful for IPv4, see [`IpLayerIpExt`].
pub fn gen_ip_packet_id<I: IpLayerIpExt, CC: IpDeviceStateContext<I>>(
    core_ctx: &mut CC,
) -> I::PacketId {
    core_ctx.with_next_packet_id(|state| I::next_packet_id_from_state(state))
}

/// The stack's IPv6 state.
pub struct Ipv6State<StrongDeviceId: StrongDeviceIdentifier, BT: IpLayerBindingsTypes> {
    /// The common inner IP layer state.
    pub inner: IpStateInner<Ipv6, StrongDeviceId, BT>,
    /// ICMPv6 state.
    pub icmp: Icmpv6State<BT>,
    /// Stateless address autoconfiguration counters.
    pub slaac_counters: SlaacCounters,
    /// Secret key used for generating SLAAC temporary addresses.
    pub slaac_temp_secret_key: IidSecret,
}

impl<StrongDeviceId: StrongDeviceIdentifier, BT: IpLayerBindingsTypes>
    AsRef<IpStateInner<Ipv6, StrongDeviceId, BT>> for Ipv6State<StrongDeviceId, BT>
{
    fn as_ref(&self) -> &IpStateInner<Ipv6, StrongDeviceId, BT> {
        &self.inner
    }
}

impl<I: IpLayerIpExt, D: StrongDeviceIdentifier, BT: IpLayerBindingsTypes>
    OrderedLockAccess<IpPacketFragmentCache<I, BT>> for IpStateInner<I, D, BT>
{
    type Lock = Mutex<IpPacketFragmentCache<I, BT>>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(&self.fragment_cache)
    }
}

impl<I: IpLayerIpExt, D: StrongDeviceIdentifier, BT: IpLayerBindingsTypes>
    OrderedLockAccess<PmtuCache<I, BT>> for IpStateInner<I, D, BT>
{
    type Lock = Mutex<PmtuCache<I, BT>>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(&self.pmtu_cache)
    }
}

impl<I: IpLayerIpExt, D: StrongDeviceIdentifier, BT: IpLayerBindingsTypes>
    OrderedLockAccess<RulesTable<I, D>> for IpStateInner<I, D, BT>
{
    type Lock = RwLock<RulesTable<I, D>>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(&self.rules_table)
    }
}

impl<I: IpLayerIpExt, D: StrongDeviceIdentifier, BT: IpLayerBindingsTypes>
    OrderedLockAccess<HashMap<RoutingTableId<I, D>, PrimaryRc<RwLock<RoutingTable<I, D>>>>>
    for IpStateInner<I, D, BT>
{
    type Lock = Mutex<HashMap<RoutingTableId<I, D>, PrimaryRc<RwLock<RoutingTable<I, D>>>>>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(&self.tables)
    }
}

impl<I: IpLayerIpExt, D: StrongDeviceIdentifier> OrderedLockAccess<RoutingTable<I, D>>
    for RoutingTableId<I, D>
{
    type Lock = RwLock<RoutingTable<I, D>>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        let Self(inner) = self;
        OrderedLockRef::new(&*inner)
    }
}

impl<I: IpLayerIpExt, D: StrongDeviceIdentifier, BT: IpLayerBindingsTypes>
    OrderedLockAccess<MulticastForwardingState<I, D, BT>> for IpStateInner<I, D, BT>
{
    type Lock = RwLock<MulticastForwardingState<I, D, BT>>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(&self.multicast_forwarding)
    }
}

impl<I: IpLayerIpExt, D: StrongDeviceIdentifier, BT: IpLayerBindingsTypes>
    OrderedLockAccess<RawIpSocketMap<I, D::Weak, BT>> for IpStateInner<I, D, BT>
{
    type Lock = RwLock<RawIpSocketMap<I, D::Weak, BT>>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(&self.raw_sockets)
    }
}

impl<I: IpLayerIpExt, D: StrongDeviceIdentifier, BT: IpLayerBindingsTypes>
    OrderedLockAccess<filter::State<I, BT>> for IpStateInner<I, D, BT>
{
    type Lock = RwLock<filter::State<I, BT>>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(&self.filter)
    }
}

/// Ip layer counters.
#[derive(Default, GenericOverIp)]
#[generic_over_ip(I, Ip)]
pub struct IpCounters<I: IpLayerIpExt> {
    /// Count of incoming IP unicast packets delivered.
    pub deliver_unicast: Counter,
    /// Count of incoming IP multicast packets delivered.
    pub deliver_multicast: Counter,
    /// Count of incoming IP packets that are dispatched to the appropriate protocol.
    pub dispatch_receive_ip_packet: Counter,
    /// Count of incoming IP packets destined to another host.
    pub dispatch_receive_ip_packet_other_host: Counter,
    /// Count of incoming IP packets received by the stack.
    pub receive_ip_packet: Counter,
    /// Count of sent outgoing IP packets.
    pub send_ip_packet: Counter,
    /// Count of packets to be forwarded which are instead dropped because
    /// forwarding is disabled.
    pub forwarding_disabled: Counter,
    /// Count of incoming packets forwarded to another host.
    pub forward: Counter,
    /// Count of incoming packets which cannot be forwarded because there is no
    /// route to the destination host.
    pub no_route_to_host: Counter,
    /// Count of incoming packets which cannot be forwarded because the MTU has
    /// been exceeded.
    pub mtu_exceeded: Counter,
    /// Count of incoming packets which cannot be forwarded because the TTL has
    /// expired.
    pub ttl_expired: Counter,
    /// Count of ICMP error messages received.
    pub receive_icmp_error: Counter,
    /// Count of IP fragment reassembly errors.
    pub fragment_reassembly_error: Counter,
    /// Count of IP fragments that could not be reassembled because more
    /// fragments were needed.
    pub need_more_fragments: Counter,
    /// Count of IP fragments that could not be reassembled because the fragment
    /// was invalid.
    pub invalid_fragment: Counter,
    /// Count of IP fragments that could not be reassembled because the stack's
    /// per-IP-protocol fragment cache was full.
    pub fragment_cache_full: Counter,
    /// Count of incoming IP packets not delivered because of a parameter problem.
    pub parameter_problem: Counter,
    /// Count of incoming IP packets with an unspecified destination address.
    pub unspecified_destination: Counter,
    /// Count of incoming IP packets with an unspecified source address.
    pub unspecified_source: Counter,
    /// Count of incoming IP packets dropped.
    pub dropped: Counter,
    /// Number of frames rejected because they'd cause illegal loopback
    /// addresses on the wire.
    pub tx_illegal_loopback_address: Counter,
    /// Version specific rx counters.
    pub version_rx: I::RxCounters,
    /// Count of incoming IP multicast packets that were dropped because
    /// The stack doesn't have any sockets that belong to the multicast group,
    /// and the stack isn't configured to forward the multicast packet.
    pub multicast_no_interest: Counter,
}

/// IPv4-specific Rx counters.
#[derive(Default)]
pub struct Ipv4RxCounters {
    /// Count of incoming broadcast IPv4 packets delivered.
    pub deliver_broadcast: Counter,
}

impl Inspectable for Ipv4RxCounters {
    fn record<I: Inspector>(&self, inspector: &mut I) {
        let Self { deliver_broadcast } = self;
        inspector.record_counter("DeliveredBroadcast", deliver_broadcast);
    }
}

/// IPv6-specific Rx counters.
#[derive(Default)]
pub struct Ipv6RxCounters {
    /// Count of incoming IPv6 packets dropped because the destination address
    /// is only tentatively assigned to the device.
    pub drop_for_tentative: Counter,
    /// Count of incoming IPv6 packets dropped due to a non-unicast source address.
    pub non_unicast_source: Counter,
    /// Count of incoming IPv6 packets discarded while processing extension
    /// headers.
    pub extension_header_discard: Counter,
    /// Count of incoming neighbor solicitations discarded as looped-back
    /// DAD probes.
    pub drop_looped_back_dad_probe: Counter,
}

impl Inspectable for Ipv6RxCounters {
    fn record<I: Inspector>(&self, inspector: &mut I) {
        let Self {
            drop_for_tentative,
            non_unicast_source,
            extension_header_discard,
            drop_looped_back_dad_probe,
        } = self;
        inspector.record_counter("DroppedTentativeDst", drop_for_tentative);
        inspector.record_counter("DroppedNonUnicastSrc", non_unicast_source);
        inspector.record_counter("DroppedExtensionHeader", extension_header_discard);
        inspector.record_counter("DroppedLoopedBackDadProbe", drop_looped_back_dad_probe);
    }
}

/// Marker trait for the bindings types required by the IP layer's inner state.
pub trait IpStateBindingsTypes:
    PmtuBindingsTypes
    + FragmentBindingsTypes
    + RawIpSocketsBindingsTypes
    + FilterBindingsTypes
    + MulticastForwardingBindingsTypes
{
}
impl<BT> IpStateBindingsTypes for BT where
    BT: PmtuBindingsTypes
        + FragmentBindingsTypes
        + RawIpSocketsBindingsTypes
        + FilterBindingsTypes
        + MulticastForwardingBindingsTypes
{
}

/// Identifier to a routing table.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct RoutingTableId<I: Ip, D>(StrongRc<RwLock<RoutingTable<I, D>>>);

impl<I: Ip, D> Debug for RoutingTableId<I, D> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let Self(rc) = self;
        f.debug_tuple("RoutingTabeId").field(&StrongRc::debug_id(rc)).finish()
    }
}

impl<I: Ip, D> RoutingTableId<I, D> {
    /// Creates a new table ID.
    pub(crate) fn new(rc: StrongRc<RwLock<RoutingTable<I, D>>>) -> Self {
        Self(rc)
    }

    /// Provides direct access to the forwarding table.
    #[cfg(any(test, feature = "testutils"))]
    pub fn table(&self) -> &RwLock<RoutingTable<I, D>> {
        let Self(inner) = self;
        &*inner
    }

    /// Downgrades the strong ID into a weak one.
    pub fn downgrade(&self) -> WeakRoutingTableId<I, D> {
        let Self(rc) = self;
        WeakRoutingTableId(StrongRc::downgrade(rc))
    }

    #[cfg(test)]
    fn get_mut(&self) -> impl DerefMut<Target = RoutingTable<I, D>> + '_ {
        let Self(rc) = self;
        rc.write()
    }
}

/// Weak Identifier to a routing table.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct WeakRoutingTableId<I: Ip, D>(WeakRc<RwLock<RoutingTable<I, D>>>);

impl<I: Ip, D> Debug for WeakRoutingTableId<I, D> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let Self(rc) = self;
        f.debug_tuple("WeakRoutingTabeId").field(&WeakRc::debug_id(rc)).finish()
    }
}

/// The inner state for the IP layer for IP version `I`.
#[derive(GenericOverIp)]
#[generic_over_ip(I, Ip)]
pub struct IpStateInner<I: IpLayerIpExt, D: StrongDeviceIdentifier, BT: IpStateBindingsTypes> {
    rules_table: RwLock<RulesTable<I, D>>,
    // TODO(https://fxbug.dev/355059838): Explore the option to let Bindings create the main table.
    main_table_id: RoutingTableId<I, D>,
    multicast_forwarding: RwLock<MulticastForwardingState<I, D, BT>>,
    multicast_forwarding_counters: MulticastForwardingCounters<I>,
    fragment_cache: Mutex<IpPacketFragmentCache<I, BT>>,
    pmtu_cache: Mutex<PmtuCache<I, BT>>,
    counters: IpCounters<I>,
    raw_sockets: RwLock<RawIpSocketMap<I, D::Weak, BT>>,
    raw_socket_counters: RawIpSocketCounters<I>,
    filter: RwLock<filter::State<I, BT>>,
    // Make sure the primary IDs are dropped last. Also note that the following hash map also stores
    // the primary ID to the main table, and if the user (Bindings) attempts to remove the main
    // table without dropping `main_table_id` first, it will panic. This serves as an assertion
    // that the main table cannot be removed and Bindings must never attempt to remove the main
    // routing table.
    tables: Mutex<HashMap<RoutingTableId<I, D>, PrimaryRc<RwLock<RoutingTable<I, D>>>>>,
}

impl<I: IpLayerIpExt, D: StrongDeviceIdentifier, BT: IpStateBindingsTypes> IpStateInner<I, D, BT> {
    /// Gets the IP counters.
    pub fn counters(&self) -> &IpCounters<I> {
        &self.counters
    }

    /// Gets the multicast forwarding counters.
    pub fn multicast_forwarding_counters(&self) -> &MulticastForwardingCounters<I> {
        &self.multicast_forwarding_counters
    }

    /// Gets the aggregate raw IP socket counters.
    pub fn raw_ip_socket_counters(&self) -> &RawIpSocketCounters<I> {
        &self.raw_socket_counters
    }

    /// Gets the main table ID.
    pub fn main_table_id(&self) -> &RoutingTableId<I, D> {
        &self.main_table_id
    }

    /// Provides direct access to the path MTU cache.
    #[cfg(any(test, feature = "testutils"))]
    pub fn pmtu_cache(&self) -> &Mutex<PmtuCache<I, BT>> {
        &self.pmtu_cache
    }
}

impl<
        I: IpLayerIpExt,
        D: StrongDeviceIdentifier,
        BC: TimerContext + RngContext + IpStateBindingsTypes,
    > IpStateInner<I, D, BC>
{
    /// Creates a new inner IP layer state.
    fn new<CC: CoreTimerContext<IpLayerTimerId, BC>>(bindings_ctx: &mut BC) -> Self {
        let main_table: PrimaryRc<RwLock<RoutingTable<I, D>>> = PrimaryRc::new(Default::default());
        let main_table_id = RoutingTableId(PrimaryRc::clone_strong(&main_table));
        Self {
            rules_table: RwLock::new(RulesTable::new(main_table_id.clone())),
            tables: Mutex::new(HashMap::from_iter(core::iter::once((
                main_table_id.clone(),
                main_table,
            )))),
            main_table_id,
            multicast_forwarding: Default::default(),
            multicast_forwarding_counters: Default::default(),
            fragment_cache: Mutex::new(
                IpPacketFragmentCache::new::<NestedIntoCoreTimerCtx<CC, _>>(bindings_ctx),
            ),
            pmtu_cache: Mutex::new(PmtuCache::new::<NestedIntoCoreTimerCtx<CC, _>>(bindings_ctx)),
            counters: Default::default(),
            raw_sockets: Default::default(),
            raw_socket_counters: Default::default(),
            filter: RwLock::new(filter::State::new::<NestedIntoCoreTimerCtx<CC, _>>(bindings_ctx)),
        }
    }
}

/// The identifier for timer events in the IP layer.
#[derive(Debug, Clone, Eq, PartialEq, Hash, GenericOverIp)]
#[generic_over_ip()]
pub enum IpLayerTimerId {
    /// A timer event for IPv4 packet reassembly timers.
    ReassemblyTimeoutv4(FragmentTimerId<Ipv4>),
    /// A timer event for IPv6 packet reassembly timers.
    ReassemblyTimeoutv6(FragmentTimerId<Ipv6>),
    /// A timer event for IPv4 path MTU discovery.
    PmtuTimeoutv4(PmtuTimerId<Ipv4>),
    /// A timer event for IPv6 path MTU discovery.
    PmtuTimeoutv6(PmtuTimerId<Ipv6>),
    /// A timer event for IPv4 filtering timers.
    FilterTimerv4(FilterTimerId<Ipv4>),
    /// A timer event for IPv6 filtering timers.
    FilterTimerv6(FilterTimerId<Ipv6>),
    /// A timer event for IPv4 Multicast forwarding timers.
    MulticastForwardingTimerv4(MulticastForwardingTimerId<Ipv4>),
    /// A timer event for IPv6 Multicast forwarding timers.
    MulticastForwardingTimerv6(MulticastForwardingTimerId<Ipv6>),
}

impl<I: Ip> From<FragmentTimerId<I>> for IpLayerTimerId {
    fn from(timer: FragmentTimerId<I>) -> IpLayerTimerId {
        I::map_ip(timer, IpLayerTimerId::ReassemblyTimeoutv4, IpLayerTimerId::ReassemblyTimeoutv6)
    }
}

impl<I: Ip> From<PmtuTimerId<I>> for IpLayerTimerId {
    fn from(timer: PmtuTimerId<I>) -> IpLayerTimerId {
        I::map_ip(timer, IpLayerTimerId::PmtuTimeoutv4, IpLayerTimerId::PmtuTimeoutv6)
    }
}

impl<I: Ip> From<FilterTimerId<I>> for IpLayerTimerId {
    fn from(timer: FilterTimerId<I>) -> IpLayerTimerId {
        I::map_ip(timer, IpLayerTimerId::FilterTimerv4, IpLayerTimerId::FilterTimerv6)
    }
}

impl<I: Ip> From<MulticastForwardingTimerId<I>> for IpLayerTimerId {
    fn from(timer: MulticastForwardingTimerId<I>) -> IpLayerTimerId {
        I::map_ip(
            timer,
            IpLayerTimerId::MulticastForwardingTimerv4,
            IpLayerTimerId::MulticastForwardingTimerv6,
        )
    }
}

impl<CC, BC> HandleableTimer<CC, BC> for IpLayerTimerId
where
    CC: TimerHandler<BC, FragmentTimerId<Ipv4>>
        + TimerHandler<BC, FragmentTimerId<Ipv6>>
        + TimerHandler<BC, PmtuTimerId<Ipv4>>
        + TimerHandler<BC, PmtuTimerId<Ipv6>>
        + TimerHandler<BC, FilterTimerId<Ipv4>>
        + TimerHandler<BC, FilterTimerId<Ipv6>>
        + TimerHandler<BC, MulticastForwardingTimerId<Ipv4>>
        + TimerHandler<BC, MulticastForwardingTimerId<Ipv6>>,
    BC: TimerBindingsTypes,
{
    fn handle(self, core_ctx: &mut CC, bindings_ctx: &mut BC, timer: BC::UniqueTimerId) {
        match self {
            IpLayerTimerId::ReassemblyTimeoutv4(id) => {
                core_ctx.handle_timer(bindings_ctx, id, timer)
            }
            IpLayerTimerId::ReassemblyTimeoutv6(id) => {
                core_ctx.handle_timer(bindings_ctx, id, timer)
            }
            IpLayerTimerId::PmtuTimeoutv4(id) => core_ctx.handle_timer(bindings_ctx, id, timer),
            IpLayerTimerId::PmtuTimeoutv6(id) => core_ctx.handle_timer(bindings_ctx, id, timer),
            IpLayerTimerId::FilterTimerv4(id) => core_ctx.handle_timer(bindings_ctx, id, timer),
            IpLayerTimerId::FilterTimerv6(id) => core_ctx.handle_timer(bindings_ctx, id, timer),
            IpLayerTimerId::MulticastForwardingTimerv4(id) => {
                core_ctx.handle_timer(bindings_ctx, id, timer)
            }
            IpLayerTimerId::MulticastForwardingTimerv6(id) => {
                core_ctx.handle_timer(bindings_ctx, id, timer)
            }
        }
    }
}

/// An ICMP error, and the metadata required to send it.
///
/// This allows the sending of the ICMP error to be decoupled from the
/// generation of the error, which is advantageous because sending the error
/// requires the underlying packet buffer, which cannot be "moved" in certain
/// contexts.
pub(crate) struct IcmpErrorSender<'a, I: IcmpHandlerIpExt, D> {
    /// The ICMP error that should be sent.
    err: I::IcmpError,
    /// The original source IP address of the packet (before the local-ingress
    /// hook evaluation).
    src_ip: I::SourceAddress,
    /// The original destination IP address of the packet (before the
    /// local-ingress hook evaluation).
    dst_ip: SpecifiedAddr<I::Addr>,
    /// The frame destination of the packet.
    frame_dst: Option<FrameDestination>,
    /// The device out which to send the error.
    device: &'a D,
    /// The metadata from the packet, allowing the packet's backing buffer to be
    /// returned to it's pre-IP-parse state with [`GrowBuffer::undo_parse`].
    meta: ParseMetadata,
}

impl<'a, I: IcmpHandlerIpExt, D> IcmpErrorSender<'a, I, D> {
    /// Generate an send an appropriate ICMP error in response to this error.
    ///
    /// The provided `body` must be the original buffer from which the IP
    /// packet responsible for this error was parsed. It is expected to be in a
    /// state that allows undoing the IP packet parse (e.g. unmodified after the
    /// IP packet was parsed).
    fn respond_with_icmp_error<B, BC, CC>(
        self,
        core_ctx: &mut CC,
        bindings_ctx: &mut BC,
        mut body: B,
    ) where
        B: BufferMut,
        CC: IcmpErrorHandler<I, BC, DeviceId = D>,
    {
        let IcmpErrorSender { err, src_ip, dst_ip, frame_dst, device, meta } = self;
        // Undo the parsing of the IP Packet, moving the buffer's cursor so that
        // it points at the start of the IP header. This way, the sent ICMP
        // error will contain the entire original IP packet.
        body.undo_parse(meta);

        core_ctx.send_icmp_error_message(
            bindings_ctx,
            device,
            frame_dst,
            src_ip,
            dst_ip,
            body,
            err,
        );
    }
}

// TODO(joshlf): Once we support multiple extension headers in IPv6, we will
// need to verify that the callers of this function are still sound. In
// particular, they may accidentally pass a parse_metadata argument which
// corresponds to a single extension header rather than all of the IPv6 headers.

/// Dispatch a received IPv4 packet to the appropriate protocol.
///
/// `device` is the device the packet was received on. `parse_metadata` is the
/// parse metadata associated with parsing the IP headers. It is used to undo
/// that parsing. Both `device` and `parse_metadata` are required in order to
/// send ICMP messages in response to unrecognized protocols or ports. If either
/// of `device` or `parse_metadata` is `None`, the caller promises that the
/// protocol and port are recognized.
///
/// # Panics
///
/// `dispatch_receive_ipv4_packet` panics if the protocol is unrecognized and
/// `parse_metadata` is `None`. If an IGMP message is received but it is not
/// coming from a device, i.e., `device` given is `None`,
/// `dispatch_receive_ip_packet` will also panic.
fn dispatch_receive_ipv4_packet<
    'a,
    'b,
    BC: IpLayerBindingsContext<Ipv4, CC::DeviceId>,
    CC: IpLayerIngressContext<Ipv4, BC> + CounterContext<IpCounters<Ipv4>>,
>(
    core_ctx: &'a mut CC,
    bindings_ctx: &'a mut BC,
    device: &'b CC::DeviceId,
    frame_dst: Option<FrameDestination>,
    mut packet: Ipv4Packet<&'a mut [u8]>,
    mut packet_metadata: IpLayerPacketMetadata<Ipv4, BC>,
    transparent_override: Option<TransparentLocalDelivery<Ipv4>>,
    broadcast_marker: Option<<Ipv4 as BroadcastIpExt>::BroadcastMarker>,
) -> Result<(), IcmpErrorSender<'b, Ipv4, CC::DeviceId>> {
    core_ctx.increment(|counters: &IpCounters<Ipv4>| &counters.dispatch_receive_ip_packet);

    match frame_dst {
        Some(FrameDestination::Individual { local: false }) => {
            core_ctx.increment(|counters: &IpCounters<Ipv4>| {
                &counters.dispatch_receive_ip_packet_other_host
            });
        }
        Some(FrameDestination::Individual { local: true })
        | Some(FrameDestination::Multicast)
        | Some(FrameDestination::Broadcast)
        | None => (),
    }

    let proto = packet.proto();

    match core_ctx.filter_handler().local_ingress_hook(
        bindings_ctx,
        &mut packet,
        device,
        &mut packet_metadata,
    ) {
        filter::Verdict::Drop => {
            packet_metadata.acknowledge_drop();
            return Ok(());
        }
        filter::Verdict::Accept => {}
    }
    packet_metadata.acknowledge_drop();

    let src_ip = packet.src_ip();
    // `dst_ip` is validated to be specified before a packet is provided to this
    // function, but it's possible for the LOCAL_INGRESS hook to rewrite the packet,
    // so we have to re-verify this.
    let Some(dst_ip) = SpecifiedAddr::new(packet.dst_ip()) else {
        core_ctx.increment(|counters: &IpCounters<Ipv4>| &counters.unspecified_destination);
        debug!(
            "dispatch_receive_ipv4_packet: Received packet with unspecified destination IP address \
            after the LOCAL_INGRESS hook; dropping"
        );
        return Ok(());
    };

    core_ctx.deliver_packet_to_raw_ip_sockets(bindings_ctx, &packet, &device);

    let meta = ReceiveIpPacketMeta {
        broadcast: broadcast_marker,
        transparent_override,
        dscp_and_ecn: packet.dscp_and_ecn(),
    };

    let buffer = Buf::new(packet.body_mut(), ..);

    core_ctx
        .dispatch_receive_ip_packet(bindings_ctx, device, src_ip, dst_ip, proto, buffer, meta)
        .or_else(|err| {
            if let Some(src_ip) = SpecifiedAddr::new(src_ip) {
                let (_, _, _, meta) = packet.into_metadata();
                Err(IcmpErrorSender {
                    err: err.into_icmpv4_error(meta.header_len()),
                    src_ip,
                    dst_ip,
                    frame_dst,
                    device,
                    meta,
                })
            } else {
                Ok(())
            }
        })
}

/// Dispatch a received IPv6 packet to the appropriate protocol.
///
/// `dispatch_receive_ipv6_packet` has the same semantics as
/// `dispatch_receive_ipv4_packet`, but for IPv6.
fn dispatch_receive_ipv6_packet<
    'a,
    'b,
    BC: IpLayerBindingsContext<Ipv6, CC::DeviceId>,
    CC: IpLayerIngressContext<Ipv6, BC> + CounterContext<IpCounters<Ipv6>>,
>(
    core_ctx: &'a mut CC,
    bindings_ctx: &'a mut BC,
    device: &'b CC::DeviceId,
    frame_dst: Option<FrameDestination>,
    mut packet: Ipv6Packet<&'a mut [u8]>,
    mut packet_metadata: IpLayerPacketMetadata<Ipv6, BC>,
    meta: ReceiveIpPacketMeta<Ipv6>,
) -> Result<(), IcmpErrorSender<'b, Ipv6, CC::DeviceId>> {
    // TODO(https://fxbug.dev/42095067): Once we support multiple extension
    // headers in IPv6, we will need to verify that the callers of this
    // function are still sound. In particular, they may accidentally pass a
    // parse_metadata argument which corresponds to a single extension
    // header rather than all of the IPv6 headers.

    core_ctx.increment(|counters: &IpCounters<Ipv6>| &counters.dispatch_receive_ip_packet);

    match frame_dst {
        Some(FrameDestination::Individual { local: false }) => {
            core_ctx.increment(|counters: &IpCounters<Ipv6>| {
                &counters.dispatch_receive_ip_packet_other_host
            });
        }
        Some(FrameDestination::Individual { local: true })
        | Some(FrameDestination::Multicast)
        | Some(FrameDestination::Broadcast)
        | None => (),
    }

    let proto = packet.proto();

    match core_ctx.filter_handler().local_ingress_hook(
        bindings_ctx,
        &mut packet,
        device,
        &mut packet_metadata,
    ) {
        filter::Verdict::Drop => {
            packet_metadata.acknowledge_drop();
            return Ok(());
        }
        filter::Verdict::Accept => {}
    }

    // These invariants are validated by the caller of this function, but it's
    // possible for the LOCAL_INGRESS hook to rewrite the packet, so we have to
    // check them again.
    let Some(src_ip) = packet.src_ipv6() else {
        debug!(
            "dispatch_receive_ipv6_packet: received packet from non-unicast source {} after the \
            LOCAL_INGRESS hook; dropping",
            packet.src_ip()
        );
        core_ctx.increment(|counters: &IpCounters<Ipv6>| &counters.version_rx.non_unicast_source);
        return Ok(());
    };
    let Some(dst_ip) = SpecifiedAddr::new(packet.dst_ip()) else {
        core_ctx.increment(|counters: &IpCounters<Ipv6>| &counters.unspecified_destination);
        debug!(
            "dispatch_receive_ipv6_packet: Received packet with unspecified destination IP address \
            after the LOCAL_INGRESS hook; dropping"
        );
        return Ok(());
    };

    core_ctx.deliver_packet_to_raw_ip_sockets(bindings_ctx, &packet, &device);

    let buffer = Buf::new(packet.body_mut(), ..);

    let result = core_ctx
        .dispatch_receive_ip_packet(bindings_ctx, device, src_ip, dst_ip, proto, buffer, meta)
        .or_else(|err| {
            if let Ipv6SourceAddr::Unicast(src_ip) = src_ip {
                let (_, _, _, meta) = packet.into_metadata();
                Err(IcmpErrorSender {
                    err: err.into_icmpv6_error(meta.header_len()),
                    src_ip: *src_ip,
                    dst_ip,
                    frame_dst,
                    device,
                    meta,
                })
            } else {
                Ok(())
            }
        });
    packet_metadata.acknowledge_drop();
    result
}

/// The metadata required to forward an IP Packet.
///
/// This allows the forwarding of the packet to be decoupled from the
/// determination of how to forward. This is advantageous because forwarding
/// requires the underlying packet buffer, which cannot be "moved" in certain
/// contexts.
pub(crate) struct IpPacketForwarder<'a, I: IpLayerIpExt, D, BT: FilterBindingsTypes> {
    inbound_device: &'a D,
    outbound_device: &'a D,
    packet_meta: IpLayerPacketMetadata<I, BT>,
    src_ip: I::RecvSrcAddr,
    dst_ip: SpecifiedAddr<I::Addr>,
    destination: IpPacketDestination<I, &'a D>,
    proto: I::Proto,
    parse_meta: ParseMetadata,
    frame_dst: Option<FrameDestination>,
}

impl<'a, I, D, BC> IpPacketForwarder<'a, I, D, BC>
where
    I: IpLayerIpExt,
    BC: IpLayerBindingsContext<I, D>,
{
    // Forward the provided buffer as specified by this [`IpPacketForwarder`].
    fn forward_with_buffer<CC, B>(self, core_ctx: &mut CC, bindings_ctx: &mut BC, buffer: B)
    where
        B: BufferMut,
        CC: IpLayerForwardingContext<I, BC, DeviceId = D>,
    {
        let Self {
            inbound_device,
            outbound_device,
            packet_meta,
            src_ip,
            dst_ip,
            destination,
            proto,
            parse_meta,
            frame_dst,
        } = self;

        let packet = ForwardedPacket::new(src_ip.into(), dst_ip.get(), proto, parse_meta, buffer);

        trace!("forward_with_buffer: forwarding {} packet", I::NAME);

        match send_ip_frame(
            core_ctx,
            bindings_ctx,
            outbound_device,
            destination,
            packet,
            packet_meta,
            Mtu::no_limit(),
        ) {
            Ok(()) => (),
            Err(IpSendFrameError { serializer, error }) => {
                match error {
                    IpSendFrameErrorReason::Device(
                        SendFrameErrorReason::SizeConstraintsViolation,
                    ) => {
                        debug!("failed to forward {} packet: MTU exceeded", I::NAME);
                        core_ctx.increment(|counters: &IpCounters<I>| &counters.mtu_exceeded);
                        let mtu = core_ctx.get_mtu(inbound_device);
                        // NB: Ipv6 sends a PacketTooBig error. Ipv4 sends nothing.
                        let Some(err) = I::new_mtu_exceeded(proto, parse_meta.header_len(), mtu)
                        else {
                            return;
                        };
                        // NB: Only send an ICMP error if the sender's src
                        // is specified.
                        let Some(src_ip) = I::received_source_as_icmp_source(src_ip) else {
                            return;
                        };
                        // TODO(https://fxbug.dev/362489447): Increment the TTL since we
                        // just decremented it. The fact that we don't do this is
                        // technically a violation of the ICMP spec (we're not
                        // encapsulating the original packet that caused the
                        // issue, but a slightly modified version of it), but
                        // it's not that big of a deal because it won't affect
                        // the sender's ability to figure out the minimum path
                        // MTU. This may break other logic, though, so we should
                        // still fix it eventually.
                        core_ctx.send_icmp_error_message(
                            bindings_ctx,
                            inbound_device,
                            frame_dst,
                            src_ip,
                            dst_ip,
                            serializer.into_buffer(),
                            err,
                        );
                    }
                    IpSendFrameErrorReason::Device(SendFrameErrorReason::QueueFull)
                    | IpSendFrameErrorReason::Device(SendFrameErrorReason::Alloc)
                    | IpSendFrameErrorReason::IllegalLoopbackAddress => (),
                }
                debug!("failed to forward {} packet: {error:?}", I::NAME);
            }
        }
    }
}

/// The action to take for a packet that was a candidate for forwarding.
pub(crate) enum ForwardingAction<'a, I: IpLayerIpExt, D, BT: FilterBindingsTypes> {
    /// Drop the packet without forwarding it or generating an ICMP error.
    SilentlyDrop,
    /// Forward the packet, as specified by the [`IpPacketForwarder`].
    Forward(IpPacketForwarder<'a, I, D, BT>),
    /// Drop the packet without forwarding, and generate an ICMP error as
    /// specified by the [`IcmpErrorSender`].
    DropWithIcmpError(IcmpErrorSender<'a, I, D>),
}

impl<'a, I, D, BC> ForwardingAction<'a, I, D, BC>
where
    I: IpLayerIpExt,
    BC: IpLayerBindingsContext<I, D>,
{
    /// Perform the action prescribed by self, with the provided packet buffer.
    pub(crate) fn perform_action_with_buffer<CC, B>(
        self,
        core_ctx: &mut CC,
        bindings_ctx: &mut BC,
        buffer: B,
    ) where
        B: BufferMut,
        CC: IpLayerForwardingContext<I, BC, DeviceId = D>,
    {
        match self {
            ForwardingAction::SilentlyDrop => {}
            ForwardingAction::Forward(forwarder) => {
                forwarder.forward_with_buffer(core_ctx, bindings_ctx, buffer)
            }
            ForwardingAction::DropWithIcmpError(icmp_sender) => {
                icmp_sender.respond_with_icmp_error(core_ctx, bindings_ctx, buffer)
            }
        }
    }
}

/// Determine which [`ForwardingAction`] should be taken for an IP packet.
pub(crate) fn determine_ip_packet_forwarding_action<'a, 'b, I, BC, CC>(
    core_ctx: &'a mut CC,
    mut packet: I::Packet<&'a mut [u8]>,
    mut packet_meta: IpLayerPacketMetadata<I, BC>,
    minimum_ttl: Option<u8>,
    inbound_device: &'b CC::DeviceId,
    outbound_device: &'b CC::DeviceId,
    destination: IpPacketDestination<I, &'b CC::DeviceId>,
    frame_dst: Option<FrameDestination>,
    src_ip: I::RecvSrcAddr,
    dst_ip: SpecifiedAddr<I::Addr>,
) -> ForwardingAction<'b, I, CC::DeviceId, BC>
where
    I: IpLayerIpExt,
    BC: IpLayerBindingsContext<I, CC::DeviceId>,
    CC: IpLayerForwardingContext<I, BC>,
{
    // When forwarding, if a datagram's TTL is one or zero, discard it, as
    // decrementing the TTL would put it below the allowed minimum value.
    // For IPv4, see "TTL" section, https://tools.ietf.org/html/rfc791#page-14.
    // For IPv6, see "Hop Limit" section, https://datatracker.ietf.org/doc/html/rfc2460#page-5.
    const DEFAULT_MINIMUM_FORWARDING_TTL: u8 = 2;
    let minimum_ttl = minimum_ttl.unwrap_or(DEFAULT_MINIMUM_FORWARDING_TTL);

    let ttl = packet.ttl();
    if ttl < minimum_ttl {
        debug!(
            "{} packet not forwarded due to inadequate TTL: got={ttl} minimum={minimum_ttl}",
            I::NAME
        );
        // As per RFC 792's specification of the Time Exceeded Message:
        //     If the gateway processing a datagram finds the time to live
        //     field is zero it must discard the datagram. The gateway may
        //     also notify the source host via the time exceeded message.
        // And RFC 4443 section 3.3:
        //    If a router receives a packet with a Hop Limit of zero, or if
        //    a router decrements a packet's Hop Limit to zero, it MUST
        //    discard the packet and originate an ICMPv6 Time Exceeded
        //    message with Code 0 to the source of the packet.
        // Don't send a Time Exceeded Message in cases where the netstack is
        // enforcing a higher minimum TTL (e.g. as part of a multicast route).
        if ttl > 1 {
            packet_meta.acknowledge_drop();
            return ForwardingAction::SilentlyDrop;
        }

        core_ctx.increment(|counters: &IpCounters<I>| &counters.ttl_expired);

        // Only send an ICMP error if the src_ip is specified.
        let Some(src_ip) = I::received_source_as_icmp_source(src_ip) else {
            core_ctx.increment(|counters: &IpCounters<I>| &counters.unspecified_source);
            packet_meta.acknowledge_drop();
            return ForwardingAction::SilentlyDrop;
        };

        // Construct and send the appropriate ICMP error for the IP version.
        let version_specific_meta = packet.version_specific_meta();
        let (_, _, proto, parse_meta): (I::Addr, I::Addr, _, _) = packet.into_metadata();
        let err = I::new_ttl_expired(proto, parse_meta.header_len(), version_specific_meta);
        packet_meta.acknowledge_drop();
        return ForwardingAction::DropWithIcmpError(IcmpErrorSender {
            err,
            src_ip,
            dst_ip,
            frame_dst,
            device: inbound_device,
            meta: parse_meta,
        });
    }

    trace!("determine_ip_packet_forwarding_action: adequate TTL");

    // For IPv6 packets, handle extension headers first.
    //
    // Any previous handling of extension headers was done under the
    // assumption that we are the final destination of the packet. Now that
    // we know we're forwarding, we need to re-examine them.
    let maybe_ipv6_packet_action = I::map_ip_in(
        &packet,
        |_packet| None,
        |packet| {
            Some(ipv6::handle_extension_headers(core_ctx, inbound_device, frame_dst, packet, false))
        },
    );
    match maybe_ipv6_packet_action {
        None => {} // NB: Ipv4 case.
        Some(Ipv6PacketAction::_Discard) => {
            core_ctx.increment(|counters: &IpCounters<I>| {
                #[derive(GenericOverIp)]
                #[generic_over_ip(I, Ip)]
                struct InCounters<'a, I: IpLayerIpExt>(&'a I::RxCounters);
                let IpInvariant(counter) = I::map_ip(
                    InCounters(&counters.version_rx),
                    |_counters| {
                        unreachable!(
                            "`I` must be `Ipv6` because we're handling IPv6 extension headers"
                        )
                    },
                    |InCounters(counters)| IpInvariant(&counters.extension_header_discard),
                );
                counter
            });
            trace!(
                "determine_ip_packet_forwarding_action: handled IPv6 extension headers: \
                discarding packet"
            );
            packet_meta.acknowledge_drop();
            return ForwardingAction::SilentlyDrop;
        }
        Some(Ipv6PacketAction::Continue) => {
            trace!(
                "determine_ip_packet_forwarding_action: handled IPv6 extension headers: \
                forwarding packet"
            );
        }
        Some(Ipv6PacketAction::ProcessFragment) => {
            unreachable!(
                "When forwarding packets, we should only ever look at the hop by hop \
                    options extension header (if present)"
            )
        }
    };

    match core_ctx.filter_handler().forwarding_hook(
        I::as_filter_packet(&mut packet),
        inbound_device,
        outbound_device,
        &mut packet_meta,
    ) {
        filter::Verdict::Drop => {
            packet_meta.acknowledge_drop();
            trace!("determine_ip_packet_forwarding_action: filter verdict: Drop");
            return ForwardingAction::SilentlyDrop;
        }
        filter::Verdict::Accept => {}
    }

    packet.set_ttl(ttl - 1);
    let (_, _, proto, parse_meta): (I::Addr, I::Addr, _, _) = packet.into_metadata();
    ForwardingAction::Forward(IpPacketForwarder {
        inbound_device,
        outbound_device,
        packet_meta,
        src_ip,
        dst_ip,
        destination,
        proto,
        parse_meta,
        frame_dst,
    })
}

pub(crate) fn send_ip_frame<I, CC, BC, S>(
    core_ctx: &mut CC,
    bindings_ctx: &mut BC,
    device: &CC::DeviceId,
    destination: IpPacketDestination<I, &CC::DeviceId>,
    mut body: S,
    mut packet_metadata: IpLayerPacketMetadata<I, BC>,
    limit_mtu: Mtu,
) -> Result<(), IpSendFrameError<S>>
where
    I: IpLayerIpExt,
    BC: FilterBindingsContext,
    CC: IpLayerEgressContext<I, BC> + IpDeviceMtuContext<I>,
    S: Serializer + IpPacket<I>,
    S::Buffer: BufferMut,
{
    let (verdict, proof) = core_ctx.filter_handler().egress_hook(
        bindings_ctx,
        &mut body,
        device,
        &mut packet_metadata,
    );
    match verdict {
        filter::Verdict::Drop => {
            packet_metadata.acknowledge_drop();
            return Ok(());
        }
        filter::Verdict::Accept => {}
    }
    packet_metadata.acknowledge_drop();

    // The filtering layer may have changed our address. Perform a last moment
    // check to protect against sending loopback addresses on the wire for
    // non-loopback devices, which is an RFC violation.
    if !device.is_loopback()
        && (I::LOOPBACK_SUBNET.contains(&body.src_addr())
            || I::LOOPBACK_SUBNET.contains(&body.dst_addr()))
    {
        core_ctx.increment(|c: &IpCounters<I>| &c.tx_illegal_loopback_address);
        return Err(IpSendFrameError {
            serializer: body,
            error: IpSendFrameErrorReason::IllegalLoopbackAddress,
        });
    }

    // Use the minimum MTU between the target device and the requested mtu.
    let mtu = limit_mtu.min(core_ctx.get_mtu(device));

    // TODO(https://fxbug.dev/42148827): Check that the serializer fits in MTU
    // and fragment if necessary instead of just applying the limit.
    let body = body.with_size_limit(mtu.into());
    core_ctx.send_ip_frame(bindings_ctx, device, destination, body, proof).map_err(
        |ErrorAndSerializer { serializer, error }| IpSendFrameError {
            serializer: serializer.into_inner(),
            error: error.into(),
        },
    )
}

/// Drop a packet and undo the effects of parsing it.
///
/// `drop_packet_and_undo_parse!` takes a `$packet` and a `$buffer` which the
/// packet was parsed from. It saves the results of the `src_ip()`, `dst_ip()`,
/// `proto()`, and `parse_metadata()` methods. It drops `$packet` and uses the
/// result of `parse_metadata()` to undo the effects of parsing the packet.
/// Finally, it returns the source IP, destination IP, protocol, and parse
/// metadata.
macro_rules! drop_packet_and_undo_parse {
    ($packet:expr, $buffer:expr) => {{
        let (src_ip, dst_ip, proto, meta) = $packet.into_metadata();
        $buffer.undo_parse(meta);
        (src_ip, dst_ip, proto, meta)
    }};
}

/// The result of calling [`process_fragment`], depending on what action needs
/// to be taken by the caller.
enum ProcessFragmentResult<'a, I: IpLayerIpExt> {
    /// Processing of the packet is complete and no more action should be
    /// taken.
    Done,

    /// Reassembly is not needed. The returned packet is the same one that was
    /// passed in the call to [`process_fragment`].
    NotNeeded(I::Packet<&'a mut [u8]>),

    /// A packet was successfully reassembled into the provided buffer. If a
    /// parsed packet is needed, then the caller must perform that parsing.
    Reassembled(Vec<u8>),
}

/// Process a fragment and reassemble if required.
///
/// Attempts to process a potential fragment packet and reassemble if we are
/// ready to do so. Returns an enum to the caller with the result of processing
/// the potential fragment.
fn process_fragment<'a, I, CC, BC>(
    core_ctx: &mut CC,
    bindings_ctx: &mut BC,
    packet: I::Packet<&'a mut [u8]>,
) -> ProcessFragmentResult<'a, I>
where
    I: IpLayerIpExt,
    for<'b> I::Packet<&'b mut [u8]>: FragmentablePacket,
    CC: IpLayerIngressContext<I, BC> + CounterContext<IpCounters<I>>,
    BC: IpLayerBindingsContext<I, CC::DeviceId>,
{
    match FragmentHandler::<I, _>::process_fragment::<&mut [u8]>(core_ctx, bindings_ctx, packet) {
        // Handle the packet right away since reassembly is not needed.
        FragmentProcessingState::NotNeeded(packet) => {
            trace!("receive_ip_packet: not fragmented");
            ProcessFragmentResult::NotNeeded(packet)
        }
        // Ready to reassemble a packet.
        FragmentProcessingState::Ready { key, packet_len } => {
            trace!("receive_ip_packet: fragmented, ready for reassembly");
            // Allocate a buffer of `packet_len` bytes.
            let mut buffer = Buf::new(alloc::vec![0; packet_len], ..);

            // Attempt to reassemble the packet.
            let reassemble_result = match FragmentHandler::<I, _>::reassemble_packet(
                core_ctx,
                bindings_ctx,
                &key,
                buffer.buffer_view_mut(),
            ) {
                // Successfully reassembled the packet, handle it.
                Ok(()) => ProcessFragmentResult::Reassembled(buffer.into_inner()),
                Err(e) => {
                    core_ctx
                        .increment(|counters: &IpCounters<I>| &counters.fragment_reassembly_error);
                    debug!("receive_ip_packet: fragmented, failed to reassemble: {:?}", e);
                    ProcessFragmentResult::Done
                }
            };
            reassemble_result
        }
        // Cannot proceed since we need more fragments before we
        // can reassemble a packet.
        FragmentProcessingState::NeedMoreFragments => {
            core_ctx.increment(|counters: &IpCounters<I>| &counters.need_more_fragments);
            trace!("receive_ip_packet: fragmented, need more before reassembly");
            ProcessFragmentResult::Done
        }
        // TODO(ghanan): Handle invalid fragments.
        FragmentProcessingState::InvalidFragment => {
            core_ctx.increment(|counters: &IpCounters<I>| &counters.invalid_fragment);
            trace!("receive_ip_packet: fragmented, invalid");
            ProcessFragmentResult::Done
        }
        FragmentProcessingState::OutOfMemory => {
            core_ctx.increment(|counters: &IpCounters<I>| &counters.fragment_cache_full);
            trace!("receive_ip_packet: fragmented, dropped because OOM");
            ProcessFragmentResult::Done
        }
    }
}

// TODO(joshlf): Can we turn `try_parse_ip_packet` into a function? So far, I've
// been unable to get the borrow checker to accept it.

/// Try to parse an IP packet from a buffer.
///
/// If parsing fails, return the buffer to its original state so that its
/// contents can be used to send an ICMP error message. When invoked, the macro
/// expands to an expression whose type is `Result<P, P::Error>`, where `P` is
/// the parsed packet type.
macro_rules! try_parse_ip_packet {
    ($buffer:expr) => {{
        let p_len = $buffer.prefix_len();
        let s_len = $buffer.suffix_len();

        let result = $buffer.parse_mut();

        if let Err(err) = result {
            // Revert `buffer` to it's original state.
            let n_p_len = $buffer.prefix_len();
            let n_s_len = $buffer.suffix_len();

            if p_len > n_p_len {
                $buffer.grow_front(p_len - n_p_len);
            }

            if s_len > n_s_len {
                $buffer.grow_back(s_len - n_s_len);
            }

            Err(err)
        } else {
            result
        }
    }};
}

/// Clone an IP packet so that it may be delivered to a multicast route target.
///
/// Note: We must copy the underlying data here, as the filtering
/// engine may uniquely modify each instance as part of
/// performing forwarding.
///
/// In the future there are potential optimizations we could
/// pursue, including:
///   * Copy-on-write semantics for the buffer/packet so that
///     copies of the underlying data are done on an as-needed
///     basis.
///   * Avoid reparsing the IP packet. Because we're parsing an
///     exact copy of a known good packet, it would be safe to
///     adopt the data as an IP packet without performing any
///     validation.
// NB: This is a macro, not a function, because Rust's "move" semantics prevent
// us from returning both a buffer and a packet referencing that buffer.
macro_rules! clone_packet_for_mcast_forwarding {
    {let ($new_data:ident, $new_buffer:ident, $new_packet:ident) = $packet:ident} => {
        let mut $new_data = $packet.to_vec();
        let mut $new_buffer: Buf<&mut [u8]> = Buf::new($new_data.as_mut(), ..);
        let $new_packet = try_parse_ip_packet!($new_buffer).unwrap();
    };
}

/// Receive an IPv4 packet from a device.
///
/// `frame_dst` specifies how this packet was received; see [`FrameDestination`]
/// for options.
pub fn receive_ipv4_packet<
    BC: IpLayerBindingsContext<Ipv4, CC::DeviceId>,
    B: BufferMut,
    CC: IpLayerIngressContext<Ipv4, BC> + CounterContext<IpCounters<Ipv4>>,
>(
    core_ctx: &mut CC,
    bindings_ctx: &mut BC,
    device: &CC::DeviceId,
    frame_dst: Option<FrameDestination>,
    buffer: B,
) {
    if !core_ctx.is_ip_device_enabled(&device) {
        return;
    }

    // This is required because we may need to process the buffer that was
    // passed in or a reassembled one, which have different types.
    let mut buffer: packet::Either<B, Buf<Vec<u8>>> = packet::Either::A(buffer);

    core_ctx.increment(|counters: &IpCounters<Ipv4>| &counters.receive_ip_packet);
    trace!("receive_ip_packet({device:?})");

    let packet: Ipv4Packet<_> = match try_parse_ip_packet!(buffer) {
        Ok(packet) => packet,
        // Conditionally send an ICMP response if we encountered a parameter
        // problem error when parsing an IPv4 packet. Note, we do not always
        // send back an ICMP response as it can be used as an attack vector for
        // DDoS attacks. We only send back an ICMP response if the RFC requires
        // that we MUST send one, as noted by `must_send_icmp` and `action`.
        // TODO(https://fxbug.dev/42157630): test this code path once
        // `Ipv4Packet::parse` can return an `IpParseError::ParameterProblem`
        // error.
        Err(IpParseError::ParameterProblem {
            src_ip,
            dst_ip,
            code,
            pointer,
            must_send_icmp,
            header_len,
            action,
        }) if must_send_icmp && action.should_send_icmp(&dst_ip) => {
            core_ctx.increment(|counters: &IpCounters<Ipv4>| &counters.parameter_problem);
            // `should_send_icmp_to_multicast` should never return `true` for IPv4.
            assert!(!action.should_send_icmp_to_multicast());
            let dst_ip = match SpecifiedAddr::new(dst_ip) {
                Some(ip) => ip,
                None => {
                    core_ctx
                        .increment(|counters: &IpCounters<Ipv4>| &counters.unspecified_destination);
                    debug!("receive_ipv4_packet: Received packet with unspecified destination IP address; dropping");
                    return;
                }
            };
            let src_ip = match SpecifiedAddr::new(src_ip) {
                Some(ip) => ip,
                None => {
                    core_ctx.increment(|counters: &IpCounters<Ipv4>| &counters.unspecified_source);
                    trace!("receive_ipv4_packet: Cannot send ICMP error in response to packet with unspecified source IP address");
                    return;
                }
            };
            IcmpErrorHandler::<Ipv4, _>::send_icmp_error_message(
                core_ctx,
                bindings_ctx,
                device,
                frame_dst,
                src_ip,
                dst_ip,
                buffer,
                Icmpv4Error {
                    kind: Icmpv4ErrorKind::ParameterProblem {
                        code,
                        pointer,
                        // When the call to `action.should_send_icmp` returns true, it always means that
                        // the IPv4 packet that failed parsing is an initial fragment.
                        fragment_type: Ipv4FragmentType::InitialFragment,
                    },
                    header_len,
                },
            );
            return;
        }
        _ => return, // TODO(joshlf): Do something with ICMP here?
    };

    // We verify this later by actually creating the `SpecifiedAddr` witness
    // type after the INGRESS filtering hook, but we keep this check here as an
    // optimization to return early if the packet has an unspecified
    // destination.
    if !packet.dst_ip().is_specified() {
        core_ctx.increment(|counters: &IpCounters<Ipv4>| &counters.unspecified_destination);
        debug!("receive_ipv4_packet: Received packet with unspecified destination IP; dropping");
        return;
    };

    // Reassemble all packets before local delivery or forwarding. Reassembly
    // before forwarding is not RFC-compliant, but it's the easiest way to
    // ensure that fragments are filtered properly. Linux does this and it
    // doesn't seem to create major problems.
    //
    // TODO(https://fxbug.dev/345814518): Forward fragments without reassembly.
    //
    // Note, the `process_fragment` function could panic if the packet does not
    // have fragment data. However, we are guaranteed that it will not panic
    // because the fragment data is in the fixed header so it is always present
    // (even if the fragment data has values that implies that the packet is not
    // fragmented).
    let mut packet = match process_fragment(core_ctx, bindings_ctx, packet) {
        ProcessFragmentResult::Done => return,
        ProcessFragmentResult::NotNeeded(packet) => packet,
        ProcessFragmentResult::Reassembled(buf) => {
            let buf = Buf::new(buf, ..);
            buffer = packet::Either::B(buf);

            match buffer.parse_mut() {
                Ok(packet) => packet,
                Err(err) => {
                    core_ctx.increment(|counters: &IpCounters<Ipv4>| {
                        &counters.fragment_reassembly_error
                    });
                    debug!("receive_ip_packet: fragmented, failed to reassemble: {:?}", err);
                    return;
                }
            }
        }
    };

    // TODO(ghanan): Act upon options.

    let mut packet_metadata = IpLayerPacketMetadata::default();
    let mut filter = core_ctx.filter_handler();
    match filter.ingress_hook(bindings_ctx, &mut packet, device, &mut packet_metadata) {
        IngressVerdict::Verdict(filter::Verdict::Accept) => {}
        IngressVerdict::Verdict(filter::Verdict::Drop) => {
            packet_metadata.acknowledge_drop();
            return;
        }
        IngressVerdict::TransparentLocalDelivery { addr, port } => {
            // Drop the filter handler since it holds a mutable borrow of `core_ctx`, which
            // we need to provide to the packet dispatch function.
            drop(filter);

            let Some(addr) = SpecifiedAddr::new(addr) else {
                core_ctx.increment(|counters: &IpCounters<Ipv4>| &counters.unspecified_destination);
                debug!("cannot perform transparent delivery to unspecified destination; dropping");
                return;
            };

            // It's possible that the packet was actually sent to a broadcast
            // address, but it doesn't matter here since it's being delivered
            // to a transparent proxy.
            let broadcast_marker = None;

            // Short-circuit the routing process and override local demux, providing a local
            // address and port to which the packet should be transparently delivered at the
            // transport layer.
            dispatch_receive_ipv4_packet(
                core_ctx,
                bindings_ctx,
                device,
                frame_dst,
                packet,
                packet_metadata,
                Some(TransparentLocalDelivery { addr, port }),
                broadcast_marker,
            )
            .unwrap_or_else(|err| err.respond_with_icmp_error(core_ctx, bindings_ctx, buffer));
            return;
        }
    }
    // Drop the filter handler since it holds a mutable borrow of `core_ctx`, which
    // we need below.
    drop(filter);

    let action = receive_ipv4_packet_action(core_ctx, bindings_ctx, device, &packet, frame_dst);
    match action {
        ReceivePacketAction::MulticastForward { targets, address_status, dst_ip } => {
            let src_ip = packet.src_ip();
            // TOOD(https://fxbug.dev/364242513): Support connection tracking of
            // the multiplexed flows created by multicast forwarding. Here, we
            // use the existing metadata for the first action taken, and then
            // a default instance for each subsequent action. The first action
            // will populate the conntrack table with an entry, which will then
            // be used by all subsequent forwards.
            let mut packet_metadata = Some(packet_metadata);
            for MulticastRouteTarget { output_interface, min_ttl } in targets.as_ref() {
                clone_packet_for_mcast_forwarding! {
                    let (copy_of_data, copy_of_buffer, copy_of_packet) = packet
                };
                determine_ip_packet_forwarding_action::<Ipv4, _, _>(
                    core_ctx,
                    copy_of_packet,
                    packet_metadata.take().unwrap_or_default(),
                    Some(*min_ttl),
                    device,
                    &output_interface,
                    IpPacketDestination::from_addr(dst_ip),
                    frame_dst,
                    src_ip,
                    dst_ip,
                )
                .perform_action_with_buffer(core_ctx, bindings_ctx, copy_of_buffer);
            }

            // If we also have an interest in the packet, deliver it locally.
            if let Some(address_status) = address_status {
                dispatch_receive_ipv4_packet(
                    core_ctx,
                    bindings_ctx,
                    device,
                    frame_dst,
                    packet,
                    packet_metadata.take().unwrap_or_default(),
                    None,
                    address_status.to_broadcast_marker(),
                )
                .unwrap_or_else(|err| err.respond_with_icmp_error(core_ctx, bindings_ctx, buffer));
            }
        }
        ReceivePacketAction::Deliver { address_status, internal_forwarding } => {
            // NB: when performing internal forwarding, hit the
            // forwarding hook.
            match internal_forwarding {
                InternalForwarding::Used(outbound_device) => {
                    core_ctx.increment(|counters: &IpCounters<Ipv4>| &counters.forward);
                    match core_ctx.filter_handler().forwarding_hook(
                        &mut packet,
                        device,
                        &outbound_device,
                        &mut packet_metadata,
                    ) {
                        filter::Verdict::Drop => {
                            packet_metadata.acknowledge_drop();
                            return;
                        }
                        filter::Verdict::Accept => {}
                    }
                }
                InternalForwarding::NotUsed => {}
            }

            dispatch_receive_ipv4_packet(
                core_ctx,
                bindings_ctx,
                device,
                frame_dst,
                packet,
                packet_metadata,
                None,
                address_status.to_broadcast_marker(),
            )
            .unwrap_or_else(|err| err.respond_with_icmp_error(core_ctx, bindings_ctx, buffer));
        }
        ReceivePacketAction::Forward {
            original_dst,
            dst: Destination { device: dst_device, next_hop },
        } => {
            let src_ip = packet.src_ip();
            determine_ip_packet_forwarding_action::<Ipv4, _, _>(
                core_ctx,
                packet,
                packet_metadata,
                None,
                device,
                &dst_device,
                IpPacketDestination::from_next_hop(next_hop, original_dst),
                frame_dst,
                src_ip,
                original_dst,
            )
            .perform_action_with_buffer(core_ctx, bindings_ctx, buffer);
        }
        ReceivePacketAction::SendNoRouteToDest { dst: dst_ip } => {
            use packet_formats::ipv4::Ipv4Header as _;
            core_ctx.increment(|counters: &IpCounters<Ipv4>| &counters.no_route_to_host);
            debug!("received IPv4 packet with no known route to destination {}", dst_ip);
            let fragment_type = packet.fragment_type();
            let (src_ip, _, proto, meta): (_, Ipv4Addr, _, _) =
                drop_packet_and_undo_parse!(packet, buffer);
            packet_metadata.acknowledge_drop();
            let src_ip = match SpecifiedAddr::new(src_ip) {
                Some(ip) => ip,
                None => {
                    core_ctx.increment(|counters: &IpCounters<Ipv4>| &counters.unspecified_source);
                    trace!("receive_ipv4_packet: Cannot send ICMP error in response to packet with unspecified source IP address");
                    return;
                }
            };
            IcmpErrorHandler::<Ipv4, _>::send_icmp_error_message(
                core_ctx,
                bindings_ctx,
                device,
                frame_dst,
                src_ip,
                dst_ip,
                buffer,
                Icmpv4Error {
                    kind: Icmpv4ErrorKind::NetUnreachable { proto, fragment_type },
                    header_len: meta.header_len(),
                },
            );
        }
        ReceivePacketAction::Drop { reason } => {
            let src_ip = packet.src_ip();
            let dst_ip = packet.dst_ip();
            packet_metadata.acknowledge_drop();
            core_ctx.increment(|counters: &IpCounters<Ipv4>| &counters.dropped);
            debug!(
                "receive_ipv4_packet: dropping packet from {src_ip} to {dst_ip} received on \
                {device:?}: {reason:?}",
            );
        }
    }
}

/// Receive an IPv6 packet from a device.
///
/// `frame_dst` specifies how this packet was received; see [`FrameDestination`]
/// for options.
pub fn receive_ipv6_packet<
    BC: IpLayerBindingsContext<Ipv6, CC::DeviceId>,
    B: BufferMut,
    CC: IpLayerIngressContext<Ipv6, BC> + CounterContext<IpCounters<Ipv6>>,
>(
    core_ctx: &mut CC,
    bindings_ctx: &mut BC,
    device: &CC::DeviceId,
    frame_dst: Option<FrameDestination>,
    buffer: B,
) {
    if !core_ctx.is_ip_device_enabled(&device) {
        return;
    }

    // This is required because we may need to process the buffer that was
    // passed in or a reassembled one, which have different types.
    let mut buffer: packet::Either<B, Buf<Vec<u8>>> = packet::Either::A(buffer);

    core_ctx.increment(|counters: &IpCounters<Ipv6>| &counters.receive_ip_packet);
    trace!("receive_ipv6_packet({:?})", device);

    let packet: Ipv6Packet<_> = match try_parse_ip_packet!(buffer) {
        Ok(packet) => packet,
        // Conditionally send an ICMP response if we encountered a parameter
        // problem error when parsing an IPv4 packet. Note, we do not always
        // send back an ICMP response as it can be used as an attack vector for
        // DDoS attacks. We only send back an ICMP response if the RFC requires
        // that we MUST send one, as noted by `must_send_icmp` and `action`.
        Err(IpParseError::ParameterProblem {
            src_ip,
            dst_ip,
            code,
            pointer,
            must_send_icmp,
            header_len: _,
            action,
        }) if must_send_icmp && action.should_send_icmp(&dst_ip) => {
            core_ctx.increment(|counters: &IpCounters<Ipv6>| &counters.parameter_problem);
            let dst_ip = match SpecifiedAddr::new(dst_ip) {
                Some(ip) => ip,
                None => {
                    core_ctx
                        .increment(|counters: &IpCounters<Ipv6>| &counters.unspecified_destination);
                    debug!("receive_ipv6_packet: Received packet with unspecified destination IP address; dropping");
                    return;
                }
            };
            let src_ip = match UnicastAddr::new(src_ip) {
                Some(ip) => ip,
                None => {
                    core_ctx.increment(|counters: &IpCounters<Ipv6>| {
                        &counters.version_rx.non_unicast_source
                    });
                    trace!("receive_ipv6_packet: Cannot send ICMP error in response to packet with non unicast source IP address");
                    return;
                }
            };
            IcmpErrorHandler::<Ipv6, _>::send_icmp_error_message(
                core_ctx,
                bindings_ctx,
                device,
                frame_dst,
                src_ip,
                dst_ip,
                buffer,
                Icmpv6ErrorKind::ParameterProblem {
                    code,
                    pointer,
                    allow_dst_multicast: action.should_send_icmp_to_multicast(),
                },
            );
            return;
        }
        _ => return, // TODO(joshlf): Do something with ICMP here?
    };

    trace!("receive_ipv6_packet: parsed packet: {:?}", packet);

    // TODO(ghanan): Act upon extension headers.

    // We verify these properties later by actually creating the corresponding
    // witness types after the INGRESS filtering hook, but we keep these checks
    // here as an optimization to return early and save some work.
    if packet.src_ipv6().is_none() {
        debug!(
            "receive_ipv6_packet: received packet from non-unicast source {}; dropping",
            packet.src_ip()
        );
        core_ctx.increment(|counters: &IpCounters<Ipv6>| &counters.version_rx.non_unicast_source);
        return;
    };
    if !packet.dst_ip().is_specified() {
        core_ctx.increment(|counters: &IpCounters<Ipv6>| &counters.unspecified_destination);
        debug!("receive_ipv6_packet: Received packet with unspecified destination IP; dropping");
        return;
    };

    // Reassemble all packets before local delivery or forwarding. Reassembly
    // before forwarding is not RFC-compliant, but it's the easiest way to
    // ensure that fragments are filtered properly. Linux does this and it
    // doesn't seem to create major problems.
    //
    // TODO(https://fxbug.dev/345814518): Forward fragments without reassembly.
    //
    // delivery_extension_header_action is used to prevent looking at the
    // extension headers twice when a non-fragmented packet is delivered
    // locally.
    let (mut packet, delivery_extension_header_action) =
        match ipv6::handle_extension_headers(core_ctx, device, frame_dst, &packet, true) {
            Ipv6PacketAction::_Discard => {
                core_ctx.increment(|counters: &IpCounters<Ipv6>| {
                    &counters.version_rx.extension_header_discard
                });
                trace!("receive_ipv6_packet: handled IPv6 extension headers: discarding packet");
                return;
            }
            Ipv6PacketAction::Continue => {
                trace!("receive_ipv6_packet: handled IPv6 extension headers: dispatching packet");
                (packet, Some(Ipv6PacketAction::Continue))
            }
            Ipv6PacketAction::ProcessFragment => {
                trace!(
                    "receive_ipv6_packet: handled IPv6 extension headers: handling \
                    fragmented packet"
                );

                // Note, `IpPacketFragmentCache::process_fragment`
                // could panic if the packet does not have fragment data.
                // However, we are guaranteed that it will not panic for an
                // IPv6 packet because the fragment data is in an (optional)
                // fragment extension header which we attempt to handle by
                // calling `ipv6::handle_extension_headers`. We will only
                // end up here if its return value is
                // `Ipv6PacketAction::ProcessFragment` which is only
                // possible when the packet has the fragment extension
                // header (even if the fragment data has values that implies
                // that the packet is not fragmented).
                match process_fragment(core_ctx, bindings_ctx, packet) {
                    ProcessFragmentResult::Done => return,
                    ProcessFragmentResult::NotNeeded(packet) => {
                        // While strange, it's possible for there to be a Fragment
                        // header that says the packet doesn't need defragmentation.
                        // As per RFC 8200 4.5:
                        //
                        //   If the fragment is a whole datagram (that is, both the
                        //   Fragment Offset field and the M flag are zero), then it
                        //   does not need any further reassembly and should be
                        //   processed as a fully reassembled packet (i.e., updating
                        //   Next Header, adjust Payload Length, removing the
                        //   Fragment header, etc.).
                        //
                        // In this case, we're not technically reassembling the
                        // packet, since, per the RFC, that would mean removing the
                        // Fragment header.
                        (packet, Some(Ipv6PacketAction::Continue))
                    }
                    ProcessFragmentResult::Reassembled(buf) => {
                        let buf = Buf::new(buf, ..);
                        buffer = packet::Either::B(buf);

                        match buffer.parse_mut() {
                            Ok(packet) => (packet, None),
                            Err(err) => {
                                core_ctx.increment(|counters: &IpCounters<Ipv6>| {
                                    &counters.fragment_reassembly_error
                                });
                                debug!(
                                    "receive_ip_packet: fragmented, failed to reassemble: {:?}",
                                    err
                                );
                                return;
                            }
                        }
                    }
                }
            }
        };

    let mut packet_metadata = IpLayerPacketMetadata::default();
    let mut filter = core_ctx.filter_handler();
    match filter.ingress_hook(bindings_ctx, &mut packet, device, &mut packet_metadata) {
        IngressVerdict::Verdict(filter::Verdict::Accept) => {}
        IngressVerdict::Verdict(filter::Verdict::Drop) => {
            packet_metadata.acknowledge_drop();
            return;
        }
        IngressVerdict::TransparentLocalDelivery { addr, port } => {
            // Drop the filter handler since it holds a mutable borrow of `core_ctx`, which
            // we need to provide to the packet dispatch function.
            drop(filter);

            let Some(addr) = SpecifiedAddr::new(addr) else {
                core_ctx.increment(|counters: &IpCounters<Ipv6>| &counters.unspecified_destination);
                debug!("cannot perform transparent delivery to unspecified destination; dropping");
                return;
            };

            let meta = ReceiveIpPacketMeta {
                broadcast: None,
                transparent_override: Some(TransparentLocalDelivery { addr, port }),
                dscp_and_ecn: packet.dscp_and_ecn(),
            };

            // Short-circuit the routing process and override local demux, providing a local
            // address and port to which the packet should be transparently delivered at the
            // transport layer.
            dispatch_receive_ipv6_packet(
                core_ctx,
                bindings_ctx,
                device,
                frame_dst,
                packet,
                packet_metadata,
                meta,
            )
            .unwrap_or_else(|err| err.respond_with_icmp_error(core_ctx, bindings_ctx, buffer));
            return;
        }
    }
    // Drop the filter handler since it holds a mutable borrow of `core_ctx`, which
    // we need below.
    drop(filter);

    let Some(src_ip) = packet.src_ipv6() else {
        debug!(
            "receive_ipv6_packet: received packet from non-unicast source {}; dropping",
            packet.src_ip()
        );
        core_ctx.increment(|counters: &IpCounters<Ipv6>| &counters.version_rx.non_unicast_source);
        return;
    };

    match receive_ipv6_packet_action(core_ctx, bindings_ctx, device, &packet, frame_dst) {
        ReceivePacketAction::MulticastForward { targets, address_status, dst_ip } => {
            // TOOD(https://fxbug.dev/364242513): Support connection tracking of
            // the multiplexed flows created by multicast forwarding. Here, we
            // use the existing metadata for the first action taken, and then
            // a default instance for each subsequent action. The first action
            // will populate the conntrack table with an entry, which will then
            // be used by all subsequent forwards.
            let mut packet_metadata = Some(packet_metadata);
            for MulticastRouteTarget { output_interface, min_ttl } in targets.as_ref() {
                clone_packet_for_mcast_forwarding! {
                    let (copy_of_data, copy_of_buffer, copy_of_packet) = packet
                };
                determine_ip_packet_forwarding_action::<Ipv6, _, _>(
                    core_ctx,
                    copy_of_packet,
                    packet_metadata.take().unwrap_or_default(),
                    Some(*min_ttl),
                    device,
                    &output_interface,
                    IpPacketDestination::from_addr(dst_ip),
                    frame_dst,
                    src_ip,
                    dst_ip,
                )
                .perform_action_with_buffer(core_ctx, bindings_ctx, copy_of_buffer);
            }

            // If we also have an interest in the packet, deliver it locally.
            if let Some(_) = address_status {
                dispatch_receive_ipv6_packet(
                    core_ctx,
                    bindings_ctx,
                    device,
                    frame_dst,
                    packet,
                    packet_metadata.take().unwrap_or_default(),
                    ReceiveIpPacketMeta::default(),
                )
                .unwrap_or_else(|err| err.respond_with_icmp_error(core_ctx, bindings_ctx, buffer));
            }
        }
        ReceivePacketAction::Deliver { address_status: _, internal_forwarding } => {
            trace!("receive_ipv6_packet: delivering locally");

            let action = if let Some(action) = delivery_extension_header_action {
                action
            } else {
                ipv6::handle_extension_headers(core_ctx, device, frame_dst, &packet, true)
            };
            match action {
                Ipv6PacketAction::_Discard => {
                    core_ctx.increment(|counters: &IpCounters<Ipv6>| {
                        &counters.version_rx.extension_header_discard
                    });
                    trace!(
                        "receive_ipv6_packet: handled IPv6 extension headers: discarding packet"
                    );
                    packet_metadata.acknowledge_drop();
                }
                Ipv6PacketAction::Continue => {
                    trace!(
                        "receive_ipv6_packet: handled IPv6 extension headers: dispatching packet"
                    );

                    // NB: when performing internal forwarding, hit the
                    // forwarding hook.
                    match internal_forwarding {
                        InternalForwarding::Used(outbound_device) => {
                            core_ctx.increment(|counters: &IpCounters<Ipv6>| &counters.forward);
                            match core_ctx.filter_handler().forwarding_hook(
                                &mut packet,
                                device,
                                &outbound_device,
                                &mut packet_metadata,
                            ) {
                                filter::Verdict::Drop => {
                                    packet_metadata.acknowledge_drop();
                                    return;
                                }
                                filter::Verdict::Accept => {}
                            }
                        }
                        InternalForwarding::NotUsed => {}
                    }

                    let meta = ReceiveIpPacketMeta {
                        broadcast: None,
                        transparent_override: None,
                        dscp_and_ecn: packet.dscp_and_ecn(),
                    };

                    // TODO(joshlf):
                    // - Do something with ICMP if we don't have a handler for
                    //   that protocol?
                    // - Check for already-expired TTL?
                    dispatch_receive_ipv6_packet(
                        core_ctx,
                        bindings_ctx,
                        device,
                        frame_dst,
                        packet,
                        packet_metadata,
                        meta,
                    )
                    .unwrap_or_else(|err| {
                        err.respond_with_icmp_error(core_ctx, bindings_ctx, buffer)
                    });
                }
                Ipv6PacketAction::ProcessFragment => {
                    debug!("receive_ipv6_packet: found fragment header after reassembly; dropping");
                    packet_metadata.acknowledge_drop();
                }
            }
        }
        ReceivePacketAction::Forward {
            original_dst,
            dst: Destination { device: dst_device, next_hop },
        } => {
            determine_ip_packet_forwarding_action::<Ipv6, _, _>(
                core_ctx,
                packet,
                packet_metadata,
                None,
                device,
                &dst_device,
                IpPacketDestination::from_next_hop(next_hop, original_dst),
                frame_dst,
                src_ip,
                original_dst,
            )
            .perform_action_with_buffer(core_ctx, bindings_ctx, buffer);
        }
        ReceivePacketAction::SendNoRouteToDest { dst: dst_ip } => {
            core_ctx.increment(|counters: &IpCounters<Ipv6>| &counters.no_route_to_host);
            let (_, _, proto, meta): (Ipv6Addr, Ipv6Addr, _, _) =
                drop_packet_and_undo_parse!(packet, buffer);
            debug!("received IPv6 packet with no known route to destination {}", dst_ip);
            packet_metadata.acknowledge_drop();

            if let Ipv6SourceAddr::Unicast(src_ip) = src_ip {
                IcmpErrorHandler::<Ipv6, _>::send_icmp_error_message(
                    core_ctx,
                    bindings_ctx,
                    device,
                    frame_dst,
                    *src_ip,
                    dst_ip,
                    buffer,
                    Icmpv6ErrorKind::NetUnreachable { proto, header_len: meta.header_len() },
                );
            }
        }
        ReceivePacketAction::Drop { reason } => {
            core_ctx.increment(|counters: &IpCounters<Ipv6>| &counters.dropped);
            let src_ip = packet.src_ip();
            let dst_ip = packet.dst_ip();
            packet_metadata.acknowledge_drop();
            debug!(
                "receive_ipv6_packet: dropping packet from {src_ip} to {dst_ip} received on \
                {device:?}: {reason:?}",
            );
        }
    }
}

/// The action to take in order to process a received IP packet.
#[derive(Debug, PartialEq)]
pub enum ReceivePacketAction<I: BroadcastIpExt + IpLayerIpExt, DeviceId: StrongDeviceIdentifier> {
    /// Deliver the packet locally.
    Deliver {
        /// Status of the receiving IP address.
        address_status: I::AddressStatus,
        /// `InternalForwarding::Used(d)` if we're delivering the packet as a
        /// Weak Host performing internal forwarding via output device `d`.
        internal_forwarding: InternalForwarding<DeviceId>,
    },

    /// Forward the packet to the given destination.
    Forward {
        /// The original destination IP address of the packet.
        original_dst: SpecifiedAddr<I::Addr>,
        /// The destination that the packet should be forwarded to.
        dst: Destination<I::Addr, DeviceId>,
    },

    /// A multicast packet that should be forwarded (& optional local delivery).
    ///
    /// The packet should be forwarded to each of the given targets. This case
    /// is only returned when the packet is eligible for multicast forwarding;
    /// `Self::Deliver` is used for packets that are ineligible (either because
    /// multicast forwarding is disabled, or because there are no applicable
    /// multicast routes with which to forward the packet).
    MulticastForward {
        /// The multicast targets to forward the packet via.
        targets: MulticastRouteTargets<DeviceId>,
        /// Some if the host is a member of the multicast group and the packet
        /// should be delivered locally (in addition to forwarding).
        address_status: Option<I::AddressStatus>,
        /// The multicast address the packet should be forwarded to.
        dst_ip: SpecifiedAddr<I::Addr>,
    },

    /// Send a Destination Unreachable ICMP error message to the packet's sender
    /// and drop the packet.
    ///
    /// For ICMPv4, use the code "net unreachable". For ICMPv6, use the code "no
    /// route to destination".
    SendNoRouteToDest {
        /// The destination IP Address to which there was no route.
        dst: SpecifiedAddr<I::Addr>,
    },

    /// Silently drop the packet.
    ///
    /// `reason` describes why the packet was dropped.
    #[allow(missing_docs)]
    Drop { reason: DropReason },
}

/// The reason a received IP packet is dropped.
#[derive(Debug, PartialEq)]
pub enum DropReason {
    /// Remote packet destined to tentative address.
    Tentative,
    /// Remote packet destined to the unspecified address.
    UnspecifiedDestination,
    /// Cannot forward a packet with unspecified source address.
    ForwardUnspecifiedSource,
    /// Packet should be forwarded but packet's inbound interface has forwarding
    /// disabled.
    ForwardingDisabledInboundIface,
    /// Remote packet destined to a multicast address that could not be:
    /// * delivered locally (because we are not a member of the multicast
    ///   group), or
    /// * forwarded (either because multicast forwarding is disabled, or no
    ///   applicable multicast route has been installed).
    MulticastNoInterest,
}

/// Computes the action to take in order to process a received IPv4 packet.
pub fn receive_ipv4_packet_action<BC, CC, B>(
    core_ctx: &mut CC,
    bindings_ctx: &mut BC,
    device: &CC::DeviceId,
    packet: &Ipv4Packet<B>,
    frame_dst: Option<FrameDestination>,
) -> ReceivePacketAction<Ipv4, CC::DeviceId>
where
    BC: IpLayerBindingsContext<Ipv4, CC::DeviceId>,
    CC: IpLayerContext<Ipv4, BC> + CounterContext<IpCounters<Ipv4>>,
    B: SplitByteSlice,
{
    let Some(dst_ip) = SpecifiedAddr::new(packet.dst_ip()) else {
        core_ctx.increment(|counters: &IpCounters<Ipv4>| &counters.unspecified_destination);
        return ReceivePacketAction::Drop { reason: DropReason::UnspecifiedDestination };
    };

    // If the packet arrived at the loopback interface, check if any local
    // interface has the destination address assigned. This effectively lets
    // the loopback interface operate as a weak host for incoming packets.
    //
    // Note that (as of writing) the stack sends all locally destined traffic to
    // the loopback interface so we need this hack to allow the stack to accept
    // packets that arrive at the loopback interface (after being looped back)
    // but destined to an address that is assigned to another local interface.
    //
    // TODO(https://fxbug.dev/42175703): This should instead be controlled by the
    // routing table.

    // Since we treat all addresses identically, it doesn't matter whether one
    // or more than one device has the address assigned. That means we can just
    // take the first status and ignore the rest.
    let first_status = if device.is_loopback() {
        core_ctx.with_address_statuses(dst_ip, |it| it.map(|(_device, status)| status).next())
    } else {
        core_ctx.address_status_for_device(dst_ip, device).into_present()
    };
    match first_status {
        Some(
            address_status @ (Ipv4PresentAddressStatus::Unicast
            | Ipv4PresentAddressStatus::LoopbackSubnet),
        ) => {
            core_ctx.increment(|counters: &IpCounters<Ipv4>| &counters.deliver_unicast);
            ReceivePacketAction::Deliver {
                address_status,
                internal_forwarding: InternalForwarding::NotUsed,
            }
        }
        Some(address_status @ Ipv4PresentAddressStatus::Multicast) => {
            receive_ip_multicast_packet_action(
                core_ctx,
                bindings_ctx,
                device,
                packet,
                Some(address_status),
                dst_ip,
                frame_dst,
            )
        }
        Some(
            address_status @ (Ipv4PresentAddressStatus::LimitedBroadcast
            | Ipv4PresentAddressStatus::SubnetBroadcast),
        ) => {
            core_ctx
                .increment(|counters: &IpCounters<Ipv4>| &counters.version_rx.deliver_broadcast);
            ReceivePacketAction::Deliver {
                address_status,
                internal_forwarding: InternalForwarding::NotUsed,
            }
        }
        None => receive_ip_packet_action_common::<Ipv4, _, _, _>(
            core_ctx,
            bindings_ctx,
            dst_ip,
            device,
            packet,
            frame_dst,
        ),
    }
}

/// Computes the action to take in order to process a received IPv6 packet.
pub fn receive_ipv6_packet_action<BC, CC, B>(
    core_ctx: &mut CC,
    bindings_ctx: &mut BC,
    device: &CC::DeviceId,
    packet: &Ipv6Packet<B>,
    frame_dst: Option<FrameDestination>,
) -> ReceivePacketAction<Ipv6, CC::DeviceId>
where
    BC: IpLayerBindingsContext<Ipv6, CC::DeviceId>,
    CC: IpLayerContext<Ipv6, BC> + CounterContext<IpCounters<Ipv6>>,
    B: SplitByteSlice,
{
    let Some(dst_ip) = SpecifiedAddr::new(packet.dst_ip()) else {
        core_ctx.increment(|counters: &IpCounters<Ipv6>| &counters.unspecified_destination);
        return ReceivePacketAction::Drop { reason: DropReason::UnspecifiedDestination };
    };

    // If the packet arrived at the loopback interface, check if any local
    // interface has the destination address assigned. This effectively lets
    // the loopback interface operate as a weak host for incoming packets.
    //
    // Note that (as of writing) the stack sends all locally destined traffic to
    // the loopback interface so we need this hack to allow the stack to accept
    // packets that arrive at the loopback interface (after being looped back)
    // but destined to an address that is assigned to another local interface.
    //
    // TODO(https://fxbug.dev/42175703): This should instead be controlled by the
    // routing table.

    // It's possible that there is more than one device with the address
    // assigned. Since IPv6 addresses are either multicast or unicast, we
    // don't expect to see one device with `UnicastAssigned` or
    // `UnicastTentative` and another with `Multicast`. We might see one
    // assigned and one tentative status, though, in which case we should
    // prefer the former.
    fn choose_highest_priority(
        address_statuses: impl Iterator<Item = Ipv6PresentAddressStatus>,
        dst_ip: SpecifiedAddr<Ipv6Addr>,
    ) -> Option<Ipv6PresentAddressStatus> {
        address_statuses.max_by(|lhs, rhs| {
            use Ipv6PresentAddressStatus::*;
            match (lhs, rhs) {
                (UnicastAssigned | UnicastTentative, Multicast)
                | (Multicast, UnicastAssigned | UnicastTentative) => {
                    unreachable!("the IPv6 address {:?} is not both unicast and multicast", dst_ip)
                }
                (UnicastAssigned, UnicastTentative) => Ordering::Greater,
                (UnicastTentative, UnicastAssigned) => Ordering::Less,
                (UnicastTentative, UnicastTentative)
                | (UnicastAssigned, UnicastAssigned)
                | (Multicast, Multicast) => Ordering::Equal,
            }
        })
    }

    let highest_priority = if device.is_loopback() {
        core_ctx.with_address_statuses(dst_ip, |it| {
            let it = it.map(|(_device, status)| status);
            choose_highest_priority(it, dst_ip)
        })
    } else {
        core_ctx.address_status_for_device(dst_ip, device).into_present()
    };
    match highest_priority {
        Some(address_status @ Ipv6PresentAddressStatus::Multicast) => {
            receive_ip_multicast_packet_action(
                core_ctx,
                bindings_ctx,
                device,
                packet,
                Some(address_status),
                dst_ip,
                frame_dst,
            )
        }
        Some(address_status @ Ipv6PresentAddressStatus::UnicastAssigned) => {
            core_ctx.increment(|counters: &IpCounters<Ipv6>| &counters.deliver_unicast);
            ReceivePacketAction::Deliver {
                address_status,
                internal_forwarding: InternalForwarding::NotUsed,
            }
        }
        Some(Ipv6PresentAddressStatus::UnicastTentative) => {
            // If the destination address is tentative (which implies that
            // we are still performing NDP's Duplicate Address Detection on
            // it), then we don't consider the address "assigned to an
            // interface", and so we drop packets instead of delivering them
            // locally.
            //
            // As per RFC 4862 section 5.4:
            //
            //   An address on which the Duplicate Address Detection
            //   procedure is applied is said to be tentative until the
            //   procedure has completed successfully. A tentative address
            //   is not considered "assigned to an interface" in the
            //   traditional sense.  That is, the interface must accept
            //   Neighbor Solicitation and Advertisement messages containing
            //   the tentative address in the Target Address field, but
            //   processes such packets differently from those whose Target
            //   Address matches an address assigned to the interface. Other
            //   packets addressed to the tentative address should be
            //   silently discarded. Note that the "other packets" include
            //   Neighbor Solicitation and Advertisement messages that have
            //   the tentative (i.e., unicast) address as the IP destination
            //   address and contain the tentative address in the Target
            //   Address field.  Such a case should not happen in normal
            //   operation, though, since these messages are multicasted in
            //   the Duplicate Address Detection procedure.
            //
            // That is, we accept no packets destined to a tentative
            // address. NS and NA packets should be addressed to a multicast
            // address that we would have joined during DAD so that we can
            // receive those packets.
            core_ctx
                .increment(|counters: &IpCounters<Ipv6>| &counters.version_rx.drop_for_tentative);
            ReceivePacketAction::Drop { reason: DropReason::Tentative }
        }
        None => receive_ip_packet_action_common::<Ipv6, _, _, _>(
            core_ctx,
            bindings_ctx,
            dst_ip,
            device,
            packet,
            frame_dst,
        ),
    }
}

/// Computes the action to take for multicast packets on behalf of
/// [`receive_ipv4_packet_action`] and [`receive_ipv6_packet_action`].
fn receive_ip_multicast_packet_action<
    I: IpLayerIpExt,
    B: SplitByteSlice,
    BC: IpLayerBindingsContext<I, CC::DeviceId>,
    CC: IpLayerContext<I, BC> + CounterContext<IpCounters<I>>,
>(
    core_ctx: &mut CC,
    bindings_ctx: &mut BC,
    device: &CC::DeviceId,
    packet: &I::Packet<B>,
    address_status: Option<I::AddressStatus>,
    dst_ip: SpecifiedAddr<I::Addr>,
    frame_dst: Option<FrameDestination>,
) -> ReceivePacketAction<I, CC::DeviceId> {
    let targets = multicast_forwarding::lookup_multicast_route_or_stash_packet(
        core_ctx,
        bindings_ctx,
        packet,
        device,
        frame_dst,
    );
    match (targets, address_status) {
        (Some(targets), address_status) => {
            if address_status.is_some() {
                core_ctx.increment(|counters: &IpCounters<I>| &counters.deliver_multicast);
            }
            ReceivePacketAction::MulticastForward { targets, address_status, dst_ip }
        }
        (None, Some(address_status)) => {
            // If the address was present on the device (e.g. the host is a
            // member of the multicast group), fallback to local delivery.
            core_ctx.increment(|counters: &IpCounters<I>| &counters.deliver_multicast);
            ReceivePacketAction::Deliver {
                address_status,
                internal_forwarding: InternalForwarding::NotUsed,
            }
        }
        (None, None) => {
            // As per RFC 1122 Section 3.2.2
            //   An ICMP error message MUST NOT be sent as the result of
            //   receiving:
            //   ...
            //   * a datagram destined to an IP broadcast or IP multicast
            //     address
            //
            // As such, drop the packet
            core_ctx.increment(|counters: &IpCounters<I>| &counters.multicast_no_interest);
            ReceivePacketAction::Drop { reason: DropReason::MulticastNoInterest }
        }
    }
}

/// Computes the remaining protocol-agnostic actions on behalf of
/// [`receive_ipv4_packet_action`] and [`receive_ipv6_packet_action`].
fn receive_ip_packet_action_common<
    I: IpLayerIpExt,
    B: SplitByteSlice,
    BC: IpLayerBindingsContext<I, CC::DeviceId>,
    CC: IpLayerContext<I, BC> + CounterContext<IpCounters<I>>,
>(
    core_ctx: &mut CC,
    bindings_ctx: &mut BC,
    dst_ip: SpecifiedAddr<I::Addr>,
    device_id: &CC::DeviceId,
    packet: &I::Packet<B>,
    frame_dst: Option<FrameDestination>,
) -> ReceivePacketAction<I, CC::DeviceId> {
    if dst_ip.is_multicast() {
        return receive_ip_multicast_packet_action(
            core_ctx,
            bindings_ctx,
            device_id,
            packet,
            None,
            dst_ip,
            frame_dst,
        );
    }

    // The packet is not destined locally, so we attempt to forward it.
    if !core_ctx.is_device_unicast_forwarding_enabled(device_id) {
        // Forwarding is disabled; we are operating only as a host.
        //
        // For IPv4, per RFC 1122 Section 3.2.1.3, "A host MUST silently discard
        // an incoming datagram that is not destined for the host."
        //
        // For IPv6, per RFC 4443 Section 3.1, the only instance in which a host
        // sends an ICMPv6 Destination Unreachable message is when a packet is
        // destined to that host but on an unreachable port (Code 4 - "Port
        // unreachable"). Since the only sensible error message to send in this
        // case is a Destination Unreachable message, we interpret the RFC text
        // to mean that, consistent with IPv4's behavior, we should silently
        // discard the packet in this case.
        core_ctx.increment(|counters: &IpCounters<I>| &counters.forwarding_disabled);
        return ReceivePacketAction::Drop { reason: DropReason::ForwardingDisabledInboundIface };
    }
    // Per https://www.rfc-editor.org/rfc/rfc4291.html#section-2.5.2:
    //   An IPv6 packet with a source address of unspecified must never be forwarded by an IPv6
    //   router.
    // Per https://datatracker.ietf.org/doc/html/rfc1812#section-5.3.7:
    //   A router SHOULD NOT forward any packet that has an invalid IP source address or a source
    //   address on network 0
    let Some(source_address) = SpecifiedAddr::new(packet.src_ip()) else {
        return ReceivePacketAction::Drop { reason: DropReason::ForwardUnspecifiedSource };
    };

    // If forwarding is enabled, allow local delivery if the packet is destined
    // for an IP assigned to a different interface.
    //
    // This enables a weak host model when the Netstack is configured as a
    // router. Conceptually, the netstack is forwarding the packet from the
    // input device, to the destination IP's device.
    if let Some(dst_ip) = NonMappedAddr::new(dst_ip).and_then(NonMulticastAddr::new) {
        if let Some((outbound_device, address_status)) =
            get_device_with_assigned_address(core_ctx, IpDeviceAddr::new_from_witness(dst_ip))
        {
            return ReceivePacketAction::Deliver {
                address_status,
                internal_forwarding: InternalForwarding::Used(outbound_device),
            };
        }
    }

    match lookup_route_table(
        core_ctx,
        *dst_ip,
        RuleInput {
            packet_origin: PacketOrigin::NonLocal { source_address, incoming_device: device_id },
            // TODO(https://fxbug.dev/369133279): packets can have marks as a result of a filtering
            // target like `MARK`.
            marks: &Default::default(),
        },
    ) {
        Some(dst) => {
            core_ctx.increment(|counters: &IpCounters<I>| &counters.forward);
            ReceivePacketAction::Forward { original_dst: dst_ip, dst }
        }
        None => {
            core_ctx.increment(|counters: &IpCounters<I>| &counters.no_route_to_host);
            ReceivePacketAction::SendNoRouteToDest { dst: dst_ip }
        }
    }
}

// Look up the route to a host.
fn lookup_route_table<I: IpLayerIpExt, CC: IpStateContext<I>>(
    core_ctx: &mut CC,
    dst_ip: I::Addr,
    rule_input: RuleInput<'_, I, CC::DeviceId>,
) -> Option<Destination<I::Addr, CC::DeviceId>> {
    let bound_device = match rule_input.packet_origin {
        PacketOrigin::Local { bound_address: _, bound_device } => bound_device,
        PacketOrigin::NonLocal { source_address: _, incoming_device: _ } => None,
    };
    core_ctx.with_rules_table(|core_ctx, rules| {
        match walk_rules(core_ctx, rules, (), &rule_input, |(), core_ctx, table| {
            match table.lookup(core_ctx, bound_device, dst_ip) {
                Some(dst) => ControlFlow::Break(Some(dst)),
                None => ControlFlow::Continue(()),
            }
        }) {
            ControlFlow::Break(RuleAction::Lookup(RuleWalkInfo {
                inner: dst,
                observed_source_address_matcher: _,
            })) => dst,
            ControlFlow::Break(RuleAction::Unreachable) => None,
            ControlFlow::Continue(RuleWalkInfo {
                inner: (),
                observed_source_address_matcher: _,
            }) => None,
        }
    })
}

/// Packed destination passed to [`IpDeviceSendContext::send_ip_frame`].
#[derive(Debug, Derivative, Clone)]
#[derivative(Eq(bound = "D: Eq"), PartialEq(bound = "D: PartialEq"))]
pub enum IpPacketDestination<I: BroadcastIpExt, D> {
    /// Broadcast packet.
    Broadcast(I::BroadcastMarker),

    /// Multicast packet to the specified IP.
    Multicast(MulticastAddr<I::Addr>),

    /// Send packet to the neighbor with the specified IP (the receiving
    /// node is either a router or the final recipient of the packet).
    Neighbor(SpecifiedAddr<I::Addr>),

    /// Loopback the packet to the specified device. Can be used only when
    /// sending to the loopback device.
    Loopback(D),
}

impl<I: BroadcastIpExt, D> IpPacketDestination<I, D> {
    /// Creates `IpPacketDestination` for IP address.
    pub fn from_addr(addr: SpecifiedAddr<I::Addr>) -> Self {
        match MulticastAddr::new(addr.into_addr()) {
            Some(mc_addr) => Self::Multicast(mc_addr),
            None => Self::Neighbor(addr),
        }
    }

    /// Create `IpPacketDestination` from `NextHop`.
    pub fn from_next_hop(next_hop: NextHop<I::Addr>, dst_ip: SpecifiedAddr<I::Addr>) -> Self {
        match next_hop {
            NextHop::RemoteAsNeighbor => Self::from_addr(dst_ip),
            NextHop::Gateway(gateway) => Self::Neighbor(gateway),
            NextHop::Broadcast(marker) => Self::Broadcast(marker),
        }
    }
}

/// The metadata associated with an outgoing IP packet.
#[derive(Debug, Clone)]
pub struct SendIpPacketMeta<I: IpExt, D, Src> {
    /// The outgoing device.
    pub device: D,

    /// The source address of the packet.
    pub src_ip: Src,

    /// The destination address of the packet.
    pub dst_ip: SpecifiedAddr<I::Addr>,

    /// The destination for the send operation.
    pub destination: IpPacketDestination<I, D>,

    /// The upper-layer protocol held in the packet's payload.
    pub proto: I::Proto,

    /// The time-to-live (IPv4) or hop limit (IPv6) for the packet.
    ///
    /// If not set, a default TTL may be used.
    pub ttl: Option<NonZeroU8>,

    /// An MTU to artificially impose on the whole IP packet.
    ///
    /// Note that the device's and discovered path MTU may still be imposed on
    /// the packet.
    pub mtu: Mtu,

    /// Traffic Class (IPv6) or Type of Service (IPv4) field for the packet.
    pub dscp_and_ecn: DscpAndEcn,
}

impl<I: IpExt, D> From<SendIpPacketMeta<I, D, SpecifiedAddr<I::Addr>>>
    for SendIpPacketMeta<I, D, Option<SpecifiedAddr<I::Addr>>>
{
    fn from(
        SendIpPacketMeta { device, src_ip, dst_ip, destination, proto, ttl, mtu, dscp_and_ecn }: SendIpPacketMeta<
            I,
            D,
            SpecifiedAddr<I::Addr>,
        >,
    ) -> SendIpPacketMeta<I, D, Option<SpecifiedAddr<I::Addr>>> {
        SendIpPacketMeta {
            device,
            src_ip: Some(src_ip),
            dst_ip,
            destination,
            proto,
            ttl,
            mtu,
            dscp_and_ecn,
        }
    }
}

/// Trait for abstracting the IP layer for locally-generated traffic.  That is,
/// traffic generated by the netstack itself (e.g. ICMP, IGMP, or MLD).
///
/// NOTE: Due to filtering rules, it is possible that the device provided in
/// `meta` will not be the device that final IP packet is actually sent from.
pub trait IpLayerHandler<I: IpExt, BC>: DeviceIdContext<AnyDevice> {
    /// Encapsulate and send the provided transport packet and from the device
    /// provided in `meta`.
    fn send_ip_packet_from_device<S>(
        &mut self,
        bindings_ctx: &mut BC,
        meta: SendIpPacketMeta<I, &Self::DeviceId, Option<SpecifiedAddr<I::Addr>>>,
        body: S,
    ) -> Result<(), IpSendFrameError<S>>
    where
        S: TransportPacketSerializer<I>,
        S::Buffer: BufferMut;

    /// Send an IP packet that doesn't require the encapsulation and other
    /// processing of [`send_ip_packet_from_device`] from the device specified
    /// in `meta`.
    // TODO(https://fxbug.dev/333908066): The packets going through this
    // function only hit the EGRESS filter hook, bypassing LOCAL_EGRESS.
    // Refactor callers and other functions to prevent this.
    fn send_ip_frame<S>(
        &mut self,
        bindings_ctx: &mut BC,
        device: &Self::DeviceId,
        destination: IpPacketDestination<I, &Self::DeviceId>,
        body: S,
    ) -> Result<(), IpSendFrameError<S>>
    where
        S: Serializer + IpPacket<I>,
        S::Buffer: BufferMut;
}

impl<
        I: IpLayerIpExt,
        BC: IpLayerBindingsContext<I, <CC as DeviceIdContext<AnyDevice>>::DeviceId>,
        CC: IpLayerEgressContext<I, BC> + IpDeviceStateContext<I> + IpDeviceMtuContext<I>,
    > IpLayerHandler<I, BC> for CC
{
    fn send_ip_packet_from_device<S>(
        &mut self,
        bindings_ctx: &mut BC,
        meta: SendIpPacketMeta<I, &CC::DeviceId, Option<SpecifiedAddr<I::Addr>>>,
        body: S,
    ) -> Result<(), IpSendFrameError<S>>
    where
        S: TransportPacketSerializer<I>,
        S::Buffer: BufferMut,
    {
        send_ip_packet_from_device(self, bindings_ctx, meta, body, IpLayerPacketMetadata::default())
    }

    fn send_ip_frame<S>(
        &mut self,
        bindings_ctx: &mut BC,
        device: &Self::DeviceId,
        destination: IpPacketDestination<I, &Self::DeviceId>,
        body: S,
    ) -> Result<(), IpSendFrameError<S>>
    where
        S: Serializer + IpPacket<I>,
        S::Buffer: BufferMut,
    {
        send_ip_frame(
            self,
            bindings_ctx,
            device,
            destination,
            body,
            IpLayerPacketMetadata::default(),
            Mtu::no_limit(),
        )
    }
}

/// Sends an Ip packet with the specified metadata.
///
/// # Panics
///
/// Panics if either the source or destination address is the loopback address
/// and the device is a non-loopback device.
pub(crate) fn send_ip_packet_from_device<I, BC, CC, S>(
    core_ctx: &mut CC,
    bindings_ctx: &mut BC,
    meta: SendIpPacketMeta<
        I,
        &<CC as DeviceIdContext<AnyDevice>>::DeviceId,
        Option<SpecifiedAddr<I::Addr>>,
    >,
    body: S,
    packet_metadata: IpLayerPacketMetadata<I, BC>,
) -> Result<(), IpSendFrameError<S>>
where
    I: IpLayerIpExt,
    BC: FilterBindingsContext,
    CC: IpLayerEgressContext<I, BC> + IpDeviceStateContext<I> + IpDeviceMtuContext<I>,
    S: TransportPacketSerializer<I>,
    S::Buffer: BufferMut,
{
    let SendIpPacketMeta { device, src_ip, dst_ip, destination, proto, ttl, mtu, dscp_and_ecn } =
        meta;
    let next_packet_id = gen_ip_packet_id(core_ctx);
    let ttl = ttl.unwrap_or_else(|| core_ctx.get_hop_limit(device)).get();
    let src_ip = src_ip.map_or(I::UNSPECIFIED_ADDRESS, |a| a.get());
    let mut builder = I::PacketBuilder::new(src_ip, dst_ip.get(), ttl, proto);

    #[derive(GenericOverIp)]
    #[generic_over_ip(I, Ip)]
    struct Wrap<'a, I: IpLayerIpExt> {
        builder: &'a mut I::PacketBuilder,
        next_packet_id: I::PacketId,
    }

    I::map_ip::<_, ()>(
        Wrap { builder: &mut builder, next_packet_id },
        |Wrap { builder, next_packet_id }| {
            builder.id(next_packet_id);
        },
        |Wrap { builder: _, next_packet_id: () }| {
            // IPv6 doesn't have packet IDs.
        },
    );

    builder.set_dscp_and_ecn(dscp_and_ecn);

    let ip_frame = body.encapsulate(builder);
    send_ip_frame(core_ctx, bindings_ctx, device, destination, ip_frame, packet_metadata, mtu)
        .map_err(|ser| ser.map_serializer(|s| s.into_inner()))
}

/// Abstracts access to a [`filter::FilterHandler`] for core contexts.
pub trait FilterHandlerProvider<I: packet_formats::ip::IpExt, BT: FilterBindingsTypes>:
    DeviceIdContext<AnyDevice, DeviceId: filter::InterfaceProperties<BT::DeviceClass>>
{
    /// The filter handler.
    type Handler<'a>: filter::FilterHandler<I, BT, DeviceId = Self::DeviceId>
    where
        Self: 'a;

    /// Gets the filter handler for this context.
    fn filter_handler(&mut self) -> Self::Handler<'_>;
}

#[cfg(any(test, feature = "testutils"))]
pub(crate) mod testutil {
    use super::*;

    use netstack3_base::testutil::{FakeCoreCtx, FakeStrongDeviceId};
    use netstack3_base::{SendFrameContext, SendFrameError, SendableFrameMeta};

    /// A [`SendIpPacketMeta`] for dual stack contextx.
    #[derive(Debug, GenericOverIp)]
    #[generic_over_ip()]
    #[allow(missing_docs)]
    pub enum DualStackSendIpPacketMeta<D> {
        V4(SendIpPacketMeta<Ipv4, D, SpecifiedAddr<Ipv4Addr>>),
        V6(SendIpPacketMeta<Ipv6, D, SpecifiedAddr<Ipv6Addr>>),
    }

    impl<I: IpExt, D> From<SendIpPacketMeta<I, D, SpecifiedAddr<I::Addr>>>
        for DualStackSendIpPacketMeta<D>
    {
        fn from(value: SendIpPacketMeta<I, D, SpecifiedAddr<I::Addr>>) -> Self {
            #[derive(GenericOverIp)]
            #[generic_over_ip(I, Ip)]
            struct Wrap<I: IpExt, D>(SendIpPacketMeta<I, D, SpecifiedAddr<I::Addr>>);
            use DualStackSendIpPacketMeta::*;
            I::map_ip_in(Wrap(value), |Wrap(value)| V4(value), |Wrap(value)| V6(value))
        }
    }

    impl<I: IpExt, S, DeviceId, BC>
        SendableFrameMeta<FakeCoreCtx<S, DualStackSendIpPacketMeta<DeviceId>, DeviceId>, BC>
        for SendIpPacketMeta<I, DeviceId, SpecifiedAddr<I::Addr>>
    {
        fn send_meta<SS>(
            self,
            core_ctx: &mut FakeCoreCtx<S, DualStackSendIpPacketMeta<DeviceId>, DeviceId>,
            bindings_ctx: &mut BC,
            frame: SS,
        ) -> Result<(), SendFrameError<SS>>
        where
            SS: Serializer,
            SS::Buffer: BufferMut,
        {
            SendFrameContext::send_frame(
                &mut core_ctx.frames,
                bindings_ctx,
                DualStackSendIpPacketMeta::from(self),
                frame,
            )
        }
    }

    /// Error returned when the IP version doesn't match.
    #[derive(Debug)]
    pub struct WrongIpVersion;

    impl<D> DualStackSendIpPacketMeta<D> {
        /// Returns the internal [`SendIpPacketMeta`] if this is carrying the
        /// version matching `I`.
        pub fn try_as<I: IpExt>(
            &self,
        ) -> Result<&SendIpPacketMeta<I, D, SpecifiedAddr<I::Addr>>, WrongIpVersion> {
            #[derive(GenericOverIp)]
            #[generic_over_ip(I, Ip)]
            struct Wrap<'a, I: IpExt, D>(
                Option<&'a SendIpPacketMeta<I, D, SpecifiedAddr<I::Addr>>>,
            );
            use DualStackSendIpPacketMeta::*;
            let Wrap(dual_stack) = I::map_ip(
                self,
                |value| {
                    Wrap(match value {
                        V4(meta) => Some(meta),
                        V6(_) => None,
                    })
                },
                |value| {
                    Wrap(match value {
                        V4(_) => None,
                        V6(meta) => Some(meta),
                    })
                },
            );
            dual_stack.ok_or(WrongIpVersion)
        }
    }

    impl<I, BC, S, Meta, DeviceId> FilterHandlerProvider<I, BC> for FakeCoreCtx<S, Meta, DeviceId>
    where
        I: packet_formats::ip::IpExt,
        BC: FilterBindingsContext,
        DeviceId: FakeStrongDeviceId + filter::InterfaceProperties<BC::DeviceClass>,
    {
        type Handler<'a>
            = filter::testutil::NoopImpl<DeviceId>
        where
            Self: 'a;

        fn filter_handler(&mut self) -> Self::Handler<'_> {
            filter::testutil::NoopImpl::default()
        }
    }
}